jg-agent-hq 2.0.0 → 4.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 (155) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +14 -14
  3. package/api/README.md +97 -65
  4. package/dist/actions/actions.js +15 -0
  5. package/dist/cli/cli.js +28 -5
  6. package/dist/cli/utilities.d.ts +3 -0
  7. package/dist/cli/utilities.js +13 -0
  8. package/dist/collaboration/dispatch/types.d.ts +2 -2
  9. package/dist/contracts/actions/types.d.ts +4 -4
  10. package/dist/contracts/browser/index.d.ts +1 -3
  11. package/dist/contracts/browser/index.js +1 -3
  12. package/dist/contracts/browser/types.d.ts +15 -1447
  13. package/dist/contracts/browser/types.js +3 -112
  14. package/dist/contracts/index.d.ts +9 -11
  15. package/dist/contracts/index.js +6 -8
  16. package/dist/contracts/plans/index.d.ts +4 -6
  17. package/dist/contracts/plans/index.js +2 -4
  18. package/dist/contracts/plans/types.d.ts +38 -905
  19. package/dist/contracts/plans/types.js +13 -139
  20. package/dist/contracts/sessions/index.d.ts +2 -0
  21. package/dist/contracts/sessions/index.js +2 -0
  22. package/dist/contracts/sessions/types.d.ts +101 -0
  23. package/dist/contracts/sessions/types.js +43 -0
  24. package/dist/contracts/types.d.ts +551 -1035
  25. package/dist/contracts/types.js +32 -0
  26. package/dist/index.d.ts +2 -2
  27. package/dist/index.js +1 -1
  28. package/dist/plans/admission.d.ts +6 -6
  29. package/dist/plans/admission.js +1 -1
  30. package/dist/plans/authority.d.ts +2 -0
  31. package/dist/plans/authority.js +23 -13
  32. package/dist/plans/documents.d.ts +20 -17
  33. package/dist/plans/documents.js +29 -63
  34. package/dist/plans/files.d.ts +2 -2
  35. package/dist/plans/files.js +5 -5
  36. package/dist/plans/finalization.d.ts +6 -8
  37. package/dist/plans/finalization.js +25 -26
  38. package/dist/plans/index.d.ts +2 -3
  39. package/dist/plans/index.js +1 -2
  40. package/dist/plans/plans.d.ts +8 -8
  41. package/dist/plans/plans.js +36 -83
  42. package/dist/plans/projections.d.ts +2 -2
  43. package/dist/plans/projections.js +44 -82
  44. package/dist/plans/revisions.d.ts +4 -5
  45. package/dist/plans/revisions.js +5 -44
  46. package/dist/plans/types.d.ts +5 -281
  47. package/dist/plans/types.js +2 -30
  48. package/dist/plans/utilities.js +2 -11
  49. package/dist/providers/claude/agents/agents.d.ts +16 -0
  50. package/dist/providers/claude/agents/agents.js +80 -0
  51. package/dist/providers/claude/agents/constants.d.ts +3 -0
  52. package/dist/providers/claude/agents/constants.js +4 -0
  53. package/dist/providers/claude/agents/index.d.ts +1 -0
  54. package/dist/providers/claude/agents/index.js +2 -0
  55. package/dist/providers/claude/agents/types.d.ts +14 -0
  56. package/dist/providers/claude/agents/types.js +9 -0
  57. package/dist/providers/claude/claude.js +2 -0
  58. package/dist/providers/claude/history/history.model.js +2 -0
  59. package/dist/providers/claude/history/types.d.ts +115 -368
  60. package/dist/providers/claude/index.d.ts +1 -0
  61. package/dist/providers/claude/index.js +2 -0
  62. package/dist/providers/claude/transformers.js +14 -1
  63. package/dist/providers/codex/adapter.d.ts +1 -1
  64. package/dist/providers/codex/adapter.js +26 -3
  65. package/dist/providers/codex/codex.js +51 -18
  66. package/dist/providers/codex/events.d.ts +2 -1
  67. package/dist/providers/codex/events.js +8 -3
  68. package/dist/providers/codex/index.d.ts +1 -1
  69. package/dist/providers/codex/index.js +1 -1
  70. package/dist/providers/codex/rpc.d.ts +9 -4
  71. package/dist/providers/codex/rpc.js +109 -47
  72. package/dist/providers/codex/skill-roots/constants.d.ts +4 -0
  73. package/dist/providers/codex/skill-roots/constants.js +7 -0
  74. package/dist/providers/codex/skill-roots/index.d.ts +2 -0
  75. package/dist/providers/codex/skill-roots/index.js +4 -0
  76. package/dist/providers/codex/skill-roots/skill-roots.d.ts +35 -0
  77. package/dist/providers/codex/skill-roots/skill-roots.js +93 -0
  78. package/dist/providers/codex/transformers.d.ts +3 -1
  79. package/dist/providers/codex/transformers.js +41 -3
  80. package/dist/providers/codex/types.d.ts +38 -1
  81. package/dist/providers/codex/types.js +15 -3
  82. package/dist/providers/codex/websocket/constants.d.ts +11 -0
  83. package/dist/providers/codex/websocket/constants.js +18 -0
  84. package/dist/providers/codex/websocket/index.d.ts +1 -0
  85. package/dist/providers/codex/websocket/index.js +2 -0
  86. package/dist/providers/codex/websocket/websocket.d.ts +7 -0
  87. package/dist/providers/codex/websocket/websocket.js +219 -0
  88. package/dist/providers/index.d.ts +2 -2
  89. package/dist/providers/index.js +1 -1
  90. package/dist/providers/process.d.ts +2 -2
  91. package/dist/providers/process.js +37 -4
  92. package/dist/providers/registry/registry.js +2 -1
  93. package/dist/providers/types.d.ts +25 -2
  94. package/dist/runtime/runtime.js +11 -3
  95. package/dist/runtime/state/index.d.ts +1 -1
  96. package/dist/runtime/state/index.js +1 -1
  97. package/dist/runtime/state/state.d.ts +15 -0
  98. package/dist/runtime/state/state.js +92 -1
  99. package/dist/runtime/types.d.ts +0 -2
  100. package/dist/runtime/types.js +0 -3
  101. package/dist/sessions/sessions.js +2 -0
  102. package/dist/snapshots/archive/archive.d.ts +29 -0
  103. package/dist/snapshots/archive/archive.js +342 -0
  104. package/dist/snapshots/archive/constants.d.ts +5 -0
  105. package/dist/snapshots/archive/constants.js +8 -0
  106. package/dist/snapshots/archive/index.d.ts +1 -0
  107. package/dist/snapshots/archive/index.js +2 -0
  108. package/dist/snapshots/artifacts.d.ts +10 -1
  109. package/dist/snapshots/artifacts.js +38 -13
  110. package/dist/snapshots/capture.d.ts +15 -0
  111. package/dist/snapshots/capture.js +158 -0
  112. package/dist/snapshots/database.d.ts +2 -0
  113. package/dist/snapshots/database.js +35 -55
  114. package/dist/snapshots/fences.d.ts +10 -0
  115. package/dist/snapshots/fences.js +51 -0
  116. package/dist/snapshots/index.d.ts +1 -0
  117. package/dist/snapshots/index.js +2 -0
  118. package/dist/snapshots/snapshots.d.ts +7 -3
  119. package/dist/snapshots/snapshots.js +31 -117
  120. package/dist/snapshots/snapshots.worker.js +5 -1
  121. package/dist/snapshots/types.d.ts +35 -3
  122. package/dist/snapshots/types.js +19 -4
  123. package/dist/storage/index.d.ts +2 -1
  124. package/dist/storage/index.js +2 -1
  125. package/dist/storage/schema/constants.d.ts +2 -0
  126. package/dist/storage/schema/constants.js +9 -0
  127. package/dist/storage/schema/index.d.ts +3 -0
  128. package/dist/storage/schema/index.js +6 -0
  129. package/dist/storage/schema/schema.d.ts +18 -0
  130. package/dist/storage/schema/schema.js +59 -0
  131. package/dist/storage/schema/types.d.ts +7 -0
  132. package/dist/storage/schema/types.js +8 -0
  133. package/dist/storage/storage.d.ts +1 -1
  134. package/dist/storage/storage.js +2 -2
  135. package/dist/storage/types.d.ts +0 -5
  136. package/dist/storage/types.js +0 -6
  137. package/dist/store/collaboration/collaboration.model.d.ts +2 -2
  138. package/dist/store/control/types.d.ts +16 -16
  139. package/dist/store/plans/plans.model.d.ts +3 -105
  140. package/dist/store/plans/plans.model.js +6 -46
  141. package/dist/store/schema.js +7 -35
  142. package/dist/store/schema.sql +91 -16
  143. package/dist/store/sessions/index.d.ts +1 -0
  144. package/dist/store/sessions/index.js +2 -0
  145. package/dist/store/sessions/sessions.model.d.ts +28 -0
  146. package/dist/store/sessions/sessions.model.js +105 -0
  147. package/dist/store/store.js +13 -7
  148. package/dist/store/store.worker.js +16 -11
  149. package/dist/store/types.d.ts +134 -513
  150. package/dist/store/types.js +21 -7
  151. package/docs/recovery.md +8 -4
  152. package/errors/README.md +3 -3
  153. package/package.json +2 -2
  154. package/dist/plans/reconciliation.d.ts +0 -34
  155. package/dist/plans/reconciliation.js +0 -246
@@ -1,12 +1,12 @@
1
1
  import { z } from 'zod';
2
2
  import { type IPlanCommand, type IActionEnvelope, type IPlanResult, type IPlanRevisionWorkflow } from '../contracts/index.js';
3
3
  import type { IStore } from '../store/index.js';
4
- import type { IPlanContractParser, IPlanStopJob } from './types.js';
4
+ import type { IPlanStopJob } from './types.js';
5
5
  /**
6
6
  * Coordinates bounded selected-plan files under the existing metadata lock.
7
7
  * @returns A handler for plan records and projections; it never dispatches native input.
8
8
  */
9
- export declare const createPlans: (coordinationRoot: string, roots: string[], store: IStore, runtimeEpoch: string, parseContract?: IPlanContractParser) => {
9
+ export declare const createPlans: (coordinationRoot: string, roots: string[], store: IStore, runtimeEpoch: string) => {
10
10
  /** Installs the runtime's one owner for stop/checkpoint work. */
11
11
  setStopHandler(handler: (job: IPlanStopJob) => void): void;
12
12
  /** Releases an owned phase after confirmed success or a retained failure. */
@@ -129,7 +129,7 @@ export declare const createPlans: (coordinationRoot: string, roots: string[], st
129
129
  threadId: string | null;
130
130
  nativeTurnId: string | null;
131
131
  nativeRequestId: string | null;
132
- delivery: "failed" | "canceled" | "queued" | "submitted" | "acknowledged" | "uncertain";
132
+ delivery: "failed" | "canceled" | "uncertain" | "queued" | "submitted" | "acknowledged";
133
133
  completion: "completed" | "failed" | "interrupted" | null;
134
134
  failure: "state-conflict" | "access-denied" | "agent-unavailable" | "operation-failed" | null;
135
135
  relatedActionId: string | null;
@@ -202,10 +202,10 @@ export declare const createPlans: (coordinationRoot: string, roots: string[], st
202
202
  isArchived: boolean;
203
203
  name: string;
204
204
  workspaceRoot: string;
205
- ownership: "uncertain" | "managed";
205
+ ownership: "managed" | "uncertain";
206
206
  runtimeEpoch: string | null;
207
207
  activeTurnId: string | null;
208
- state: "unknown" | "idle" | "completed" | "failed" | "interrupted" | "waiting-input" | "creating" | "inactive" | "starting" | "running" | "waiting-approval" | "stopping";
208
+ state: "unknown" | "idle" | "completed" | "failed" | "interrupted" | "waiting-input" | "running" | "creating" | "inactive" | "starting" | "waiting-approval" | "stopping";
209
209
  createdAt: number;
210
210
  updatedAt: number;
211
211
  } | null;
@@ -223,7 +223,7 @@ export declare const createPlans: (coordinationRoot: string, roots: string[], st
223
223
  threadId: string | null;
224
224
  nativeTurnId: string | null;
225
225
  nativeRequestId: string | null;
226
- delivery: "failed" | "canceled" | "queued" | "submitted" | "acknowledged" | "uncertain";
226
+ delivery: "failed" | "canceled" | "uncertain" | "queued" | "submitted" | "acknowledged";
227
227
  completion: "completed" | "failed" | "interrupted" | null;
228
228
  failure: "state-conflict" | "access-denied" | "agent-unavailable" | "operation-failed" | null;
229
229
  relatedActionId: string | null;
@@ -296,10 +296,10 @@ export declare const createPlans: (coordinationRoot: string, roots: string[], st
296
296
  isArchived: boolean;
297
297
  name: string;
298
298
  workspaceRoot: string;
299
- ownership: "uncertain" | "managed";
299
+ ownership: "managed" | "uncertain";
300
300
  runtimeEpoch: string | null;
301
301
  activeTurnId: string | null;
302
- state: "unknown" | "idle" | "completed" | "failed" | "interrupted" | "waiting-input" | "creating" | "inactive" | "starting" | "running" | "waiting-approval" | "stopping";
302
+ state: "unknown" | "idle" | "completed" | "failed" | "interrupted" | "waiting-input" | "running" | "creating" | "inactive" | "starting" | "waiting-approval" | "stopping";
303
303
  createdAt: number;
304
304
  updatedAt: number;
305
305
  };
@@ -9,13 +9,12 @@ import { resolveWorkspaceTarget } from '../runtime/state/index.js';
9
9
  import { canExecutePlanUnit, describePlan, updatePlanAuthority } from './authority.js';
10
10
  import { createPlanAdmission } from './admission.js';
11
11
  import { readPlanPage } from './projections.js';
12
- import { prepareAggregateProgress, prepareSequenceMarkers } from './documents.js';
13
- import { finalizeInitialSequence } from './finalization.js';
12
+ import { invalid, prepareAggregateProgress, prepareSequenceMarkers } from './documents.js';
13
+ import { finalizePlanSequence } from './finalization.js';
14
14
  import { beginPlanRevision, finishPlanCheckpoint, recordPlanCompletion, refreshPlanBaseline, } from './revisions.js';
15
15
  import { capturePlanWorktrees } from './evidence.js';
16
- import { proposeReconciliation, confirmReconciliation, renderReconciledSequence, } from './reconciliation.js';
17
16
  import { parsePlanCoordination, serializePlanCoordination, readPlanArtifacts, readPlanFile, writePlanFile, removePlanMilestones, resolvePlanDirectory, } from './files.js';
18
- import { hashPlanContent, isSamePlanRevision, computePlanRevision, parsePlanMilestones, } from './utilities.js';
17
+ import { hashPlanContent, isSamePlanRevision, parsePlanMilestones } from './utilities.js';
19
18
  const conflict = () => {
20
19
  throw new Exception('The HQ action conflicts with its recorded state', {
21
20
  code: 'JG_AGENT_HQ_ACTION_CONFLICT',
@@ -28,7 +27,7 @@ const conflict = () => {
28
27
  * Coordinates bounded selected-plan files under the existing metadata lock.
29
28
  * @returns A handler for plan records and projections; it never dispatches native input.
30
29
  */
31
- export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseContract) => {
30
+ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch) => {
32
31
  const assertWriteBounds = (intent) => {
33
32
  const markdown = [
34
33
  intent.plan,
@@ -53,7 +52,7 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
53
52
  const status = describePlan(artifacts, pendingActionId);
54
53
  const workflow = artifacts.coordination.revision;
55
54
  if (workflow &&
56
- ['quiescing', 'editing', 'reconciling', 'blocked'].includes(workflow.phase) &&
55
+ ['quiescing', 'editing', 'blocked'].includes(workflow.phase) &&
57
56
  (workflow.ownerRuntimeEpoch !== runtimeEpoch ||
58
57
  (workflow.phase === 'quiescing' && !activeStopPhases.has(workflow.phaseActionId)))) {
59
58
  status.state = 'blocked';
@@ -65,7 +64,7 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
65
64
  /** Converts unavailable contract reads into paused input, preserving the underlying diagnostics. */
66
65
  const readAdmissionPlan = async (directory, translateError, apply) => {
67
66
  try {
68
- return await readPlanArtifacts({ directory }, roots, parseContract);
67
+ return await readPlanArtifacts({ directory }, roots);
69
68
  }
70
69
  catch (cause) {
71
70
  if (stopHandler &&
@@ -326,7 +325,7 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
326
325
  phaseActionId: id,
327
326
  controls: observedConflict.controls,
328
327
  });
329
- return readPlanArtifacts({ directory: artifacts.directory }, roots, parseContract);
328
+ return readPlanArtifacts({ directory: artifacts.directory }, roots);
330
329
  };
331
330
  const implementationDigest = (action) => hashPlanContent(JSON.stringify(['implementation-progress', action]));
332
331
  const resumeImplementation = async (directory, action) => {
@@ -400,7 +399,7 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
400
399
  * - JG_AGENT_HQ_PLAN_FAILED: The HQ plan operation failed
401
400
  */
402
401
  async stopPhase(target) {
403
- return (await readPlanArtifacts(target, roots, parseContract)).coordination.revision;
402
+ return (await readPlanArtifacts(target, roots)).coordination.revision;
404
403
  },
405
404
  /**
406
405
  * Retains failed quiescence/checkpoint work without releasing the editing gate.
@@ -427,7 +426,7 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
427
426
  */
428
427
  async blockRevision(target, revisionId, phaseActionId, reason) {
429
428
  await withHqLock(coordinationRoot, 'plan-revision-blocked', () => withDocuments(target.directory, async (apply) => {
430
- const artifacts = await readPlanArtifacts(target, roots, parseContract);
429
+ const artifacts = await readPlanArtifacts(target, roots);
431
430
  const workflow = artifacts.coordination.revision;
432
431
  if (!workflow ||
433
432
  workflow.id !== revisionId ||
@@ -480,6 +479,12 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
480
479
  * - JG_AGENT_HQ_LOCK_OWNERSHIP_CHANGED: HQ lock ownership changed before release
481
480
  */
482
481
  async handle(command) {
482
+ if (command.kind === 'register') {
483
+ // registration takes no locks and never reads plan files
484
+ const directory = await resolvePlanDirectory(command.target.directory, roots);
485
+ await store.registerPlan(directory);
486
+ return { kind: 'registered', result: { directory } };
487
+ }
483
488
  const completionWorktrees = command.kind === 'complete' ? await capturePlanWorktrees(command.checkouts, roots) : [];
484
489
  const result = await withHqLock(coordinationRoot, `plan-${command.kind}`, () => withDocuments(command.target.directory, async (apply) => {
485
490
  let artifacts = await readAdmissionPlan(command.target.directory, false, apply);
@@ -488,7 +493,7 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
488
493
  artifacts = await observeChange(artifacts, apply);
489
494
  if (command.kind === 'status')
490
495
  return { kind: 'status', result: describeCurrent(artifacts, pendingActionId) };
491
- if (command.kind === 'milestones' || command.kind === 'reconciliation')
496
+ if (command.kind === 'milestones')
492
497
  return readPlanPage(store, artifacts, command);
493
498
  if (command.kind === 'check-execution') {
494
499
  const status = describePlan(artifacts, pendingActionId);
@@ -518,7 +523,7 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
518
523
  if (previous.digest !== digest || previous.directory !== artifacts.directory)
519
524
  conflict();
520
525
  await apply(previous);
521
- artifacts = await readPlanArtifacts(command.target, roots, parseContract);
526
+ artifacts = await readPlanArtifacts(command.target, roots);
522
527
  const current = describeCurrent(artifacts, await store.getPendingPlanOperationId(artifacts.directory));
523
528
  return command.kind === 'finalize' && current.isFinalized
524
529
  ? { kind: 'finalized', result: current, content: artifacts.milestones }
@@ -529,7 +534,6 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
529
534
  const coordination = structuredClone(artifacts.coordination);
530
535
  let milestones = null;
531
536
  let planSource = null;
532
- let needsReconciliation = false;
533
537
  if (command.kind === 'begin-revision') {
534
538
  const threadIds = [
535
539
  ...new Set([
@@ -550,12 +554,11 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
550
554
  if (!workflow ||
551
555
  workflow.id !== command.revisionId ||
552
556
  !workflow.checkpoint ||
553
- !['editing', 'reconciling', 'blocked'].includes(workflow.phase))
557
+ !['editing', 'blocked'].includes(workflow.phase))
554
558
  conflict();
555
559
  if (command.skill === 'jg-breakdown' && !describePlan(artifacts).isPlanApproved)
556
560
  conflict();
557
561
  workflow.hasUncertainEffects ||= !isSamePlanRevision(workflow.checkpoint.revision, artifacts.revision);
558
- workflow.proposal = null;
559
562
  workflow.phase = 'quiescing';
560
563
  workflow.phaseActionId = command.action.id;
561
564
  workflow.ownerRuntimeEpoch = runtimeEpoch;
@@ -582,83 +585,35 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
582
585
  coordination.completions.push(receipt);
583
586
  if (artifacts.milestones !== null &&
584
587
  artifacts.parsed.some((entry) => entry.id === command.milestoneId)) {
585
- const drafts = artifacts.parsed.map((entry) => ({
586
- ...entry,
587
- id: entry.id ?? conflict(),
588
- contractDigest: entry.contractDigest ?? conflict(),
589
- matchedSourceId: null,
590
- status: entry.id === command.milestoneId ? 'done' : entry.status,
591
- }));
592
- milestones = renderReconciledSequence(artifacts.milestones, drafts);
588
+ if (artifacts.parsed.some((entry) => !entry.id))
589
+ conflict();
590
+ const entry = artifacts.parsed.find((item) => item.id === command.milestoneId);
591
+ milestones = prepareSequenceMarkers(artifacts.milestones, [
592
+ { ordinal: entry.ordinal, id: entry.id, status: 'done' },
593
+ ]);
593
594
  coordination.baseline = refreshPlanBaseline(artifacts, milestones, artifacts.revision);
594
595
  }
595
596
  }
596
597
  else if (command.kind === 'finalize') {
598
+ if (!artifacts.conformance.sequence)
599
+ invalid();
597
600
  if (artifacts.skillsBinding === 'stale')
598
601
  conflict();
599
602
  const workflow = coordination.revision;
600
- let finalized = null;
601
603
  if (workflow && workflow.phase !== 'finished') {
602
- if (!['editing', 'reconciling', 'awaiting-approval'].includes(workflow.phase))
604
+ if (!['editing', 'awaiting-approval'].includes(workflow.phase))
603
605
  conflict();
604
606
  if ((await store.getPlanThreads(artifacts.directory)).length)
605
607
  conflict();
606
608
  if (!workflow.checkpoint?.isQuiescent)
607
609
  conflict();
608
- const proposal = workflow.proposal ?? proposeReconciliation(artifacts, command.action);
609
- if (proposal.inspectionHash !== artifacts.hashes.milestones ||
610
- !isSamePlanRevision(proposal.revision, artifacts.revision))
611
- conflict();
612
- workflow.proposal = proposal;
613
- if (proposal.unmatchedSourceIds.length && !command.confirmation) {
614
- workflow.phase = 'reconciling';
615
- needsReconciliation = true;
616
- }
617
- else {
618
- let drafts = proposal.drafts;
619
- if (proposal.unmatchedSourceIds.length) {
620
- if (command.confirmation.proposalId !== proposal.id)
621
- conflict();
622
- const confirmed = confirmReconciliation(artifacts, proposal, command.action, command.confirmation.decisions);
623
- drafts = confirmed.drafts;
624
- coordination.correspondences.push(...confirmed.records);
625
- proposal.confirmation = {
626
- action: command.action,
627
- decisions: command.confirmation.decisions,
628
- };
629
- }
630
- else if (command.confirmation)
631
- conflict();
632
- const content = artifacts.milestones === null
633
- ? null
634
- : renderReconciledSequence(artifacts.milestones, drafts);
635
- const revision = computePlanRevision({
636
- ...artifacts.contract,
637
- milestones: content,
638
- });
639
- for (const record of coordination.correspondences)
640
- if (record.action.id === command.action.id)
641
- record.revision = revision;
642
- finalized = { content, revision };
643
- workflow.phase = 'awaiting-approval';
644
- workflow.reason = null;
645
- }
646
- }
647
- else {
648
- if (command.confirmation)
649
- conflict();
650
- finalized = finalizeInitialSequence(artifacts);
651
- }
652
- if (finalized) {
653
- milestones = finalized.content;
654
- coordination.finalized = {
655
- action: command.action,
656
- revision: finalized.revision,
657
- fileHash: milestones === null ? null : hashPlanContent(milestones),
658
- createdAt: Date.now(),
659
- };
660
- coordination.baseline = refreshPlanBaseline(artifacts, milestones, finalized.revision);
610
+ workflow.phase = 'awaiting-approval';
611
+ workflow.reason = null;
661
612
  }
613
+ else if (coordination.finalized &&
614
+ !isSamePlanRevision(coordination.finalized.revision, artifacts.revision))
615
+ conflict();
616
+ Object.assign(coordination, finalizePlanSequence(artifacts, coordination, command.action));
662
617
  }
663
618
  else
664
619
  Object.assign(coordination, updatePlanAuthority(artifacts, command, runtimeEpoch));
@@ -694,14 +649,12 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
694
649
  state: 'prepared',
695
650
  });
696
651
  await apply(intent);
697
- artifacts = await readPlanArtifacts(command.target, roots, parseContract);
652
+ artifacts = await readPlanArtifacts(command.target, roots);
698
653
  await store.projectPlan({
699
654
  directory: artifacts.directory,
700
655
  sourceHash: artifacts.hashes.milestones,
701
656
  milestones: artifacts.parsed.map((milestone) => PlanMilestoneSchema.parse(milestone)),
702
657
  });
703
- if (needsReconciliation)
704
- return { kind: 'reconciliation-required', result: describeCurrent(artifacts) };
705
658
  return command.kind === 'finalize'
706
659
  ? {
707
660
  kind: 'finalized',
@@ -808,13 +761,13 @@ export const createPlans = (coordinationRoot, roots, store, runtimeEpoch, parseC
808
761
  * - JG_AGENT_HQ_LOCK_OWNERSHIP_CHANGED: HQ lock ownership changed before release
809
762
  */
810
763
  async checkpoint(target, revisionId, phaseActionId) {
811
- const selected = await readPlanArtifacts(target, roots, parseContract);
764
+ const selected = await readPlanArtifacts(target, roots);
812
765
  const current = selected.coordination.revision;
813
766
  if (!current || current.id !== revisionId || current.phaseActionId !== phaseActionId)
814
767
  conflict();
815
768
  const proofs = await capturePlanWorktrees(current.checkouts, roots);
816
769
  await withHqLock(coordinationRoot, 'plan-checkpoint', () => withDocuments(target.directory, async (apply) => {
817
- const artifacts = await readPlanArtifacts(target, roots, parseContract);
770
+ const artifacts = await readPlanArtifacts(target, roots);
818
771
  const workflow = artifacts.coordination.revision;
819
772
  if (!workflow || workflow.id !== revisionId || workflow.phaseActionId !== phaseActionId)
820
773
  conflict();
@@ -3,11 +3,11 @@ import type { IStore } from '../store/index.js';
3
3
  import { type IPlanArtifacts } from './types.js';
4
4
  /**
5
5
  * Reads a selected authoritative-file projection through bounded revision-bound seek pages.
6
- * @returns A milestone or retained-evidence page.
6
+ * @returns A milestone page.
7
7
  * @throws
8
8
  * - JG_AGENT_HQ_CURSOR_INVALID: The HQ cursor does not match this request
9
9
  * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
10
10
  */
11
11
  export declare const readPlanPage: (store: IStore, artifacts: IPlanArtifacts, command: Extract<IPlanCommand, {
12
- kind: "milestones" | "reconciliation";
12
+ kind: "milestones";
13
13
  }>) => Promise<IPlanResult>;
@@ -1,9 +1,8 @@
1
1
  import { Exception } from 'jg-exception';
2
2
  import { PlanMilestoneSchema } from '../contracts/index.js';
3
3
  import { decodeHistoryCursor, encodeHistoryCursor } from '../sessions/index.js';
4
- import { projectPlanRevision } from './revisions.js';
5
4
  import { isSamePlanRevision } from './utilities.js';
6
- import { PlanMilestonePositionSchema, PlanRevisionPositionSchema, } from './types.js';
5
+ import { PlanMilestonePositionSchema } from './types.js';
7
6
  const conflict = () => {
8
7
  throw new Exception('The HQ action conflicts with its recorded state', {
9
8
  code: 'JG_AGENT_HQ_ACTION_CONFLICT',
@@ -14,92 +13,55 @@ const conflict = () => {
14
13
  };
15
14
  /**
16
15
  * Reads a selected authoritative-file projection through bounded revision-bound seek pages.
17
- * @returns A milestone or retained-evidence page.
16
+ * @returns A milestone page.
18
17
  * @throws
19
18
  * - JG_AGENT_HQ_CURSOR_INVALID: The HQ cursor does not match this request
20
19
  * - JG_AGENT_HQ_STORE_FAILED: The HQ store failed
21
20
  */
22
21
  export const readPlanPage = async (store, artifacts, command) => {
23
- if (command.kind === 'milestones') {
24
- const filters = {
25
- directory: artifacts.directory,
26
- limit: command.limit,
27
- };
28
- const decoded = decodeHistoryCursor(command.cursor, filters);
29
- let after = 0;
30
- if (decoded) {
31
- try {
32
- const position = PlanMilestonePositionSchema.parse(JSON.parse(decoded));
33
- if (!isSamePlanRevision(position.revision, artifacts.revision) ||
34
- position.inspection !== artifacts.hashes.milestones)
35
- conflict();
36
- after = position.ordinal;
37
- }
38
- catch (cause) {
39
- throw new Exception('The HQ cursor does not match this request', {
40
- code: 'JG_AGENT_HQ_CURSOR_INVALID',
41
- data: { kind: 'invalid-request' },
42
- cause,
43
- });
44
- }
22
+ const filters = {
23
+ directory: artifacts.directory,
24
+ limit: command.limit,
25
+ };
26
+ const decoded = decodeHistoryCursor(command.cursor, filters);
27
+ let after = 0;
28
+ if (decoded) {
29
+ try {
30
+ const position = PlanMilestonePositionSchema.parse(JSON.parse(decoded));
31
+ if (!isSamePlanRevision(position.revision, artifacts.revision) ||
32
+ position.inspection !== artifacts.hashes.milestones)
33
+ conflict();
34
+ after = position.ordinal;
45
35
  }
46
- await store.projectPlan({
47
- directory: artifacts.directory,
48
- sourceHash: artifacts.hashes.milestones,
49
- milestones: artifacts.parsed.map((milestone) => PlanMilestoneSchema.parse(milestone)),
50
- });
51
- const page = await store.listPlanMilestones({
52
- directory: artifacts.directory,
53
- limit: command.limit,
54
- after,
55
- });
56
- return {
57
- kind: 'milestones',
58
- result: {
59
- data: page.data,
60
- nextCursor: encodeHistoryCursor(page.hasMore
61
- ? JSON.stringify({
62
- ordinal: page.data.at(-1).ordinal,
63
- inspection: artifacts.hashes.milestones,
64
- revision: artifacts.revision,
65
- })
66
- : null, filters),
67
- },
68
- };
69
- }
70
- {
71
- const filters = {
72
- directory: artifacts.directory,
73
- collection: command.collection,
74
- limit: command.limit,
75
- };
76
- const decoded = decodeHistoryCursor(command.cursor, filters);
77
- let after = '';
78
- if (decoded) {
79
- try {
80
- const position = PlanRevisionPositionSchema.parse(JSON.parse(decoded));
81
- if (position.inspection !== artifacts.hashes.coordination)
82
- conflict();
83
- after = position.id;
84
- }
85
- catch (cause) {
86
- throw new Exception('The HQ cursor does not match this request', {
87
- code: 'JG_AGENT_HQ_CURSOR_INVALID',
88
- data: { kind: 'invalid-request' },
89
- cause,
90
- });
91
- }
36
+ catch (cause) {
37
+ throw new Exception('The HQ cursor does not match this request', {
38
+ code: 'JG_AGENT_HQ_CURSOR_INVALID',
39
+ data: { kind: 'invalid-request' },
40
+ cause,
41
+ });
92
42
  }
93
- await store.projectPlanRevision(projectPlanRevision(artifacts));
94
- const page = await store.listPlanRevision({ ...filters, after });
95
- return {
96
- kind: 'reconciliation',
97
- result: {
98
- data: page.data,
99
- nextCursor: encodeHistoryCursor(page.hasMore
100
- ? JSON.stringify({ id: page.lastId, inspection: artifacts.hashes.coordination })
101
- : null, filters),
102
- },
103
- };
104
43
  }
44
+ await store.projectPlan({
45
+ directory: artifacts.directory,
46
+ sourceHash: artifacts.hashes.milestones,
47
+ milestones: artifacts.parsed.map((milestone) => PlanMilestoneSchema.parse(milestone)),
48
+ });
49
+ const page = await store.listPlanMilestones({
50
+ directory: artifacts.directory,
51
+ limit: command.limit,
52
+ after,
53
+ });
54
+ return {
55
+ kind: 'milestones',
56
+ result: {
57
+ data: page.data,
58
+ nextCursor: encodeHistoryCursor(page.hasMore
59
+ ? JSON.stringify({
60
+ ordinal: page.data.at(-1).ordinal,
61
+ inspection: artifacts.hashes.milestones,
62
+ revision: artifacts.revision,
63
+ })
64
+ : null, filters),
65
+ },
66
+ };
105
67
  };
@@ -1,7 +1,7 @@
1
1
  import { type IPlanCheckpoint, type IPlanCoordination, type IPlanOperatorAction, type IPlanCheckout, type IPlanWorktreeProof, type IPlanCompletion } from '../contracts/index.js';
2
- import type { IPlanArtifacts, IPlanRevisionProjection } from './types.js';
2
+ import type { IPlanArtifacts } from './types.js';
3
3
  /**
4
- * Saves contract identity before any planning skill can remove the milestone file.
4
+ * Saves the current contract, milestone identities and progress before planning edits begin.
5
5
  * @returns A durable snapshot; native quiescence and worktree evidence are recorded separately.
6
6
  * @throws
7
7
  * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
@@ -41,11 +41,10 @@ export declare const recordPlanCompletion: (artifacts: IPlanArtifacts, input: {
41
41
  checks: IPlanCompletion["checks"];
42
42
  }, checkouts: IPlanWorktreeProof[]) => IPlanCompletion;
43
43
  /**
44
- * Retains the latest canonical identities for reconciliation of directly edited/deleted files.
44
+ * Retains the latest finalized identities and progress, so a later checkpoint starts from them
45
+ * even after the files were edited directly.
45
46
  * @returns A new baseline without changing original completion receipts.
46
47
  * @throws
47
48
  * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
48
49
  */
49
50
  export declare const refreshPlanBaseline: (artifacts: IPlanArtifacts, content: string | null, revision: IPlanCheckpoint["revision"]) => IPlanCheckpoint;
50
- /** Builds indexed retained evidence without exposing whole coordination collections to clients. */
51
- export declare const projectPlanRevision: (artifacts: IPlanArtifacts) => IPlanRevisionProjection;
@@ -11,7 +11,7 @@ const conflict = () => {
11
11
  });
12
12
  };
13
13
  /**
14
- * Saves contract identity before any planning skill can remove the milestone file.
14
+ * Saves the current contract, milestone identities and progress before planning edits begin.
15
15
  * @returns A durable snapshot; native quiescence and worktree evidence are recorded separately.
16
16
  * @throws
17
17
  * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
@@ -73,7 +73,6 @@ export const beginPlanRevision = (artifacts, input) => {
73
73
  checkouts: input.checkouts,
74
74
  checkpoint,
75
75
  invocation: null,
76
- proposal: null,
77
76
  createdAt: Date.now(),
78
77
  hasUncertainEffects: !!artifacts.coordination.observedConflict ||
79
78
  !isSamePlanRevision(checkpoint.revision, artifacts.revision),
@@ -136,17 +135,13 @@ export const recordPlanCompletion = (artifacts, input, checkouts) => {
136
135
  checkouts,
137
136
  checks: input.checks,
138
137
  completedAt: Date.now(),
139
- reopenActionId: null,
138
+ reopenedBy: null,
140
139
  };
141
140
  }
142
141
  const milestone = artifacts.parsed.find((entry) => entry.id === input.milestoneId) ??
143
142
  artifacts.coordination.revision?.checkpoint?.entries.find((entry) => entry.id === input.milestoneId);
144
143
  if (!milestone?.id || !milestone.contractDigest)
145
144
  conflict();
146
- const reopened = [...artifacts.coordination.correspondences]
147
- .reverse()
148
- .find((record) => record.relation === 'reopened' &&
149
- record.targets.some((target) => target.id === input.milestoneId));
150
145
  return {
151
146
  id: input.action.id,
152
147
  action: input.action,
@@ -159,11 +154,12 @@ export const recordPlanCompletion = (artifacts, input, checkouts) => {
159
154
  checkouts,
160
155
  checks: input.checks,
161
156
  completedAt: Date.now(),
162
- reopenActionId: reopened?.action.id ?? null,
157
+ reopenedBy: null,
163
158
  };
164
159
  };
165
160
  /**
166
- * Retains the latest canonical identities for reconciliation of directly edited/deleted files.
161
+ * Retains the latest finalized identities and progress, so a later checkpoint starts from them
162
+ * even after the files were edited directly.
167
163
  * @returns A new baseline without changing original completion receipts.
168
164
  * @throws
169
165
  * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
@@ -183,38 +179,3 @@ export const refreshPlanBaseline = (artifacts, content, revision) => {
183
179
  capturedAt: Date.now(),
184
180
  };
185
181
  };
186
- /** Builds indexed retained evidence without exposing whole coordination collections to clients. */
187
- export const projectPlanRevision = (artifacts) => {
188
- const records = [];
189
- const sources = new Map();
190
- for (const correspondence of artifacts.coordination.correspondences) {
191
- for (const source of correspondence.sources)
192
- sources.set(`${source.id}:${source.contractDigest}`, source);
193
- records.push({
194
- collection: 'correspondences',
195
- id: correspondence.id,
196
- entry: {
197
- kind: 'correspondence',
198
- entry: {
199
- ...correspondence,
200
- sources: correspondence.sources.map(({ id, contractDigest, status }) => ({
201
- id,
202
- contractDigest,
203
- status,
204
- })),
205
- },
206
- },
207
- });
208
- }
209
- for (const source of artifacts.coordination.revision?.checkpoint?.entries ?? [])
210
- sources.set(`${source.id}:${source.contractDigest}`, source);
211
- for (const source of artifacts.coordination.baseline?.entries ?? [])
212
- sources.set(`${source.id}:${source.contractDigest}`, source);
213
- for (const [id, entry] of sources)
214
- records.push({ collection: 'sources', id, entry: { kind: 'source', entry } });
215
- for (const entry of artifacts.coordination.revision?.proposal?.drafts ?? [])
216
- records.push({ collection: 'drafts', id: entry.id, entry: { kind: 'draft', entry } });
217
- for (const entry of artifacts.coordination.completions)
218
- records.push({ collection: 'evidence', id: entry.id, entry: { kind: 'evidence', entry } });
219
- return { directory: artifacts.directory, sourceHash: artifacts.hashes.coordination, records };
220
- };