From 1028ff65a5d9e4a532310473db6eaa1eef615df4 Mon Sep 17 00:00:00 2001 From: Affaan Mustafa Date: Sun, 15 Nov 2026 01:45:31 -0500 Subject: [PATCH] feat(work-items): verify artifacts before completion --- .../verified-work-item-outcomes.md | 172 ++++++++++++ manifests/context-packs/skill-triggers@1.json | 2 +- scripts/lib/control-pane/server.js | 6 +- .../lib/control-pane/work-item-mutations.js | 3 + scripts/lib/harness-adapter-compliance.js | 4 +- scripts/lib/state-store/queries.js | 45 +-- scripts/lib/work-item-verification.js | 191 +++++++++++++ scripts/work-items.js | 37 ++- skills/agent-harness-construction/SKILL.md | 26 ++ tests/lib/work-item-verification.test.js | 259 ++++++++++++++++++ tests/scripts/control-pane.test.js | 44 +++ 11 files changed, 767 insertions(+), 22 deletions(-) create mode 100644 docs/architecture/verified-work-item-outcomes.md create mode 100644 scripts/lib/work-item-verification.js create mode 100644 tests/lib/work-item-verification.test.js diff --git a/docs/architecture/verified-work-item-outcomes.md b/docs/architecture/verified-work-item-outcomes.md new file mode 100644 index 000000000..c581902e5 --- /dev/null +++ b/docs/architecture/verified-work-item-outcomes.md @@ -0,0 +1,172 @@ +# Verified Work-Item Outcomes + +ECC connects the tools that agents already use. A queue selects work; a +workspace or multiplexer hosts sessions; a harness chooses actions; tools make +changes; a validator checks the result. These responsibilities can remain in +different products while sharing an explicit completion contract. + +This slice adds opt-in artifact verification to the existing local work-items +store. It gives a failed check, a repair, and a successful check a common +record. It does not introduce another queue, terminal, model runtime, or skill +catalog. + +## Position In The Stack + +```text +Queue / workspace select and assign a task + | +Terminal / multiplexer host the worker session + | +Agent harness choose actions and handle observations + | +Tools inspect, edit, and repair an artifact + | +ECC verification check the declared result and record evidence +``` + +The work-item ID connects task state to its owner and session. The declared +validator connects completion to an artifact check. Queues and session UIs +can consume those records without adopting a new execution environment. +FocusQueue integration is a planned consumer, not a shipped adapter in this +slice. Existing session adapters are described in the +[harness adapter matrix](harness-adapter-compliance.md). + +## First Validator + +`harness-adapter-documentation/v1` checks a Markdown artifact against ECC's +canonical harness adapter matrix. Its scope is documentation consistency: +the expected matrix markers and contents must match the registered validator's +reference data. A passing result does not prove that each documented harness +was exercised or that an external deployment succeeded. + +Validation runs through the registered ECC implementation. A task supplies an +artifact path, not a shell command or a replacement validator. Keep the +checker independent of the artifact being repaired. + +## Use The Contract + +Run these commands from an ECC checkout. The session must already exist in +the same state database; `sessions-cli.js` lists available IDs. Replace the +example session value with an ID from that output. If using a separate +database, pass the same `--db ` to every command, including the session +lookup. + +```bash +node scripts/sessions-cli.js --json +ecc_docs_session='existing-session-id' + +node scripts/work-items.js upsert adapter-matrix-docs \ + --title 'Keep the harness adapter matrix consistent' \ + --repo-root "$PWD" \ + --verify harness-adapter-documentation/v1 \ + --artifact docs/architecture/harness-adapter-compliance.md + +node scripts/work-items.js claim adapter-matrix-docs \ + --owner docs-worker --as agent --session-id "$ecc_docs_session" + +node scripts/work-items.js verify adapter-matrix-docs --json +node scripts/work-items.js show adapter-matrix-docs --json +``` + +Register the contract when creating a new work item, before claiming it. +Existing items cannot acquire a contract, including legacy items that are still +open; use a new work-item ID. The validator, artifact path, and task identity +(`id`, `source`, `sourceId`, `title`, `repoRoot`) remain fixed for that item. + +| Check result | Work-item status | Next action | +| --- | --- | --- | +| Success | `done` | Inspect the recorded evidence. | +| Failure | `blocked` | Repair the artifact, then run `verify` again. | +| Unknown | `blocked` | Resolve the check's error, then run `verify` again. | + +Failed attempts remain in the record when a later check succeeds. Cancelling +work does not establish success. A manual close cannot substitute for the +registered check on a contracted item. + +`verify --json` returns `{ verified, attempt, item }`; a failed or unknown +check exits with status 1 while preserving its receipt. Running `verify` again +always performs a new check and appends a new attempt, even if the artifact +has not changed. + +A success-state update, such as `close`, requires a previous successful check +bound to the same task, owner, and session. It also rechecks the current +artifact and validator reference. A failed completion recheck records another +attempt and moves the item to `blocked`; the CLI exits with status 1. A close +without a previous bound success is rejected. After a repair or reassignment, +run `verify` to establish a fresh result. + +## Local Receipt + +`show --json` exposes `metadata.verification`: + +```json +{ + "contract": { + "verifier": "harness-adapter-documentation/v1", + "artifact": "docs/architecture/harness-adapter-compliance.md" + }, + "registeredAt": "2026-11-15T00:00:00.000Z", + "attempts": [] +} +``` + +The timestamp above is illustrative. Each recorded attempt contains: + +| Fields | Meaning | +| --- | --- | +| `schemaVersion` | `ecc.work-item-verification.v1`. | +| `attemptId`, `previousAttemptId` | Unique check ID and previous check ID, or `null` for the first attempt. | +| `kind` | `verification` or `completion-recheck`. | +| `taskId`, `sessionId`, `owner` | Work item and executor attribution. | +| `verifier`, `verifierDigest` | Registered validator ID and SHA-256 of that ID plus its rendered reference matrix. | +| `contractDigest` | SHA-256 binding the repository root, validator ID, and artifact path. | +| `taskDigest` | SHA-256 binding task identity, owner, session, and contract digest. | +| `outcome`, `reasons` | `success`, `failure`, or `unknown`, plus check diagnostics. | +| `artifactDigest` | SHA-256 of the inspected bytes, or `null` when a trustworthy read was unavailable. | +| `durationMs`, `checkedAt` | Local verification duration in milliseconds and ISO timestamp. | + +Receipts store hashes and diagnostics, not the artifact body. Diagnostics may +include local file paths; treat the store as local operational data. The +previous-attempt link is an ordering aid, not a tamper-proof audit chain. +`durationMs` measures the check, not total task time. Token usage, monetary +cost, and human interventions are not measured by this receipt. + +The artifact must be a regular `.md` file no larger than 1 MiB, addressed by a +relative path within the registered repository root. Path traversal and +symlink artifacts or path components are rejected. A work item retains at +most 1,000 attempts; reaching that limit requires a new work item rather than +silently discarding its history. + +## Learning Fits The Same Interface + +A future compact execution model could choose a tool, compose a short workflow, +or propose a repair. Deterministic code can still perform file operations, +enforce contracts, and check the result. Both large and small models can use +the same task, tool, and outcome interfaces. + +The useful learning signal is whether an action produced the required result, +what failed, and how much recovery it required. This slice records local +verification attempts; it does not train a model, produce a training dataset, +measure model quality, or demonstrate transfer to new environments. Those +experiments need separate baselines, consent and data handling, held-out tasks, +and cost and latency measurements. + +## Boundaries + +- Verification is opt-in. Existing manual and imported work retains its + previous lifecycle; a manual `done` status is not a verified outcome. +- The record is local evidence, not remote attestation. A person who can + modify the local database or ECC implementation can alter its contents. +- An artifact check covers the inspected file at the time of the attempt. + It is not a claim about all repository files or a permanent guarantee after + later edits. +- This change does not add hosted execution, authorization, model training, + a FocusQueue adapter, or automatic repair. The worker performs the repair + and explicitly requests another check. + +## Related Contracts + +- [Progress sync](progress-sync-contract.md): queue and handoff sources of truth. +- [Session adapters](session-adapter-contract.md): portable session inspection. +- [Harness construction](../../skills/agent-harness-construction/SKILL.md): + action spaces, observations, and recovery. diff --git a/manifests/context-packs/skill-triggers@1.json b/manifests/context-packs/skill-triggers@1.json index 48081c3fb..a29e21516 100644 --- a/manifests/context-packs/skill-triggers@1.json +++ b/manifests/context-packs/skill-triggers@1.json @@ -10,7 +10,7 @@ "id": "hand-seeded", "source": "manual-curation-pending-regeneration" }, - "registryDigest": "6f213dc845937b4093bc018d041b25b538d88d78451b9d799ad614989b360ee4", + "registryDigest": "a7c995d29b7a4757adf87c85fcad7b578297ac594b0c936636f26d9733a490f7", "schemaVersion": 1, "triggers": { "skill:agent-runtime-gateway-smoke-test": [ diff --git a/scripts/lib/control-pane/server.js b/scripts/lib/control-pane/server.js index cf4d73168..718d5749a 100644 --- a/scripts/lib/control-pane/server.js +++ b/scripts/lib/control-pane/server.js @@ -347,7 +347,11 @@ function createControlPaneServer(options = {}) { } : { id, lane: body.lane } ); - sendJson(res, 200, { ok: true, ...result }); + if (result.moved === false && result.reason === 'verification-failed') { + sendJson(res, 409, { ...result, ok: false, error: 'Verification failed; the work item is blocked. Run verify after repair.' }); + } else { + sendJson(res, 200, { ok: true, ...result }); + } } catch (mutationError) { if (mutationError.code === 'STATE_STORE_BUSY') { res.setHeader('Retry-After', '1'); diff --git a/scripts/lib/control-pane/work-item-mutations.js b/scripts/lib/control-pane/work-item-mutations.js index c26395a9a..d59f34701 100644 --- a/scripts/lib/control-pane/work-item-mutations.js +++ b/scripts/lib/control-pane/work-item-mutations.js @@ -116,6 +116,9 @@ function moveWorkItem(store, { id, lane } = {}) { status: LANE_TO_STATUS[laneKey], updatedAt: new Date().toISOString() }); + if (item.status !== LANE_TO_STATUS[laneKey]) { + return { moved: false, reason: 'verification-failed', item }; + } return { moved: true, item }; } diff --git a/scripts/lib/harness-adapter-compliance.js b/scripts/lib/harness-adapter-compliance.js index c4178a9f4..18a28f6f9 100644 --- a/scripts/lib/harness-adapter-compliance.js +++ b/scripts/lib/harness-adapter-compliance.js @@ -503,7 +503,9 @@ function validateDocumentation(options = {}) { const repoRoot = options.repoRoot || path.resolve(__dirname, '..', '..'); const docPath = options.docPath || path.join(repoRoot, 'docs', 'architecture', 'harness-adapter-compliance.md'); const errors = []; - const source = fs.readFileSync(docPath, 'utf8'); + // Callers may supply an already bounded snapshot, so validation and hashing + // inspect the same bytes without reopening a mutable artifact. + const source = options.source === undefined ? fs.readFileSync(docPath, 'utf8') : options.source; const actual = extractMatrixBlock(source); const expected = renderMarkdownTable(); diff --git a/scripts/lib/state-store/queries.js b/scripts/lib/state-store/queries.js index d7e8782d8..5624ca559 100644 --- a/scripts/lib/state-store/queries.js +++ b/scripts/lib/state-store/queries.js @@ -1,6 +1,7 @@ 'use strict'; const { assertValidEntity } = require('./schema'); +const { prepareVerifiedUpdate, verifyWorkItem } = require('../work-item-verification'); const ACTIVE_SESSION_STATES = ['active', 'running', 'idle']; const SUCCESS_OUTCOMES = new Set(['success', 'succeeded', 'passed']); @@ -732,6 +733,28 @@ function createQueryApi(db, { prepareRead = sql => db.prepare(sql) } = {}) { updated_at = excluded.updated_at `); + function persistWorkItem(workItem) { + const normalized = normalizeWorkItemInput(workItem); + assertValidEntity('workItem', normalized); + upsertWorkItemStatement.run({ + id: normalized.id, + source: normalized.source, + source_id: normalized.sourceId, + title: normalized.title, + status: normalized.status, + priority: normalized.priority, + url: normalized.url, + owner: normalized.owner, + repo_root: normalized.repoRoot, + session_id: normalized.sessionId, + metadata: stringifyJson(normalized.metadata, 'workItem.metadata'), + created_at: normalized.createdAt, + updated_at: normalized.updatedAt, + }); + const row = getWorkItemStatement.get(normalized.id); + return row ? mapWorkItemRow(row) : null; + } + function getSessionById(id) { const row = getSessionStatement.get(id); return row ? mapSessionRow(row) : null; @@ -909,23 +932,11 @@ function createQueryApi(db, { prepareRead = sql => db.prepare(sql) } = {}) { upsertWorkItem(workItem) { const normalized = normalizeWorkItemInput(workItem); assertValidEntity('workItem', normalized); - upsertWorkItemStatement.run({ - id: normalized.id, - source: normalized.source, - source_id: normalized.sourceId, - title: normalized.title, - status: normalized.status, - priority: normalized.priority, - url: normalized.url, - owner: normalized.owner, - repo_root: normalized.repoRoot, - session_id: normalized.sessionId, - metadata: stringifyJson(normalized.metadata, 'workItem.metadata'), - created_at: normalized.createdAt, - updated_at: normalized.updatedAt, - }); - const row = getWorkItemStatement.get(normalized.id); - return row ? mapWorkItemRow(row) : null; + return persistWorkItem(prepareVerifiedUpdate(getWorkItemById(normalized.id), normalized)); + }, + verifyWorkItem(id) { + const result = verifyWorkItem(getWorkItemById(id)); + return { ...result, item: persistWorkItem(result.item) }; }, upsertSession(session) { const normalized = normalizeSessionInput(session); diff --git a/scripts/lib/work-item-verification.js b/scripts/lib/work-item-verification.js new file mode 100644 index 000000000..952f2c5e9 --- /dev/null +++ b/scripts/lib/work-item-verification.js @@ -0,0 +1,191 @@ +'use strict'; + +// Opt-in artifact verification for a local, user-owned queue. This is an +// application invariant, not an authorization boundary against a DB/file owner. +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); +const { performance } = require('perf_hooks'); +const { isDeepStrictEqual } = require('util'); +const { renderMarkdownTable, validateDocumentation } = require('./harness-adapter-compliance'); + +const VERIFIER = 'harness-adapter-documentation/v1'; +const MAX_ARTIFACT_BYTES = 1024 * 1024; +const MAX_ATTEMPTS = 1000; +const SUCCESS_STATUSES = new Set(['done', 'closed', 'resolved', 'merged']); +const RUNNING_STATUSES = new Set(['running', 'claimed', 'in-progress']); +const VERIFIABLE_STATUSES = new Set([...RUNNING_STATUSES, ...SUCCESS_STATUSES, 'blocked']); +const statusKey = value => String(value || '').trim().toLowerCase(); +const digest = value => crypto.createHash('sha256').update(value).digest('hex'); +const record = value => value !== null && typeof value === 'object' && !Array.isArray(value); +const hasVerification = item => Boolean(item && item.metadata && Object.hasOwn(item.metadata, 'verification')); + +function validateContract(contract, repoRoot) { + if (!record(contract) || Object.keys(contract).sort().join(',') !== 'artifact,verifier' || contract.verifier !== VERIFIER) { + throw new Error(`Verification contract requires verifier '${VERIFIER}' and artifact only.`); + } + const artifact = contract.artifact; + if (typeof artifact !== 'string' || !artifact || artifact.length > 4096 || artifact.includes('\0') || artifact.includes('\\') + || path.isAbsolute(artifact) || path.win32.isAbsolute(artifact) || artifact.split('/').some(part => !part || part === '.' || part === '..') + || path.extname(artifact) !== '.md') { + throw new Error('Verification artifact must be a bounded relative .md path without traversal.'); + } + if (typeof repoRoot !== 'string' || !path.isAbsolute(repoRoot)) { + throw new Error('Verification requires an absolute repo root.'); + } + return { verifier: VERIFIER, artifact }; +} + +function identity(item) { + return [item.id, item.source, item.sourceId, item.title, item.repoRoot]; +} + +function binding(item) { + const contract = item.metadata.verification.contract; + const contractDigest = digest(JSON.stringify([item.repoRoot, contract.verifier, contract.artifact])); + return { contractDigest, taskDigest: digest(JSON.stringify([...identity(item), item.owner, item.sessionId, contractDigest])) }; +} + +function requireClaim(item) { + if (!item.owner || !item.sessionId || !VERIFIABLE_STATUSES.has(statusKey(item.status))) { + throw new Error('Verification requires claimed work with an owner and registered session.'); + } +} + +function assertContained(root, filename) { + const relative = path.relative(root, filename); + if (!relative || relative.startsWith(`..${path.sep}`) || relative === '..' || path.isAbsolute(relative)) { + throw new Error('Artifact escapes the registered repo root.'); + } +} + +function readArtifact(item) { + const { artifact } = validateContract(item.metadata.verification.contract, item.repoRoot); + const root = fs.realpathSync(item.repoRoot); + if (root !== item.repoRoot) throw new Error('Registered repo root changed or became a symlink.'); + let filename = root; + for (const component of artifact.split('/')) { + filename = path.join(filename, component); + if (fs.lstatSync(filename).isSymbolicLink()) throw new Error('Artifact symlinks are not supported.'); + } + assertContained(root, fs.realpathSync(filename)); + const descriptor = fs.openSync(filename, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0) | (fs.constants.O_NONBLOCK || 0)); + try { + const before = fs.fstatSync(descriptor); + if (!before.isFile() || before.size > MAX_ARTIFACT_BYTES) throw new Error('Artifact must be a regular file no larger than 1 MiB.'); + const buffer = Buffer.alloc(MAX_ARTIFACT_BYTES + 1); + let length = 0; + while (length < buffer.length) { + const count = fs.readSync(descriptor, buffer, length, buffer.length - length, length); + if (!count) break; + length += count; + } + const after = fs.fstatSync(descriptor); + // Detect replacement/changes during read; validate exactly the bytes hashed. + assertContained(root, fs.realpathSync(filename)); + const current = fs.lstatSync(filename); + if (current.isSymbolicLink() || length > MAX_ARTIFACT_BYTES || before.size !== length + || ['dev', 'ino', 'size', 'mtimeMs', 'ctimeMs'].some(key => before[key] !== after[key] || after[key] !== current[key])) { + throw new Error('Artifact changed during verification; retry.'); + } + return { filename, bytes: buffer.subarray(0, length) }; + } finally { + fs.closeSync(descriptor); + } +} + +function checkArtifact(item) { + try { + const { filename, bytes } = readArtifact(item); + const reasons = validateDocumentation({ repoRoot: item.repoRoot, docPath: filename, source: bytes.toString('utf8') }); + return { outcome: reasons.length ? 'failure' : 'success', reasons, artifactDigest: digest(bytes) }; + } catch (error) { + return { outcome: 'unknown', reasons: [error.message], artifactDigest: null }; + } +} + +function appendAttempt(item, kind = 'verification') { + requireClaim(item); + const previous = item.metadata.verification; + if (previous.attempts.length >= MAX_ATTEMPTS) throw new Error('Verification attempt limit reached; create a new work item.'); + const started = performance.now(); + const result = checkArtifact(item); + const attempt = { + schemaVersion: 'ecc.work-item-verification.v1', + attemptId: crypto.randomUUID(), + previousAttemptId: previous.attempts.at(-1)?.attemptId || null, + kind, + taskId: item.id, + sessionId: item.sessionId, + owner: item.owner, + verifier: VERIFIER, + verifierDigest: digest(`${VERIFIER}\n${renderMarkdownTable()}`), + ...binding(item), + ...result, + durationMs: Math.round((performance.now() - started) * 1000) / 1000, + checkedAt: new Date().toISOString() + }; + return { + verified: attempt.outcome === 'success', + attempt, + item: { + ...item, + status: attempt.outcome === 'success' ? 'done' : 'blocked', + updatedAt: attempt.checkedAt, + metadata: { ...item.metadata, verification: { ...previous, attempts: [...previous.attempts, attempt] } } + } + }; +} + +function registerVerification(existing, item) { + if (existing) throw new Error('Register verification at creation of a new work item, before work begins.'); + const verification = item.metadata.verification; + if (!record(verification) || Object.keys(verification).join(',') !== 'contract' || item.owner + || !['open', 'ready', 'needs-review'].includes(statusKey(item.status))) { + throw new Error('Register a verification contract before assigning or running work; outcome history is reserved.'); + } + const contract = validateContract(verification.contract, item.repoRoot); + const repoRoot = fs.realpathSync(item.repoRoot); + if (!fs.statSync(repoRoot).isDirectory()) throw new Error('Verification repo root must be a directory.'); + return { + ...item, + repoRoot, + metadata: { ...item.metadata, verification: { contract, registeredAt: new Date().toISOString(), attempts: [] } } + }; +} + +// Called centrally by state-store upsert, covering CLI, board and runner writes. +function prepareVerifiedUpdate(existing, item) { + if (!hasVerification(existing)) return hasVerification(item) ? registerVerification(existing, item) : item; + if (!hasVerification(item) || !isDeepStrictEqual(existing.metadata.verification, item.metadata.verification)) { + throw new Error('Verification contract and attempt history are reserved and cannot be replaced or removed.'); + } + if (!isDeepStrictEqual(identity(existing), identity(item))) { + throw new Error('Contracted task identity is immutable; create a new work item.'); + } + if (RUNNING_STATUSES.has(statusKey(item.status))) requireClaim(item); + if (!SUCCESS_STATUSES.has(statusKey(item.status))) return item; + const last = item.metadata.verification.attempts.at(-1); + if (!last || last.outcome !== 'success' || last.taskDigest !== binding(item).taskDigest) { + throw new Error('Completion requires a successful verification for this task and session; run verify.'); + } + const checked = appendAttempt(item, 'completion-recheck'); + // Persist failed observations too: a previously done item must not retain a + // success-only history after its artifact regresses. Fresh semantic success + // binds any changed valid bytes to this new completion receipt. + return checked.verified ? { ...checked.item, status: item.status } : checked.item; +} + +function verifyWorkItem(item) { + if (!item) throw new Error('Work item not found.'); + if (!hasVerification(item)) throw new Error('Work item has no verification contract.'); + return appendAttempt(item); +} + +function verificationLabel(item) { + if (!hasVerification(item)) return 'unverified (no contract)'; + const last = item.metadata.verification.attempts.at(-1); + return last ? `last check ${last.outcome} at ${last.checkedAt} (${last.attemptId})` : 'unverified (contract registered)'; +} + +module.exports = { prepareVerifiedUpdate, verifyWorkItem, verificationLabel }; diff --git a/scripts/work-items.js b/scripts/work-items.js index db38c0dcb..dd4dd7ee2 100644 --- a/scripts/work-items.js +++ b/scripts/work-items.js @@ -5,9 +5,12 @@ const os = require('os'); const { spawnSync } = require('child_process'); const { createStateStore } = require('./lib/state-store'); const { claimWorkItem } = require('./lib/control-pane/work-item-mutations'); +const { verificationLabel } = require('./lib/work-item-verification'); const VALUE_FLAGS = new Set([ '--as', + '--artifact', + '--verify', '--db', '--github-repo', '--id', @@ -33,6 +36,7 @@ Usage: node scripts/work-items.js show [--db ] [--json] node scripts/work-items.js upsert [] --title [options] [--json] node scripts/work-items.js close <id> [--status done] [--db <path>] [--json] + node scripts/work-items.js verify <id> [--db <path>] [--json] node scripts/work-items.js claim [<id>] --owner <name> [--as agent|human] [--db <path>] [--json] node scripts/work-items.js sync-github --repo <owner/repo> [--db <path>] [--json] @@ -40,6 +44,8 @@ Track Linear, GitHub, handoff, and manual roadmap items in the ECC SQLite state store so "ecc status" can include linked work and blocked operator follow-up. Options: + --verify <verifier> Register harness-adapter-documentation/v1 on a NEW item + --artifact <relative.md> Artifact within --repo-root; use with --verify --id <id> Stable local work-item id for upsert --source <source> Source system, e.g. linear, github, handoff, manual --source-id <id> Source-local identifier, e.g. ECC-20 or PR number @@ -62,6 +68,8 @@ Options: function assignOption(options, flag, value) { if (flag === '--as') options.claimAs = value; + else if (flag === '--artifact') options.artifact = value; + else if (flag === '--verify') options.verifier = value; else if (flag === '--db') options.dbPath = value; else if (flag === '--github-repo') options.githubRepo = value; else if (flag === '--id') options.id = value; @@ -390,6 +398,13 @@ function buildUpsertPayload(options, existing = null) { throw new Error('Missing --title for a new work item.'); } + let metadata = options.metadataJson !== undefined ? parseMetadataJson(options.metadataJson) : ((existing && existing.metadata) ?? null); + if (options.verifier || options.artifact) { + if (!options.verifier || !options.artifact) throw new Error('--verify and --artifact must be supplied together.'); + if (metadata !== null && (typeof metadata !== 'object' || Array.isArray(metadata))) throw new Error('Verification metadata must be an object.'); + metadata = { ...metadata, verification: { contract: { verifier: options.verifier, artifact: options.artifact } } }; + } + return { id, source: options.source ?? (existing && existing.source) ?? 'manual', @@ -401,7 +416,7 @@ function buildUpsertPayload(options, existing = null) { owner: options.owner ?? (existing && existing.owner) ?? null, repoRoot: options.repoRoot ?? (existing && existing.repoRoot) ?? process.cwd(), sessionId: options.sessionId ?? (existing && existing.sessionId) ?? null, - metadata: options.metadataJson !== undefined ? parseMetadataJson(options.metadataJson) : ((existing && existing.metadata) ?? null), + metadata, createdAt: existing ? existing.createdAt : undefined, updatedAt: new Date().toISOString() }; @@ -416,6 +431,7 @@ function printWorkItem(item) { console.log(`Repo: ${item.repoRoot || '(none)'}`); console.log(`Session: ${item.sessionId || '(none)'}`); console.log(`Updated: ${item.updatedAt}`); + console.log(`Verification: ${verificationLabel(item)}`); if (item.url) { console.log(`URL: ${item.url}`); } @@ -434,6 +450,7 @@ function printWorkItemList(payload) { console.log(` ID: ${item.id}`); console.log(` Owner: ${item.owner || '(unassigned)'}`); console.log(` Updated: ${item.updatedAt}`); + console.log(` Verification: ${verificationLabel(item)}`); if (item.url) { console.log(` URL: ${item.url}`); } @@ -514,10 +531,25 @@ async function main() { return; } + if (options.command === 'verify') { + const id = resolveWorkItemId(options); + if (!id) throw new Error('Missing work item id.'); + const result = store.verifyWorkItem(id); + if (options.json) console.log(JSON.stringify(result, null, 2)); + else { + printWorkItem(result.item); + for (const reason of result.attempt.reasons) console.log(` - ${reason}`); + } + if (!result.verified) process.exitCode = 1; + return; + } + if (options.command === 'upsert') { const id = resolveWorkItemId(options); const existing = id ? store.getWorkItemById(id) : null; - const item = store.upsertWorkItem(buildUpsertPayload(options, existing)); + const payload = buildUpsertPayload(options, existing); + const item = store.upsertWorkItem(payload); + if (item.status !== payload.status) process.exitCode = 1; if (options.json) { console.log(JSON.stringify(item, null, 2)); } else { @@ -545,6 +577,7 @@ async function main() { existing ) ); + if (item.status !== (options.status || 'done')) process.exitCode = 1; if (options.json) { console.log(JSON.stringify(item, null, 2)); } else { diff --git a/skills/agent-harness-construction/SKILL.md b/skills/agent-harness-construction/SKILL.md index 6f828f922..4830684f1 100644 --- a/skills/agent-harness-construction/SKILL.md +++ b/skills/agent-harness-construction/SKILL.md @@ -66,6 +66,32 @@ Track: - pass@1 and pass@3 - cost per successful task +## Verify The Work Product + +Define a narrow completion check before the worker starts. Keep queue selection, +session hosting, action selection, and result validation separate so different +tools and models can share the same contract. + +ECC's opt-in [verified work-item flow](https://github.com/affaan-m/ECC/blob/main/docs/architecture/verified-work-item-outcomes.md) +registers a deterministic artifact check and records failed and successful +attempts. Start with the `harness-adapter-documentation/v1` validator for adapter +matrix documentation. Repair the artifact after a failed check, then verify it +again. A manual `done` status is not evidence that a validator passed. + +From an ECC checkout, set `ECC_SESSION_ID` to an existing session ID in the same +state database, then use a new work-item ID: + +```bash +node scripts/work-items.js upsert adapter-docs --title 'Check adapter matrix' \ + --repo-root "$PWD" --verify harness-adapter-documentation/v1 \ + --artifact docs/architecture/harness-adapter-compliance.md +node scripts/work-items.js claim adapter-docs --owner docs-worker --as agent --session-id "$ECC_SESSION_ID" +node scripts/work-items.js verify adapter-docs --json +``` + +Compact models can eventually choose or repair tool calls through these same +interfaces; the current flow does not train models or automate those repairs. + ## Anti-Patterns - Too many tools with overlapping semantics. diff --git a/tests/lib/work-item-verification.test.js b/tests/lib/work-item-verification.test.js new file mode 100644 index 000000000..47af4f6df --- /dev/null +++ b/tests/lib/work-item-verification.test.js @@ -0,0 +1,259 @@ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync, spawn } = require('child_process'); +const { createStateStore } = require('../../scripts/lib/state-store'); +const { claimWorkItem, moveWorkItem } = require('../../scripts/lib/control-pane/work-item-mutations'); +const { MATRIX_BLOCK_START, MATRIX_BLOCK_END, renderMarkdownTable } = require('../../scripts/lib/harness-adapter-compliance'); + +const CLI = path.resolve(__dirname, '../../scripts/work-items.js'); +const verifier = 'harness-adapter-documentation/v1'; +const validDoc = () => `${MATRIX_BLOCK_START}\n${renderMarkdownTable()}\n${MATRIX_BLOCK_END}\n`; +let passed = 0; +let failed = 0; + +async function fixture(fn) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-outcome-')); + const store = await createStateStore({ dbPath: path.join(root, 'state.db') }); + for (const id of ['session-1', 'session-2']) store.upsertSession({ id, adapterId: 'test', harness: 'test', state: 'active', snapshot: {} }); + const base = { id: 'docs-task', source: 'manual', title: 'Repair matrix', status: 'open', repoRoot: root, metadata: { verification: { contract: { verifier, artifact: 'matrix.md' } } } }; + const register = () => store.upsertWorkItem(base); + const claim = () => claimWorkItem(store, { id: base.id, owner: 'agent', assigneeKind: 'agent', sessionId: 'session-1' }); + try { await fn({ root, store, base, register, claim, artifact: path.join(root, 'matrix.md') }); } + finally { store.close(); fs.rmSync(root, { recursive: true, force: true }); } +} + +async function test(name, fn) { + try { await fixture(fn); passed++; console.log(` PASS ${name}`); } + catch (error) { failed++; console.error(` FAIL ${name}: ${error.stack}`); } +} + +async function run() { + await test('failure then repair yields bound independent outcomes and completes only on repair', ({ store, register, claim, artifact }) => { + const registered = register(); + assert.deepStrictEqual(registered.metadata.verification.attempts, []); + claim(); fs.writeFileSync(artifact, 'broken matrix'); + const failure = store.verifyWorkItem('docs-task'); + assert.strictEqual(failure.attempt.outcome, 'failure'); + assert.strictEqual(failure.item.status, 'blocked'); + assert.match(failure.attempt.reasons.join(' '), /matrix/); + fs.writeFileSync(artifact, validDoc()); + const success = store.verifyWorkItem('docs-task'); + assert.strictEqual(success.attempt.outcome, 'success'); + assert.strictEqual(success.item.status, 'done'); + assert.strictEqual(success.item.metadata.verification.attempts.length, 2); + assert.strictEqual(success.attempt.previousAttemptId, failure.attempt.attemptId); + assert.strictEqual(success.attempt.sessionId, 'session-1'); + assert.strictEqual(success.attempt.taskId, 'docs-task'); + assert.match(success.attempt.artifactDigest, /^[a-f0-9]{64}$/); + assert.match(success.attempt.contractDigest, /^[a-f0-9]{64}$/); + assert.ok(success.attempt.durationMs >= 0); + assert.notStrictEqual(success.attempt.artifactDigest, failure.attempt.artifactDigest); + assert.strictEqual(success.attempt.verifier, verifier); + }); + + await test('legacy tasks remain compatible and are visibly unverified', ({ store, root }) => { + store.upsertWorkItem({ id: 'legacy', source: 'manual', title: 'Legacy', status: 'done' }); + const result = spawnSync(process.execPath, [CLI, 'show', 'legacy', '--db', path.join(root, 'state.db')], { encoding: 'utf8' }); + assert.strictEqual(result.status, 0, result.stderr); + assert.match(result.stdout, /unverified/i); + assert.throws(() => store.verifyWorkItem('legacy'), /contract/i); + }); + + await test('terminal status, metadata replacement and contract edits cannot bypass verification', ({ store, register, claim }) => { + const original = register(); claim(); + const current = store.getWorkItemById('docs-task'); + for (const status of ['done', 'closed', 'resolved', 'merged']) assert.throws(() => store.upsertWorkItem({ ...current, status }), /verif/i); + assert.throws(() => moveWorkItem(store, { id: current.id, lane: 'done' }), /verif/i); + for (const metadata of [null, {}, { verification: null }, { verification: { ...current.metadata.verification, attempts: [{ outcome: 'success' }] } }, { verification: { ...current.metadata.verification, contract: { verifier, artifact: 'other.md' } } }]) { + assert.throws(() => store.upsertWorkItem({ ...current, metadata }), /verif|contract/i); + } + assert.strictEqual(store.getWorkItemById('docs-task').metadata.verification.registeredAt, original.metadata.verification.registeredAt); + assert.strictEqual(store.upsertWorkItem({ ...current, status: 'cancelled' }).status, 'cancelled'); + }); + + await test('registration must precede work and cannot forge outcome history', ({ store, base }) => { + for (const change of [{ status: 'running' }, { owner: 'agent' }, { status: 'done' }, { metadata: { verification: { contract: { verifier, artifact: 'matrix.md' }, attempts: [{ outcome: 'success' }] } } }]) { + assert.throws(() => store.upsertWorkItem({ ...base, ...change }), /contract|verif|register/i); + } + store.upsertWorkItem({ ...base, metadata: {}, status: 'running' }); + store.upsertWorkItem({ ...base, metadata: {}, status: 'open' }); + assert.throws(() => store.upsertWorkItem(base), /new work item|creation/i); + }); + + await test('contract validation rejects unknown verifier and escaping or invalid paths', ({ store, base }) => { + for (const contract of [null, {}, { verifier: 'shell', artifact: 'matrix.md' }, { verifier, artifact: '../matrix.md' }, { verifier, artifact: '/tmp/matrix.md' }, { verifier, artifact: 'a/../../matrix.md' }, { verifier, artifact: 'a\\..\\matrix.md' }, { verifier, artifact: 'bad\0.md' }, { verifier, artifact: 'matrix.txt' }, { verifier, artifact: 'matrix.md', command: 'touch file' }]) { + assert.throws(() => store.upsertWorkItem({ ...base, metadata: { verification: { contract } } }), /contract|verif|artifact/i); + } + assert.throws(() => store.upsertWorkItem({ ...base, repoRoot: 'relative' }), /root|absolute/i); + }); + + await test('missing artifact is unknown and claimed session is required', ({ store, register, claim }) => { + register(); + assert.throws(() => store.verifyWorkItem('docs-task'), /owner|claim|session/i); + assert.throws(() => claimWorkItem(store, { id: 'docs-task', owner: 'agent' }), /session/i); + claim(); + const result = store.verifyWorkItem('docs-task'); + assert.strictEqual(result.attempt.outcome, 'unknown'); + assert.strictEqual(result.item.status, 'blocked'); + assert.strictEqual(result.attempt.artifactDigest, null); + assert.throws(() => store.verifyWorkItem('missing'), /not found/i); + }); + + await test('old success cannot complete after artifact, session, owner or identity changes', ({ store, register, claim, artifact }) => { + register(); claim(); fs.writeFileSync(artifact, validDoc()); + let success = store.verifyWorkItem('docs-task'); + fs.writeFileSync(artifact, 'changed'); + const rejected = store.upsertWorkItem({ ...success.item, status: 'done' }); + assert.strictEqual(rejected.status, 'blocked'); + assert.strictEqual(rejected.metadata.verification.attempts.at(-1).outcome, 'failure'); + assert.strictEqual(store.getWorkItemById('docs-task').status, 'blocked'); + assert.throws(() => moveWorkItem(store, { id: 'docs-task', lane: 'done' }), /verif|artifact/i); + fs.writeFileSync(artifact, validDoc()); + success = store.verifyWorkItem('docs-task'); + for (const patch of [{ sessionId: 'session-2' }, { owner: 'other' }, { title: 'Different objective' }, { source: 'different' }, { sourceId: 'different' }]) { + assert.throws(() => store.upsertWorkItem({ ...success.item, ...patch }), /verif|identity|new work item/i); + } + const reopened = store.upsertWorkItem({ ...success.item, sessionId: 'session-2', status: 'running' }); + assert.throws(() => store.upsertWorkItem({ ...reopened, status: 'done' }), /verif/i); + const repeated = store.verifyWorkItem('docs-task'); + assert.strictEqual(repeated.attempt.sessionId, 'session-2'); + assert.strictEqual(repeated.item.metadata.verification.attempts.length, 4); + }); + + await test('duplicate verification creates distinct ordered attempts with identical artifact binding', ({ store, register, claim, artifact }) => { + register(); claim(); fs.writeFileSync(artifact, validDoc()); + const first = store.verifyWorkItem('docs-task'); + const second = store.verifyWorkItem('docs-task'); + assert.notStrictEqual(first.attempt.attemptId, second.attempt.attemptId); + assert.strictEqual(second.attempt.previousAttemptId, first.attempt.attemptId); + assert.strictEqual(first.attempt.artifactDigest, second.attempt.artifactDigest); + assert.strictEqual(second.item.metadata.verification.attempts.length, 2); + }); + + await test('symlink artifacts, directories and oversized files fail closed', ({ root, store, register, claim, artifact }) => { + register(); claim(); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-outside-')); + try { + fs.writeFileSync(path.join(outside, 'matrix.md'), validDoc()); + fs.symlinkSync(path.join(outside, 'matrix.md'), artifact); + assert.strictEqual(store.verifyWorkItem('docs-task').attempt.outcome, 'unknown'); + fs.unlinkSync(artifact); fs.mkdirSync(artifact); + assert.strictEqual(store.verifyWorkItem('docs-task').attempt.outcome, 'unknown'); + fs.rmdirSync(artifact); fs.writeFileSync(artifact, Buffer.alloc(1024 * 1024 + 1)); + assert.strictEqual(store.verifyWorkItem('docs-task').attempt.outcome, 'unknown'); + const nested = { id: 'nested', source: 'manual', title: 'nested', status: 'open', repoRoot: root, metadata: { verification: { contract: { verifier, artifact: 'linked/matrix.md' } } } }; + fs.symlinkSync(outside, path.join(root, 'linked')); + store.upsertWorkItem(nested); claimWorkItem(store, { id: 'nested', owner: 'agent', sessionId: 'session-1' }); + assert.strictEqual(store.verifyWorkItem('nested').attempt.outcome, 'unknown'); + } finally { fs.rmSync(outside, { recursive: true, force: true }); } + }); + + await test('CLI register claim verify show repair close form an end-to-end flow', ({ root, artifact }) => { + function cli(args) { return spawnSync(process.execPath, [CLI, ...args, '--db', path.join(root, 'state.db'), '--json'], { encoding: 'utf8' }); } + const registration = cli(['upsert', 'cli-task', '--title', 'Repair actual matrix', '--repo-root', root, '--verify', verifier, '--artifact', 'matrix.md']); + assert.strictEqual(registration.status, 0, registration.stderr); + const claimed = cli(['claim', 'cli-task', '--owner', 'codex', '--session-id', 'session-1']); + assert.strictEqual(claimed.status, 0, claimed.stderr); + const failedClose = cli(['close', 'cli-task']); + assert.notStrictEqual(failedClose.status, 0); + fs.writeFileSync(artifact, 'wrong'); + const failure = cli(['verify', 'cli-task']); + assert.strictEqual(failure.status, 1); + assert.strictEqual(JSON.parse(failure.stdout).attempt.outcome, 'failure'); + fs.writeFileSync(artifact, validDoc()); + const success = cli(['verify', 'cli-task']); + assert.strictEqual(success.status, 0, success.stderr); + assert.strictEqual(JSON.parse(success.stdout).item.status, 'done'); + const shown = cli(['show', 'cli-task']); + assert.strictEqual(JSON.parse(shown.stdout).metadata.verification.attempts.length, 2); + assert.strictEqual(cli(['close', 'cli-task']).status, 0); + fs.writeFileSync(artifact, 'regression'); + assert.notStrictEqual(cli(['close', 'cli-task']).status, 0); + const regressed = JSON.parse(cli(['show', 'cli-task']).stdout); + assert.strictEqual(regressed.status, 'blocked'); + assert.strictEqual(regressed.metadata.verification.attempts.at(-1).outcome, 'failure'); + }); + + await test('board preserves a failed completion check and reports that done was refused', ({ store, register, claim, artifact }) => { + register(); claim(); fs.writeFileSync(artifact, validDoc()); store.verifyWorkItem('docs-task'); + fs.writeFileSync(artifact, 'regression'); + const result = moveWorkItem(store, { id: 'docs-task', lane: 'done' }); + assert.strictEqual(result.moved, false); + assert.strictEqual(result.reason, 'verification-failed'); + assert.strictEqual(result.item.status, 'blocked'); + assert.strictEqual(result.item.metadata.verification.attempts.length, 2); + }); + + await test('completion rechecks changed valid bytes and records their new digest', ({ store, register, claim, artifact }) => { + register(); claim(); fs.writeFileSync(artifact, validDoc()); + const success = store.verifyWorkItem('docs-task'); + fs.writeFileSync(artifact, `# Updated introduction\n${validDoc()}`); + const updated = store.upsertWorkItem({ ...success.item, status: 'done' }); + assert.strictEqual(updated.status, 'done'); + assert.notStrictEqual(updated.metadata.verification.attempts.at(-1).artifactDigest, success.attempt.artifactDigest); + assert.strictEqual(updated.metadata.verification.attempts.at(-1).kind, 'completion-recheck'); + }); + + await test('concurrent verifications preserve both ordered attempts', async ({ root, store, register, claim, artifact }) => { + register(); claim(); fs.writeFileSync(artifact, validDoc()); + const results = await Promise.all([1, 2].map(() => new Promise((resolve, reject) => { + const child = spawn(process.execPath, [CLI, 'verify', 'docs-task', '--db', path.join(root, 'state.db'), '--json']); + let stdout = ''; let stderr = ''; + child.stdout.on('data', chunk => { stdout += chunk; }); + child.stderr.on('data', chunk => { stderr += chunk; }); + child.on('error', reject); + child.on('close', code => resolve({ code, stdout, stderr })); + }))); + for (const result of results) assert.strictEqual(result.code, 0, result.stderr); + const attempts = store.getWorkItemById('docs-task').metadata.verification.attempts; + assert.strictEqual(attempts.length, 2); + assert.strictEqual(attempts[1].previousAttemptId, attempts[0].attemptId); + }); + + await test('cancelled work stays cancelled until explicitly reopened and legacy verification cannot be forged', ({ store, register, claim, artifact }) => { + const registered = register(); + const cancelled = store.upsertWorkItem({ ...registered, status: 'cancelled' }); + assert.throws(() => store.verifyWorkItem('docs-task'), /claim|session/i); + assert.strictEqual(store.getWorkItemById('docs-task').status, 'cancelled'); + store.upsertWorkItem({ ...cancelled, status: 'open' }); claim(); + fs.writeFileSync(artifact, validDoc()); + assert.strictEqual(store.verifyWorkItem('docs-task').verified, true); + }); + + await test('FIFO artifacts and regular files replaced by FIFOs never block verification', ({ root, store, register, claim, artifact }) => { + if (process.platform === 'win32') return; + register(); claim(); + const makeFifo = () => { + const result = spawnSync('mkfifo', [artifact], { encoding: 'utf8' }); + assert.strictEqual(result.status, 0, result.stderr); + }; + makeFifo(); + assert.strictEqual(store.verifyWorkItem('docs-task').attempt.outcome, 'unknown'); + fs.unlinkSync(artifact); fs.writeFileSync(artifact, validDoc()); + const canonicalArtifact = path.join(fs.realpathSync(root), 'matrix.md'); + const open = fs.openSync; + fs.openSync = function (filename, ...args) { + if (filename === canonicalArtifact) { fs.unlinkSync(artifact); makeFifo(); } + return open.call(fs, filename, ...args); + }; + try { assert.strictEqual(store.verifyWorkItem('docs-task').attempt.outcome, 'unknown'); } + finally { fs.openSync = open; } + }); + + await test('the validator comes from ECC, never a module supplied by the artifact repository', ({ root, store, register, claim, artifact }) => { + fs.mkdirSync(path.join(root, 'scripts/lib'), { recursive: true }); + fs.writeFileSync(path.join(root, 'scripts/lib/harness-adapter-compliance.js'), 'throw new Error("must never execute");'); + register(); claim(); fs.writeFileSync(artifact, 'invalid matrix'); + assert.strictEqual(store.verifyWorkItem('docs-task').attempt.outcome, 'failure'); + fs.writeFileSync(artifact, validDoc()); + assert.strictEqual(store.verifyWorkItem('docs-task').attempt.outcome, 'success'); + }); + + console.log(`\nPassed: ${passed}, Failed: ${failed}`); + if (failed) process.exitCode = 1; +} +run(); diff --git a/tests/scripts/control-pane.test.js b/tests/scripts/control-pane.test.js index 8f90d9a44..b1018e55a 100644 --- a/tests/scripts/control-pane.test.js +++ b/tests/scripts/control-pane.test.js @@ -728,6 +728,50 @@ async function runTests() { passed++; else failed++; + if ( + await test('board reports a failed verification move and persists the blocked receipt', async () => { + const { createStateStore } = require('../../scripts/lib/state-store'); + const { MATRIX_BLOCK_START, MATRIX_BLOCK_END, renderMarkdownTable } = require('../../scripts/lib/harness-adapter-compliance'); + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-board-verification-')); + const stateDbPath = path.join(tempDir, 'state.db'); + const artifact = path.join(tempDir, 'matrix.md'); + let app; + try { + const store = await createStateStore({ dbPath: stateDbPath }); + try { + store.upsertSession({ id: 'docs-session', adapterId: 'test', harness: 'test', state: 'active', snapshot: {} }); + const item = store.upsertWorkItem({ id: 'verified', source: 'manual', title: 'Matrix', status: 'open', repoRoot: tempDir, + metadata: { verification: { contract: { verifier: 'harness-adapter-documentation/v1', artifact: 'matrix.md' } } } }); + store.upsertWorkItem({ ...item, owner: 'agent', sessionId: 'docs-session', status: 'running' }); + fs.writeFileSync(artifact, `${MATRIX_BLOCK_START}\n${renderMarkdownTable()}\n${MATRIX_BLOCK_END}`); + store.verifyWorkItem('verified'); + } finally { store.close(); } + fs.writeFileSync(artifact, 'regression'); + app = await createControlPaneServer({ host: '127.0.0.1', port: 0, stateDbPath, repoRoot: REPO_ROOT, allowActions: true }); + await app.listen(); + const response = await fetchLocal(`${app.url}/api/work-items/verified/move`, { + method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ lane: 'done' }) + }); + assert.strictEqual(response.status, 409); + const result = await response.json(); + assert.strictEqual(result.ok, false); + assert.strictEqual(result.moved, false); + assert.match(result.error, /verification/i); + assert.strictEqual(result.item.status, 'blocked'); + const reopened = await createStateStore({ dbPath: stateDbPath }); + try { + const persisted = reopened.getWorkItemById('verified'); + assert.strictEqual(persisted.status, 'blocked'); + assert.strictEqual(persisted.metadata.verification.attempts.at(-1).outcome, 'failure'); + } finally { reopened.close(); } + } finally { + if (app) await app.close(); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }) + ) passed++; + else failed++; + console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); process.exit(failed > 0 ? 1 : 0); }