返回 CodeWhale
quality-gates.js
根目录 / crates / plugins / assets / agent-teams / lib / quality-gates.js
1 /**
2 * Pure quality-gate rules: contracts, path audit, completion, follow-up,
3 * coverage, and resume. Tools and persistence call these; they do not I/O.
4 * @module dsh-agent-teams/quality-gates
5 */
6 import { FINDING_SEVERITIES, REVIEW_VERDICTS, TASK_KINDS, TERMINAL_TASK_STATUSES, } from "./types.js";
7 const QUALITY_KINDS = [
8 'requirements',
9 'implementation',
10 'verification',
11 'review',
12 'repair',
13 'integration',
14 ];
15 const WRITE_KINDS = ['implementation', 'repair'];
16 const OPEN_STATUSES = ['pending', 'claimed', 'in_progress'];
17 const DEFAULT_REVIEW_POLICY = {
18 requirementsMinRounds: 1,
19 requirementsMaxRounds: 4,
20 codeMaxRounds: 3,
21 maxRepairAttempts: 2,
22 };
23 export const DEFAULT_REVIEW_ACCEPTANCE = [
24 'The latest implementation meets the user goal',
25 'No unresolved blocker or high findings',
26 ];
27 export const DEFAULT_REVIEW_OBJECTIVE = 'Review whether the latest implementation satisfies the user goal';
28 const GATE_TEST_CONTRACT = /needs[_ ]revision|拒绝路径|verdict\s*=\s*needs_revision|cannot complete|不能完成|触发拒绝/iu;
29 export function taskKindOf(task) {
30 return task?.kind ?? 'work';
31 }
32 export function isQualityKind(kind) {
33 return kind !== undefined && kind !== 'work' && QUALITY_KINDS.includes(kind);
34 }
35 export function resolveReviewPolicy(policy) {
36 return {
37 ...DEFAULT_REVIEW_POLICY,
38 ...policy,
39 requirementsMinRounds: policy?.requirementsMinRounds ?? DEFAULT_REVIEW_POLICY.requirementsMinRounds,
40 requirementsMaxRounds: policy?.requirementsMaxRounds ?? DEFAULT_REVIEW_POLICY.requirementsMaxRounds,
41 codeMaxRounds: policy?.codeMaxRounds ?? DEFAULT_REVIEW_POLICY.codeMaxRounds,
42 maxRepairAttempts: policy?.maxRepairAttempts ?? DEFAULT_REVIEW_POLICY.maxRepairAttempts,
43 };
44 }
45 export function isReviewPolicy(value) {
46 if (value === undefined)
47 return true;
48 if (!isRecord(value))
49 return false;
50 const numbers = ['requirementsMinRounds', 'requirementsMaxRounds', 'codeMaxRounds', 'maxRepairAttempts'];
51 for (const key of numbers) {
52 const item = value[key];
53 if (item === undefined)
54 continue;
55 if (!Number.isSafeInteger(item) || item < 1)
56 return false;
57 }
58 const min = value['requirementsMinRounds'] ?? DEFAULT_REVIEW_POLICY.requirementsMinRounds;
59 const max = value['requirementsMaxRounds'] ?? DEFAULT_REVIEW_POLICY.requirementsMaxRounds;
60 if (min > max)
61 return false;
62 if (value['requiredReviewers'] !== undefined) {
63 if (!Array.isArray(value['requiredReviewers']))
64 return false;
65 if (!value['requiredReviewers'].every((item) => typeof item === 'string' && item.trim() !== ''))
66 return false;
67 }
68 const allowed = new Set([...numbers, 'requiredReviewers']);
69 return Object.keys(value).every((key) => allowed.has(key));
70 }
71 /** Normalize a workspace-relative POSIX path. `undefined` means illegal. */
72 export function normalizeWorkspacePath(path) {
73 if (typeof path !== 'string')
74 return undefined;
75 const trimmed = path.trim();
76 if (trimmed === '')
77 return undefined;
78 if (trimmed.startsWith('~') || /^[A-Za-z]:/.test(trimmed))
79 return undefined;
80 const posix = trimmed.replaceAll('\\', '/');
81 if (posix.startsWith('/'))
82 return undefined;
83 const parts = [];
84 for (const part of posix.split('/')) {
85 if (part === '' || part === '.')
86 continue;
87 if (part === '..')
88 return undefined;
89 parts.push(part);
90 }
91 return parts.join('/');
92 }
93 export function pathMatchesScope(path, pattern) {
94 const normalizedPath = normalizeWorkspacePath(path);
95 if (normalizedPath === undefined)
96 return false;
97 const rawPattern = pattern.trim().replaceAll('\\', '/');
98 if (rawPattern.startsWith('~') || rawPattern.startsWith('/') || /^[A-Za-z]:/.test(rawPattern))
99 return false;
100 const directory = rawPattern.endsWith('/');
101 const normalizedPattern = normalizeWorkspacePath(rawPattern);
102 if (normalizedPattern === undefined) {
103 if (directory && (rawPattern === './' || rawPattern === '/' || rawPattern === '.'))
104 return true;
105 return false;
106 }
107 if (directory || rawPattern === './' || rawPattern === '.') {
108 if (normalizedPattern === '')
109 return true;
110 return normalizedPath === normalizedPattern || normalizedPath.startsWith(`${normalizedPattern}/`);
111 }
112 return normalizedPath === normalizedPattern;
113 }
114 /**
115 * Paths no quality contract may claim: version control, harness/plugin state,
116 * secrets and private keys. Exported because the completion gate and contract
117 * generation (including the artifact reader that must not walk into
118 * `.agent-teams/`, `secrets/` or `.env*`) have to share exactly one predicate.
119 */
120 export function isDefaultExcludedPath(path) {
121 const normalized = normalizeWorkspacePath(path);
122 if (normalized === undefined)
123 return false;
124 const segments = normalized.split('/');
125 const base = segments[segments.length - 1] ?? '';
126 if (segments[0] === '.git' || segments[0] === '.dsh' || segments[0] === '.agent-teams')
127 return true;
128 if (base === '.env' || base.startsWith('.env.'))
129 return true;
130 if (segments.includes('secrets'))
131 return true;
132 if (base.startsWith('id_rsa'))
133 return true;
134 return false;
135 }
136 function isDefaultExcluded(path) {
137 return isDefaultExcludedPath(path);
138 }
139 export function classifyChangedPath(path, inScope = [], outOfScope = []) {
140 if (normalizeWorkspacePath(path) === undefined)
141 return 'illegal';
142 if (isDefaultExcluded(path))
143 return 'out_of_scope';
144 if (outOfScope.some((pattern) => pathMatchesScope(path, pattern)))
145 return 'out_of_scope';
146 if (inScope.some((pattern) => pathMatchesScope(path, pattern)))
147 return 'in_scope';
148 return 'undeclared';
149 }
150 export function collectChangedPaths(gitStatusText) {
151 const paths = [];
152 const seen = new Set();
153 for (const rawLine of gitStatusText.split(/\r?\n/u)) {
154 const line = rawLine.trimEnd();
155 if (line.trim() === '')
156 continue;
157 let candidate = line;
158 const rename = /->\s+(\S+)$/u.exec(line);
159 if (/^[ MADRCU?!]{1,2}\s+/u.test(line)) {
160 candidate = rename?.[1] ?? line.replace(/^[ MADRCU?!]{1,2}\s+/u, '');
161 }
162 const cleaned = candidate.replace(/^"|"$/gu, '').trim();
163 const normalized = normalizeWorkspacePath(cleaned);
164 if (normalized === undefined || seen.has(normalized))
165 continue;
166 seen.add(normalized);
167 paths.push(normalized);
168 }
169 return paths;
170 }
171 export function inScopeOverlap(left, right) {
172 if (left === undefined || right === undefined)
173 return [];
174 const hits = [];
175 for (const a of left) {
176 for (const b of right) {
177 if (pathMatchesScope(a, b) || pathMatchesScope(b, a) || a === b) {
178 if (!hits.includes(a))
179 hits.push(a);
180 }
181 }
182 }
183 return hits;
184 }
185 function nonemptyString(value) {
186 return typeof value === 'string' && value.trim() !== '';
187 }
188 function nonemptyStringList(value) {
189 return Array.isArray(value) && value.length > 0 && value.every(nonemptyString);
190 }
191 function dependencyClosureContains(tasks, dependencies, targetId) {
192 const byId = new Map(tasks.map((task) => [task.id, task]));
193 const pending = [...dependencies];
194 const visited = new Set();
195 while (pending.length > 0) {
196 const id = pending.pop();
197 if (id === undefined || visited.has(id))
198 continue;
199 if (id === targetId)
200 return true;
201 visited.add(id);
202 pending.push(...(byId.get(id)?.dependencies ?? []));
203 }
204 return false;
205 }
206 export function validateCreateTask(team, input) {
207 const kind = input.kind ?? 'work';
208 if (!TASK_KINDS.includes(kind)) {
209 return { ok: false, error: `unknown task kind "${String(kind)}"` };
210 }
211 if (team.halted === true) {
212 const reason = input.resumeReason?.trim() ?? '';
213 if (input.resume !== true || reason === '') {
214 return { ok: false, error: 'team is halted; resume with a non-empty reason before create_task' };
215 }
216 }
217 if (isQualityKind(kind)) {
218 if (!nonemptyString(input.objective)) {
219 return { ok: false, error: `${kind} tasks require a non-empty objective` };
220 }
221 if (!nonemptyStringList(input.acceptance)) {
222 return { ok: false, error: `${kind} tasks require at least one acceptance criterion` };
223 }
224 }
225 if (WRITE_KINDS.includes(kind)) {
226 if (!nonemptyStringList(input.inScope)) {
227 return { ok: false, error: `${kind} tasks require a non-empty inScope` };
228 }
229 if (!nonemptyStringList(input.verify)) {
230 return { ok: false, error: `${kind} tasks require a non-empty verify list` };
231 }
232 }
233 if (kind === 'review') {
234 if (!nonemptyString(input.reviewedTaskId)) {
235 return { ok: false, error: 'review tasks require reviewedTaskId' };
236 }
237 if (!team.tasks.some((item) => item.id === input.reviewedTaskId)) {
238 return { ok: false, error: `reviewed task "${input.reviewedTaskId}" does not exist` };
239 }
240 }
241 if (kind === 'repair') {
242 if (!nonemptyString(input.sourceTaskId) || !nonemptyStringList(input.sourceFindingIds)) {
243 return { ok: false, error: 'repair tasks require sourceTaskId and at least one sourceFindingId' };
244 }
245 if (!team.tasks.some((item) => item.id === input.sourceTaskId)) {
246 return { ok: false, error: `source task "${input.sourceTaskId}" does not exist` };
247 }
248 const duplicate = team.tasks.find(item => taskKindOf(item) === 'repair'
249 && OPEN_STATUSES.includes(item.status) && item.sourceTaskId === input.sourceTaskId
250 && findingKey(item.sourceFindingIds ?? []) === findingKey(input.sourceFindingIds ?? []));
251 if (duplicate !== undefined)
252 return { ok: false, error: `repair task ${duplicate.id} already covers these findings; use that task instead of creating duplicate work` };
253 }
254 const dependencies = input.dependencies ?? [];
255 for (const dependency of dependencies) {
256 const upstream = team.tasks.find((item) => item.id === dependency);
257 if (upstream === undefined) {
258 return { ok: false, error: `dependency "${dependency}" does not exist` };
259 }
260 if ((kind === 'repair' || kind === 'review') && (upstream.status === 'failed' || upstream.status === 'cancelled')) {
261 return { ok: false, error: `${kind} must not depend on ${upstream.status} task "${dependency}"` };
262 }
263 }
264 if (WRITE_KINDS.includes(kind) && nonemptyStringList(input.inScope)) {
265 for (const other of team.tasks) {
266 if (!WRITE_KINDS.includes(taskKindOf(other)))
267 continue;
268 if (!OPEN_STATUSES.includes(other.status))
269 continue;
270 if (dependencies.includes(other.id) || other.dependencies.includes('pending-new'))
271 continue;
272 if (dependencies.includes(other.id))
273 continue;
274 const overlap = inScopeOverlap(input.inScope, other.inScope);
275 if (overlap.length > 0) {
276 return {
277 ok: false,
278 error: `inScope overlaps ${other.id} at ${overlap.join(', ')}; serialize these tasks or split the paths`,
279 };
280 }
281 }
282 }
283 if (kind === 'implementation') {
284 const requirements = team.tasks.filter((item) => taskKindOf(item) === 'requirements');
285 const passed = requirements.some((item) => item.status === 'completed' && item.verdict === 'pass');
286 const behindRequirements = requirements.some((item) => (dependencyClosureContains(team.tasks, dependencies, item.id)));
287 // Planning an implementation is safe in either approval mode when its
288 // dependency chain fences execution behind requirements. Scheduling and
289 // claiming still wait for successful dependency completion.
290 if (requirements.length > 0 && !passed && !behindRequirements) {
291 return {
292 ok: false,
293 error: 'implementation must depend on a requirements task until requirements completes with verdict=pass',
294 };
295 }
296 }
297 const nextTeam = team.halted === true && input.resume === true
298 ? { ...team, halted: false, haltedAt: undefined }
299 : team;
300 return {
301 ok: true,
302 kind,
303 team: nextTeam,
304 task: {
305 subject: input.subject,
306 kind,
307 ...input.description === undefined ? {} : { description: input.description },
308 ...input.assignee === undefined ? {} : { assignee: input.assignee },
309 dependencies,
310 ...input.round === undefined ? {} : { round: input.round },
311 ...input.objective === undefined ? {} : { objective: input.objective },
312 ...input.inScope === undefined ? {} : { inScope: input.inScope },
313 ...input.outOfScope === undefined ? {} : { outOfScope: input.outOfScope },
314 ...input.acceptance === undefined ? {} : { acceptance: input.acceptance },
315 ...input.verify === undefined ? {} : { verify: input.verify },
316 ...input.deliverables === undefined ? {} : { deliverables: input.deliverables },
317 ...input.nonGoals === undefined ? {} : { nonGoals: input.nonGoals },
318 ...input.reviewedTaskId === undefined ? {} : { reviewedTaskId: input.reviewedTaskId },
319 ...input.sourceTaskId === undefined ? {} : { sourceTaskId: input.sourceTaskId },
320 ...input.sourceFindingIds === undefined ? {} : { sourceFindingIds: input.sourceFindingIds },
321 ...input.coverageOf === undefined ? {} : { coverageOf: input.coverageOf },
322 },
323 };
324 }
325 const STATUS_TRANSITIONS = {
326 pending: ['claimed', 'cancelled'],
327 claimed: ['in_progress', 'failed', 'cancelled'],
328 in_progress: ['completed', 'failed', 'cancelled'],
329 completed: [],
330 failed: [],
331 cancelled: [],
332 };
333 function openHighFindings(findings) {
334 return (findings ?? []).filter((finding) => (finding.resolved !== true && (finding.severity === 'high' || finding.severity === 'blocker')));
335 }
336 function acceptanceCovered(required, results) {
337 if (results === undefined)
338 return false;
339 const byCriterion = new Map(results.map((item) => [item.criterion, item]));
340 if ((required ?? []).every((criterion) => byCriterion.get(criterion)?.status === 'passed'))
341 return true;
342 // Structured result arrays naturally preserve the contract order. Accept a
343 // same-length all-pass report even when a model paraphrases punctuation or
344 // whitespace in `criterion`; verification evidence remains independently
345 // required below. This avoids turning display text into an opaque id.
346 return results.length === (required ?? []).length && results.every((item) => item.status === 'passed');
347 }
348 function verifyCovered(required, results) {
349 if (results === undefined)
350 return false;
351 const byCommand = new Map(results.map((item) => [item.command, item]));
352 if ((required ?? []).every((command) => byCommand.get(command)?.status === 'passed'))
353 return true;
354 return results.length === (required ?? []).length && results.every((item) => item.status === 'passed');
355 }
356 export function evaluateQualityCompletion(task, update) {
357 const nextStatus = update.status;
358 if (nextStatus !== undefined && nextStatus !== task.status) {
359 if (!STATUS_TRANSITIONS[task.status].includes(nextStatus)) {
360 return { ok: false, error: `task status cannot move from "${task.status}" to "${nextStatus}"` };
361 }
362 }
363 const kind = taskKindOf(task);
364 if (kind === 'work')
365 return { ok: true };
366 const verdict = update.verdict ?? task.verdict;
367 const findings = update.findings ?? task.findings;
368 if (kind === 'review' || kind === 'requirements') {
369 if (nextStatus === 'completed') {
370 if (verdict === undefined)
371 return { ok: false, error: `${kind} cannot complete without verdict=pass` };
372 if (verdict !== 'pass')
373 return { ok: false, error: `${kind} with verdict=${verdict} cannot complete` };
374 if (openHighFindings(findings).length > 0) {
375 return { ok: false, error: `${kind} pass cannot leave unresolved high/blocker findings` };
376 }
377 }
378 if (nextStatus === 'failed' && (verdict === 'needs_revision' || verdict === 'reject')) {
379 if ((findings ?? []).length < 1) {
380 return { ok: false, error: `${kind} ${verdict} requires at least one finding` };
381 }
382 }
383 return { ok: true };
384 }
385 if (kind === 'implementation' || kind === 'repair' || kind === 'verification' || kind === 'integration') {
386 const commands = update.commandsRun ?? task.commandsRun;
387 if (commands?.some((item) => item.status === 'failed') === true) {
388 if (nextStatus === 'completed') {
389 return { ok: false, error: 'verify failure must fail the task', requiredStatus: 'failed' };
390 }
391 }
392 if (nextStatus !== 'completed')
393 return { ok: true };
394 const acceptanceResults = update.acceptanceResults ?? task.acceptanceResults;
395 if (acceptanceResults === undefined || !acceptanceCovered(task.acceptance, acceptanceResults)) {
396 return { ok: false, error: `${kind} completion requires passed acceptanceResults for every acceptance item` };
397 }
398 if (commands === undefined || !verifyCovered(task.verify, commands)) {
399 return { ok: false, error: `${kind} completion requires a passed commandsRun entry for every verify command` };
400 }
401 if (kind === 'implementation' || kind === 'repair') {
402 const changed = update.changedPaths ?? task.changedPaths;
403 if (changed === undefined) {
404 return { ok: false, error: `${kind} completion requires changedPaths` };
405 }
406 for (const path of changed) {
407 const classification = classifyChangedPath(path, task.inScope ?? [], task.outOfScope ?? []);
408 if (classification !== 'in_scope') {
409 return { ok: false, error: `${kind} cannot complete: ${path} is ${classification}` };
410 }
411 }
412 }
413 }
414 return { ok: true };
415 }
416 function unresolvedFindings(task) {
417 return (task.findings ?? []).filter((finding) => finding.resolved !== true);
418 }
419 function findingKey(ids) {
420 return [...ids].sort().join(',');
421 }
422 /**
423 * Path-like tokens worth considering as repair-scope candidates. Two shapes:
424 * slash paths (`src/parser.ts`, `docs/guide.md`) and bare filenames with a
425 * known code/doc extension (`README.md`, `wc.js`). An optional `:line`
426 * suffix is tolerated and stripped. The extension allowlist keeps version
427 * tokens (`v0.1.17`), hex hashes, and prose out of the derived scope.
428 */
429 const REPAIR_SCOPE_PATH_PATTERN = /(?:[A-Za-z0-9_.\-]+(?:\/[A-Za-z0-9_.\-]+)+|[\w.\-]+\.(?:tsx?|jsx?|mjs|cjs|json|md|txt|ya?ml|py|rs|go|java|html?|css|scss|sh|ps1|toml|xml|sql))(?::\d+)?/gu;
430 const REPAIR_SCOPE_LINE_SUFFIX = /:\d+$/;
431 /**
432 * Derive the repair round's inScope from the findings that caused it.
433 *
434 * `finding.file` records where the problem was OBSERVED, but the fix often
435 * targets a different file named in `requiredFix` (docs vs sample data,
436 * config vs code). Deriving the scope from both keeps the auto-generated
437 * repair contract satisfiable; deriving from `file` alone can produce a
438 * contract where the acceptance ("edit README.md") names a path the scope
439 * forbids, so no honest completion exists and the repair dead-locks.
440 *
441 * Absolute and otherwise illegal paths are dropped (they can never match
442 * workspace-relative scope patterns anyway), and so are paths the completion
443 * gate refuses by default (`secrets/` segments, `.env*`, `.git`, `.dsh`,
444 * `id_rsa*` — issue #183). `classifyChangedPath` checks that default-exclusion
445 * set BEFORE inScope, so collecting such a path here would generate a contract
446 * that demands an edit the gate calls `out_of_scope`: no honest completion
447 * exists and the repair burns its rounds. Contract generation and the
448 * completion gate must agree; the exemption channel stays the user-configured
449 * outOfScope list, never a reviewer's finding.
450 *
451 * When nothing legal remains, the source task's own inScope is kept as the
452 * fallback. Over-inclusion is accepted otherwise: inScope is an audit upper
453 * bound, and the requiredFix text still tells the implementer what to touch.
454 * Keep every remaining derived path until the generator resolves inherited
455 * exclusions; filtering those first would silently discard a required fix
456 * target.
457 */
458 export function repairScopeFromFindings(findings, fallback) {
459 const derived = [];
460 for (const finding of findings) {
461 for (const path of findingDerivedPaths(finding)) {
462 if (isDefaultExcludedPath(path) || derived.includes(path))
463 continue;
464 derived.push(path);
465 }
466 }
467 return derived.length > 0 ? derived : fallback === undefined ? undefined : [...new Set(fallback)];
468 }
469 /**
470 * Every workspace-relative path one finding names, before any exclusion rule:
471 * the observed file plus the fix targets referenced by `requiredFix`.
472 */
473 export function findingDerivedPaths(finding) {
474 const paths = [];
475 const push = (raw) => {
476 const normalized = normalizeWorkspacePath(raw.replace(REPAIR_SCOPE_LINE_SUFFIX, ''));
477 if (normalized === undefined || paths.includes(normalized))
478 return;
479 paths.push(normalized);
480 };
481 if (nonemptyString(finding.file))
482 push(finding.file);
483 for (const match of finding.requiredFix.matchAll(REPAIR_SCOPE_PATH_PATTERN))
484 push(match[0]);
485 return paths;
486 }
487 /**
488 * Findings whose every cited path is default-excluded. They cannot become an
489 * honest repair contract (see {@link repairScopeFromFindings}), so they are
490 * surfaced to the captain instead of silently disappearing or dead-locking a
491 * member. A finding that names no path at all is NOT excluded: it simply falls
492 * back to the judged task's own scope, exactly as before.
493 */
494 export function excludedFindingsOf(findings, pathExists) {
495 return findings.filter((finding) => {
496 const paths = findingDerivedPaths(finding);
497 if (paths.length === 0)
498 return false;
499 const own = normalizeWorkspacePath(finding.file ?? '');
500 return paths.every((path) => {
501 if (isDefaultExcludedPath(path))
502 return true;
503 // A path extracted from prose that does not exist is not something the
504 // workspace can act on (real run: "console/stream write" became a
505 // repair scope while the finding's actual target was excluded). The
506 // finding's own `file` always counts, so "create this new file" stays
507 // actionable.
508 if (pathExists === undefined || path === own)
509 return false;
510 return !pathExists(path);
511 });
512 });
513 }
514 const AMENDABLE_CONTRACT_FIELDS = ['objective', 'acceptance', 'verify', 'inScope', 'outOfScope'];
515 /**
516 * Controlled contract amendment (the pure rule; tooling keeps it
517 * captain-only). When a quality contract is wrong — a verify command that
518 * cannot pass, an inScope that forbids the file the objective names — the
519 * worker has no honest completion and either dead-locks or games the gate.
520 * Instead the captain may fix the contract mid-flight: every amendment is
521 * recorded on the task as a {@link TaskRevision} (previous values + reason),
522 * and once a review/requirements task has passed judgment on this task the
523 * contract is frozen. Amendments replace whole fields (lists are full
524 * replacements, not deltas); the implementer re-reads the amended contract
525 * before its next quality gate. Completion gates need no special casing:
526 * they read the task's current fields, so they naturally evaluate the
527 * amended contract.
528 */
529 export function amendTaskContract(team, task, input, by, reason) {
530 if (!nonemptyString(by))
531 return { ok: false, error: 'contract amendment requires a non-empty author identity' };
532 if (!nonemptyString(reason))
533 return { ok: false, error: 'contract amendment requires a non-empty reason' };
534 if (TERMINAL_TASK_STATUSES.includes(task.status)) {
535 return { ok: false, error: `task ${task.id} is ${task.status}; terminal contracts are immutable` };
536 }
537 if (taskKindOf(task) === 'work') {
538 return { ok: false, error: `task ${task.id} has kind=work and no contract to amend` };
539 }
540 if (!AMENDABLE_CONTRACT_FIELDS.some((field) => input[field] !== undefined)) {
541 return { ok: false, error: `amendment requires at least one of: ${AMENDABLE_CONTRACT_FIELDS.join(', ')}` };
542 }
543 const next = {};
544 const previous = {};
545 if (input.objective !== undefined) {
546 if (!nonemptyString(input.objective)) {
547 return { ok: false, error: 'amended objective must be a non-empty string' };
548 }
549 next['objective'] = input.objective;
550 previous['objective'] = task.objective;
551 }
552 for (const field of ['acceptance', 'verify']) {
553 const value = input[field];
554 if (value === undefined)
555 continue;
556 if (!nonemptyStringList(value)) {
557 return { ok: false, error: `amended ${field} must be a non-empty list of non-empty strings` };
558 }
559 next[field] = value;
560 previous[field] = task[field];
561 }
562 for (const field of ['inScope', 'outOfScope']) {
563 const value = input[field];
564 if (value === undefined)
565 continue;
566 if (!nonemptyStringList(value)) {
567 return { ok: false, error: `amended ${field} must be a non-empty list of non-empty strings` };
568 }
569 for (const entry of value) {
570 if (normalizeWorkspacePath(entry) === undefined) {
571 return {
572 ok: false,
573 error: `amended ${field} entry "${entry}" is not a workspace-relative path (absolute paths and ".." can never match scope patterns)`,
574 };
575 }
576 }
577 next[field] = value;
578 previous[field] = task[field];
579 }
580 const reviewPassed = team.tasks.some((item) => ((taskKindOf(item) === 'review' || taskKindOf(item) === 'requirements')
581 && item.reviewedTaskId === task.id
582 && item.verdict === 'pass'));
583 if (reviewPassed) {
584 return { ok: false, error: `task ${task.id} already passed review; its contract is frozen` };
585 }
586 const revision = {
587 at: Date.now(),
588 by,
589 reason,
590 fields: Object.keys(next),
591 previous,
592 };
593 return {
594 ok: true,
595 revision,
596 task: {
597 ...task,
598 ...next,
599 revisions: [...(task.revisions ?? []), revision],
600 updatedAt: Date.now(),
601 },
602 };
603 }
604 const CAPTAIN_ASSIGNEE = 'captain';
605 const OPEN_FOLLOW_UP_STATUSES = ['pending', 'claimed', 'in_progress'];
606 function schedulableAssignee(preferred, team, forbidden) {
607 if (preferred !== undefined && preferred !== CAPTAIN_ASSIGNEE && preferred !== forbidden) {
608 const live = team.members.find((member) => member.name === preferred && member.status !== 'removed');
609 if (live !== undefined)
610 return live.name;
611 }
612 return team.members.find((member) => (member.status !== 'removed'
613 && member.name !== CAPTAIN_ASSIGNEE
614 && member.name !== forbidden))?.name;
615 }
616 function countRepairAttempts(team, sourceTaskId, findingIds) {
617 const key = findingKey(findingIds);
618 return team.tasks.filter((item) => (taskKindOf(item) === 'repair'
619 && item.sourceTaskId === sourceTaskId
620 && findingKey(item.sourceFindingIds ?? []) === key)).length;
621 }
622 function hasOpenFollowUp(team, sourceTaskId, findingIds) {
623 const key = findingKey(findingIds);
624 return team.tasks.some((item) => (taskKindOf(item) === 'repair'
625 && item.sourceTaskId === sourceTaskId
626 && findingKey(item.sourceFindingIds ?? []) === key
627 && OPEN_FOLLOW_UP_STATUSES.includes(item.status)));
628 }
629 /** Drop previous-round exclusions that intersect this generated repair's scope. */
630 function withoutScopeConflicts(outOfScope, inScope) {
631 if (outOfScope === undefined)
632 return undefined;
633 const conflicting = new Set(inScopeOverlap(outOfScope, inScope ?? []));
634 return outOfScope.filter((pattern) => !conflicting.has(pattern));
635 }
636 /**
637 * Line anchors (`file.ts:42`, `deliver.go:503-505`) cannot survive an edit
638 * anywhere above them, so generated text never asserts one. Callers locate the
639 * cited code by content anchor instead. Fully anchored numbers (`12:30`, a
640 * version, a URL port) are left alone.
641 */
642 const LINE_ANCHOR_PATTERN = /(?<!\/\/)(?<=[A-Za-z_./\\-][A-Za-z0-9_./\\-]*):\d+(?:-\d+)?\b/gu;
643 /** Remove drifting line anchors from generated contract text. */
644 export function stripLineAnchors(text) {
645 return text.replaceAll(LINE_ANCHOR_PATTERN, '');
646 }
647 /**
648 * Acceptance items derived from a failed verification: the concrete failures
649 * the member must resolve. A verification carries no review findings, so the
650 * generator uses the evidence the task itself recorded.
651 */
652 function verificationFailureAcceptance(closed) {
653 const items = [];
654 for (const result of closed.acceptanceResults ?? []) {
655 if (result.status === 'failed')
656 items.push(`Satisfy the failed acceptance item recorded by ${closed.id}: ${stripLineAnchors(result.criterion)}`);
657 }
658 for (const command of closed.commandsRun ?? []) {
659 if (command.status !== 'failed')
660 continue;
661 items.push(`Make \`${command.command}\` pass (it failed${command.exitCode === undefined ? '' : ` with exit code ${command.exitCode}`})`);
662 }
663 if (items.length === 0) {
664 items.push(`Resolve what failed in ${closed.id}${closed.output === undefined ? '' : `: ${closed.output.slice(0, 200)}`}`);
665 }
666 return items;
667 }
668 /**
669 * What the generator tells the member about a work order it derived from
670 * someone else's findings. The plugin cannot verify a finding's claims (a
671 * target count, a symbol that still exists, an action the product supports),
672 * and says so instead of lending them authority.
673 */
674 function generatedRepairDescription(closed, excluded) {
675 const lines = [
676 `Auto-generated repair round derived from the findings of ${closed.id} (${taskKindOf(closed)}).`,
677 'The plugin did not verify the finding text: line numbers were removed because an edit anywhere above them invalidates them, and claims such as a target count, a symbol that still exists, or an action the product supports are the reporter\'s, not confirmed facts. Locate the cited code by content anchor (symbol, string, call site) and check every acceptance item against the current workspace before editing; if an item is already satisfied or impossible as written, report that instead of forcing a change.',
678 ];
679 if (excluded.length > 0) {
680 lines.push(`Excluded from this contract on purpose: ${excluded.map((finding) => finding.file ?? finding.id).join(', ')} — the completion gate refuses those paths by default, so they need a human decision rather than a member edit.`);
681 }
682 return lines.join(' ');
683 }
684 export function planQualityFollowUp(team, closed, options = {}) {
685 const empty = { created: [], tasks: [] };
686 const escalate = (reason) => ({ ...empty, escalated: true, status: 'escalated', reason });
687 const kind = taskKindOf(closed);
688 if (closed.status !== 'failed')
689 return empty;
690 if (kind === 'review' || kind === 'requirements') {
691 if (closed.verdict === 'reject')
692 return escalate(`${closed.id} returned verdict=reject; automatic repair is not a substitute for a human decision`);
693 if (closed.verdict !== 'needs_revision')
694 return empty;
695 }
696 else if (kind !== 'verification') {
697 // Both quality gates share the findings → repair → re-check contract, so
698 // a failed verification self-heals exactly like a failed review (#175B).
699 return empty;
700 }
701 const policy = resolveReviewPolicy(team.reviewPolicy);
702 const currentRound = closed.round ?? 1;
703 const nextRound = currentRound + 1;
704 const maxRounds = kind === 'requirements' ? policy.requirementsMaxRounds : policy.codeMaxRounds;
705 if (nextRound > maxRounds)
706 return escalate(`${closed.id} reached the ${kind} round ceiling (${maxRounds}); the loop cannot open round ${nextRound}`);
707 if (kind === 'requirements') {
708 const next = {
709 kind: 'requirements',
710 subject: `requirements-round-${nextRound}`,
711 assignee: closed.assignee,
712 dependencies: [],
713 round: nextRound,
714 objective: sanitizeReviewObjective(closed.objective, 'Converge remaining open questions'),
715 acceptance: sanitizeReviewAcceptance(unresolvedFindings(closed).map((finding) => finding.requiredFix)),
716 };
717 return { created: [next], tasks: [next] };
718 }
719 const target = reviewedTargetOf(team, closed);
720 const sourceId = closed.reviewedTaskId ?? closed.sourceTaskId ?? target?.id;
721 if (sourceId === undefined)
722 return empty;
723 const source = team.tasks.find((item) => item.id === sourceId);
724 const findings = unresolvedFindings(closed);
725 const excluded = excludedFindingsOf(findings, options.pathExists);
726 const actionable = findings.filter((finding) => !excluded.includes(finding));
727 if (findings.length > 0 && actionable.length === 0) {
728 return {
729 ...empty,
730 escalated: true,
731 status: 'escalated',
732 reason: `every finding of ${closed.id} cites only default-excluded paths (${excluded.map((finding) => finding.file ?? finding.id).join(', ')}); the completion gate classifies those out_of_scope, so no honest repair contract exists — a human must decide`,
733 excludedFindings: excluded.map((finding) => finding.id),
734 };
735 }
736 const findingIds = actionable.map((finding) => finding.id);
737 if (hasOpenFollowUp(team, sourceId, findingIds))
738 return empty;
739 if (countRepairAttempts(team, sourceId, findingIds) >= policy.maxRepairAttempts) {
740 return escalate(`${sourceId} already used ${policy.maxRepairAttempts} automatic repair attempts for these findings`);
741 }
742 // inScope is derived from the actionable findings below: the observed file
743 // plus any workspace-relative paths referenced by the requiredFix
744 // instructions, minus everything the completion gate refuses by default.
745 const repairScope = repairScopeFromFindings(actionable, source?.inScope);
746 const verifyCommands = source?.verify ?? closed.verify;
747 const implementer = schedulableAssignee(source?.assignee, team);
748 // The causal edge to the failed gate is recorded explicitly: it cannot be a
749 // `dependencies` entry, because a failed task never reaches `completed` and
750 // `unsatisfiedDependencies` would then make this repair unclaimable forever.
751 const repairDependencies = [sourceId];
752 const repair = {
753 id: `repair-round-${nextRound}`,
754 kind: 'repair',
755 subject: `repair-round-${nextRound}`,
756 description: generatedRepairDescription(closed, excluded),
757 assignee: implementer,
758 dependencies: repairDependencies,
759 round: nextRound,
760 objective: source?.objective ?? closed.objective ?? `Fix findings from ${sourceId}`,
761 inScope: repairScope,
762 outOfScope: withoutScopeConflicts(source?.outOfScope, repairScope),
763 verify: verifyCommands,
764 acceptance: actionable.length > 0
765 ? actionable.map((finding) => stripLineAnchors(finding.requiredFix))
766 : verificationFailureAcceptance(closed),
767 sourceTaskId: sourceId,
768 sourceFindingIds: findingIds,
769 findingSourceTaskIds: [closed.id],
770 contractPaths: repairScope,
771 };
772 const checker = schedulableAssignee(closed.assignee !== implementer ? closed.assignee : undefined, team, implementer);
773 const recheck = kind === 'verification'
774 ? {
775 id: `verification-round-${nextRound}`,
776 kind: 'verification',
777 subject: `verification-round-${nextRound}`,
778 assignee: checker,
779 dependencies: [repair.id ?? `repair-round-${nextRound}`],
780 round: nextRound,
781 objective: closed.objective ?? `Re-verify ${sourceId} after ${repair.id ?? `repair-round-${nextRound}`}`,
782 acceptance: sanitizeReviewAcceptance(closed.acceptance),
783 verify: verifyCommands,
784 }
785 : {
786 id: `review-round-${nextRound}`,
787 kind: 'review',
788 subject: `review-round-${nextRound}`,
789 assignee: checker,
790 dependencies: [repair.id ?? `repair-round-${nextRound}`],
791 round: nextRound,
792 objective: sanitizeReviewObjective(closed.objective, DEFAULT_REVIEW_OBJECTIVE),
793 acceptance: sanitizeReviewAcceptance(closed.acceptance),
794 reviewedTaskId: repair.id,
795 };
796 const result = { created: [repair, recheck], tasks: [repair, recheck] };
797 if (excluded.length > 0)
798 result.excludedFindings = excluded.map((finding) => finding.id);
799 return result;
800 }
801 export function buildCoverageMatrix(goalItems, tasks) {
802 return goalItems.map((goalItem) => {
803 const covering = tasks.filter((item) => item.coverageOf?.includes(goalItem));
804 const taskIds = covering.map((item) => item.id);
805 if (covering.length === 0)
806 return { goal_item: goalItem, task_ids: taskIds, status: 'missing' };
807 if (covering.some((item) => item.status === 'failed' || item.status === 'cancelled')) {
808 return { goal_item: goalItem, task_ids: taskIds, status: 'blocked' };
809 }
810 if (covering.every((item) => item.status === 'completed')) {
811 return { goal_item: goalItem, task_ids: taskIds, status: 'passed' };
812 }
813 return { goal_item: goalItem, task_ids: taskIds, status: 'in_progress' };
814 });
815 }
816 /* ------------------------------------------------------------------------ *
817 * Content-bound verdicts (issue #161) and generated work orders (issue #174) *
818 * ------------------------------------------------------------------------ */
819 const VERDICT_KINDS = ['review', 'requirements', 'verification'];
820 /** Kinds whose completion is a verdict about a revision. */
821 export function isVerdictKind(kind) {
822 return kind !== undefined && VERDICT_KINDS.includes(kind);
823 }
824 function shortDigest(value) {
825 return value === undefined || value === '' ? 'absent' : value.slice(0, 8);
826 }
827 /**
828 * Compare recorded bytes against the bytes on disk now, keeping the path each
829 * reason belongs to. "Cannot be read" is reported as its own reason: a
830 * permission error is not a match, and a partial read is not proof of an
831 * unchanged file.
832 */
833 export function artifactDriftDetails(recorded, current) {
834 if (recorded === undefined || recorded.length === 0 || current === undefined)
835 return [];
836 const now = new Map(current.map((item) => [item.path, item]));
837 const drift = [];
838 for (const before of recorded) {
839 const after = now.get(before.path);
840 if (after === undefined) {
841 drift.push({ path: before.path, message: `${before.path} was not in the current workspace snapshot` });
842 continue;
843 }
844 if (after.unreadable === true) {
845 drift.push({ path: after.path, message: `${after.path} cannot be read now (${after.reason ?? 'unknown error'}), so its recorded bytes cannot be confirmed` });
846 continue;
847 }
848 if (before.unreadable === true) {
849 drift.push({ path: before.path, message: `${before.path} was not readable when this evidence was recorded (${before.reason ?? 'unknown error'}), so it never covered those bytes` });
850 continue;
851 }
852 if (before.present !== after.present) {
853 drift.push({
854 path: before.path,
855 message: after.present
856 ? `${before.path} was absent when recorded and now exists`
857 : `${before.path} was deleted after it was recorded`,
858 });
859 continue;
860 }
861 if (before.present && after.present && before.sha256 !== after.sha256) {
862 drift.push({ path: before.path, message: `${before.path} changed (sha256 ${shortDigest(before.sha256)} -> ${shortDigest(after.sha256)})` });
863 }
864 }
865 return drift;
866 }
867 /** Message-only view of {@link artifactDriftDetails}. */
868 export function artifactDrift(recorded, current) {
869 return artifactDriftDetails(recorded, current).map((detail) => detail.message);
870 }
871 /** A partially enumerated scope is incomplete evidence, never a silent pass. */
872 export function gapDrift(gaps) {
873 return (gaps ?? []).map((gap) => `${gap.pattern}: ${gap.reason}`);
874 }
875 /**
876 * The task a verdict is about: an explicit `reviewedTaskId`/`sourceTaskId`
877 * first, otherwise the implementation/repair this gate depends on.
878 */
879 export function reviewedTargetOf(team, task) {
880 const explicit = task.reviewedTaskId ?? task.sourceTaskId;
881 if (explicit !== undefined) {
882 const found = team.tasks.find((item) => item.id === explicit);
883 if (found !== undefined)
884 return found;
885 }
886 for (const dependency of task.dependencies) {
887 const candidate = team.tasks.find((item) => item.id === dependency);
888 if (candidate !== undefined && (taskKindOf(candidate) === 'implementation' || taskKindOf(candidate) === 'repair')) {
889 return candidate;
890 }
891 }
892 return undefined;
893 }
894 export function bindReviewToRevision(team, task, binding) {
895 const target = reviewedTargetOf(team, task);
896 if (target === undefined || binding.artifacts.length === 0)
897 return task;
898 const kind = taskKindOf(task);
899 return {
900 ...task,
901 ...kind === 'review' || kind === 'requirements' ? { reviewedTaskId: task.reviewedTaskId ?? target.id } : {},
902 reviewedAttempt: target.attempt ?? 0,
903 reviewedArtifacts: binding.artifacts.map((item) => ({ ...item })),
904 ...binding.gaps === undefined || binding.gaps.length === 0 ? {} : { reviewedGaps: binding.gaps.map((gap) => ({ ...gap })) },
905 ...binding.scope === undefined || binding.scope.length === 0 ? {} : { reviewedScope: [...binding.scope] },
906 ...binding.duringDrift === undefined || binding.duringDrift.length === 0 ? {} : { reviewedDuringDrift: [...binding.duringDrift] },
907 };
908 }
909 /**
910 * Scope a verdict must bind: the paths the judged task changed, otherwise the
911 * scope patterns of its contract (expanded by the caller).
912 */
913 export function verdictScopePatterns(team, task) {
914 const lineage = verdictLineageTasks(team, task);
915 // Every implementation/repair this gate transitively judges: the original
916 // source AND the repairs that followed it. A pre-planned review whose edge
917 // was rewired to a re-verification must still bind the bytes the original
918 // source changed, otherwise a later edit to the repair's target would have
919 // no valid review evidence at all (#161 x #175).
920 const changed = new Set();
921 for (const item of lineage) {
922 const kind = taskKindOf(item);
923 if (kind !== 'implementation' && kind !== 'repair')
924 continue;
925 for (const path of item.changedPaths ?? []) {
926 const normalized = normalizeWorkspacePath(path);
927 if (normalized !== undefined)
928 changed.add(normalized);
929 }
930 }
931 if (changed.size > 0)
932 return [...changed];
933 const scope = new Set([
934 ...(task.inScope ?? []),
935 ...lineage.flatMap((item) => item.inScope ?? []),
936 ]);
937 if (scope.size > 0)
938 return [...scope];
939 return (reviewedTargetOf(team, task)?.deliverables ?? [])
940 .map((path) => normalizeWorkspacePath(path))
941 .filter((path) => path !== undefined);
942 }
943 /**
944 * The artifacts a gate transitively judges: follow explicit review/source
945 * links and dependency edges (a repair records the source it fixes, a
946 * verification depends on the repair, a review depends on the verification).
947 */
948 function verdictLineageTasks(team, task) {
949 const byId = new Map(team.tasks.map((item) => [item.id, item]));
950 const visited = new Set();
951 const queue = [...task.dependencies];
952 const explicit = task.reviewedTaskId ?? task.sourceTaskId;
953 if (explicit !== undefined)
954 queue.push(explicit);
955 const target = reviewedTargetOf(team, task);
956 if (target !== undefined && target.id !== task.id)
957 queue.push(target.id);
958 const found = [];
959 while (queue.length > 0) {
960 const id = queue.shift();
961 if (visited.has(id))
962 continue;
963 visited.add(id);
964 const item = byId.get(id);
965 if (item === undefined)
966 continue;
967 found.push(item);
968 queue.push(...item.dependencies);
969 const link = item.reviewedTaskId ?? item.sourceTaskId;
970 if (link !== undefined)
971 queue.push(link);
972 }
973 return found;
974 }
975 /** Scope patterns recorded verdicts bound, for new-file detection. */
976 export function deliveryScopePatterns(team) {
977 const patterns = new Set();
978 for (const task of team.tasks) {
979 const kind = taskKindOf(task);
980 if (!VERDICT_KINDS.includes(kind) || task.status !== 'completed')
981 continue;
982 for (const pattern of task.reviewedScope ?? [])
983 patterns.add(pattern);
984 }
985 return [...patterns];
986 }
987 function isDirectoryPattern(pattern) {
988 const trimmed = pattern.trim();
989 return trimmed.endsWith('/') || trimmed === '.' || trimmed === './';
990 }
991 /** Root of the artifact lineage a gate judges (the implementation/repair chain). */
992 function lineageRoot(team, task) {
993 let current = task;
994 const visited = new Set();
995 while (!visited.has(current.id)) {
996 visited.add(current.id);
997 const nextId = current.reviewedTaskId ?? current.sourceTaskId ?? current.dependencies[0];
998 const next = nextId === undefined ? undefined : team.tasks.find((item) => item.id === nextId);
999 if (next === undefined)
1000 break;
1001 current = next;
1002 }
1003 if (current.id === task.id) {
1004 const kind = taskKindOf(task);
1005 return kind === 'implementation' || kind === 'repair' ? task.id : undefined;
1006 }
1007 return current.id;
1008 }
1009 const VERDICT_WEIGHT = { verification: 1, review: 2, requirements: 2 };
1010 /**
1011 * Does `candidate` cover `prior`'s evidence? A later sound verdict that either
1012 * depends on the prior gate or judges the same artifact lineage supersedes it,
1013 * so a legitimately changed revision does not block delivery forever behind an
1014 * old snapshot.
1015 */
1016 function supersedes(team, candidate, prior) {
1017 if (candidate.id === prior.id || candidate.status !== 'completed')
1018 return false;
1019 if ((VERDICT_WEIGHT[taskKindOf(candidate)] ?? 0) < (VERDICT_WEIGHT[taskKindOf(prior)] ?? 0))
1020 return false;
1021 if (candidate.createdAt < prior.createdAt)
1022 return false;
1023 if (candidate.createdAt === prior.createdAt && (candidate.round ?? 0) <= (prior.round ?? 0))
1024 return false;
1025 if (dependencyClosureContains(team.tasks, candidate.dependencies, prior.id))
1026 return true;
1027 const candidateRoot = lineageRoot(team, candidate);
1028 return candidateRoot !== undefined && candidateRoot === lineageRoot(team, prior);
1029 }
1030 /** Paths whose current bytes decide whether recorded verdicts and orders hold. */
1031 export function deliveryArtifactPaths(team) {
1032 const paths = new Set();
1033 for (const task of team.tasks) {
1034 for (const artifact of task.reviewedArtifacts ?? [])
1035 paths.add(artifact.path);
1036 for (const artifact of task.contractSnapshot?.artifacts ?? [])
1037 paths.add(artifact.path);
1038 }
1039 // Legacy verdicts carry no digests; the changed paths of the task they
1040 // judged still let the delivery check detect a later edit by mtime.
1041 for (const task of team.tasks) {
1042 const kind = taskKindOf(task);
1043 if (!VERDICT_KINDS.includes(kind))
1044 continue;
1045 if (task.status !== 'completed')
1046 continue;
1047 if ((task.reviewedArtifacts?.length ?? 0) > 0)
1048 continue;
1049 for (const changed of reviewedTargetOf(team, task)?.changedPaths ?? []) {
1050 const normalized = normalizeWorkspacePath(changed);
1051 if (normalized !== undefined)
1052 paths.add(normalized);
1053 }
1054 }
1055 return [...paths];
1056 }
1057 /**
1058 * File mtimes carry sub-millisecond precision while task stamps are whole
1059 * milliseconds, so a file written in the same millisecond as the verdict would
1060 * otherwise read as "modified after". Only a clearly later write counts;
1061 * content digests are exact and need no tolerance.
1062 */
1063 const MTIME_TOLERANCE_MS = 1;
1064 function verdictDrift(team, item, audit) {
1065 const issues = [];
1066 const target = reviewedTargetOf(team, item);
1067 if (target !== undefined && item.reviewedAttempt !== undefined && (target.attempt ?? 0) !== item.reviewedAttempt) {
1068 issues.push({ message: `${target.id} was re-attempted after this verdict (attempt ${item.reviewedAttempt} -> ${target.attempt ?? 0})` });
1069 }
1070 for (const gap of gapDrift(item.reviewedGaps))
1071 issues.push({ message: gap });
1072 for (const drift of item.reviewedDuringDrift ?? []) {
1073 issues.push({ message: `the workspace changed while this verdict was being formed (${drift}), so it does not bind a stable revision` });
1074 }
1075 const recorded = item.reviewedArtifacts;
1076 // A file that appeared under a bound directory scope after the verdict was
1077 // never reviewed: a broad scope must not quietly absorb new work.
1078 const recordedPaths = new Set((recorded ?? []).map((artifact) => artifact.path));
1079 for (const pattern of item.reviewedScope ?? []) {
1080 if (!isDirectoryPattern(pattern))
1081 continue;
1082 for (const entry of audit.expandedScope ?? []) {
1083 if (entry.present !== true || recordedPaths.has(entry.path))
1084 continue;
1085 if (!pathMatchesScope(entry.path, pattern))
1086 continue;
1087 issues.push({ path: entry.path, message: `${entry.path} appeared under the reviewed scope ${pattern} after the verdict and was never reviewed` });
1088 }
1089 }
1090 if (recorded !== undefined && recorded.length > 0) {
1091 issues.push(...artifactDriftDetails(recorded, audit.artifacts));
1092 return issues;
1093 }
1094 // A record written before content-bound verdicts existed carries no digests,
1095 // but the revision it judged is still identifiable: the bytes the target
1096 // claimed to change cannot have been written after the verdict closed.
1097 for (const changed of target?.changedPaths ?? []) {
1098 const normalized = normalizeWorkspacePath(changed);
1099 if (normalized === undefined)
1100 continue;
1101 const current = audit.artifacts?.find((artifact) => artifact.path === normalized);
1102 if (current === undefined)
1103 continue;
1104 if (current.unreadable === true) {
1105 issues.push({ path: normalized, message: `${normalized} cannot be read now (${current.reason ?? 'unknown error'}), so the verdict cannot be confirmed` });
1106 continue;
1107 }
1108 if (current.present === true && current.mtimeMs !== undefined && current.mtimeMs > item.updatedAt + MTIME_TOLERANCE_MS) {
1109 issues.push({ path: normalized, message: `${normalized} was modified after this verdict closed (file mtime is later than the verdict)` });
1110 continue;
1111 }
1112 if (current.present !== true) {
1113 // No digest was recorded, so the plugin cannot date the disappearance:
1114 // the file the implementation changed is gone and the verdict cannot be
1115 // confirmed against it. A later sound verdict supersedes this one.
1116 issues.push({ path: normalized, message: `${normalized} is recorded as changed by ${target?.id ?? 'the judged task'} but no longer exists, and no digest was recorded to confirm the verdict` });
1117 }
1118 }
1119 return issues;
1120 }
1121 /** A verdict whose evidence is absent altogether cannot be audited at all. */
1122 function unboundVerdict(item) {
1123 return (item.reviewedArtifacts?.length ?? 0) === 0
1124 && (item.reviewedGaps?.length ?? 0) === 0
1125 && item.reviewedAttempt === undefined;
1126 }
1127 /**
1128 * Audit every completed verdict against the current revision (issue #161).
1129 *
1130 * A drifted review/requirements pass is the delivery evidence itself, so it
1131 * blocks — unless a later sound verdict covers the same lineage, which is the
1132 * normal shape of `pass → repair → new pass` and must converge instead of
1133 * blocking forever behind an old snapshot. A drifted `verification` or a
1134 * superseded pass is reported as a warning: a later repair legitimately
1135 * supersedes it, but never silently. A verdict that predates content binding
1136 * is reported as an unauditable gap rather than being read as a pass over the
1137 * current bytes.
1138 */
1139 export function verdictAuditNotes(team, audit = {}) {
1140 const notes = [];
1141 const verdicts = team.tasks.filter((item) => {
1142 const kind = taskKindOf(item);
1143 if (!VERDICT_KINDS.includes(kind))
1144 return false;
1145 if (item.status !== 'completed')
1146 return false;
1147 return !((kind === 'review' || kind === 'requirements') && item.verdict !== 'pass');
1148 });
1149 const issues = new Map();
1150 for (const item of verdicts) {
1151 const found = verdictDrift(team, item, audit);
1152 if (found.length > 0)
1153 issues.set(item.id, found);
1154 }
1155 // Only a verdict that actually recorded the bytes it judged, over a complete
1156 // scope, and that still matches the workspace may supersede an older one. An
1157 // unbound (pre-fix) pass records no identity at all: it cannot "bind the
1158 // current bytes" and must never clear another verdict's drift.
1159 const sound = verdicts.filter((item) => !issues.has(item.id) && bindsRecordedRevision(team, item, audit));
1160 for (const item of verdicts) {
1161 const kind = taskKindOf(item);
1162 const found = issues.get(item.id);
1163 if (found === undefined) {
1164 if (unboundVerdict(item) && audit.artifacts !== undefined) {
1165 notes.push({
1166 taskId: item.id,
1167 level: 'warning',
1168 message: `${item.id} (${kind}) predates content-bound verdicts and recorded no artifact identity; delivery cannot confirm the current bytes are the revision it judged — re-review to bind them`,
1169 });
1170 }
1171 continue;
1172 }
1173 const detail = `${item.id} (${kind}) verdict covers a revision that no longer exists: ${found.map((entry) => entry.message).join('; ')}`;
1174 // Superseding needs the same lineage AND coverage of every drifted path or
1175 // gap: a narrower new review over path A must not clear an unreviewed
1176 // change to path B.
1177 const covering = sound.find((candidate) => (supersedes(team, candidate, item) && coversDrift(team, candidate, item, found)));
1178 if (covering !== undefined) {
1179 notes.push({ taskId: item.id, level: 'warning', message: `${detail} — superseded by ${covering.id}, which binds the current bytes` });
1180 continue;
1181 }
1182 // A drifted gate without a sound covering verdict leaves the current bytes
1183 // with no valid evidence, whether it is a review or a verification: the
1184 // only difference is what the captain has to do next.
1185 if (kind === 'verification') {
1186 notes.push({ taskId: item.id, level: 'blocker', message: `${detail} — re-verify the current bytes; no later sound verdict bound them` });
1187 continue;
1188 }
1189 notes.push({ taskId: item.id, level: 'blocker', message: `${detail} — re-review the current bytes; do not report this revision as verified` });
1190 }
1191 return notes;
1192 }
1193 /**
1194 * Does this verdict hold a real, complete, still-matching record of the bytes
1195 * it judged? Attempt drift, an incomplete scope, or a workspace that moved
1196 * while the gate was open all disqualify it.
1197 */
1198 function bindsRecordedRevision(team, item, audit) {
1199 if ((item.reviewedArtifacts?.length ?? 0) === 0)
1200 return false;
1201 if ((item.reviewedGaps?.length ?? 0) > 0)
1202 return false;
1203 if ((item.reviewedDuringDrift?.length ?? 0) > 0)
1204 return false;
1205 const target = reviewedTargetOf(team, item);
1206 if (target !== undefined && item.reviewedAttempt !== undefined && (target.attempt ?? 0) !== item.reviewedAttempt)
1207 return false;
1208 if (audit.artifacts === undefined)
1209 return false;
1210 return artifactDriftDetails(item.reviewedArtifacts, audit.artifacts).length === 0;
1211 }
1212 /**
1213 * A later verdict clears an older one only when it covers what actually
1214 * drifted: every implicated path must be among the bytes it bound. Reasons
1215 * that name no path (an incomplete scope, a re-attempted target, a workspace
1216 * that moved mid-review) are cleared only by a sound verdict about the same
1217 * target's current attempt.
1218 */
1219 function coversDrift(team, candidate, prior, drifted) {
1220 if (drifted.length === 0)
1221 return false;
1222 const bound = new Set((candidate.reviewedArtifacts ?? []).map((artifact) => artifact.path));
1223 for (const issue of drifted) {
1224 if (issue.path !== undefined) {
1225 if (!bound.has(issue.path))
1226 return false;
1227 continue;
1228 }
1229 const candidateTarget = reviewedTargetOf(team, candidate);
1230 const priorTarget = reviewedTargetOf(team, prior);
1231 if (candidateTarget === undefined || priorTarget === undefined || candidateTarget.id !== priorTarget.id)
1232 return false;
1233 if (candidate.reviewedAttempt !== (candidateTarget.attempt ?? 0))
1234 return false;
1235 if (lineageRoot(team, candidate) === undefined || lineageRoot(team, candidate) !== lineageRoot(team, prior))
1236 return false;
1237 }
1238 return true;
1239 }
1240 function verdictBindingIssues(team, audit) {
1241 const blockers = [];
1242 const warnings = [];
1243 for (const note of verdictAuditNotes(team, audit)) {
1244 if (note.level === 'blocker')
1245 blockers.push(note.message);
1246 else
1247 warnings.push(note.message);
1248 }
1249 return { blockers, warnings };
1250 }
1251 /** Staleness of one auto-generated work order against the current workspace. */
1252 export function contractStaleness(task, current) {
1253 const snapshot = task.contractSnapshot;
1254 if (snapshot === undefined)
1255 return [];
1256 const stale = [];
1257 for (const gap of gapDrift(snapshot.gaps)) {
1258 stale.push(`${task.id} work order recorded only partial coverage (${gap}), so a change outside it would not be visible`);
1259 }
1260 if (snapshot.artifacts.length === 0 || current === undefined)
1261 return stale;
1262 stale.push(...artifactDrift(snapshot.artifacts, current).map((item) => `${task.id} work order was generated before: ${item}`));
1263 return stale;
1264 }
1265 /**
1266 * Open auto-generated work orders whose cited bytes moved on (issue #174).
1267 * A repair round's acceptance/inScope is a snapshot of the workspace at
1268 * finding-generation time; every later round invalidates it, and nothing used
1269 * to say so — a member following it literally edits the wrong line or redoes
1270 * work that is already done.
1271 */
1272 export function workOrderWarnings(team, current) {
1273 if (current === undefined)
1274 return [];
1275 const warnings = [];
1276 for (const task of team.tasks) {
1277 if (task.contractSnapshot === undefined)
1278 continue;
1279 if (!OPEN_FOLLOW_UP_STATUSES.includes(task.status))
1280 continue;
1281 const stale = contractStaleness(task, current);
1282 if (stale.length === 0)
1283 continue;
1284 warnings.push({
1285 taskId: task.id,
1286 message: `${stale.join('; ')}. Its auto-generated acceptance/inScope describe the workspace as it was then: locate the cited code by content anchor, and amend the contract if the target is gone.`,
1287 });
1288 }
1289 return warnings;
1290 }
1291 /** Statuses in which a repair still counts as the follow-up of a failed gate. */
1292 const FOLLOW_UP_VISIBLE_STATUSES = ['pending', 'claimed', 'in_progress', 'completed'];
1293 /**
1294 * Does a repair exist that addresses this failed gate's findings? The causal
1295 * link can be recorded three ways, and all of them count: the repair's
1296 * declared source, an explicit dependency edge on the failed gate, or the
1297 * finding ids the repair was opened for (issue #175A — the transcript edge
1298 * used to be invisible to the graph, so delivery reported
1299 * `failed without a follow-up repair` for loops that were already closed).
1300 */
1301 function hasFollowUpRepair(team, item) {
1302 const kind = taskKindOf(item);
1303 if (kind === 'requirements') {
1304 return team.tasks.some((candidate) => (taskKindOf(candidate) === 'requirements' && (candidate.round ?? 1) > (item.round ?? 1)));
1305 }
1306 const findingIds = new Set((item.findings ?? []).map((finding) => finding.id));
1307 const upstreams = new Set([item.id, item.reviewedTaskId ?? item.sourceTaskId].filter((id) => id !== undefined));
1308 return team.tasks.some((candidate) => {
1309 if (taskKindOf(candidate) !== 'repair' || !FOLLOW_UP_VISIBLE_STATUSES.includes(candidate.status))
1310 return false;
1311 if (candidate.sourceTaskId !== undefined && upstreams.has(candidate.sourceTaskId))
1312 return true;
1313 if (candidate.dependencies.includes(item.id))
1314 return true;
1315 if (candidate.findingSourceTaskIds?.includes(item.id) === true)
1316 return true;
1317 return candidate.sourceFindingIds !== undefined
1318 && candidate.sourceFindingIds.some((findingId) => findingIds.has(findingId));
1319 });
1320 }
1321 /** Failed gates with no follow-up at all: work that genuinely remains. */
1322 function unresolvedGates(team) {
1323 return team.tasks.filter((item) => isQualityKind(taskKindOf(item))
1324 && item.status === 'failed'
1325 && !hasFollowUpRepair(team, item));
1326 }
1327 export function canDeclareDelivery(team, audit = {}) {
1328 const blockers = [];
1329 const warnings = [];
1330 if (team.phase === 'staged')
1331 blockers.push('team plan is awaiting approval');
1332 if (team.halted === true)
1333 blockers.push('team is halted');
1334 if (team.escalated === true)
1335 blockers.push('team requires escalation resolution');
1336 if (team.tasks.length === 0)
1337 blockers.push('team has no completed work');
1338 for (const item of team.tasks.filter(item => !isQualityKind(taskKindOf(item)))) {
1339 if (item.status !== 'completed' && item.status !== 'cancelled')
1340 blockers.push(`${item.id} (${taskKindOf(item)}) is not completed`);
1341 }
1342 if (team.tasks.length > 0 && team.tasks.every(item => item.status === 'cancelled'))
1343 blockers.push('all work was cancelled');
1344 const quality = team.tasks.filter((item) => isQualityKind(taskKindOf(item)));
1345 const implementations = quality.filter((item) => taskKindOf(item) === 'implementation' || taskKindOf(item) === 'repair');
1346 const reviews = quality.filter((item) => taskKindOf(item) === 'review');
1347 for (const item of quality) {
1348 const kind = taskKindOf(item);
1349 if (item.status === 'completed') {
1350 if ((kind === 'review' || kind === 'requirements') && item.verdict !== 'pass') {
1351 blockers.push(`${item.id} completed without verdict=pass`);
1352 }
1353 continue;
1354 }
1355 if (item.status === 'failed') {
1356 if (!hasFollowUpRepair(team, item))
1357 blockers.push(`${item.id} failed without a follow-up repair`);
1358 continue;
1359 }
1360 if (item.status === 'cancelled')
1361 continue;
1362 blockers.push(`${item.id} (${kind}) is not completed`);
1363 }
1364 if (implementations.some((item) => item.status === 'completed') && !reviews.some((item) => item.status === 'completed' && item.verdict === 'pass')) {
1365 if (!blockers.some((item) => item.includes('review'))) {
1366 blockers.push('completed implementation has no passing review');
1367 }
1368 }
1369 for (const item of implementations) {
1370 for (const path of item.changedPaths ?? []) {
1371 if (classifyChangedPath(path, item.inScope ?? [], item.outOfScope ?? []) !== 'in_scope') {
1372 blockers.push(`${item.id} has unaudited path ${path}`);
1373 }
1374 }
1375 }
1376 const binding = verdictBindingIssues(team, audit);
1377 blockers.push(...binding.blockers);
1378 warnings.push(...binding.warnings);
1379 if (audit.artifacts !== undefined) {
1380 warnings.push(...workOrderWarnings(team, audit.artifacts).map((warning) => warning.message));
1381 }
1382 // An incomplete audit is not evidence: a scope that outgrew its cap, or a
1383 // path that cannot be read, must block instead of passing as a clean read.
1384 const auditGaps = audit.gaps ?? [];
1385 if (auditGaps.length > 0 && (quality.length > 0 || blockers.length > 0 || audit.artifacts !== undefined)) {
1386 const shown = auditGaps.slice(0, 3).map((gap) => `${gap.pattern}: ${gap.reason}`);
1387 const more = auditGaps.length > shown.length ? ` (+${auditGaps.length - shown.length} more)` : '';
1388 blockers.push(`the current workspace audit is incomplete (${shown.join('; ')}${more}); no recorded verdict can be confirmed over partially enumerated or unreadable artifacts`);
1389 }
1390 return { ok: blockers.length === 0, blockers, warnings };
1391 }
1392 export function resumeTeamState(team, reason) {
1393 if (!nonemptyString(reason)) {
1394 return { ok: false, status: 'rejected', error: 'resume requires a non-empty reason' };
1395 }
1396 if (team.halted !== true) {
1397 return { ok: true, status: 'already_running', team };
1398 }
1399 return {
1400 ok: true,
1401 status: 'resumed',
1402 team: {
1403 ...team,
1404 halted: false,
1405 haltedAt: undefined,
1406 },
1407 };
1408 }
1409 /**
1410 * The durable `findings[].line` contract, shared by the write-side parser
1411 * (`parseFindings`) and the durable validator (`isReviewFinding`) so the two
1412 * cannot drift apart again (issue #188, #105 class).
1413 */
1414 export function isValidFindingLine(value) {
1415 return Number.isSafeInteger(value) && value >= 0;
1416 }
1417 export function isReviewFinding(value) {
1418 if (!isRecord(value))
1419 return false;
1420 return nonemptyString(value['id'])
1421 && FINDING_SEVERITIES.includes(value['severity'])
1422 && nonemptyString(value['problem'])
1423 && nonemptyString(value['requiredFix'])
1424 && (value['file'] === undefined || nonemptyString(value['file']))
1425 && (value['line'] === undefined || isValidFindingLine(value['line']))
1426 && (value['resolved'] === undefined || typeof value['resolved'] === 'boolean');
1427 }
1428 export function isAcceptanceResult(value) {
1429 if (!isRecord(value))
1430 return false;
1431 return nonemptyString(value['criterion'])
1432 && (value['status'] === 'passed' || value['status'] === 'failed')
1433 && (value['evidence'] === undefined || typeof value['evidence'] === 'string');
1434 }
1435 export function isCommandResult(value) {
1436 if (!isRecord(value))
1437 return false;
1438 return nonemptyString(value['command'])
1439 && (value['status'] === 'passed' || value['status'] === 'failed')
1440 && (value['exitCode'] === undefined || (Number.isSafeInteger(value['exitCode'])))
1441 && (value['evidence'] === undefined || typeof value['evidence'] === 'string');
1442 }
1443 export function isTaskRevision(value) {
1444 if (!isRecord(value))
1445 return false;
1446 return Number.isSafeInteger(value['at'])
1447 && nonemptyString(value['by'])
1448 && nonemptyString(value['reason'])
1449 && nonemptyStringList(value['fields'])
1450 && isRecord(value['previous']);
1451 }
1452 export function isArtifactDigest(value) {
1453 if (!isRecord(value))
1454 return false;
1455 if (!nonemptyString(value['path']) || normalizeWorkspacePath(value['path']) === undefined)
1456 return false;
1457 if (typeof value['present'] !== 'boolean')
1458 return false;
1459 if (value['sha256'] !== undefined && !(typeof value['sha256'] === 'string' && /^[0-9a-f]{64}$/u.test(value['sha256'])))
1460 return false;
1461 if (value['size'] !== undefined && !(Number.isSafeInteger(value['size']) && value['size'] >= 0))
1462 return false;
1463 if (value['mtimeMs'] !== undefined && !(typeof value['mtimeMs'] === 'number' && Number.isFinite(value['mtimeMs'])))
1464 return false;
1465 if (value['unreadable'] !== undefined && typeof value['unreadable'] !== 'boolean')
1466 return false;
1467 if (value['reason'] !== undefined && !nonemptyString(value['reason']))
1468 return false;
1469 if (value['present'] === true && value['sha256'] === undefined)
1470 return false;
1471 return true;
1472 }
1473 export function isArtifactScopeGap(value) {
1474 return isRecord(value) && nonemptyString(value['pattern']) && nonemptyString(value['reason']);
1475 }
1476 export function isArtifactSnapshot(value) {
1477 if (!isRecord(value))
1478 return false;
1479 if (!Number.isSafeInteger(value['at']) || value['at'] < 0)
1480 return false;
1481 if (!Array.isArray(value['artifacts']) || !value['artifacts'].every(isArtifactDigest))
1482 return false;
1483 return value['gaps'] === undefined
1484 || (Array.isArray(value['gaps']) && value['gaps'].length > 0 && value['gaps'].every(isArtifactScopeGap));
1485 } // Optional fields whose persisted values must be non-empty when present
1486 // (mirrors the checks in hasValidQualityTaskFields). Some models materialize
1487 // optional tool parameters as "" instead of omitting them (e.g. GPT-5.6
1488 // sending reviewedTaskId:"" or profile:""), which would otherwise be written
1489 // to team.json and then brick the whole team state on reload.
1490 const BLANK_SENSITIVE_STRING_FIELDS = ['objective', 'reviewedTaskId', 'sourceTaskId'];
1491 const BLANK_SENSITIVE_STRING_LIST_FIELDS = [
1492 'inScope',
1493 'outOfScope',
1494 'acceptance',
1495 'verify',
1496 'deliverables',
1497 'nonGoals',
1498 'changedPaths',
1499 'sourceFindingIds',
1500 'coverageOf',
1501 ];
1502 /**
1503 * Normalize blank optional task fields to omitted ("blank means absent").
1504 * Blank string scalars are deleted; string lists have blank entries filtered
1505 * out, and a list that only contained blanks is omitted entirely. Non-blank
1506 * values and every other field are passed through untouched, so durable-state
1507 * validation stays strict.
1508 */
1509 export function normalizeBlankOptionalTaskFields(task) {
1510 const next = { ...task };
1511 for (const key of BLANK_SENSITIVE_STRING_FIELDS) {
1512 const value = next[key];
1513 if (typeof value === 'string' && value.trim() === '')
1514 delete next[key];
1515 }
1516 for (const key of BLANK_SENSITIVE_STRING_LIST_FIELDS) {
1517 const value = next[key];
1518 if (!Array.isArray(value))
1519 continue;
1520 const kept = value.filter((item) => !(typeof item === 'string' && item.trim() === ''));
1521 if (kept.length === value.length)
1522 continue;
1523 if (kept.length === 0)
1524 delete next[key];
1525 else
1526 next[key] = kept;
1527 }
1528 return normalizeSentinelNumericTaskFields(next);
1529 }
1530 /**
1531 * Numeric task fields whose durable contract is a bounded range, paired with
1532 * their minimum (`Number.isSafeInteger` plus the lower bound). Some models
1533 * materialize "no value" as a numeric sentinel (`line: -1`, `round: 0`,
1534 * `reviewedAttempt: -1`) that the write side used to persist verbatim and the
1535 * durable validator then rejected — bricking the whole team on the next read
1536 * (issue #188, #105 class).
1537 */
1538 const SENTINEL_NUMERIC_TASK_FIELDS = [
1539 ['round', 1],
1540 ['reviewedAttempt', 0],
1541 ['attempt', 0],
1542 ];
1543 /**
1544 * Treat an out-of-contract **numeric** sentinel as absent, including
1545 * `findings[].line` (contract: `isValidFindingLine`).
1546 *
1547 * Only numbers are healed. A value of any other type (`round: "oops"`,
1548 * `attempt: {}`, `line: "12"`) is left exactly as written and stays a hard,
1549 * named validation failure, so genuine corruption is never silently swallowed
1550 * while `-1`-style sentinels — the #188 brick — self-heal. Field order, unknown
1551 * fields and every in-range value are preserved.
1552 */
1553 export function normalizeSentinelNumericTaskFields(task) {
1554 const next = { ...task };
1555 let changed = false;
1556 for (const [key, minimum] of SENTINEL_NUMERIC_TASK_FIELDS) {
1557 const value = next[key];
1558 if (typeof value !== 'number')
1559 continue;
1560 if (Number.isSafeInteger(value) && value >= minimum)
1561 continue;
1562 delete next[key];
1563 changed = true;
1564 }
1565 if (Array.isArray(next['findings'])) {
1566 let findingsChanged = false;
1567 const findings = next['findings'].map((finding) => {
1568 if (!isRecord(finding))
1569 return finding;
1570 const line = finding['line'];
1571 if (typeof line !== 'number' || isValidFindingLine(line))
1572 return finding;
1573 const cleaned = { ...finding };
1574 delete cleaned['line'];
1575 findingsChanged = true;
1576 return cleaned;
1577 });
1578 if (findingsChanged) {
1579 next['findings'] = findings;
1580 changed = true;
1581 }
1582 }
1583 return (changed ? next : task);
1584 }
1585 export function hasValidQualityTaskFields(value) {
1586 if (value['kind'] !== undefined && !TASK_KINDS.includes(value['kind']))
1587 return false;
1588 if (value['verdict'] !== undefined && !REVIEW_VERDICTS.includes(value['verdict']))
1589 return false;
1590 if (value['round'] !== undefined && !(Number.isSafeInteger(value['round']) && value['round'] >= 1))
1591 return false;
1592 if (value['objective'] !== undefined && !nonemptyString(value['objective']))
1593 return false;
1594 if (value['reviewedTaskId'] !== undefined && !nonemptyString(value['reviewedTaskId']))
1595 return false;
1596 if (value['sourceTaskId'] !== undefined && !nonemptyString(value['sourceTaskId']))
1597 return false;
1598 if (value['reviewedAttempt'] !== undefined && !(Number.isSafeInteger(value['reviewedAttempt']) && value['reviewedAttempt'] >= 0)) {
1599 return false;
1600 }
1601 const stringLists = ['inScope', 'outOfScope', 'acceptance', 'verify', 'deliverables', 'nonGoals', 'changedPaths', 'sourceFindingIds', 'findingSourceTaskIds', 'coverageOf'];
1602 for (const key of stringLists) {
1603 if (value[key] === undefined)
1604 continue;
1605 if (!Array.isArray(value[key]) || !value[key].every(nonemptyString))
1606 return false;
1607 }
1608 if (value['findings'] !== undefined) {
1609 if (!Array.isArray(value['findings']) || !value['findings'].every(isReviewFinding))
1610 return false;
1611 const ids = value['findings'].map((finding) => finding.id);
1612 if (new Set(ids).size !== ids.length)
1613 return false;
1614 }
1615 if (value['acceptanceResults'] !== undefined) {
1616 if (!Array.isArray(value['acceptanceResults']) || !value['acceptanceResults'].every(isAcceptanceResult))
1617 return false;
1618 }
1619 if (value['commandsRun'] !== undefined) {
1620 if (!Array.isArray(value['commandsRun']) || !value['commandsRun'].every(isCommandResult))
1621 return false;
1622 }
1623 if (value['supplementalEvidence'] !== undefined && (!Array.isArray(value['supplementalEvidence']) || !value['supplementalEvidence'].every(isTaskEvidence)))
1624 return false;
1625 if (value['revisions'] !== undefined) {
1626 if (!Array.isArray(value['revisions']) || !value['revisions'].every(isTaskRevision))
1627 return false;
1628 }
1629 if (value['reviewedArtifacts'] !== undefined
1630 && (!Array.isArray(value['reviewedArtifacts']) || !value['reviewedArtifacts'].every(isArtifactDigest)))
1631 return false;
1632 if (value['reviewedGaps'] !== undefined
1633 && (!Array.isArray(value['reviewedGaps']) || value['reviewedGaps'].length === 0 || !value['reviewedGaps'].every(isArtifactScopeGap)))
1634 return false;
1635 if (value['reviewedScope'] !== undefined && !nonemptyStringList(value['reviewedScope']))
1636 return false;
1637 if (value['reviewedDuringDrift'] !== undefined && !nonemptyStringList(value['reviewedDuringDrift']))
1638 return false;
1639 if (value['contractSnapshot'] !== undefined && !isArtifactSnapshot(value['contractSnapshot']))
1640 return false;
1641 if (value['verdictStartSnapshot'] !== undefined && !isArtifactSnapshot(value['verdictStartSnapshot']))
1642 return false;
1643 return true;
1644 }
1645 function isRecord(value) {
1646 return typeof value === 'object' && value !== null && !Array.isArray(value);
1647 }
1648 export function isTaskKind(value) {
1649 return typeof value === 'string' && TASK_KINDS.includes(value);
1650 }
1651 export function isReviewVerdict(value) {
1652 return typeof value === 'string' && REVIEW_VERDICTS.includes(value);
1653 }
1654 export function isFindingSeverity(value) {
1655 return typeof value === 'string' && FINDING_SEVERITIES.includes(value);
1656 }
1657 export function looksLikeGateTestContract(value) {
1658 return typeof value === 'string' && GATE_TEST_CONTRACT.test(value);
1659 }
1660 export function sanitizeReviewObjective(value, fallback = DEFAULT_REVIEW_OBJECTIVE) {
1661 if (!nonemptyString(value) || looksLikeGateTestContract(value))
1662 return fallback;
1663 return value.trim();
1664 }
1665 export function sanitizeReviewAcceptance(values) {
1666 const cleaned = (values ?? []).map((item) => item.trim()).filter((item) => item !== '' && !looksLikeGateTestContract(item));
1667 return cleaned.length > 0 ? cleaned : [...DEFAULT_REVIEW_ACCEPTANCE];
1668 }
1669 export function defaultQualityDeliveryGraph(input) {
1670 const goal = input.goal.trim() || 'the stated user goal';
1671 const analyst = input.analyst;
1672 const implementer = input.implementer;
1673 const tester = input.tester ?? input.implementer;
1674 const reviewer = input.reviewer;
1675 const integrator = input.integrator ?? input.reviewer;
1676 return [
1677 {
1678 subject: 'requirements-round-1',
1679 kind: 'requirements',
1680 assignee: analyst,
1681 dependencies: [],
1682 objective: `Converge requirements for: ${goal}`,
1683 acceptance: ['Open questions are closed or explicitly deferred', 'Acceptance criteria are testable'],
1684 coverageOf: [goal],
1685 },
1686 {
1687 subject: 'implementation',
1688 kind: 'implementation',
1689 assignee: implementer,
1690 dependencies: ['requirements-round-1'],
1691 objective: `Implement the approved requirements for: ${goal}`,
1692 acceptance: ['The implementation matches the approved requirements'],
1693 inScope: ['src/'],
1694 verify: ['pnpm test'],
1695 coverageOf: [goal],
1696 },
1697 {
1698 subject: 'verification',
1699 kind: 'verification',
1700 assignee: tester,
1701 dependencies: ['implementation'],
1702 objective: `Verify the implementation of: ${goal}`,
1703 acceptance: ['Declared verification commands pass'],
1704 coverageOf: [goal],
1705 },
1706 {
1707 subject: 'review-round-1',
1708 kind: 'review',
1709 assignee: reviewer,
1710 dependencies: ['verification'],
1711 objective: DEFAULT_REVIEW_OBJECTIVE,
1712 acceptance: [...DEFAULT_REVIEW_ACCEPTANCE],
1713 coverageOf: [goal],
1714 },
1715 {
1716 subject: 'integration',
1717 kind: 'integration',
1718 assignee: integrator,
1719 dependencies: ['review-round-1'],
1720 objective: `Confirm the team can declare delivery for: ${goal}`,
1721 acceptance: ['All required quality tasks are completed with passing reviews'],
1722 coverageOf: [goal],
1723 },
1724 ];
1725 }
1726 export function qualityPlanningPrompt() {
1727 return [
1728 'When the user explicitly requests full quality-mode planning, use this order unless a constraint forbids a stage: requirements → implementation → verification → review → integration.',
1729 'Build that entire DAG while the team is staged: an implementation may be created before requirements finishes when its dependency chain includes that requirements task. This is supported; do not wait for requirements to run and do not inspect plugin source to confirm it.',
1730 'A staged integration task may depend on review round 1. If that review later returns needs_revision, the system automatically rewires still-pending downstream dependencies to the generated repair + next-review gate, so keep integration in the original plan instead of omitting or manually recreating it.',
1731 'Derive inScope and verification commands from the actual workspace or explicit profile; never assume src/ or pnpm test.',
1732 'Give every quality task a contract. Review acceptance must judge the latest implementation, not whether the gate rejects needs_revision.',
1733 'Do not write smoke-test scripts into tasks. Do not ask reviewers to submit needs_revision on purpose.',
1734 'Do not claim implementation or review yourself unless the user asked the captain to take over.',
1735 'After a failed review, wait for the automatic repair + next review. Do not recreate that loop by hand.',
1736 'halted means the human stopped the team; call agent_teams_resume before creating more work. escalated means the automatic review loop hit its ceiling; that is not halt.',
1737 ].join(' ');
1738 }
1739 export function describeQualityLoop(team, audit = {}) {
1740 const delivery = canDeclareDelivery(team, audit);
1741 const warnings = [...delivery.warnings];
1742 if (team.halted === true) {
1743 return {
1744 state: 'halted',
1745 halted: true,
1746 escalated: team.escalated === true,
1747 deliverable: false,
1748 summary: 'Team is halted. Call agent_teams_resume with a reason before creating more work.',
1749 warnings,
1750 };
1751 }
1752 if (delivery.ok) {
1753 return {
1754 state: 'deliverable',
1755 halted: false,
1756 escalated: team.escalated === true,
1757 deliverable: true,
1758 summary: `All required work and quality gates passed. The captain may report delivery.${warnings.length === 0 ? '' : ` Warnings: ${warnings.join('; ')}`}`,
1759 warnings,
1760 };
1761 }
1762 if (team.escalated === true) {
1763 const unresolved = unresolvedGates(team);
1764 return {
1765 state: 'escalated',
1766 halted: false,
1767 escalated: true,
1768 deliverable: false,
1769 summary: `Automatic review/repair loop hit its ceiling. The team is still running; do not treat this as halt. Escalate to the user instead of inventing another needs_revision cycle.${unresolved.length === 0 ? '' : ` Genuinely unresolved gates: ${unresolved.map((item) => `${item.id} (${taskKindOf(item)})`).join(', ')}; any failed gate not listed here already has a follow-up repair.`}`,
1770 warnings,
1771 };
1772 }
1773 const open = team.tasks.some((item) => OPEN_STATUSES.includes(item.status));
1774 return {
1775 state: open ? 'running' : 'blocked',
1776 halted: false,
1777 escalated: false,
1778 deliverable: false,
1779 summary: open
1780 ? 'Work remains on the shared task list; wait for the scheduler or complete owned tasks.'
1781 : `Delivery is blocked: ${delivery.blockers.join('; ') || 'unresolved quality gates'}.${warnings.length === 0 ? '' : ` Warnings: ${warnings.join('; ')}`}`,
1782 warnings,
1783 };
1784 }
1785 export { QUALITY_KINDS, WRITE_KINDS };
1786 /** Persisted evidence must remain loadable after process restart. */
1787 export function isTaskEvidence(value) {
1788 if (!isRecord(value))
1789 return false;
1790 return typeof value['at'] === 'number' && Number.isFinite(value['at'])
1791 && nonemptyString(value['by']) && Number.isSafeInteger(value['attempt']) && value['attempt'] >= 0
1792 && (value['attemptId'] === undefined || nonemptyString(value['attemptId']))
1793 && (value['note'] === undefined || nonemptyString(value['note']))
1794 && (value['acceptanceResults'] === undefined || (Array.isArray(value['acceptanceResults']) && value['acceptanceResults'].every(isAcceptanceResult)))
1795 && (value['commandsRun'] === undefined || (Array.isArray(value['commandsRun']) && value['commandsRun'].every(isCommandResult)))
1796 && (value['note'] !== undefined || (Array.isArray(value['acceptanceResults']) && value['acceptanceResults'].length > 0) || (Array.isArray(value['commandsRun']) && value['commandsRun'].length > 0));
1797 }
1798 /** Append observations without mutating the original result or its completion time. */
1799 export function appendTaskEvidence(task, input, by) {
1800 if (!TERMINAL_TASK_STATUSES.includes(task.status))
1801 throw new Error('supplemental evidence requires a terminal task');
1802 // Key order must not turn a retried JSON object into a different observation.
1803 const stable = (value) => JSON.stringify(value, (_key, item) => typeof item === 'object' && item !== null && !Array.isArray(item)
1804 ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
1805 for (const key of ['status', 'output', 'verdict', 'findings', 'changedPaths']) {
1806 if (input[key] !== undefined && stable(input[key]) !== stable(task[key])) {
1807 throw new Error(`terminal task ${task.id} is immutable: cannot change ${key}; append evidence with evidence_note, acceptanceResults or commandsRun instead. Do not reclaim or redo completed work.`);
1808 }
1809 }
1810 const prior = (task.supplementalEvidence ?? []).filter(row => row.by === by && row.attempt === (task.attempt ?? 0) && row.attemptId === task.attemptId);
1811 const freshItems = (items, existing) => {
1812 const seen = new Set(existing.map(stable));
1813 return (items ?? []).filter(item => { const key = stable(item); if (seen.has(key))
1814 return false; seen.add(key); return true; });
1815 };
1816 const acceptanceResults = freshItems(input.acceptanceResults, [...task.acceptanceResults ?? [], ...prior.flatMap(row => row.acceptanceResults ?? [])]);
1817 const commandsRun = freshItems(input.commandsRun, [...task.commandsRun ?? [], ...prior.flatMap(row => row.commandsRun ?? [])]);
1818 const trimmed = input.evidence_note?.trim();
1819 const note = trimmed && !prior.some(row => row.note === trimmed) ? trimmed : undefined;
1820 if (!note && acceptanceResults.length === 0 && commandsRun.length === 0)
1821 return false;
1822 const entry = { at: Date.now(), by, attempt: task.attempt ?? 0,
1823 ...task.attemptId === undefined ? {} : { attemptId: task.attemptId },
1824 ...note === undefined ? {} : { note },
1825 ...acceptanceResults.length === 0 ? {} : { acceptanceResults },
1826 ...commandsRun.length === 0 ? {} : { commandsRun },
1827 };
1828 if (!isTaskEvidence(entry))
1829 throw new Error('invalid supplemental evidence');
1830 task.supplementalEvidence = [...task.supplementalEvidence ?? [], entry];
1831 return true;
1832 }
1833
1833 lines JAVASCRIPT