Repository navigation
Expand file tree
/
Copy pathcontextCompiler.ts
More file actions
1580 lines (1547 loc) · 67.4 KB
/
Copy pathcontextCompiler.ts
File metadata and controls
1580 lines (1547 loc) · 67.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from 'node:path';
import { canonicalMathJson, mathDigest } from '../math/mathRuntimeIo';
import { inspectLeanDeclarations, inspectLeanDeclarationRegions } from '../math/leanSource';
import { maskLeanCommentsAndStrings } from '../math/leanSyntax';
import type { CooperationState } from './cooperationShared';
import { deliveryFinding, researchFindingRequestsDecision, type DeliveryRecord } from './deliveries';
import { originalDeclarationRegions, type SolverProblem } from './problem';
import {
assignmentDeliveryFile,
hasTaskAcceptance,
leadPlanDeliveryFile,
taskGroup,
taskReferenceDependencies,
taskVersion,
type CooperativeAction,
type TaskRecord,
} from './tasks';
import { buildProofContinuation } from './progress';
import { contextTaskConsumers } from './taskConsumers';
import { mathematicalGapContextText } from './mathematicalGaps';
import { nextCheckContextText } from './nextChecks';
import { goalProgressTaskContext } from './goalProgress';
import { leadPlanPublicationFeedback, LEAD_PLAN_REPAIR_INSTRUCTION } from './cooperationShared';
import { contextCheckpointRejectionFeedback } from './contextCheckpoint';
import { researchDecisionMatches, type ResearchDecision } from './researchDecisions';
export const DEFAULT_TASK_CONTEXT_BYTES = 512 * 1024;
export const DEFAULT_OPTIONAL_TASK_CONTEXT_BYTES = 64 * 1024;
const COMPACT_OPTIONAL_TASK_CONTEXT_BYTES = 8 * 1024;
/** Above this size a source is shown compactly: definition bodies are omitted and the statement is cited, not repeated. */
export const COMPACT_CONTEXT_SOURCE_BYTES = 64 * 1024;
/** A compact source keeps definition bodies up to this size inline. */
const COMPACT_INLINE_BODY_BYTES = 32;
const COMPACT_BODY_MARKER = '\n/- body omitted -/\n';
export type ContextItemKind =
| 'problem'
| 'assignment'
| 'interfaces'
| 'sources'
| 'feedback'
| 'delivery'
| 'finding'
| 'history'
| 'blocker'
| 'routes'
| 'continuation'
| 'statement-review'
| 'checkpoint'
| 'groups';
export type ContextOmissionReason =
| 'budget'
| 'superseded'
| 'stale-version'
| 'duplicate'
| 'selection-limit'
| 'advisory-summary-limit'
| 'advisory-details-by-reference'
| 'optional-budget'
| 'encapsulated-private-dependency'
| 'outside-task-scope';
export type ContextManifest = Readonly<{
schema: 'theorem-os.task-context.v1';
evidence: 'recorded-not-replayed';
maxBytes: number;
usedBytes: number;
mandatoryBytes: number;
maxOptionalBytes: number;
optionalBytes: number;
contentDigest: string;
requiredTaskIds: readonly string[];
included: readonly { id: string; kind: ContextItemKind; required: boolean; bytes: number }[];
omitted: readonly { id: string; kind: ContextItemKind; reason: ContextOmissionReason }[];
}>;
export type ContextSection = Readonly<{ id: string; kind: ContextItemKind; text: string; priority?: number }>;
export type TaskContextInput = Readonly<{
problem: SolverProblem;
cooperation?: CooperationState;
action?: CooperativeAction;
instructions: string;
taskText: string;
feedback?: string;
checkpoint?: string;
/** Frozen source projection containing complete context and fixed definitions, with proof bodies omitted. */
frozenContexts?: Readonly<Record<string, string>>;
maxContextBytes?: number;
environmentDigest?: string;
/** Optional hints have their own allowance; exact mathematical contracts never use it. */
maxOptionalContextBytes?: number;
mandatory?: readonly ContextSection[];
optional?: readonly ContextSection[];
/** The same thread already has this frozen problem; still send the new task's exact interfaces. */
taskSwitch?: boolean;
/** The active assignment survived compaction, but its exact inputs must be sent again. */
compactedResume?: boolean;
}>;
export class TaskContextError extends Error {
constructor(
readonly code:
| 'math_context_missing_required'
| 'math_context_stale_required'
| 'math_context_mandatory_overflow'
| 'math_context_invalid_budget',
readonly itemId: string,
) {
super(`${code}:${itemId}`);
}
}
const json = (value: unknown) => JSON.stringify(value);
const section = (id: string, kind: ContextItemKind, title: string, value: unknown): ContextSection => ({
id,
kind,
text: `${title}\n${typeof value === 'string' ? value : json(value)}`,
});
const missing = (id: string): never => {
throw new TaskContextError('math_context_missing_required', id);
};
const stale = (id: string): never => {
throw new TaskContextError('math_context_stale_required', id);
};
const present = (value: unknown): value is string => typeof value === 'string' && !!value.trim();
const localName = (name: string) => name.split('.').at(-1);
const sourcePath = (problem: SolverProblem, file: string) =>
path.posix.join(problem.projectRelative.replaceAll('\\', '/'), file);
const ARCHIVE_INDEX_THRESHOLD = 48;
const compactArchive = (cooperation?: CooperationState) =>
Boolean(
cooperation &&
(cooperation.tasks.length + (cooperation.history?.length ?? 0) > ARCHIVE_INDEX_THRESHOLD ||
(cooperation.deliveries?.length ?? 0) > ARCHIVE_INDEX_THRESHOLD),
);
const oneLine = (text: string) => {
const summary = text.trim().replace(/\s+/gu, ' ');
return summary.length > 120 ? summary.slice(0, 119) + '…' : summary;
};
export function deliveryIndexRow(record: DeliveryRecord, proofPath?: string) {
return {
id: record.id,
kind: record.kind,
status: record.status,
taskId: record.taskId,
summary: oneLine(record.summary),
commit: record.commit,
findingDigest: record.findingDigest,
file: record.commit ? ((record.kind === 'proof' ? proofPath : undefined) ?? 'RESEARCH.md') : 'COOPERATION.json',
};
}
export function landedHelperSection(cooperation?: CooperationState) {
const helpers = cooperation?.landedHelpers;
if (!helpers?.length) return;
return section(
'landed-helpers',
'sources',
'Latest verified standalone helper signatures. Look up older entries in COOPERATION.json landedHelpers. ' +
'Read the exact Lean type at the recorded commit before use.',
helpers.slice(-4),
);
}
/**
* Preserve source-level variables, scopes, instances and fixed definitions; never copy an existing proof body.
* A source above COMPACT_CONTEXT_SOURCE_BYTES also omits definition and instance bodies, which stay in the frozen file.
*/
export function frozenSourceContext(problem: SolverProblem, file: string, source: string): string {
const regions = inspectLeanDeclarationRegions(source),
originals = problem.declarations[file] ?? [];
const bytes = Buffer.byteLength(source),
compact = bytes > COMPACT_CONTEXT_SOURCE_BYTES;
const masked = compact ? maskLeanCommentsAndStrings(source) : '';
const matching = originalDeclarationRegions(source, regions);
if (
originals.some(original => {
const found = matching(original);
return (
found.length !== 1 ||
found[0].declarationType !== original.header ||
(original.body && mathDigest(source.slice(found[0].bodyOffset, found[0].endOffset).trim()) !== original.body)
);
})
)
return stale(`frozen-source:${file}`);
const kinds = new Map(inspectLeanDeclarations(source).map(item => [item.startOffset, item.kind]));
for (const [index, region] of [...regions.entries()].reverse()) {
const isTarget = problem.targets.some(
target => target.proofPath === file && localName(target.theoremName) === localName(region.name),
);
if (kinds.get(region.startOffset) === 'theorem' || isTarget) {
// A mutual block can extend a region over the next declaration; a compact cut stops before it.
const end = compact ? Math.min(region.endOffset, regions[index + 1]?.startOffset ?? Infinity) : region.endOffset;
source =
source.slice(0, region.bodyOffset) +
'\n/- Proof body omitted by the host context compiler. -/\n' +
source.slice(end);
} else if (compact) {
// Structure-instance fields follow `where`; the first `:=` would sit inside them.
const where = /(?<![\p{L}\p{M}\p{N}_'.?!])where(?![\p{L}\p{M}\p{N}_'.?!])/u.exec(
masked.slice(region.startOffset, region.bodyOffset),
);
const start = where ? region.startOffset + where.index + where[0].length : region.bodyOffset;
const end = Math.min(region.endOffset, regions[index + 1]?.startOffset ?? Infinity);
if (Buffer.byteLength(source.slice(start, end)) > COMPACT_INLINE_BODY_BYTES)
source = source.slice(0, start) + COMPACT_BODY_MARKER + source.slice(end);
}
}
return compact
? `/- Host context note: this ${bytes}-byte source is shown compactly. Definition and instance bodies ` +
`over ${COMPACT_INLINE_BODY_BYTES} bytes appear as "body omitted"; read them with git show COMMIT:PATH from this file's frozen-sources entry. -/\n` +
source
: source;
}
/** A large statement that is a frozen file is cited by commit and path instead of being repeated. */
function originalProblemSection(input: TaskContextInput): ContextSection {
const { problem } = input,
statement = problem.contract.formalStatement,
bytes = Buffer.byteLength(statement);
const title = `${input.taskText}\n\nOriginal problem:`,
digest = mathDigest(statement);
const file =
bytes > (input.compactedResume || compactArchive(input.cooperation) ? 4 * 1024 : COMPACT_CONTEXT_SOURCE_BYTES) &&
present(problem.baseCommit)
? Object.keys(problem.trustedFiles ?? {})
.sort()
.find(file => problem.trustedFiles[file] === digest)
: undefined;
if (!file) return section('original-problem', 'problem', title, statement);
return section('original-problem', 'problem', title, {
commit: problem.baseCommit,
path: sourcePath(problem, file),
bytes,
sha256: digest,
retrieval:
'This statement is large, so it is cited rather than repeated. Read the complete text with git show COMMIT:PATH in this isolated worktree. ' +
'The frozen source context below shows the same declarations, scopes and headers with proof and long definition bodies omitted.',
});
}
function frozenHeader(problem: SolverProblem, node: Pick<TaskRecord, 'task'>): string | undefined {
if (node.task.kind !== 'goal') return node.task.type;
const exact =
problem.declarations[node.task.proofPath!]?.filter(
item => item.name === node.task.theoremName || localName(item.name) === localName(node.task.theoremName!),
) ?? [];
if (exact.length !== 1) return missing(`interface:${node.task.id}`);
return exact[0].header;
}
/** Kernel-verified at one target commit, with at least one receipt and every receipt at that commit. */
const receiptsComplete = ({ verification }: NonNullable<TaskRecord['proof']>) =>
verification.status === 'kernel_verified' &&
present(verification.targetCommit) &&
verification.results.length > 0 &&
verification.results.every(
result =>
result.status === 'kernel_verified' &&
result.targetCommit === verification.targetCommit &&
present(result.receiptId),
);
function taskEvidence(problem: SolverProblem, node: TaskRecord, environmentDigest?: string) {
const proof = node.integratedCheck ?? node.proof;
if (!proof) return undefined;
if (
proof.taskDigest !== taskVersion(node.task) ||
(environmentDigest && proof.references && proof.references.environmentDigest !== environmentDigest) ||
(proof.passed && !receiptsComplete(proof))
)
return stale(`evidence:${node.task.id}`);
return {
evidence: 'recorded-not-replayed',
passed: proof.passed,
commit: proof.commit,
path: node.task.proofPath && sourcePath(problem, node.task.proofPath),
sourceDigest: proof.sourceDigest,
taskDigest: proof.taskDigest,
conditions: proof.conditions ?? [],
verification: {
status: proof.verification.status,
targetCommit: proof.verification.targetCommit,
receipts: proof.verification.results.map(result => ({
receiptId: result.receiptId,
status: result.status,
targetCommit: result.targetCommit,
})),
},
references: proof.references && {
sourceCommit: proof.references.sourceCommit,
environmentDigest: proof.references.environmentDigest,
contextDigest: proof.references.contextDigest,
root: proof.references.root,
tasks: proof.references.tasks,
},
imports: proof.imports,
};
}
function closedLeadHelper(node: TaskRecord): boolean {
const proof = node.integratedCheck;
return (
node.task.kind === 'lemma' &&
node.status === 'integrated' &&
!!proof?.passed &&
!proof.conditions?.length &&
hasTaskAcceptance(proof) &&
present(proof.commit) &&
present(proof.sourceDigest) &&
present(node.task.proofPath) &&
present(node.task.theoremName)
);
}
function leadTaskInterface(
node: TaskRecord,
action: CooperativeAction | undefined,
omitted: ContextManifest['omitted'][number][],
) {
if (action?.kind === 'task' && node.task.id === action.task.id) return { id: node.task.id };
const finishedAdvisory = node.status === 'completed' && ['research', 'sketch'].includes(node.task.kind);
if (
action?.kind !== 'lead' ||
!(closedLeadHelper(node) || finishedAdvisory) ||
Buffer.byteLength(node.task.objective) <= 1024
)
return node.task;
// The full typed interface remains inline; only settled planning prose moves to the live peer index.
const { objective, ...task } = node.task;
omitted.push({ id: `objective:${task.id}`, kind: 'interfaces', reason: 'advisory-details-by-reference' });
return { ...task, objectiveDigest: mathDigest(objective) };
}
/** Closed shared interfaces encapsulate private implementation prerequisites, never unresolved assumptions. */
function requiredTasks(input: TaskContextInput, omitted: ContextManifest['omitted'][number][]) {
const tasks = input.cooperation?.tasks ?? [],
byId = new Map(tasks.map(node => [node.task.id, node]));
if (byId.size !== tasks.length) return missing('duplicate-task-id');
const required = new Set<string>(),
visiting = new Set<string>();
const action = input.action;
const scopedLead = action?.kind === 'lead' && tasks.some(node => node.task.kind === 'goal');
if (action?.kind === 'task') {
if (action.assignment.taskId !== action.task.id || action.assignment.taskDigest !== taskVersion(action.task))
return stale(`assignment:${action.task.id}`);
const current = byId.get(action.task.id);
if (!current) return missing(`task:${action.task.id}`);
if (taskVersion(current.task) !== action.assignment.taskDigest) return stale(`task:${action.task.id}`);
}
const visit = (id: string, consumer?: TaskRecord) => {
const node = byId.get(id);
if (!node) {
const proof = consumer?.integratedCheck;
if (
consumer?.status === 'integrated' &&
proof?.passed &&
!proof.conditions?.length &&
proof.taskDigest === taskVersion(consumer.task) &&
receiptsComplete(proof)
) {
omitted.push({ id: `interface:${id}`, kind: 'interfaces', reason: 'encapsulated-private-dependency' });
return;
}
return missing(`dependency:${id}`);
}
if (visiting.has(id)) return missing(`dependency-cycle:${id}`);
if (required.has(id)) return;
visiting.add(id);
// A typed interface must be supplied exactly; advisory tasks have no admitted proposition.
if (['lemma', 'goal'].includes(node.task.kind) && !present(frozenHeader(input.problem, node)))
return missing(`interface:${id}`);
taskEvidence(input.problem, node, input.environmentDigest);
required.add(id);
const proof = node.integratedCheck ?? node.proof;
for (const condition of proof?.conditions ?? []) {
const dependency = byId.get(condition.taskId);
if (!dependency) return missing(`condition:${condition.taskId}`);
if (taskVersion(dependency.task) !== condition.taskDigest) return stale(`condition:${condition.taskId}`);
visit(condition.taskId);
}
if (!scopedLead || !closedLeadHelper(node)) {
const references = taskReferenceDependencies(node);
for (const dependency of references ?? node.task.dependsOn.map(taskId => ({ taskId }))) {
const current = byId.get(dependency.taskId);
if ('taskDigest' in dependency && current && taskVersion(current.task) !== dependency.taskDigest)
return stale(`dependency:${dependency.taskId}`);
visit(dependency.taskId, node);
}
if (action?.kind === 'lead' && !references)
for (const route of [...(input.cooperation?.proofRoutes ?? []), ...(node.alternativeRoutes ?? [])])
if (route.targetTaskId === id)
[...route.prerequisiteTaskIds, route.closingTaskId].forEach(dependency => visit(dependency));
}
visiting.delete(id);
};
// Unadopted proposals and refutations are ordinary planning inputs; their sources join the Lead's scope.
const visitLeadInputs = () => {
for (const delivery of selectedLeadResearchInputs(input, byId)) {
visit(delivery.taskId!);
delivery.dependencies.forEach(input => visit(input.taskId));
for (const proposal of selectedLeadProposals(delivery, byId))
proposal.dependsOn.filter(id => byId.has(id)).forEach(id => visit(id));
}
};
if (action?.kind === 'task') visit(action.task.id);
else if (scopedLead) {
tasks.filter(node => node.task.kind === 'goal').forEach(node => visit(node.task.id));
visitLeadInputs();
} else tasks.forEach(node => visit(node.task.id));
const route =
action?.kind === 'task' && action.assignment.routeId
? (input.cooperation?.proofRoutes?.find(route => route.id === action.assignment.routeId) ??
byId.get(action.task.id)?.alternativeRoutes?.find(route => route.id === action.assignment.routeId))
: undefined;
if (action?.kind === 'task' && action.assignment.routeId) {
if (!route || route.targetTaskId !== action.task.id) return missing(`route:${action.assignment.routeId}`);
[...route.prerequisiteTaskIds, route.closingTaskId].forEach(id => visit(id));
}
if (action?.kind === 'task')
for (const dependency of action.assignment.dependencies ?? []) {
const current = byId.get(dependency.taskId);
if (!current) {
if (
!omitted.some(
item => item.id === `interface:${dependency.taskId}` && item.reason === 'encapsulated-private-dependency',
)
)
return missing(`dependency:${dependency.taskId}`);
} else {
if (taskVersion(current.task) !== dependency.taskDigest) return stale(`dependency:${dependency.taskId}`);
visit(dependency.taskId);
}
}
const deferred = scopedLead ? tasks.filter(node => !required.has(node.task.id)) : [];
for (const node of deferred)
omitted.push({ id: `interface:${node.task.id}`, kind: 'interfaces', reason: 'advisory-details-by-reference' });
return { tasks: tasks.filter(node => required.has(node.task.id)), deferred, byId, required, route };
}
function taskRecordReference(node: TaskRecord) {
return {
id: node.task.id,
taskDigest: taskVersion(node.task),
recordDigest: mathDigest(canonicalMathJson(node)),
kind: node.task.kind,
status: node.task.status ?? 'active',
executionStatus: node.status,
groupId: taskGroup(node.task),
owner: node.assignment?.workerId ?? node.task.ownerId,
dependsOn: node.task.dependsOn,
theoremName: node.task.theoremName,
proofPath: node.task.proofPath,
};
}
function compactTaskReference(node: TaskRecord) {
return {
id: node.task.id,
kind: node.task.kind,
status: node.status,
summary: oneLine(node.task.objective),
file: node.task.proofPath,
};
}
function checkedHelperReference(input: TaskContextInput, node: TaskRecord, compact?: boolean) {
const proof = taskEvidence(input.problem, node, input.environmentDigest)!;
return {
...(compact ? compactTaskReference(node) : taskRecordReference(node)),
theoremName: node.task.theoremName,
sharing: node.task.sharing ?? 'problem',
source: {
commit: proof.commit,
path: sourcePath(input.problem, node.task.proofPath!),
sourceDigest: proof.sourceDigest,
},
evidence: 'recorded-not-replayed',
};
}
function sourceReferences(input: TaskContextInput) {
const problem = input.problem;
if (!present(problem.baseCommit)) return missing('frozen-source-commit');
if (!problem.declarations || !Array.isArray(problem.ownedFiles)) return missing('frozen-declarations');
const frozen = problem.frozenFiles ?? {};
const files = problem.ownedFiles.filter(file => file.endsWith('.lean') && !Object.hasOwn(frozen, file));
for (const file of files)
if (typeof input.frozenContexts?.[file] !== 'string') return missing(`frozen-context:${file}`);
return {
baseCommit: problem.baseCommit,
retrieval:
'Read full proofs and namespace/section/instance context with git show COMMIT:PATH in this isolated worktree. Source references identify immutable content; they grant no proof acceptance.',
files: files.map(file => {
const context = input.frozenContexts![file],
declarations = problem.declarations[file] ?? [];
if ((input.compactedResume || compactArchive(input.cooperation)) && Buffer.byteLength(context) > 4 * 1024) {
return {
commit: problem.baseCommit,
path: sourcePath(problem, file),
contextDigest: problem.sourceStructure?.[file],
imports: problem.sourceImports?.[file],
declarationCount: declarations.length,
contextByReference: true,
};
}
return {
commit: problem.baseCommit,
path: sourcePath(problem, file),
contextDigest: problem.sourceStructure?.[file],
imports: problem.sourceImports?.[file],
// Large sources already retain every exact header in context. Repeating the
// full declaration inventory can exhaust the budget before the first turn.
...(Buffer.byteLength(context) > COMPACT_CONTEXT_SOURCE_BYTES
? {
declarationsFrom: 'context',
declarationCount: declarations.length,
targetDeclarations: declarations.filter(declaration =>
problem.targets.some(
target => target.proofPath === file && localName(target.theoremName) === localName(declaration.name),
),
),
}
: { declarations }),
context,
};
}),
// Library declarations are listed by the declaration index, not inline.
...(Object.keys(frozen).length
? {
libraryFiles: Object.keys(frozen)
.sort()
.map(file => ({
commit: problem.baseCommit,
path: sourcePath(problem, file),
digest: frozen[file],
frozenLibrary: true,
declarationCount: problem.declarations[file]?.length ?? 0,
})),
}
: {}),
trustedFiles: Object.entries(problem.trustedFiles ?? {}).map(([file, digest]) => ({
commit: problem.baseCommit,
path: sourcePath(problem, file),
digest,
})),
};
}
/** Large frozen contexts already contain their headers; cite the complete order rather than repeating every name. */
function frozenDeclarationOrder(input: TaskContextInput) {
return Object.fromEntries(
Object.entries(input.problem.declarations)
.filter(([file]) => !Object.hasOwn(input.problem.frozenFiles ?? {}, file))
.map(([file, declarations]) => {
const names = declarations.map(declaration => declaration.name),
context = input.frozenContexts?.[file];
const byReference =
context &&
Buffer.byteLength(context) >
(input.compactedResume || compactArchive(input.cooperation) ? 4 * 1024 : COMPACT_CONTEXT_SOURCE_BYTES);
return [
file,
byReference
? {
encoding: 'frozen-declaration-order-v1',
commit: input.problem.baseCommit,
path: sourcePath(input.problem, file),
declarationCount: names.length,
orderDigest: mathDigest(canonicalMathJson(names)),
retrieval:
'Read the complete frozen file with git show COMMIT:PATH for its exact declaration order. ' +
'The ordered array of declaration names as written (including dotted names and repeated local names) must match ' +
'declarationCount and SHA-256(canonicalMathJson(names)) = orderDigest. ' +
'Missing or mismatched source is unavailable. ' +
'this reference replaces only the duplicate name list and grants no proof acceptance.',
}
: names,
];
}),
);
}
const LEAD_RESEARCH_INPUTS = 8,
LEAD_RESEARCH_PROPOSALS = 8,
LEAD_INLINE_FINDING_BYTES = 2 * 1024;
/** Current research deliveries the Lead must review: unadopted lemma proposals, refutations and decision requests. */
export function leadResearchInputs(
deliveries: readonly DeliveryRecord[],
byId: ReadonlyMap<string, TaskRecord>,
decisions: readonly ResearchDecision[] = [],
) {
return deliveries.filter(record => {
if (decisions.some(decision => researchDecisionMatches(record, decision))) return false;
const source = record.taskId ? byId.get(record.taskId) : undefined;
if (
record.kind !== 'research' ||
record.status === 'superseded' ||
!source ||
record.taskDigest !== taskVersion(source.task) ||
record.dependencies.some(
input => !byId.has(input.taskId) || taskVersion(byId.get(input.taskId)!.task) !== input.taskDigest,
)
)
return false;
if (record.lemmaRequests?.some(task => !byId.has(task.id))) return true;
// Host-bound check outcomes have their own per-publication nextCheckDecisions contract.
if (source.nextCheckId && record.checkOutcome?.checkId === source.nextCheckId && record.checkOutcomeScope)
return false;
return researchFindingRequestsDecision(record, source.finding);
});
}
function visibleLeadResearchInputs(
input: Pick<TaskContextInput, 'cooperation'>,
byId: ReadonlyMap<string, TaskRecord>,
) {
const current = leadResearchInputs(input.cooperation?.deliveries ?? [], byId, input.cooperation?.researchDecisions);
const ids = input.cooperation?.leadResearchInputIds;
return ids ? ids.flatMap(id => current.find(record => record.id === id) ?? []) : current;
}
function selectedLeadResearchInputs(input: TaskContextInput, byId: ReadonlyMap<string, TaskRecord>) {
return visibleLeadResearchInputs(input, byId).slice(-LEAD_RESEARCH_INPUTS).reverse();
}
function selectedLeadProposals(record: DeliveryRecord, byId: ReadonlyMap<string, TaskRecord>) {
return (record.lemmaRequests ?? []).filter(task => !byId.has(task.id)).slice(0, LEAD_RESEARCH_PROPOSALS);
}
/** Exact proposals stay inline; a long finding is retrievable by digest from its saved notes. */
function leadResearchInput(record: DeliveryRecord, byId: ReadonlyMap<string, TaskRecord>) {
const finding = deliveryFinding(record, byId.get(record.taskId!)?.finding);
const proposals = (record.lemmaRequests ?? []).filter(task => !byId.has(task.id));
return {
deliveryId: record.id,
producer: record.producer,
taskId: record.taskId,
taskDigest: record.taskDigest,
summary: record.summary,
evidenceRefs: record.evidenceRefs,
remainingObligations: record.remainingObligations,
...(record.sourceUses?.length
? {
sourceUseCount: record.sourceUses.length,
sourceUseConsumers: [...new Set(record.sourceUses.map(use => use.consumer.taskId))],
}
: {}),
...(finding === undefined
? {}
: Buffer.byteLength(finding) <= LEAD_INLINE_FINDING_BYTES
? { finding }
: {
findingBytes: Buffer.byteLength(finding),
findingDigest: record.findingDigest,
}),
...(record.commit ? { savedSource: { commit: record.commit, notesPath: 'RESEARCH.md' } } : {}),
...(proposals.length
? {
lemmaRequests: selectedLeadProposals(record, byId),
...(proposals.length > LEAD_RESEARCH_PROPOSALS
? { unshownProposals: proposals.length - LEAD_RESEARCH_PROPOSALS }
: {}),
}
: {}),
};
}
/** Full and same-thread Lead contexts carry the same exact presented publications. */
export function leadResearchInputSection(
input: Pick<TaskContextInput, 'cooperation'>,
byId: ReadonlyMap<string, TaskRecord> = new Map(input.cooperation?.tasks.map(node => [node.task.id, node])),
) {
// Newest first, so a stale unanswered input never hides newer evidence.
const inputs = visibleLeadResearchInputs(input, byId).reverse();
if (!inputs.length) return;
return section(
'lead-research-inputs',
'assignment',
'Research inputs for this planning decision (advisory, not checked lemmas or proof acceptance; retrieve a long finding from savedSource commit and notesPath):',
{
inputs: inputs.slice(0, LEAD_RESEARCH_INPUTS).map(record => leadResearchInput(record, byId)),
...((input.cooperation?.leadResearchInputCount ?? inputs.length) > LEAD_RESEARCH_INPUTS
? { unshown: (input.cooperation?.leadResearchInputCount ?? inputs.length) - LEAD_RESEARCH_INPUTS }
: {}),
},
);
}
/** A continued Lead turn must receive the same current host rejection as a fresh turn. */
export function leadPlanRejectionSection(input: Pick<TaskContextInput, 'action' | 'cooperation' | 'problem'>) {
if (input.action?.kind !== 'lead' || !input.cooperation?.error) return;
return section(
'plan-rejection',
'feedback',
'Host rejected the proposed plan. Repair this error while preserving every exact original target. ' +
LEAD_PLAN_REPAIR_INSTRUCTION,
{
error: input.cooperation.error,
rejection: input.cooperation.planRejection,
originalTargets: input.problem.targets.map(({ proofPath, theoremName }) => ({ proofPath, theoremName })),
},
);
}
function deliveryMatchesFinding(record: DeliveryRecord, node?: TaskRecord): boolean {
if (record.kind !== 'research' || !node || !present(node.finding)) return false;
return record.findingDigest === undefined
? record.summary === node.finding
: record.findingDigest === mathDigest(node.finding);
}
/** 0 for the active task, 1 for its required closure, 2 for its group, 3 otherwise. */
const scopeRank =
(active: TaskRecord['task'] | undefined, required: ReadonlySet<string>) => (taskId?: string, groupId?: string) =>
active && taskId === active.id
? 0
: required.has(taskId ?? '')
? 1
: active && groupId === taskGroup(active)
? 2
: 3;
function optionalDeliveries(
input: TaskContextInput,
required: ReadonlySet<string>,
byId: ReadonlyMap<string, TaskRecord>,
omitted: ContextManifest['omitted'][number][],
) {
const action = input.action,
active = action?.kind === 'task' ? action.task : undefined;
const rank = scopeRank(active, required),
priority = (record: DeliveryRecord) => rank(record.taskId, record.groupId);
const seen = new Set<string>(),
selected: DeliveryRecord[] = [];
const findingSources = new Map<
string,
{ deliveryId: string; commit: string; notesPath: 'RESEARCH.md'; sourceDigest?: string }
>();
for (const record of [...(input.cooperation?.deliveries ?? [])].reverse().sort((a, b) => priority(a) - priority(b))) {
const id = `delivery:${record.id}`,
current = record.taskId ? byId.get(record.taskId) : undefined;
let reason: ContextOmissionReason | undefined;
if (record.status === 'superseded') reason = 'superseded';
else if (
(current && record.taskDigest !== taskVersion(current.task)) ||
record.dependencies?.some(
dependency =>
byId.has(dependency.taskId) && taskVersion(byId.get(dependency.taskId)!.task) !== dependency.taskDigest,
)
)
reason = 'stale-version';
if (
!reason &&
current &&
deliveryMatchesFinding(record, current) &&
record.commit &&
!findingSources.has(current.task.id)
)
findingSources.set(current.task.id, {
deliveryId: record.id,
commit: record.commit,
notesPath: 'RESEARCH.md',
sourceDigest: record.sourceDigest,
});
const key = json([
record.taskId ?? record.id,
record.taskDigest,
record.kind,
record.producer,
record.findingDigest,
]);
if (!reason && seen.has(key)) reason = 'duplicate';
if (!reason && selected.length >= 8) reason = 'selection-limit';
if (reason) {
omitted.push({ id, kind: 'delivery', reason });
continue;
}
seen.add(key);
selected.push(record);
}
const sections = selected.flatMap(record => {
// Interfaces and receipts live in mandatory sections. A delivery summary is advisory prose.
const current = record.taskId ? byId.get(record.taskId) : undefined;
if (
(compactArchive(input.cooperation) || input.taskSwitch || input.compactedResume) &&
!(record.taskId && required.has(record.taskId))
) {
omitted.push({ id: `delivery:${record.id}:details`, kind: 'delivery', reason: 'advisory-details-by-reference' });
const file = current?.task.proofPath && sourcePath(input.problem, current.task.proofPath);
return [
{
...section(
`delivery:${record.id}`,
'delivery',
'Delivery index (advisory; retrieve the saved source or the record in COOPERATION.json before using it):',
deliveryIndexRow(record, file),
),
priority: priority(record) * 10 + 2,
},
];
}
// Keep a shared mathematical finding independently selectable from its delivery metadata.
const sharedFinding = deliveryMatchesFinding(record, current);
const ownFinding = sharedFinding ? undefined : deliveryFinding(record);
const findingId = sharedFinding
? `finding:${record.taskId}`
: ownFinding
? `finding:delivery:${record.id}`
: undefined;
if (record.actualReferences || record.artifacts?.artifacts.some(artifact => artifact.declarations.length))
omitted.push({ id: `delivery:${record.id}:details`, kind: 'delivery', reason: 'advisory-details-by-reference' });
const visible = {
id: record.id,
submissionId: record.submissionId,
statementReviewId: record.statementReviewId,
producer: record.producer,
taskId: record.taskId,
taskDigest: record.taskDigest,
groupId: record.groupId,
kind: record.kind,
status: record.status,
statement: record.statement,
premises: record.premises,
findingDigest: record.findingDigest,
dependencies: record.dependencies,
remainingObligations: record.remainingObligations,
evidenceRefs: record.evidenceRefs,
createdAt: record.createdAt,
commit: record.commit,
sourceDigest: record.sourceDigest,
savedSource: record.commit && {
commit: record.commit,
notesPath: 'RESEARCH.md',
proofPath: current && current.task.proofPath && sourcePath(input.problem, current.task.proofPath),
},
actualReferenceSource: record.actualReferences && {
sourceCommit: record.actualReferences.sourceCommit,
root: record.actualReferences.root,
environmentDigest: record.actualReferences.environmentDigest,
contextDigest: record.actualReferences.contextDigest,
tasks: record.actualReferences.tasks,
},
artifacts: record.artifacts && {
...record.artifacts,
artifacts: record.artifacts.artifacts.map(artifact => ({
...artifact,
declarations: artifact.declarations.map(({ name, sha256, draft }) => ({ name, sha256, draft })),
})),
},
artifactWarning: record.artifactWarning,
lemmaRequests: record.lemmaRequests,
sourceUseCount: record.sourceUses?.length,
};
return [
{
...section(
`delivery:${record.id}`,
'delivery',
'Current-version delivery selected for this task (advisory; retain unproved obligations):',
{ ...visible, ...(findingId ? { summarySource: findingId } : { summary: record.summary }) },
),
priority: priority(record) * 10 + 2,
},
...(ownFinding
? [
{
...section(findingId!, 'finding', 'Immutable advisory research publication:', {
taskId: record.taskId,
taskDigest: record.taskDigest,
finding: ownFinding,
findingDigest: record.findingDigest,
savedSource: { commit: record.commit, notesPath: 'RESEARCH.md' },
}),
priority: priority(record) * 10 + 1,
},
]
: []),
];
});
return { sections, findingSources };
}
/** Show a response format only when this dispatch has something to answer. */
export function cooperativeResponseSections(
cooperation: CooperationState,
action?: CooperativeAction,
): ContextSection[] {
const sections: ContextSection[] = [];
if (
action?.kind === 'task' &&
cooperation.nextChecks?.some(record => record.taskId === action.task.id && record.status === 'pending')
) {
sections.push({
id: 'next-check-response',
kind: 'assignment',
text: 'Publish the assigned result with research-observe. In the finding include checkOutcome:{checkId:"HOST_CHECK_ID",conclusion:"supporting"|"refuted"|"inconclusive",summary:"scoped result",evidenceRefs:["retained evidence"]}. Use the current check ID in COOPERATION.json.nextChecks. Unknown remains inconclusive.',
});
}
const guidanceIds = cooperation.humanGuidance
?.filter(record => record.status === 'delivered' && !record.decision)
.map(record => record.id);
if (
guidanceIds?.length &&
(action?.kind === 'lead' || action?.kind === 'task' || action?.kind === 'assemble' || action?.kind === 'review')
) {
sections.push({
id: 'human-guidance-response',
kind: 'assignment',
text:
'Unanswered human guidance is in COOPERATION.json.humanGuidance under these IDs: ' +
JSON.stringify(guidanceIds) +
'\n' +
'Include guidanceDecisions:[{guidanceId:"ID",status:"accepted"|"declined"|"needs-info",reason:"specific reason"}] ' +
'in your normal JSON delivery or final response. Use the current plan if the decision calls for a revision.',
});
}
return sections;
}
/** Compile a task's mathematical interface before dispatch. A budget can omit hints, never hypotheses. */
export function compileTaskContext(input: TaskContextInput): { message: string; manifest: ContextManifest } {
const { problem, action } = input;
const maxBytes = input.maxContextBytes ?? DEFAULT_TASK_CONTEXT_BYTES;
const compact = compactArchive(input.cooperation) || input.taskSwitch || input.compactedResume;
const optionalBudget =
input.maxOptionalContextBytes ??
(compact ? COMPACT_OPTIONAL_TASK_CONTEXT_BYTES : DEFAULT_OPTIONAL_TASK_CONTEXT_BYTES);
if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)
throw new TaskContextError('math_context_invalid_budget', 'maxContextBytes');
if (!Number.isSafeInteger(optionalBudget) || optionalBudget < 0)
throw new TaskContextError('math_context_invalid_budget', 'maxOptionalContextBytes');
const maxOptionalBytes = input.compactedResume
? Math.min(optionalBudget, COMPACT_OPTIONAL_TASK_CONTEXT_BYTES)
: optionalBudget;
if (
!present(problem.receiptDigest) ||
!present(problem.contract?.formalStatement) ||
!Array.isArray(problem.contract?.assumptions)
)
return missing('frozen-problem');
const omitted: ContextManifest['omitted'][number][] = [];
const { tasks, deferred, byId, required, route: selectedRoute } = requiredTasks(input, omitted);
const consumers =
action?.kind === 'task' ? contextTaskConsumers(action.task, input.cooperation?.tasks ?? [], input.cooperation) : [];
const consumerIds = new Set(consumers.map(consumer => consumer.task.id));
if (consumerIds.size !== consumers.length) return missing('duplicate-consumer-id');
for (const consumer of consumers) {
const current = byId.get(consumer.task.id);
if (
consumer.taskDigest !== taskVersion(consumer.task) ||
(current && taskVersion(current.task) !== consumer.taskDigest)
)
return stale(`consumer:${consumer.task.id}`);
if (['lemma', 'goal'].includes(consumer.task.kind) && !present(frozenHeader(problem, consumer)))
return missing(`interface:${consumer.task.id}`);
}
const graph = tasks.map(node => ({
...leadTaskInterface(node, action, omitted),
taskDigest: taskVersion(node.task),
status: node.task.status ?? 'active',
executionStatus: node.status,
attempts: node.attempts,
groupId: taskGroup(node.task),
producer: node.assignment?.workerId,
sharing: node.task.sharing ?? 'problem',
...(node.task.kind === 'goal' ? { exactFrozenHeader: frozenHeader(problem, node) } : {}),
evidence: taskEvidence(problem, node, input.environmentDigest),
}));
const mandatory: ContextSection[] = input.taskSwitch
? []
: [
originalProblemSection(input),
section('original-assumptions', 'problem', 'Frozen assumptions and problem identity:', {
problemReceiptDigest: problem.receiptDigest,
statementHash: problem.contract.statementHash,
leanStatementHash: problem.contract.leanStatementHash,
informalStatement: problem.contract.informalStatement,
assumptions: problem.contract.assumptions,
}),
section(
'frozen-sources',
'sources',
'Frozen source context and immutable retrieval references:',
sourceReferences(input),
),
];
if (input.taskSwitch)
mandatory.push({
id: 'same-route-task-switch',
kind: 'continuation',
text: 'Switch to the assignment below. This thread already has the frozen problem and source rules. The new contract replaces the previous assignment. Read current COOPERATION.json and RESEARCH.md for scoped work and saved evidence.',
});
if (input.compactedResume)
mandatory.push({
id: 'compacted-resume',
kind: 'continuation',
text: 'Resume the current assignment after thread compaction. Use the frozen problem and exact current interfaces below. Recover the saved argument from RESEARCH.md and retrieve relevant scoped records from COOPERATION.json before using evidence omitted from this message.',
});
if (action) mandatory.push(section('assignment', 'assignment', 'Cooperative assignment:', action));
if (action?.kind === 'task')