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