@abelxiaoxing/cadence 1.8.2 → 1.8.4

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.
@@ -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
- }