@abelxiaoxing/cadence 1.8.3 → 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.
Files changed (208) hide show
  1. package/README.md +324 -111
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/agents/design-explorer.md +14 -26
  4. package/agents/diagnosis-worker.md +14 -25
  5. package/agents/implementation-worker.md +16 -35
  6. package/config/.env.example +2 -5
  7. package/config/workflow-task.example.json +7 -0
  8. package/docs/remote-access.md +60 -0
  9. package/docs/reuse-and-distribution.md +44 -0
  10. package/docs/service-management.md +108 -0
  11. package/licenses/bundled-web.txt +6245 -0
  12. package/licenses/pi-web-ui-MIT.txt +21 -0
  13. package/licenses/pi-web-ui-reuse.md +22 -0
  14. package/package.json +94 -21
  15. package/src/index.ts +22 -1807
  16. package/src/native-build.ts +6 -0
  17. package/src/native-client.ts +103 -0
  18. package/src/native-export.ts +58 -0
  19. package/src/native-history.ts +359 -0
  20. package/src/operator-cli.mjs +453 -1937
  21. package/src/plan-proposal.ts +87 -0
  22. package/src/sdk-worker.mjs +549 -0
  23. package/src/service/contracts/active.ts +82 -0
  24. package/src/service/contracts/budget.ts +148 -0
  25. package/src/service/contracts/build.ts +67 -0
  26. package/src/service/contracts/capture.ts +48 -0
  27. package/src/service/contracts/core.ts +33 -0
  28. package/src/service/contracts/current.ts +261 -0
  29. package/src/service/contracts/domain.ts +68 -0
  30. package/src/service/contracts/history.ts +2245 -0
  31. package/src/service/contracts/models.ts +139 -0
  32. package/src/service/coordination.ts +862 -0
  33. package/src/service/private-files.ts +204 -0
  34. package/src/service-cli.mjs +5592 -0
  35. package/src/service-client.ts +747 -0
  36. package/src/service-contract.ts +245 -0
  37. package/src/service-host.mjs +22382 -0
  38. package/src/service-http-client.ts +425 -0
  39. package/src/service-wire.ts +372 -0
  40. package/src/task-shell.ts +1045 -0
  41. package/src/task-store.ts +479 -0
  42. package/src/task-types.ts +184 -0
  43. package/src/verification-diagnostics.ts +29 -72
  44. package/src/worker-capture.mjs +1197 -0
  45. package/src/worker-public.mjs +1753 -0
  46. package/src/worker-redaction.mjs +608 -0
  47. package/src/worker-tools.mjs +202 -0
  48. package/web/dist/assets/KaTeX_AMS-Regular.ttf +0 -0
  49. package/web/dist/assets/KaTeX_AMS-Regular.woff +0 -0
  50. package/web/dist/assets/KaTeX_AMS-Regular.woff2 +0 -0
  51. package/web/dist/assets/KaTeX_Caligraphic-Bold.ttf +0 -0
  52. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff +0 -0
  53. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff2 +0 -0
  54. package/web/dist/assets/KaTeX_Caligraphic-Regular.ttf +0 -0
  55. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff +0 -0
  56. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff2 +0 -0
  57. package/web/dist/assets/KaTeX_Fraktur-Bold.ttf +0 -0
  58. package/web/dist/assets/KaTeX_Fraktur-Bold.woff +0 -0
  59. package/web/dist/assets/KaTeX_Fraktur-Bold.woff2 +0 -0
  60. package/web/dist/assets/KaTeX_Fraktur-Regular.ttf +0 -0
  61. package/web/dist/assets/KaTeX_Fraktur-Regular.woff +0 -0
  62. package/web/dist/assets/KaTeX_Fraktur-Regular.woff2 +0 -0
  63. package/web/dist/assets/KaTeX_Main-Bold.ttf +0 -0
  64. package/web/dist/assets/KaTeX_Main-Bold.woff +0 -0
  65. package/web/dist/assets/KaTeX_Main-Bold.woff2 +0 -0
  66. package/web/dist/assets/KaTeX_Main-BoldItalic.ttf +0 -0
  67. package/web/dist/assets/KaTeX_Main-BoldItalic.woff +0 -0
  68. package/web/dist/assets/KaTeX_Main-BoldItalic.woff2 +0 -0
  69. package/web/dist/assets/KaTeX_Main-Italic.ttf +0 -0
  70. package/web/dist/assets/KaTeX_Main-Italic.woff +0 -0
  71. package/web/dist/assets/KaTeX_Main-Italic.woff2 +0 -0
  72. package/web/dist/assets/KaTeX_Main-Regular.ttf +0 -0
  73. package/web/dist/assets/KaTeX_Main-Regular.woff +0 -0
  74. package/web/dist/assets/KaTeX_Main-Regular.woff2 +0 -0
  75. package/web/dist/assets/KaTeX_Math-BoldItalic.ttf +0 -0
  76. package/web/dist/assets/KaTeX_Math-BoldItalic.woff +0 -0
  77. package/web/dist/assets/KaTeX_Math-BoldItalic.woff2 +0 -0
  78. package/web/dist/assets/KaTeX_Math-Italic.ttf +0 -0
  79. package/web/dist/assets/KaTeX_Math-Italic.woff +0 -0
  80. package/web/dist/assets/KaTeX_Math-Italic.woff2 +0 -0
  81. package/web/dist/assets/KaTeX_SansSerif-Bold.ttf +0 -0
  82. package/web/dist/assets/KaTeX_SansSerif-Bold.woff +0 -0
  83. package/web/dist/assets/KaTeX_SansSerif-Bold.woff2 +0 -0
  84. package/web/dist/assets/KaTeX_SansSerif-Italic.ttf +0 -0
  85. package/web/dist/assets/KaTeX_SansSerif-Italic.woff +0 -0
  86. package/web/dist/assets/KaTeX_SansSerif-Italic.woff2 +0 -0
  87. package/web/dist/assets/KaTeX_SansSerif-Regular.ttf +0 -0
  88. package/web/dist/assets/KaTeX_SansSerif-Regular.woff +0 -0
  89. package/web/dist/assets/KaTeX_SansSerif-Regular.woff2 +0 -0
  90. package/web/dist/assets/KaTeX_Script-Regular.ttf +0 -0
  91. package/web/dist/assets/KaTeX_Script-Regular.woff +0 -0
  92. package/web/dist/assets/KaTeX_Script-Regular.woff2 +0 -0
  93. package/web/dist/assets/KaTeX_Size1-Regular.ttf +0 -0
  94. package/web/dist/assets/KaTeX_Size1-Regular.woff +0 -0
  95. package/web/dist/assets/KaTeX_Size1-Regular.woff2 +0 -0
  96. package/web/dist/assets/KaTeX_Size2-Regular.ttf +0 -0
  97. package/web/dist/assets/KaTeX_Size2-Regular.woff +0 -0
  98. package/web/dist/assets/KaTeX_Size2-Regular.woff2 +0 -0
  99. package/web/dist/assets/KaTeX_Size3-Regular.ttf +0 -0
  100. package/web/dist/assets/KaTeX_Size3-Regular.woff +0 -0
  101. package/web/dist/assets/KaTeX_Size3-Regular.woff2 +0 -0
  102. package/web/dist/assets/KaTeX_Size4-Regular.ttf +0 -0
  103. package/web/dist/assets/KaTeX_Size4-Regular.woff +0 -0
  104. package/web/dist/assets/KaTeX_Size4-Regular.woff2 +0 -0
  105. package/web/dist/assets/KaTeX_Typewriter-Regular.ttf +0 -0
  106. package/web/dist/assets/KaTeX_Typewriter-Regular.woff +0 -0
  107. package/web/dist/assets/KaTeX_Typewriter-Regular.woff2 +0 -0
  108. package/web/dist/assets/cadence.css +2 -0
  109. package/web/dist/assets/cadence.js +7 -0
  110. package/web/dist/assets/markdown.js +296 -0
  111. package/web/dist/assets/react.js +9 -0
  112. package/web/dist/assets/rolldown-runtime.js +1 -0
  113. package/web/dist/assets/timeline-client.js +41 -0
  114. package/web/dist/assets/vis-timeline.css +1274 -0
  115. package/web/dist/assets/vis-timeline.js +32 -0
  116. package/web/dist/index.html +18 -0
  117. package/web/dist/manifest.json +505 -0
  118. package/config/plan-draft.example.json +0 -125
  119. package/config/plan-draft.multiple-tasks.example.json +0 -375
  120. package/config/plan-draft.quick.example.json +0 -78
  121. package/config/routes.example.json +0 -39
  122. package/prompts/abel-design.md +0 -382
  123. package/prompts/abel-diagnose.md +0 -71
  124. package/prompts/abel-implement.md +0 -284
  125. package/prompts/abel-init.md +0 -52
  126. package/src/activation.ts +0 -44
  127. package/src/activity-contracts.ts +0 -82
  128. package/src/agent-registry.ts +0 -53
  129. package/src/apply-transaction.ts +0 -1437
  130. package/src/artifact-store.ts +0 -213
  131. package/src/build-windows-job.mjs +0 -95
  132. package/src/candidate-artifact.ts +0 -143
  133. package/src/candidate-patch.ts +0 -271
  134. package/src/candidate-workspace.ts +0 -80
  135. package/src/canonical.ts +0 -16
  136. package/src/change-contract-schema.ts +0 -191
  137. package/src/change-contract.ts +0 -324
  138. package/src/change-verification.ts +0 -1617
  139. package/src/child-budget.ts +0 -58
  140. package/src/child-model.ts +0 -142
  141. package/src/child-session.ts +0 -640
  142. package/src/contracts.ts +0 -2476
  143. package/src/control-contracts.ts +0 -382
  144. package/src/delivery-compiler.ts +0 -1805
  145. package/src/delivery-revision.ts +0 -42
  146. package/src/design-control.ts +0 -1299
  147. package/src/design-diagnostics.ts +0 -181
  148. package/src/design-journal.ts +0 -1773
  149. package/src/directory-sync.ts +0 -36
  150. package/src/durable-contracts.ts +0 -231
  151. package/src/durable-workflow.ts +0 -978
  152. package/src/evidence-draft.ts +0 -122
  153. package/src/execution-profile.ts +0 -64
  154. package/src/execution-retention.ts +0 -77
  155. package/src/file-snapshot.ts +0 -163
  156. package/src/implement-continuation.ts +0 -559
  157. package/src/implement-graph.ts +0 -690
  158. package/src/implement-plan.ts +0 -72
  159. package/src/install-config.d.mts +0 -6
  160. package/src/isolation-backend.ts +0 -353
  161. package/src/model-source.ts +0 -22
  162. package/src/openspec-cli.ts +0 -494
  163. package/src/operator-cli-entry.mjs +0 -24
  164. package/src/operator-tools.ts +0 -309
  165. package/src/package-candidate.ts +0 -227
  166. package/src/package-delivery.ts +0 -486
  167. package/src/package-state.ts +0 -320
  168. package/src/package-verification.ts +0 -635
  169. package/src/package-workflow.ts +0 -342
  170. package/src/packet-runtime.ts +0 -570
  171. package/src/parent-provider.ts +0 -375
  172. package/src/phase-execution.ts +0 -2259
  173. package/src/pi-adapter.ts +0 -19
  174. package/src/plan-draft-summary.ts +0 -527
  175. package/src/plan-draft.ts +0 -502
  176. package/src/remove-path.ts +0 -32
  177. package/src/route-policy.ts +0 -545
  178. package/src/run-state.ts +0 -420
  179. package/src/run-store.ts +0 -1179
  180. package/src/safe-path.ts +0 -77
  181. package/src/scoped-grep-worker.mjs +0 -23
  182. package/src/scoped-tools.ts +0 -775
  183. package/src/single-task-draft.ts +0 -142
  184. package/src/sqlite-schema.ts +0 -171
  185. package/src/state-root.ts +0 -215
  186. package/src/storage-schema.ts +0 -360
  187. package/src/subagent-activity.ts +0 -1417
  188. package/src/submit-tool.ts +0 -950
  189. package/src/task-ledger.ts +0 -1338
  190. package/src/transport-budget.ts +0 -52
  191. package/src/verification-capability.ts +0 -1191
  192. package/src/verification-environment-io.ts +0 -389
  193. package/src/verification-environment.ts +0 -162
  194. package/src/verification-identity.ts +0 -77
  195. package/src/verification-scan.ts +0 -64
  196. package/src/windows-job-backend.ts +0 -419
  197. package/src/windows-job.c +0 -149
  198. package/src/worker-broker.ts +0 -806
  199. package/src/workflow-engine.ts +0 -28
  200. package/src/workflow-policy.ts +0 -1679
  201. package/src/workflow-recovery-policy.ts +0 -97
  202. package/src/workflow-scheduling.ts +0 -105
  203. package/src/workflow-state-machine.ts +0 -4355
  204. package/src/workflow-status.ts +0 -576
  205. package/src/workspace-io-entry.mjs +0 -76
  206. package/src/workspace-io-worker.mjs +0 -1312
  207. package/src/workspace-io.ts +0 -89
  208. package/src/workspace-store.ts +0 -634
@@ -1,950 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { defineTool } from "@earendil-works/pi-coding-agent";
3
- import { Type } from "typebox";
4
- import {
5
- type CandidatePatchOperation,
6
- compileCandidatePatch,
7
- } from "./candidate-patch.ts";
8
- import {
9
- type CandidateFailure,
10
- type DiffResult,
11
- type EvidenceResult,
12
- isAgentsPath,
13
- isValidRelativePath,
14
- LIMITS,
15
- type SubmitFinalCategory,
16
- type SubmitSchemaState,
17
- validateDiffResult,
18
- validateEvidenceResult,
19
- } from "./contracts.ts";
20
- import {
21
- completeEvidenceDraft,
22
- evidenceDraftSchema,
23
- } from "./evidence-draft.ts";
24
- import {
25
- type BeginCandidateInput,
26
- TASK_LEDGER_LIMITS,
27
- type TaskLedger,
28
- } from "./task-ledger.ts";
29
-
30
- const diffSchema = Type.Object({
31
- id: Type.String(),
32
- role: Type.String(),
33
- kind: Type.Literal("diff"),
34
- taskId: Type.String(),
35
- phase: Type.String(),
36
- summary: Type.String(),
37
- diff: Type.String(),
38
- expectedVerification: Type.String(),
39
- risks: Type.Array(Type.String()),
40
- contractCompliant: Type.Literal(true),
41
- });
42
-
43
- function candidateArtifactSchema(candidateId: string) {
44
- return Type.Union([
45
- Type.Object(
46
- {
47
- kind: Type.Literal("candidate-patch"),
48
- candidateId: Type.Literal(candidateId),
49
- operations: Type.Array(
50
- Type.Union([
51
- Type.Object(
52
- {
53
- kind: Type.Literal("replace"),
54
- path: Type.String(),
55
- oldText: Type.String({ minLength: 1 }),
56
- newText: Type.String(),
57
- },
58
- { additionalProperties: false },
59
- ),
60
- Type.Object(
61
- {
62
- kind: Type.Literal("rewrite"),
63
- path: Type.String(),
64
- content: Type.String(),
65
- },
66
- { additionalProperties: false },
67
- ),
68
- Type.Object(
69
- {
70
- kind: Type.Literal("create"),
71
- path: Type.String(),
72
- content: Type.String({ minLength: 1 }),
73
- mode: Type.Union([
74
- Type.Literal("regular"),
75
- Type.Literal("executable"),
76
- ]),
77
- },
78
- { additionalProperties: false },
79
- ),
80
- Type.Object(
81
- {
82
- kind: Type.Literal("delete"),
83
- path: Type.String(),
84
- },
85
- { additionalProperties: false },
86
- ),
87
- ]),
88
- { minItems: 1, maxItems: 128 },
89
- ),
90
- },
91
- { additionalProperties: false },
92
- ),
93
- Type.Object(
94
- {
95
- kind: Type.Literal("context-request"),
96
- candidateId: Type.Literal(candidateId),
97
- code: Type.Union([
98
- Type.Literal("approved-context-needed"),
99
- Type.Literal("task-split-needed"),
100
- ]),
101
- refs: Type.Array(
102
- Type.Union([
103
- Type.String(),
104
- Type.Object(
105
- {
106
- kind: Type.Literal("requested-path"),
107
- path: Type.String(),
108
- access: Type.Union([
109
- Type.Literal("read"),
110
- Type.Literal("write"),
111
- ]),
112
- },
113
- { additionalProperties: false },
114
- ),
115
- Type.Object(
116
- {
117
- kind: Type.Literal("source-citation"),
118
- path: Type.String(),
119
- line: Type.Integer({ minimum: 1 }),
120
- },
121
- { additionalProperties: false },
122
- ),
123
- Type.Object(
124
- {
125
- kind: Type.Literal("contract-diagnostic"),
126
- ref: Type.String(),
127
- },
128
- { additionalProperties: false },
129
- ),
130
- ]),
131
- { minItems: 1, maxItems: 32 },
132
- ),
133
- },
134
- { additionalProperties: false },
135
- ),
136
- ]);
137
- }
138
-
139
- export type CandidateContextRequestCode =
140
- | "approved-context-needed"
141
- | "task-split-needed"
142
- | "boundary-review-needed";
143
-
144
- export type CandidateContextRef =
145
- | { kind: "requested-path"; path: string; access: "read" | "write" }
146
- | { kind: "source-citation"; path: string; line: number }
147
- | { kind: "contract-diagnostic"; ref: string };
148
-
149
- export type CandidateContextRefInput = string | CandidateContextRef;
150
-
151
- export type CandidateArtifactSubmissionResult =
152
- | {
153
- kind: "sealed-candidate";
154
- candidateId: string;
155
- state: "sealed";
156
- artifactHash: string;
157
- bytes: number;
158
- paths: string[];
159
- replayed?: true;
160
- }
161
- | {
162
- kind: "context-request";
163
- candidateId: string;
164
- code: CandidateContextRequestCode;
165
- refs: CandidateContextRef[];
166
- };
167
-
168
- export type CandidateContextRequest = Extract<
169
- CandidateArtifactSubmissionResult,
170
- { kind: "context-request" }
171
- >;
172
-
173
- export interface CandidateContextBoundary {
174
- phase: "red" | "green" | "refactor";
175
- readPaths: readonly string[];
176
- writePaths: readonly string[];
177
- deletePaths?: readonly string[];
178
- taskPaths: readonly string[];
179
- contextReadRoots?: readonly string[];
180
- redWritePaths: readonly string[];
181
- agents: {
182
- impact: "none" | "update-existing" | "create-index" | "remove-index";
183
- target?: string;
184
- };
185
- }
186
-
187
- export interface ClassifiedCandidateContextRequest {
188
- kind: "paused" | "retryable" | "approval-needed";
189
- code:
190
- | "approved-context-needed"
191
- | "task-split-needed"
192
- | "boundary-review-needed"
193
- | "red-artifact-constraint"
194
- | "agents-context-needed"
195
- | "agents-write-parent-owned"
196
- | "agents-contract-insufficient";
197
- contextRequest: {
198
- code: CandidateContextRequestCode;
199
- refs: CandidateContextRef[];
200
- };
201
- }
202
-
203
- const LEGACY_CITATION = /^(.*):(\d+)$/u;
204
- const LEGACY_DIAGNOSTIC =
205
- /^(?:phase-contract|task-contract|sealed-contract|workflow-contract)\.[a-z0-9._-]+$/iu;
206
-
207
- function validDiagnosticRef(value: unknown): value is string {
208
- return (
209
- typeof value === "string" &&
210
- value.length > 0 &&
211
- value.length <= 512 &&
212
- value.trim() === value &&
213
- !/[\r\n\0]/u.test(value)
214
- );
215
- }
216
-
217
- function normalizeCandidateContextRef(
218
- input: CandidateContextRefInput,
219
- ): CandidateContextRef {
220
- if (typeof input === "string") {
221
- const citation = LEGACY_CITATION.exec(input);
222
- if (citation && isValidRelativePath(citation[1])) {
223
- const line = Number(citation[2]);
224
- if (Number.isSafeInteger(line) && line >= 1) {
225
- return { kind: "source-citation", path: citation[1], line };
226
- }
227
- }
228
- if (LEGACY_DIAGNOSTIC.test(input)) {
229
- return { kind: "contract-diagnostic", ref: input };
230
- }
231
- if (!isValidRelativePath(input)) {
232
- throw new Error("context request refs are invalid");
233
- }
234
- return { kind: "requested-path", path: input, access: "read" };
235
- }
236
- if (!input || typeof input !== "object" || Array.isArray(input)) {
237
- throw new Error("context request refs are invalid");
238
- }
239
- if (
240
- input.kind === "requested-path" &&
241
- Object.keys(input).length === 3 &&
242
- isValidRelativePath(input.path) &&
243
- (input.access === "read" || input.access === "write")
244
- ) {
245
- return { ...input };
246
- }
247
- if (
248
- input.kind === "source-citation" &&
249
- Object.keys(input).length === 3 &&
250
- isValidRelativePath(input.path) &&
251
- Number.isSafeInteger(input.line) &&
252
- input.line >= 1
253
- ) {
254
- return { ...input };
255
- }
256
- if (
257
- input.kind === "contract-diagnostic" &&
258
- Object.keys(input).length === 2 &&
259
- validDiagnosticRef(input.ref)
260
- ) {
261
- return { ...input };
262
- }
263
- throw new Error("context request refs are invalid");
264
- }
265
-
266
- export function normalizeCandidateContextRefs(
267
- value: unknown,
268
- ): CandidateContextRef[] {
269
- if (!Array.isArray(value) || value.length === 0 || value.length > 32) {
270
- throw new Error("context request refs are invalid");
271
- }
272
- const refs = value.map((entry) =>
273
- normalizeCandidateContextRef(entry as CandidateContextRefInput),
274
- );
275
- const identities = refs.map((ref) => JSON.stringify(ref));
276
- if (new Set(identities).size !== refs.length) {
277
- throw new Error("context request refs are invalid");
278
- }
279
- return refs;
280
- }
281
-
282
- function contextRefWithinBoundary(relative: string, approved: string): boolean {
283
- return (
284
- approved === "." ||
285
- relative === approved ||
286
- relative.startsWith(`${approved}/`)
287
- );
288
- }
289
-
290
- function normalizedBoundary(
291
- boundary: readonly string[] | CandidateContextBoundary,
292
- ): CandidateContextBoundary {
293
- if (!Array.isArray(boundary)) return boundary as CandidateContextBoundary;
294
- return {
295
- phase: "green",
296
- readPaths: boundary,
297
- writePaths: [],
298
- deletePaths: [],
299
- taskPaths: boundary,
300
- redWritePaths: [],
301
- agents: { impact: "none" },
302
- };
303
- }
304
-
305
- function pathWithinAny(relative: string, approved: readonly string[]): boolean {
306
- return approved.some((path) => contextRefWithinBoundary(relative, path));
307
- }
308
-
309
- export function permitsContextRead(
310
- relative: string,
311
- roots: readonly string[],
312
- ): boolean {
313
- // Dynamic discovery never grants hidden credentials or a directory tree.
314
- return (
315
- isValidRelativePath(relative) &&
316
- relative.split("/").every((part) => !part.startsWith(".")) &&
317
- !/\.(?:pem|key|p12|pfx)$/iu.test(relative) &&
318
- pathWithinAny(relative, roots)
319
- );
320
- }
321
-
322
- export function classifyCandidateContextRequest(
323
- request: {
324
- kind: "context-request";
325
- candidateId: string;
326
- code: CandidateContextRequestCode;
327
- refs: readonly CandidateContextRefInput[];
328
- },
329
- inputBoundary: readonly string[] | CandidateContextBoundary,
330
- ): ClassifiedCandidateContextRequest {
331
- const refs = normalizeCandidateContextRefs(request.refs);
332
- const boundary = normalizedBoundary(inputBoundary);
333
- const phasePaths = [
334
- ...boundary.readPaths,
335
- ...boundary.writePaths,
336
- ...(boundary.deletePaths ?? []),
337
- ];
338
- const requested = refs.filter(
339
- (ref): ref is Extract<CandidateContextRef, { kind: "requested-path" }> =>
340
- ref.kind === "requested-path",
341
- );
342
- const ordinaryRequested = requested.filter((ref) => !isAgentsPath(ref.path));
343
- const outsideOrdinary = ordinaryRequested.filter(
344
- (ref) =>
345
- !(
346
- ref.access === "read" &&
347
- permitsContextRead(ref.path, boundary.contextReadRoots ?? [])
348
- ) &&
349
- !pathWithinAny(
350
- ref.path,
351
- ref.access === "write"
352
- ? [...boundary.writePaths, ...(boundary.deletePaths ?? [])]
353
- : [...phasePaths, ...boundary.taskPaths],
354
- ),
355
- );
356
- const agentsRequested = requested.filter((ref) => isAgentsPath(ref.path));
357
- const agentsWrites = agentsRequested.filter((ref) => ref.access === "write");
358
- const citedRedArtifacts = refs.filter(
359
- (ref): ref is Extract<CandidateContextRef, { kind: "source-citation" }> =>
360
- ref.kind === "source-citation" &&
361
- pathWithinAny(ref.path, boundary.redWritePaths) &&
362
- !pathWithinAny(ref.path, [
363
- ...boundary.writePaths,
364
- ...(boundary.deletePaths ?? []),
365
- ]),
366
- );
367
- const requestedRedArtifacts = outsideOrdinary.filter(
368
- (ref) =>
369
- pathWithinAny(ref.path, boundary.redWritePaths) &&
370
- pathWithinAny(ref.path, boundary.taskPaths),
371
- );
372
- const redArtifactConstraint =
373
- boundary.phase === "green" &&
374
- (citedRedArtifacts.length > 0 || requestedRedArtifacts.length > 0) &&
375
- outsideOrdinary.every((ref) => requestedRedArtifacts.includes(ref)) &&
376
- agentsRequested.every((ref) => ref.access === "read");
377
-
378
- let classification: Pick<ClassifiedCandidateContextRequest, "kind" | "code">;
379
- if (outsideOrdinary.length > 0 && !redArtifactConstraint) {
380
- classification = {
381
- kind: "approval-needed",
382
- code: "boundary-review-needed",
383
- };
384
- } else if (agentsWrites.length > 0) {
385
- const targetMismatch = agentsWrites.some(
386
- (ref) =>
387
- boundary.agents.impact === "none" ||
388
- boundary.agents.target === undefined ||
389
- ref.path !== boundary.agents.target,
390
- );
391
- classification = targetMismatch
392
- ? { kind: "approval-needed", code: "agents-contract-insufficient" }
393
- : { kind: "paused", code: "agents-write-parent-owned" };
394
- } else if (redArtifactConstraint) {
395
- classification = { kind: "retryable", code: "red-artifact-constraint" };
396
- } else if (agentsRequested.length > 0) {
397
- classification = { kind: "paused", code: "agents-context-needed" };
398
- } else {
399
- classification = {
400
- kind: "retryable",
401
- code:
402
- request.code === "task-split-needed"
403
- ? "task-split-needed"
404
- : "approved-context-needed",
405
- };
406
- }
407
- return {
408
- ...classification,
409
- contextRequest: {
410
- code: request.code,
411
- refs,
412
- },
413
- };
414
- }
415
-
416
- export interface CandidateArtifactSubmission {
417
- ledger: Pick<
418
- TaskLedger,
419
- "beginCandidate" | "appendCandidateSegment" | "sealCandidate"
420
- >;
421
- identity: BeginCandidateInput;
422
- workspaceRoot: string;
423
- writePaths: readonly string[];
424
- deletePaths: readonly string[];
425
- }
426
-
427
- export function createCandidateArtifactTool(
428
- input: CandidateArtifactSubmission,
429
- ) {
430
- input.ledger.beginCandidate(input.identity);
431
- const parameters = candidateArtifactSchema(input.identity.candidateId);
432
- let result: CandidateArtifactSubmissionResult | undefined;
433
- let failure: CandidateFailure | undefined;
434
- let attempts = 0;
435
- let schema: SubmitSchemaState = "not-submitted";
436
- let identity: IdentityOutcome = {
437
- request: true,
438
- role: true,
439
- task: true,
440
- phase: true,
441
- };
442
- const tool = defineTool<typeof parameters, unknown>({
443
- name: "abel_submit_result",
444
- label: "Submit Abel Candidate Artifact",
445
- description:
446
- "Submit one complete structured candidate patch or request bounded approved context. Diff generation, chunking, encoding, hashes, and atomic sealing are owned by this trusted tool.",
447
- executionMode: "sequential",
448
- parameters,
449
- async execute(_toolCallId, params) {
450
- attempts++;
451
- if (result !== undefined) {
452
- schema = "invalid";
453
- failure = {
454
- kind: "artifact",
455
- code: "invalid-structural-result",
456
- stage: "structural-submit",
457
- };
458
- throw new Error("candidate terminal result already submitted");
459
- }
460
- if (attempts > 2) {
461
- schema = "invalid";
462
- failure = {
463
- kind: "artifact",
464
- code: "invalid-structural-result",
465
- stage: "structural-submit",
466
- };
467
- throw new Error("structural submission correction limit exceeded");
468
- }
469
- identity = {
470
- request: true,
471
- role: true,
472
- task: true,
473
- phase: true,
474
- };
475
- failure = undefined;
476
- const value = params as unknown as Record<string, unknown>;
477
- if (value.candidateId !== input.identity.candidateId) {
478
- identity.request = false;
479
- schema = "invalid";
480
- failure = {
481
- kind: "artifact",
482
- code: "structural-identity-mismatch",
483
- stage: "structural-submit",
484
- };
485
- throw new Error("candidate identity mismatch");
486
- }
487
- schema = "valid";
488
- if (value.kind === "candidate-patch") {
489
- let diff: string;
490
- try {
491
- diff = compileCandidatePatch({
492
- root: input.workspaceRoot,
493
- writePaths: input.writePaths,
494
- deletePaths: input.deletePaths,
495
- operations: value.operations as CandidatePatchOperation[],
496
- maxBytes: TASK_LEDGER_LIMITS.maxCandidateBytes,
497
- });
498
- } catch (error) {
499
- schema = "invalid";
500
- failure = {
501
- kind: "artifact",
502
- code: "invalid-diff",
503
- stage: "candidate-diff",
504
- };
505
- throw error;
506
- }
507
- const bytes = Buffer.from(diff, "utf8");
508
- const candidateHash = createHash("sha256").update(bytes).digest("hex");
509
- let sequence = 0;
510
- for (
511
- let offset = 0;
512
- offset < bytes.length;
513
- offset += TASK_LEDGER_LIMITS.maxSegmentBytes
514
- ) {
515
- const segment = bytes.subarray(
516
- offset,
517
- Math.min(offset + TASK_LEDGER_LIMITS.maxSegmentBytes, bytes.length),
518
- );
519
- let accepted: ReturnType<
520
- CandidateArtifactSubmission["ledger"]["appendCandidateSegment"]
521
- >;
522
- try {
523
- accepted = input.ledger.appendCandidateSegment({
524
- ...input.identity,
525
- sequence,
526
- bytes: segment,
527
- segmentHash: createHash("sha256").update(segment).digest("hex"),
528
- });
529
- } catch (error) {
530
- schema = "invalid";
531
- failure = {
532
- kind: "artifact",
533
- code: "invalid-diff",
534
- stage: "candidate-diff",
535
- };
536
- throw error;
537
- }
538
- if (!accepted.ok) {
539
- failure = {
540
- kind: "result-limit",
541
- limitBytes: accepted.limitBytes,
542
- };
543
- return {
544
- content: [],
545
- details: accepted,
546
- terminate: true,
547
- };
548
- }
549
- sequence = accepted.nextSequence;
550
- }
551
- let sealed: ReturnType<
552
- CandidateArtifactSubmission["ledger"]["sealCandidate"]
553
- >;
554
- try {
555
- sealed = input.ledger.sealCandidate({
556
- ...input.identity,
557
- segmentCount: sequence,
558
- totalBytes: bytes.length,
559
- candidateHash,
560
- });
561
- } catch (error) {
562
- schema = "invalid";
563
- const mismatch =
564
- error instanceof Error &&
565
- error.message === "candidate-write-set-mismatch";
566
- failure = {
567
- kind: "artifact",
568
- code: mismatch ? "write-set-mismatch" : "invalid-diff",
569
- stage: "candidate-diff",
570
- };
571
- throw error;
572
- }
573
- if (!sealed.ok) return { content: [], details: sealed };
574
- result = {
575
- kind: "sealed-candidate",
576
- candidateId: input.identity.candidateId,
577
- state: "sealed",
578
- artifactHash: sealed.artifactHash,
579
- bytes: sealed.bytes,
580
- paths: [...sealed.paths],
581
- ...(sealed.replayed ? { replayed: true } : {}),
582
- };
583
- return {
584
- content: [
585
- { type: "text" as const, text: "Candidate artifact sealed." },
586
- ],
587
- details: sealed,
588
- terminate: true,
589
- };
590
- }
591
- let refs: CandidateContextRef[];
592
- try {
593
- refs = normalizeCandidateContextRefs(value.refs);
594
- } catch (error) {
595
- schema = "invalid";
596
- failure = {
597
- kind: "artifact",
598
- code: "invalid-structural-result",
599
- stage: "structural-submit",
600
- };
601
- throw error;
602
- }
603
- result = {
604
- kind: "context-request",
605
- candidateId: input.identity.candidateId,
606
- code: value.code as Extract<
607
- CandidateArtifactSubmissionResult,
608
- { kind: "context-request" }
609
- >["code"],
610
- refs,
611
- };
612
- return {
613
- content: [
614
- { type: "text" as const, text: "Bounded context request accepted." },
615
- ],
616
- details: result,
617
- terminate: true,
618
- };
619
- },
620
- });
621
- return {
622
- tool,
623
- getResult: () =>
624
- result === undefined ? undefined : structuredClone(result),
625
- getAttempts: () => attempts,
626
- getSchema: () => schema,
627
- getIdentity: () => ({ ...identity }),
628
- getFailure: () =>
629
- failure === undefined ? undefined : structuredClone(failure),
630
- };
631
- }
632
-
633
- export function createStructuredPatchTool(input: {
634
- requestId: string;
635
- taskId?: string;
636
- role: string;
637
- phase: string;
638
- workspaceRoot: string;
639
- writePaths: string[];
640
- deletePaths: string[];
641
- }) {
642
- let submitted: DiffResult | CandidateContextRequest | undefined;
643
- let failure: CandidateFailure | undefined;
644
- let attempts = 0;
645
- let schema: SubmitSchemaState = "not-submitted";
646
- let identity: IdentityOutcome = {
647
- request: true,
648
- role: true,
649
- task: true,
650
- phase: true,
651
- };
652
- const candidateId = input.requestId;
653
- const tool = defineTool({
654
- name: "abel_submit_result",
655
- label: "Submit Abel Structured Patch",
656
- description:
657
- "Submit one complete structured patch. Unified-diff headers and hunks are generated by the trusted control plane.",
658
- executionMode: "sequential",
659
- parameters: candidateArtifactSchema(candidateId),
660
- async execute(_toolCallId, params) {
661
- attempts += 1;
662
- if (submitted !== undefined) {
663
- schema = "invalid";
664
- failure = {
665
- kind: "artifact",
666
- code: "invalid-structural-result",
667
- stage: "structural-submit",
668
- };
669
- throw new Error("structured patch terminal result already submitted");
670
- }
671
- if (attempts > 2) {
672
- schema = "invalid";
673
- failure = {
674
- kind: "artifact",
675
- code: "invalid-structural-result",
676
- stage: "structural-submit",
677
- };
678
- throw new Error("structural submission correction limit exceeded");
679
- }
680
- identity = {
681
- request: true,
682
- role: true,
683
- task: true,
684
- phase: true,
685
- };
686
- failure = undefined;
687
- const value = params as unknown as Record<string, unknown>;
688
- if (value.candidateId !== candidateId) {
689
- identity.request = false;
690
- schema = "invalid";
691
- failure = {
692
- kind: "artifact",
693
- code: "structural-identity-mismatch",
694
- stage: "structural-submit",
695
- };
696
- throw new Error("diagnosis candidate identity mismatch");
697
- }
698
- if (value.kind === "context-request") {
699
- let refs: CandidateContextRef[];
700
- try {
701
- refs = normalizeCandidateContextRefs(value.refs);
702
- } catch (error) {
703
- schema = "invalid";
704
- failure = {
705
- kind: "artifact",
706
- code: "invalid-structural-result",
707
- stage: "structural-submit",
708
- };
709
- throw error;
710
- }
711
- submitted = {
712
- kind: "context-request",
713
- candidateId,
714
- code: value.code as CandidateContextRequest["code"],
715
- refs,
716
- };
717
- schema = "valid";
718
- return {
719
- content: [
720
- { type: "text" as const, text: "Context request accepted." },
721
- ],
722
- details: { accepted: true },
723
- terminate: true,
724
- };
725
- }
726
- if (value.kind !== "candidate-patch") {
727
- schema = "invalid";
728
- failure = {
729
- kind: "artifact",
730
- code: "invalid-structural-result",
731
- stage: "structural-submit",
732
- };
733
- throw new Error("diagnosis result must be a patch or context request");
734
- }
735
- let compiled: ReturnType<typeof compileCandidatePatch>;
736
- try {
737
- compiled = compileCandidatePatch({
738
- root: input.workspaceRoot,
739
- operations: value.operations as CandidatePatchOperation[],
740
- writePaths: input.writePaths,
741
- deletePaths: input.deletePaths,
742
- maxBytes: LIMITS.maxCompleteResultBytes,
743
- });
744
- } catch (error) {
745
- schema = "invalid";
746
- failure = {
747
- kind: "artifact",
748
- code: "invalid-diff",
749
- stage: "candidate-diff",
750
- };
751
- throw error;
752
- }
753
- const result: DiffResult = {
754
- id: input.requestId,
755
- role: input.role,
756
- kind: "diff",
757
- taskId: input.taskId ?? input.requestId,
758
- phase: input.phase,
759
- summary:
760
- "Trusted control plane generated this diff from structured operations.",
761
- diff: compiled,
762
- expectedVerification: "parent-owned verification contract",
763
- risks: [],
764
- contractCompliant: true,
765
- };
766
- const validation = validateDiffResult(result);
767
- if (!validation.ok) {
768
- schema = "invalid";
769
- failure = validation.failure ?? {
770
- kind: "artifact",
771
- code: "invalid-structural-result",
772
- stage: "structural-submit",
773
- };
774
- throw new Error(validation.reason ?? "structured patch is invalid");
775
- }
776
- submitted = result;
777
- schema = "valid";
778
- return {
779
- content: [{ type: "text" as const, text: "Abel patch accepted." }],
780
- details: { accepted: true },
781
- terminate: true,
782
- };
783
- },
784
- });
785
- return {
786
- tool,
787
- getResult: () =>
788
- submitted === undefined ? undefined : structuredClone(submitted),
789
- getAttempts: () => attempts,
790
- getSchema: () => schema,
791
- getIdentity: () => ({ ...identity }),
792
- getFailure: () =>
793
- failure === undefined ? undefined : structuredClone(failure),
794
- };
795
- }
796
-
797
- export type FinalCategory = SubmitFinalCategory;
798
-
799
- export interface IdentityOutcome {
800
- request: boolean;
801
- role: boolean;
802
- task: boolean;
803
- phase: boolean;
804
- }
805
-
806
- export interface SubmitClassification {
807
- finalCategory: FinalCategory;
808
- attempts: number;
809
- schema: SubmitSchemaState;
810
- identity: IdentityOutcome;
811
- }
812
-
813
- export function createSubmitTool(input: {
814
- requestId: string;
815
- taskId?: string;
816
- role: string;
817
- phase: string;
818
- output: "evidence" | "diff";
819
- }) {
820
- let submitted: EvidenceResult | DiffResult | undefined;
821
- let failure: CandidateFailure | undefined;
822
- let attempts = 0;
823
- let schema: SubmitSchemaState = "not-submitted";
824
- let identity: IdentityOutcome = {
825
- request: true,
826
- role: true,
827
- task: true,
828
- phase: true,
829
- };
830
-
831
- const tool = defineTool({
832
- name: "abel_submit_result",
833
- label: "Submit Abel Result",
834
- description:
835
- "Submit one accepted final result. Evidence identity and omitted advisory fields are completed by this tool; keep citations, constraints, risks, and open questions explicit. After a rejection, correct once in this same session. Brief accompanying text is harmless.",
836
- executionMode: "sequential",
837
- parameters:
838
- input.output === "evidence"
839
- ? evidenceDraftSchema(input.requestId, input.role)
840
- : diffSchema,
841
- async execute(_toolCallId, params) {
842
- attempts++;
843
- if (submitted !== undefined) {
844
- schema = "invalid";
845
- failure = {
846
- kind: "artifact",
847
- code: "invalid-structural-result",
848
- stage: "structural-submit",
849
- };
850
- throw new Error("duplicate structural submission");
851
- }
852
- if (attempts > 2) {
853
- schema = "invalid";
854
- failure = {
855
- kind: "artifact",
856
- code: "invalid-structural-result",
857
- stage: "structural-submit",
858
- };
859
- throw new Error("structural submission correction limit exceeded");
860
- }
861
- identity = {
862
- request: true,
863
- role: true,
864
- task: true,
865
- phase: true,
866
- };
867
- failure = undefined;
868
- const value = (
869
- input.output === "evidence"
870
- ? completeEvidenceDraft(params, input.requestId, input.role)
871
- : params
872
- ) as Record<string, unknown>;
873
- if (value === null || typeof value !== "object") {
874
- identity.request = false;
875
- identity.role = false;
876
- identity.task = false;
877
- identity.phase = false;
878
- schema = "invalid";
879
- failure = {
880
- kind: "artifact",
881
- code: "invalid-structural-result",
882
- stage: "structural-submit",
883
- };
884
- throw new Error("submitted result is not an object");
885
- }
886
- if (value.id !== input.requestId) identity.request = false;
887
- if (
888
- input.role === "design-explorer" &&
889
- value.packet_id !== input.requestId
890
- ) {
891
- identity.request = false;
892
- }
893
- if (value.role !== input.role) identity.role = false;
894
- if (input.output === "diff") {
895
- if (value.taskId !== (input.taskId ?? input.requestId))
896
- identity.task = false;
897
- if (value.phase !== input.phase) identity.phase = false;
898
- }
899
- const validation =
900
- input.output === "evidence"
901
- ? validateEvidenceResult(value)
902
- : validateDiffResult(value);
903
- schema = validation.ok ? "valid" : "invalid";
904
- const matches =
905
- identity.request && identity.role && identity.task && identity.phase;
906
- if (!validation.ok || !matches) {
907
- failure = validation.ok
908
- ? {
909
- kind: "artifact",
910
- code: "structural-identity-mismatch",
911
- stage: "structural-submit",
912
- }
913
- : (validation.failure ?? {
914
- kind: "artifact",
915
- code: "invalid-structural-result",
916
- stage: "structural-submit",
917
- });
918
- throw new Error(
919
- JSON.stringify({
920
- code: "code" in failure ? failure.code : failure.kind,
921
- reason:
922
- validation.reason ?? "submitted result identity does not match",
923
- identityMismatch: Object.entries(identity)
924
- .filter(([, matches]) => !matches)
925
- .map(([field]) => field),
926
- remainingCorrections: Math.max(0, 2 - attempts),
927
- }),
928
- );
929
- }
930
- submitted = structuredClone(value) as unknown as
931
- | EvidenceResult
932
- | DiffResult;
933
- return {
934
- content: [{ type: "text" as const, text: "Abel result accepted." }],
935
- details: { accepted: true },
936
- terminate: true,
937
- };
938
- },
939
- });
940
-
941
- return {
942
- tool,
943
- getResult: () => submitted,
944
- getAttempts: () => attempts,
945
- getSchema: () => schema,
946
- getIdentity: () => ({ ...identity }),
947
- getFailure: () =>
948
- failure === undefined ? undefined : structuredClone(failure),
949
- };
950
- }