jg-agent-hq 3.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 (159) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +13 -13
  3. package/api/README.md +91 -102
  4. package/dist/actions/actions.js +15 -0
  5. package/dist/cli/cli.js +26 -35
  6. package/dist/cli/utilities.d.ts +1 -1
  7. package/dist/cli/utilities.js +8 -25
  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 +7 -9
  15. package/dist/contracts/index.js +5 -7
  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 +461 -1047
  25. package/dist/contracts/types.js +8 -0
  26. package/dist/index.d.ts +2 -4
  27. package/dist/index.js +1 -3
  28. package/dist/plans/admission.d.ts +6 -6
  29. package/dist/plans/admission.js +1 -1
  30. package/dist/plans/authority.js +15 -13
  31. package/dist/plans/documents.d.ts +3 -17
  32. package/dist/plans/documents.js +6 -62
  33. package/dist/plans/files.d.ts +2 -2
  34. package/dist/plans/files.js +2 -4
  35. package/dist/plans/finalization.d.ts +6 -8
  36. package/dist/plans/finalization.js +25 -26
  37. package/dist/plans/index.d.ts +2 -3
  38. package/dist/plans/index.js +1 -2
  39. package/dist/plans/plans.d.ts +8 -8
  40. package/dist/plans/plans.js +33 -82
  41. package/dist/plans/projections.d.ts +2 -2
  42. package/dist/plans/projections.js +44 -82
  43. package/dist/plans/revisions.d.ts +4 -5
  44. package/dist/plans/revisions.js +5 -44
  45. package/dist/plans/types.d.ts +0 -281
  46. package/dist/plans/types.js +2 -30
  47. package/dist/plans/utilities.js +2 -11
  48. package/dist/providers/claude/agents/agents.d.ts +16 -0
  49. package/dist/providers/claude/agents/agents.js +80 -0
  50. package/dist/providers/claude/agents/constants.d.ts +3 -0
  51. package/dist/providers/claude/agents/constants.js +4 -0
  52. package/dist/providers/claude/agents/index.d.ts +1 -0
  53. package/dist/providers/claude/agents/index.js +2 -0
  54. package/dist/providers/claude/agents/types.d.ts +14 -0
  55. package/dist/providers/claude/agents/types.js +9 -0
  56. package/dist/providers/claude/history/history.model.js +2 -0
  57. package/dist/providers/claude/history/types.d.ts +92 -368
  58. package/dist/providers/claude/index.d.ts +1 -0
  59. package/dist/providers/claude/index.js +2 -0
  60. package/dist/providers/codex/adapter.d.ts +1 -1
  61. package/dist/providers/codex/adapter.js +26 -3
  62. package/dist/providers/codex/codex.js +47 -18
  63. package/dist/providers/codex/events.d.ts +2 -1
  64. package/dist/providers/codex/events.js +8 -3
  65. package/dist/providers/codex/index.d.ts +1 -1
  66. package/dist/providers/codex/index.js +1 -1
  67. package/dist/providers/codex/rpc.d.ts +9 -4
  68. package/dist/providers/codex/rpc.js +109 -47
  69. package/dist/providers/codex/skill-roots/constants.d.ts +4 -0
  70. package/dist/providers/codex/skill-roots/constants.js +7 -0
  71. package/dist/providers/codex/skill-roots/index.d.ts +2 -0
  72. package/dist/providers/codex/skill-roots/index.js +4 -0
  73. package/dist/providers/codex/skill-roots/skill-roots.d.ts +35 -0
  74. package/dist/providers/codex/skill-roots/skill-roots.js +93 -0
  75. package/dist/providers/codex/transformers.d.ts +3 -1
  76. package/dist/providers/codex/transformers.js +12 -1
  77. package/dist/providers/codex/types.d.ts +4 -0
  78. package/dist/providers/codex/types.js +4 -1
  79. package/dist/providers/codex/websocket/constants.d.ts +11 -0
  80. package/dist/providers/codex/websocket/constants.js +18 -0
  81. package/dist/providers/codex/websocket/index.d.ts +1 -0
  82. package/dist/providers/codex/websocket/index.js +2 -0
  83. package/dist/providers/codex/websocket/websocket.d.ts +7 -0
  84. package/dist/providers/codex/websocket/websocket.js +219 -0
  85. package/dist/providers/index.d.ts +2 -2
  86. package/dist/providers/index.js +1 -1
  87. package/dist/providers/process.d.ts +2 -2
  88. package/dist/providers/process.js +37 -4
  89. package/dist/providers/registry/registry.js +2 -1
  90. package/dist/providers/types.d.ts +25 -2
  91. package/dist/runtime/runtime.d.ts +0 -2
  92. package/dist/runtime/runtime.js +11 -5
  93. package/dist/runtime/state/state.d.ts +1 -1
  94. package/dist/runtime/state/state.js +2 -2
  95. package/dist/runtime/types.d.ts +0 -2
  96. package/dist/runtime/types.js +0 -3
  97. package/dist/sessions/sessions.js +2 -0
  98. package/dist/snapshots/archive/archive.d.ts +29 -0
  99. package/dist/snapshots/archive/archive.js +342 -0
  100. package/dist/snapshots/archive/constants.d.ts +5 -0
  101. package/dist/snapshots/archive/constants.js +8 -0
  102. package/dist/snapshots/archive/index.d.ts +1 -0
  103. package/dist/snapshots/archive/index.js +2 -0
  104. package/dist/snapshots/artifacts.d.ts +10 -1
  105. package/dist/snapshots/artifacts.js +38 -13
  106. package/dist/snapshots/capture.d.ts +3 -2
  107. package/dist/snapshots/capture.js +29 -13
  108. package/dist/snapshots/database.d.ts +2 -2
  109. package/dist/snapshots/database.js +30 -14
  110. package/dist/snapshots/fences.d.ts +4 -9
  111. package/dist/snapshots/fences.js +9 -22
  112. package/dist/snapshots/index.d.ts +1 -2
  113. package/dist/snapshots/index.js +2 -3
  114. package/dist/snapshots/snapshots.d.ts +6 -5
  115. package/dist/snapshots/snapshots.js +13 -13
  116. package/dist/snapshots/snapshots.worker.js +1 -1
  117. package/dist/snapshots/types.d.ts +26 -5
  118. package/dist/snapshots/types.js +15 -4
  119. package/dist/storage/schema/constants.d.ts +2 -2
  120. package/dist/storage/schema/constants.js +9 -3
  121. package/dist/storage/schema/index.d.ts +2 -3
  122. package/dist/storage/schema/index.js +4 -3
  123. package/dist/storage/schema/schema.d.ts +10 -8
  124. package/dist/storage/schema/schema.js +22 -36
  125. package/dist/storage/schema/types.d.ts +1 -11
  126. package/dist/storage/schema/types.js +2 -2
  127. package/dist/storage/storage.d.ts +1 -1
  128. package/dist/storage/storage.js +2 -2
  129. package/dist/store/collaboration/collaboration.model.d.ts +2 -2
  130. package/dist/store/control/types.d.ts +16 -16
  131. package/dist/store/plans/plans.model.d.ts +3 -105
  132. package/dist/store/plans/plans.model.js +6 -46
  133. package/dist/store/schema.d.ts +0 -2
  134. package/dist/store/schema.js +6 -25
  135. package/dist/store/schema.sql +90 -16
  136. package/dist/store/sessions/index.d.ts +1 -0
  137. package/dist/store/sessions/index.js +2 -0
  138. package/dist/store/sessions/sessions.model.d.ts +28 -0
  139. package/dist/store/sessions/sessions.model.js +105 -0
  140. package/dist/store/store.d.ts +0 -2
  141. package/dist/store/store.js +13 -9
  142. package/dist/store/store.worker.js +16 -11
  143. package/dist/store/types.d.ts +134 -513
  144. package/dist/store/types.js +21 -7
  145. package/docs/recovery.md +6 -16
  146. package/errors/README.md +30 -36
  147. package/package.json +1 -1
  148. package/dist/plans/reconciliation.d.ts +0 -34
  149. package/dist/plans/reconciliation.js +0 -246
  150. package/dist/storage/schema/v1-to-v2.sql +0 -1
  151. package/dist/storage/schema/v1.sql +0 -538
  152. package/dist/storage/upgrade/index.d.ts +0 -2
  153. package/dist/storage/upgrade/index.js +0 -2
  154. package/dist/storage/upgrade/types.d.ts +0 -61
  155. package/dist/storage/upgrade/types.js +0 -42
  156. package/dist/storage/upgrade/upgrade.d.ts +0 -33
  157. package/dist/storage/upgrade/upgrade.js +0 -196
  158. package/dist/storage/upgrade/upgrade.worker.d.ts +0 -1
  159. package/dist/storage/upgrade/upgrade.worker.js +0 -220
@@ -10,6 +10,7 @@ import { SkillIdSchema, SkillPageSchema, SkillPreviewSchema } from './skills/ind
10
10
  import { NativeIdSchema, CursorSchema, NativeLineageSchema } from './identities/index.js';
11
11
  import { ProviderModelPageSchema, ProviderModelsRequestSchema } from './models/index.js';
12
12
  import { ConfigurationRequestSchema, SessionConfigurationSchema } from './configuration/index.js';
13
+ import { SessionStateSchema, SessionTransitionPageSchema } from './sessions/index.js';
13
14
  import { PlanCommandSchema, PlanResultSchema } from './plans/index.js';
14
15
  import { ActionPlanContextSchema, ActionEnvelopeSchema, ActionReceiptSchema, ActionSummarySchema, ManagedThreadSchema, NativeApprovalSchema, LifecycleEventSchema, } from './actions/index.js';
15
16
  // pagination is validated before adapters receive a native continuation
@@ -106,6 +107,11 @@ export const HqRequestSchema = z.discriminatedUnion('kind', [
106
107
  threadId: z.uuid(),
107
108
  afterRevision: z.number().int().nonnegative().optional(),
108
109
  }),
110
+ z.strictObject({
111
+ kind: z.literal('session-states'),
112
+ afterSequence: z.number().int().nonnegative().default(0),
113
+ limit: z.number().int().min(1).max(128).default(32),
114
+ }),
109
115
  ]);
110
116
  // native discovery is external/read-only until explicitly adopted for control
111
117
  export const ThreadSummarySchema = z.object({
@@ -117,6 +123,7 @@ export const ThreadSummarySchema = z.object({
117
123
  createdAt: z.number().int(),
118
124
  updatedAt: z.number().int(),
119
125
  nativeState: z.enum(['notLoaded', 'idle', 'systemError', 'active', 'unknown']),
126
+ state: SessionStateSchema,
120
127
  ownership: z.enum(['external', 'managed', 'uncertain']),
121
128
  managedId: z.uuid().nullable(),
122
129
  historyState: z.enum(['available', 'unavailable']),
@@ -287,6 +294,7 @@ export const HqResponseSchema = z.discriminatedUnion('kind', [
287
294
  }),
288
295
  }),
289
296
  z.object({ kind: z.literal('live-items'), result: LiveItemsSchema }),
297
+ z.object({ kind: z.literal('session-states'), result: SessionTransitionPageSchema }),
290
298
  ]);
291
299
  export const ErrorKindSchema = z.enum(Object.keys(PUBLIC_ERROR_MESSAGES));
292
300
  export const IpcRequestSchema = z.strictObject({
package/dist/index.d.ts CHANGED
@@ -8,12 +8,10 @@ export type { IProviderId, IProviderCapability, IProviderCapabilitySet, IProvide
8
8
  export type { IProviderModel, IProviderModelPage, IProviderModelsRequest, } from './contracts/models/index.js';
9
9
  export type { ITurnSettings, ISessionSettings, IConfigurationRequest, IConfigurationChoice, ISessionConfiguration, } from './contracts/configuration/index.js';
10
10
  export type { INativeLineage } from './contracts/identities/index.js';
11
- export { upgradeHqStorage } from './storage/upgrade/index.js';
12
- export type { IHqStorageUpgradeOptions, IHqStorageUpgradeResult } from './storage/upgrade/index.js';
13
11
  export type { IStorageDescriptor, IStorageMaintenanceOperation } from './storage/index.js';
14
- export { createHqSnapshot, inspectHqSnapshot, restoreHqSnapshot } from './snapshots/index.js';
12
+ export { createHqSnapshot, inspectHqSnapshot, restoreHqSnapshot, packHqSnapshot, unpackHqSnapshot, } from './snapshots/index.js';
15
13
  export type { IHqSnapshotInspection, IHqRestoreOptions, IHqRestoreResult, } from './snapshots/index.js';
16
14
  export { computePlanRevision } from './plans/index.js';
17
- export type { IPlanContract, IPlanContractParser } from './plans/index.js';
15
+ export type { IPlanContract } from './plans/index.js';
18
16
  export type { IProviderInputFile } from './providers/index.js';
19
17
  export type { IInputFile, IBoundInputFile, IOutputSchema, ITurnUsage, ITurnResult, IPreparedInput, } from './contracts/index.js';
package/dist/index.js CHANGED
@@ -3,9 +3,7 @@ export { RUNTIME_DIRECTORY, HQ_LOCK_FILE, getOwnerLiveness, acquireHqLock, withH
3
3
  // native runtime and local client
4
4
  export { createAgentHq } from './runtime/index.js';
5
5
  export { requestAgentHq } from './ipc/index.js';
6
- // trusted offline storage upgrades
7
- export { upgradeHqStorage } from './storage/upgrade/index.js';
8
6
  // trusted host snapshot and offline recovery
9
- export { createHqSnapshot, inspectHqSnapshot, restoreHqSnapshot } from './snapshots/index.js';
7
+ export { createHqSnapshot, inspectHqSnapshot, restoreHqSnapshot, packHqSnapshot, unpackHqSnapshot, } from './snapshots/index.js';
10
8
  // pure execution revision contracts
11
9
  export { computePlanRevision } from './plans/index.js';
@@ -69,7 +69,7 @@ export declare const createPlanAdmission: (coordinationRoot: string, store: ISto
69
69
  threadId: string | null;
70
70
  nativeTurnId: string | null;
71
71
  nativeRequestId: string | null;
72
- delivery: "failed" | "canceled" | "queued" | "submitted" | "acknowledged" | "uncertain";
72
+ delivery: "failed" | "canceled" | "uncertain" | "queued" | "submitted" | "acknowledged";
73
73
  completion: "completed" | "failed" | "interrupted" | null;
74
74
  failure: "state-conflict" | "access-denied" | "agent-unavailable" | "operation-failed" | null;
75
75
  relatedActionId: string | null;
@@ -142,10 +142,10 @@ export declare const createPlanAdmission: (coordinationRoot: string, store: ISto
142
142
  isArchived: boolean;
143
143
  name: string;
144
144
  workspaceRoot: string;
145
- ownership: "uncertain" | "managed";
145
+ ownership: "managed" | "uncertain";
146
146
  runtimeEpoch: string | null;
147
147
  activeTurnId: string | null;
148
- state: "unknown" | "idle" | "completed" | "failed" | "interrupted" | "waiting-input" | "creating" | "inactive" | "starting" | "running" | "waiting-approval" | "stopping";
148
+ state: "unknown" | "idle" | "completed" | "failed" | "interrupted" | "waiting-input" | "running" | "creating" | "inactive" | "starting" | "waiting-approval" | "stopping";
149
149
  createdAt: number;
150
150
  updatedAt: number;
151
151
  } | null;
@@ -186,7 +186,7 @@ export declare const createPlanAdmission: (coordinationRoot: string, store: ISto
186
186
  threadId: string | null;
187
187
  nativeTurnId: string | null;
188
188
  nativeRequestId: string | null;
189
- delivery: "failed" | "canceled" | "queued" | "submitted" | "acknowledged" | "uncertain";
189
+ delivery: "failed" | "canceled" | "uncertain" | "queued" | "submitted" | "acknowledged";
190
190
  completion: "completed" | "failed" | "interrupted" | null;
191
191
  failure: "state-conflict" | "access-denied" | "agent-unavailable" | "operation-failed" | null;
192
192
  relatedActionId: string | null;
@@ -259,10 +259,10 @@ export declare const createPlanAdmission: (coordinationRoot: string, store: ISto
259
259
  isArchived: boolean;
260
260
  name: string;
261
261
  workspaceRoot: string;
262
- ownership: "uncertain" | "managed";
262
+ ownership: "managed" | "uncertain";
263
263
  runtimeEpoch: string | null;
264
264
  activeTurnId: string | null;
265
- state: "unknown" | "idle" | "completed" | "failed" | "interrupted" | "waiting-input" | "creating" | "inactive" | "starting" | "running" | "waiting-approval" | "stopping";
265
+ state: "unknown" | "idle" | "completed" | "failed" | "interrupted" | "waiting-input" | "running" | "creating" | "inactive" | "starting" | "waiting-approval" | "stopping";
266
266
  createdAt: number;
267
267
  updatedAt: number;
268
268
  };
@@ -56,7 +56,7 @@ export const createPlanAdmission = (coordinationRoot, store, runtimeEpoch, readP
56
56
  context: { directory: artifacts.directory, scope, observedRevision: artifacts.revision },
57
57
  };
58
58
  };
59
- /** Blocks work on a bound thread while its contracts or owner are being reconciled. */
59
+ /** Blocks work on a bound thread while its contracts are revised or its owner is unavailable. */
60
60
  const boundArtifacts = async (context, apply) => {
61
61
  const artifacts = await readPlan(context.directory, apply);
62
62
  if ((await store.getPendingPlanOperationId(artifacts.directory)) ||
@@ -1,6 +1,5 @@
1
1
  import { Exception } from 'jg-exception';
2
2
  import { isSamePlanRevision } from './utilities.js';
3
- import { createCompletionLookup } from './reconciliation.js';
4
3
  import { invalid } from './documents.js';
5
4
  const conflict = () => {
6
5
  throw new Exception('The HQ action conflicts with its recorded state', {
@@ -24,18 +23,19 @@ export const describePlan = (artifacts, pendingActionId = null) => {
24
23
  !!coordination.sequenceApproval &&
25
24
  !coordination.sequenceApproval.revokedBy &&
26
25
  isSamePlanRevision(coordination.sequenceApproval.revision, revision);
27
- const verified = createCompletionLookup(coordination.completions, coordination.correspondences);
26
+ // a done marker counts only with a current receipt for its milestone ID
27
+ const current = coordination.completions.filter((receipt) => !receipt.reopenedBy);
28
+ const evidenced = new Set(current.map((receipt) => receipt.milestoneId));
29
+ const verified = (milestone) => !!milestone.id && evidenced.has(milestone.id);
30
+ const milestoneIds = new Set(artifacts.parsed.map((milestone) => milestone.id));
28
31
  const workflow = coordination.revision;
29
- const invalidated = new Set(coordination.correspondences.flatMap((record) => record.invalidatedReceiptIds));
30
32
  const isWholePlanComplete = artifacts.milestones === null &&
31
- coordination.completions.some((receipt) => receipt.milestoneId === null &&
33
+ current.some((receipt) => receipt.milestoneId === null &&
32
34
  receipt.contractDigest === revision.planDigest &&
33
- receipt.revision.breakdownDigest === null &&
34
- !invalidated.has(receipt.id));
35
+ receipt.revision.breakdownDigest === null);
35
36
  const state = coordination.observedConflict ||
36
37
  pendingActionId ||
37
38
  workflow?.phase === 'blocked' ||
38
- workflow?.phase === 'reconciling' ||
39
39
  artifacts.parsed.some((milestone) => milestone.status === 'done' && !verified(milestone))
40
40
  ? 'blocked'
41
41
  : workflow?.phase === 'quiescing' ||
@@ -70,7 +70,6 @@ export const describePlan = (artifacts, pendingActionId = null) => {
70
70
  milestoneCount: artifacts.parsed.length,
71
71
  coordination: {
72
72
  schemaVersion: coordination.schemaVersion,
73
- comparisonCount: coordination.comparisons.length,
74
73
  finalized: coordination.finalized,
75
74
  planApproval: coordination.planApproval,
76
75
  sequenceApproval: coordination.sequenceApproval,
@@ -78,6 +77,14 @@ export const describePlan = (artifacts, pendingActionId = null) => {
78
77
  lastActionId: coordination.lastActionId,
79
78
  observedConflict: coordination.observedConflict,
80
79
  completionCount: coordination.completions.length,
80
+ unmatchedEvidence: current
81
+ .filter((receipt) => receipt.milestoneId !== null && !milestoneIds.has(receipt.milestoneId))
82
+ .map(({ id, milestoneId, title, completedAt }) => ({
83
+ id,
84
+ milestoneId,
85
+ title,
86
+ completedAt,
87
+ })),
81
88
  revision: workflow
82
89
  ? {
83
90
  id: workflow.id,
@@ -92,11 +99,6 @@ export const describePlan = (artifacts, pendingActionId = null) => {
92
99
  createdAt: workflow.createdAt,
93
100
  hasUncertainEffects: workflow.hasUncertainEffects,
94
101
  hasCheckpoint: !!workflow.checkpoint,
95
- hasProposal: !!workflow.proposal,
96
- proposalId: workflow.proposal?.id ?? null,
97
- unmatchedCount: workflow.proposal?.confirmation
98
- ? 0
99
- : (workflow.proposal?.unmatchedSourceIds.length ?? 0),
100
102
  }
101
103
  : null,
102
104
  },
@@ -24,14 +24,12 @@ export declare const observePlanConformance: (plan: string, milestones: string |
24
24
  */
25
25
  export declare const observePlanId: (source: string) => string | null;
26
26
  /**
27
- * The default HQ profile keeps unknown contract fields, including the plan identity.
27
+ * Keeps the body and every frontmatter field except the administrative keys, including the plan
28
+ * identity, as the execution contract.
28
29
  * @throws
29
30
  * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
30
31
  */
31
- export declare const observePlanContract: (source: string, custom?: {
32
- body: string;
33
- metadata: IPlanMetadata;
34
- }) => {
32
+ export declare const observePlanContract: (source: string) => {
35
33
  body: string;
36
34
  metadata: IPlanMetadata;
37
35
  };
@@ -64,18 +62,6 @@ export declare const observeSequence: (source: string) => {
64
62
  plan_content_sha256: string;
65
63
  } | null;
66
64
  };
67
- /**
68
- * Missing identities are assigned once by the engine, then persisted by HQ's journal.
69
- * @throws
70
- * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
71
- */
72
- export declare const prepareSequenceIds: (source: string, expectedSha256: string) => string;
73
- /**
74
- * New requirements receive engine identities; exact verified correspondence retains its identity.
75
- * @throws
76
- * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
77
- */
78
- export declare const prepareReconciliationIds: (source: string, retained: Map<number, string>) => string;
79
65
  /**
80
66
  * Prepares only explicitly selected identity/progress markers, preserving all surrounding bytes.
81
67
  * @throws
@@ -1,6 +1,6 @@
1
1
  import { hashValue as fingerprintSource } from 'jg-crypto';
2
2
  import { Exception } from 'jg-exception';
3
- import { checkPlan, fingerprintPlan, parseMilestones, parsePlan, preparePlanDocumentWrite, preparePlanUpdate, } from 'jg-plans';
3
+ import { checkPlan, fingerprintPlan, parseMilestones, parsePlan, preparePlanUpdate, } from 'jg-plans';
4
4
  import { z } from 'zod';
5
5
  import { PlanMetadataSchema } from '../contracts/index.js';
6
6
  const administrativeKeys = ['created_at', 'updated_at', 'revision', 'status'];
@@ -60,28 +60,18 @@ export const observePlanId = (source) => {
60
60
  return typeof id === 'string' && id.trim().length > 0 ? id : null;
61
61
  };
62
62
  /**
63
- * The default HQ profile keeps unknown contract fields, including the plan identity.
63
+ * Keeps the body and every frontmatter field except the administrative keys, including the plan
64
+ * identity, as the execution contract.
64
65
  * @throws
65
66
  * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
66
67
  */
67
- export const observePlanContract = (source, custom) => {
68
+ export const observePlanContract = (source) => {
68
69
  const document = parsePlan(source);
69
70
  const raw = metadataOf(document);
70
71
  if (!document.body || ('id' in raw && !z.string().trim().min(1).safeParse(raw.id).success))
71
72
  return invalid();
72
- if (custom) {
73
- const parsed = PlanMetadataSchema.safeParse(custom.metadata);
74
- if (!parsed.success || custom.body !== document.body)
75
- return invalid(parsed.error);
76
- return { body: document.body, metadata: parsed.data };
77
- }
78
- const extensions = Object.fromEntries(Object.entries(raw).filter(([key]) => ![...administrativeKeys, 'scope', 'repositories', 'errorReservations'].includes(key)));
79
- const parsed = PlanMetadataSchema.safeParse({
80
- scope: 'scope' in raw ? raw.scope : 'local',
81
- repositories: 'repositories' in raw ? raw.repositories : [],
82
- errorReservations: 'errorReservations' in raw ? raw.errorReservations : [],
83
- extensions,
84
- });
73
+ const extensions = Object.fromEntries(Object.entries(raw).filter(([key]) => !administrativeKeys.includes(key)));
74
+ const parsed = PlanMetadataSchema.safeParse({ extensions });
85
75
  if (!parsed.success)
86
76
  return invalid(parsed.error);
87
77
  return { body: document.body, metadata: parsed.data };
@@ -202,52 +192,6 @@ export const observeSequence = (source) => {
202
192
  ]);
203
193
  return { entries, shared, metadata, binding };
204
194
  };
205
- /**
206
- * Missing identities are assigned once by the engine, then persisted by HQ's journal.
207
- * @throws
208
- * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
209
- */
210
- export const prepareSequenceIds = (source, expectedSha256) => {
211
- try {
212
- return preparePlanDocumentWrite(source, {
213
- document: 'milestones',
214
- expectedSha256,
215
- source,
216
- assignMissingIds: true,
217
- }).source;
218
- }
219
- catch (cause) {
220
- return invalid(cause);
221
- }
222
- };
223
- /**
224
- * New requirements receive engine identities; exact verified correspondence retains its identity.
225
- * @throws
226
- * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
227
- */
228
- export const prepareReconciliationIds = (source, retained) => {
229
- const document = parseMilestones(source);
230
- const omissions = document.milestones.flatMap((entry) => retained.has(entry.ordinal)
231
- ? []
232
- : entry.idMarkers.map((marker) => ({ start: marker.lineStart, end: marker.lineEnd })));
233
- let candidate = retainRegions(source, [{ start: 0, end: source.length }], omissions);
234
- try {
235
- if (retained.size)
236
- candidate = preparePlanUpdate(candidate, {
237
- document: 'milestones',
238
- changes: [...retained].map(([ordinal, id]) => ({ select: { ordinal }, set: { id } })),
239
- }).source;
240
- return preparePlanDocumentWrite(source, {
241
- document: 'milestones',
242
- expectedSha256: fingerprintSource(source),
243
- source: candidate,
244
- assignMissingIds: true,
245
- }).source;
246
- }
247
- catch (cause) {
248
- return invalid(cause);
249
- }
250
- };
251
195
  /**
252
196
  * Prepares only explicitly selected identity/progress markers, preserving all surrounding bytes.
253
197
  * @throws
@@ -1,5 +1,5 @@
1
1
  import { type IPlanTarget, type IPlanCoordination } from '../contracts/index.js';
2
- import type { IPlanArtifacts, IPlanContractParser } from './types.js';
2
+ import type { IPlanArtifacts } from './types.js';
3
3
  /**
4
4
  * Reads one bounded regular artifact without following a file symlink.
5
5
  * @returns Exact UTF-8 contents, or null only for an optional absent artifact.
@@ -37,7 +37,7 @@ export declare const resolvePlanDirectory: (selected: string, roots: string[]) =
37
37
  * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
38
38
  * - JG_AGENT_HQ_PLAN_FAILED: The HQ plan operation failed
39
39
  */
40
- export declare const readPlanArtifacts: (target: IPlanTarget, roots: string[], parseContract?: IPlanContractParser) => Promise<IPlanArtifacts>;
40
+ export declare const readPlanArtifacts: (target: IPlanTarget, roots: string[]) => Promise<IPlanArtifacts>;
41
41
  /**
42
42
  * Applies a private checked replacement or exclusive creation under the caller's document locks.
43
43
  * @throws
@@ -66,14 +66,12 @@ export const parsePlanCoordination = (coordinationText) => {
66
66
  return coordinationText === null
67
67
  ? {
68
68
  schemaVersion: 1,
69
- comparisons: [],
70
69
  finalized: null,
71
70
  planApproval: null,
72
71
  sequenceApproval: null,
73
72
  execution: null,
74
73
  lastActionId: null,
75
74
  completions: [],
76
- correspondences: [],
77
75
  revision: null,
78
76
  baseline: null,
79
77
  observedConflict: null,
@@ -136,7 +134,7 @@ export const resolvePlanDirectory = async (selected, roots) => {
136
134
  * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
137
135
  * - JG_AGENT_HQ_PLAN_FAILED: The HQ plan operation failed
138
136
  */
139
- export const readPlanArtifacts = async (target, roots, parseContract) => {
137
+ export const readPlanArtifacts = async (target, roots) => {
140
138
  const directory = await resolvePlanDirectory(target.directory, roots);
141
139
  const [plan, milestones, coordinationText] = await Promise.all([
142
140
  readPlanFile(directory, 'plan.md'),
@@ -148,7 +146,7 @@ export const readPlanArtifacts = async (target, roots, parseContract) => {
148
146
  code: 'JG_AGENT_HQ_PLAN_INVALID',
149
147
  data: { kind: 'invalid-request' },
150
148
  });
151
- const contract = observePlanContract(plan, parseContract ? await parseContract({ directory, content: plan }) : undefined);
149
+ const contract = observePlanContract(plan);
152
150
  const sequence = milestones === null ? null : observeSequence(milestones);
153
151
  const skillsBinding = observeSkillsBinding(plan, sequence);
154
152
  const coordination = parsePlanCoordination(coordinationText);
@@ -1,13 +1,11 @@
1
- import type { IPlanRevision } from '../contracts/index.js';
1
+ import type { IPlanCoordination, IPlanOperatorAction } from '../contracts/index.js';
2
2
  import type { IPlanArtifacts } from './types.js';
3
3
  /**
4
- * Assigns or validates the first sequence's identities without changing other source bytes.
5
- * @returns Canonical content and its revision, without approval.
4
+ * Records the current jg-breakdown identities as the finalized revision without changing any file.
5
+ * Completion evidence follows its milestone ID: receipts of a milestone the sequence no longer
6
+ * marks done stop counting, and receipts whose ID left the sequence remain as unmatched evidence.
7
+ * @returns Coordination carrying the finalization, baseline and reopened receipts.
6
8
  * @throws
7
- * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
8
9
  * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
9
10
  */
10
- export declare const finalizeInitialSequence: (artifacts: IPlanArtifacts) => {
11
- content: string | null;
12
- revision: IPlanRevision;
13
- };
11
+ export declare const finalizePlanSequence: (artifacts: IPlanArtifacts, current: IPlanCoordination, action: IPlanOperatorAction) => IPlanCoordination;
@@ -1,31 +1,30 @@
1
- import { Exception } from 'jg-exception';
2
- import { computePlanRevision, isSamePlanRevision } from './utilities.js';
3
- import { prepareSequenceIds } from './documents.js';
4
- const conflict = () => {
5
- throw new Exception('The HQ action conflicts with its recorded state', {
6
- code: 'JG_AGENT_HQ_ACTION_CONFLICT',
7
- data: {
8
- kind: 'state-conflict',
9
- },
10
- });
11
- };
1
+ import { hashPlanContent } from './utilities.js';
2
+ import { invalid } from './documents.js';
3
+ import { refreshPlanBaseline } from './revisions.js';
12
4
  /**
13
- * Assigns or validates the first sequence's identities without changing other source bytes.
14
- * @returns Canonical content and its revision, without approval.
5
+ * Records the current jg-breakdown identities as the finalized revision without changing any file.
6
+ * Completion evidence follows its milestone ID: receipts of a milestone the sequence no longer
7
+ * marks done stop counting, and receipts whose ID left the sequence remain as unmatched evidence.
8
+ * @returns Coordination carrying the finalization, baseline and reopened receipts.
15
9
  * @throws
16
- * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
17
10
  * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
18
11
  */
19
- export const finalizeInitialSequence = (artifacts) => {
20
- if (artifacts.coordination.finalized &&
21
- !isSamePlanRevision(artifacts.coordination.finalized.revision, artifacts.revision))
22
- conflict();
23
- if (artifacts.milestones === null)
24
- return { content: null, revision: artifacts.revision };
25
- const milestones = prepareSequenceIds(artifacts.milestones, artifacts.hashes.milestones);
26
- const revised = computePlanRevision({
27
- ...artifacts.contract,
28
- milestones,
29
- });
30
- return { content: milestones, revision: revised };
12
+ export const finalizePlanSequence = (artifacts, current, action) => {
13
+ if (artifacts.parsed.some((entry) => !entry.id))
14
+ invalid();
15
+ const coordination = structuredClone(current);
16
+ const statuses = new Map(artifacts.parsed.map((entry) => [entry.id, entry.status]));
17
+ for (const receipt of coordination.completions) {
18
+ const status = receipt.milestoneId === null ? undefined : statuses.get(receipt.milestoneId);
19
+ if (status && status !== 'done' && !receipt.reopenedBy)
20
+ receipt.reopenedBy = action.id;
21
+ }
22
+ coordination.finalized = {
23
+ action,
24
+ revision: artifacts.revision,
25
+ fileHash: artifacts.milestones === null ? null : hashPlanContent(artifacts.milestones),
26
+ createdAt: Date.now(),
27
+ };
28
+ coordination.baseline = refreshPlanBaseline(artifacts, artifacts.milestones, artifacts.revision);
29
+ return coordination;
31
30
  };
@@ -1,6 +1,5 @@
1
1
  export { computePlanRevision, hashPlanContent, parsePlanMilestones, isSamePlanRevision, } from './utilities.js';
2
- export type { IPlanContract, IPlanContractParser, IPlanStopJob, IParsedMilestone, IPlanArtifacts, IPlanWriteIntent, IPlanProjection, } from './types.js';
2
+ export { observePlanContract } from './documents.js';
3
+ export type { IPlanContract, IPlanStopJob, IParsedMilestone, IPlanArtifacts, IPlanWriteIntent, IPlanProjection, } from './types.js';
3
4
  export { PlanWriteIntentSchema, PlanProjectionSchema, PlanProjectionPageSchema, PlanProjectionResultSchema, } from './types.js';
4
5
  export { createPlans } from './plans.js';
5
- export { PlanRevisionProjectionSchema, PlanRevisionPageSchema, PlanRevisionPageResultSchema, } from './types.js';
6
- export type { IPlanRevisionProjection } from './types.js';
@@ -1,7 +1,6 @@
1
1
  // execution contract hashing
2
2
  export { computePlanRevision, hashPlanContent, parsePlanMilestones, isSamePlanRevision, } from './utilities.js';
3
+ export { observePlanContract } from './documents.js';
3
4
  export { PlanWriteIntentSchema, PlanProjectionSchema, PlanProjectionPageSchema, PlanProjectionResultSchema, } from './types.js';
4
5
  // selected-plan coordination
5
6
  export { createPlans } from './plans.js';
6
- // revision read projection contracts
7
- export { PlanRevisionProjectionSchema, PlanRevisionPageSchema, PlanRevisionPageResultSchema, } from './types.js';
@@ -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
  };