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
@@ -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']),
@@ -143,6 +150,24 @@ export const LiveItemsSchema = z.object({
143
150
  data: z.array(HistoryItemSchema.extend({ state: z.enum(['active', 'awaiting-flush']) })).max(128),
144
151
  hasGap: z.boolean(),
145
152
  });
153
+ // exact native credit observations; balances have no assumed currency or arithmetic semantics
154
+ export const UsageCreditsSchema = z.object({
155
+ bucket: z.string().max(256),
156
+ hasCredits: z.boolean(),
157
+ isUnlimited: z.boolean(),
158
+ balance: z.string().max(256).nullable(),
159
+ });
160
+ // availability is independent of the provider's potentially capped reset-credit detail list
161
+ export const UsageResetCreditsSchema = z.object({
162
+ availableCount: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
163
+ });
164
+ // native model/surface scope identifies independent account meters
165
+ export const UsageWindowScopeSchema = z.object({
166
+ model: z
167
+ .object({ id: z.string().max(256).nullable(), displayName: z.string().max(256) })
168
+ .nullable(),
169
+ surface: z.string().max(256).nullable(),
170
+ });
146
171
  export const UsageWindowSchema = z.object({
147
172
  id: z.string(),
148
173
  bucket: z.string(),
@@ -152,6 +177,10 @@ export const UsageWindowSchema = z.object({
152
177
  remainingPercent: z.number().min(0).max(100),
153
178
  durationMinutes: z.number().int().positive().nullable(),
154
179
  resetsAt: z.number().int().nullable(),
180
+ period: z.enum(['five-hour', 'seven-day', 'other']).optional(),
181
+ nativeKind: z.string().max(256).nullable().optional(),
182
+ group: z.string().max(256).nullable().optional(),
183
+ scope: UsageWindowScopeSchema.nullable().optional(),
155
184
  });
156
185
  export const UsageSnapshotSchema = z.object({
157
186
  provider: ProviderIdSchema,
@@ -160,6 +189,8 @@ export const UsageSnapshotSchema = z.object({
160
189
  observedAt: z.number().int().nullable(),
161
190
  ordinaryUsageAllowed: z.boolean().nullable(),
162
191
  windows: z.array(UsageWindowSchema).max(MAX_PAGE_SIZE),
192
+ credits: z.array(UsageCreditsSchema).max(MAX_PAGE_SIZE).nullable().optional(),
193
+ resetCredits: UsageResetCreditsSchema.nullable().optional(),
163
194
  });
164
195
  export const RuntimeStatusSchema = z.object({
165
196
  runtimeEpoch: z.uuid(),
@@ -263,6 +294,7 @@ export const HqResponseSchema = z.discriminatedUnion('kind', [
263
294
  }),
264
295
  }),
265
296
  z.object({ kind: z.literal('live-items'), result: LiveItemsSchema }),
297
+ z.object({ kind: z.literal('session-states'), result: SessionTransitionPageSchema }),
266
298
  ]);
267
299
  export const ErrorKindSchema = z.enum(Object.keys(PUBLIC_ERROR_MESSAGES));
268
300
  export const IpcRequestSchema = z.strictObject({
package/dist/index.d.ts CHANGED
@@ -9,9 +9,9 @@ export type { IProviderModel, IProviderModelPage, IProviderModelsRequest, } from
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
11
  export type { IStorageDescriptor, IStorageMaintenanceOperation } from './storage/index.js';
12
- export { createHqSnapshot, inspectHqSnapshot, restoreHqSnapshot } from './snapshots/index.js';
12
+ export { createHqSnapshot, inspectHqSnapshot, restoreHqSnapshot, packHqSnapshot, unpackHqSnapshot, } from './snapshots/index.js';
13
13
  export type { IHqSnapshotInspection, IHqRestoreOptions, IHqRestoreResult, } from './snapshots/index.js';
14
14
  export { computePlanRevision } from './plans/index.js';
15
- export type { IPlanContract, IPlanContractParser } from './plans/index.js';
15
+ export type { IPlanContract } from './plans/index.js';
16
16
  export type { IProviderInputFile } from './providers/index.js';
17
17
  export type { IInputFile, IBoundInputFile, IOutputSchema, ITurnUsage, ITurnResult, IPreparedInput, } from './contracts/index.js';
package/dist/index.js CHANGED
@@ -4,6 +4,6 @@ export { RUNTIME_DIRECTORY, HQ_LOCK_FILE, getOwnerLiveness, acquireHqLock, withH
4
4
  export { createAgentHq } from './runtime/index.js';
5
5
  export { requestAgentHq } from './ipc/index.js';
6
6
  // trusted host snapshot and offline recovery
7
- export { createHqSnapshot, inspectHqSnapshot, restoreHqSnapshot } from './snapshots/index.js';
7
+ export { createHqSnapshot, inspectHqSnapshot, restoreHqSnapshot, packHqSnapshot, unpackHqSnapshot, } from './snapshots/index.js';
8
8
  // pure execution revision contracts
9
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)) ||
@@ -10,9 +10,11 @@ export declare const describePlan: (artifacts: IPlanArtifacts, pendingActionId?:
10
10
  export declare const canExecutePlanUnit: (artifacts: IPlanArtifacts, milestoneId: string | null) => boolean;
11
11
  /**
12
12
  * Applies one explicit operator decision without native dispatch or filesystem mutation.
13
+ * A protocol 0.2 plan must pass the jg-plans check for the decision's stage.
13
14
  * @returns Updated current authority records.
14
15
  * @throws
15
16
  * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
17
+ * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
16
18
  */
17
19
  export declare const updatePlanAuthority: (artifacts: IPlanArtifacts, command: Extract<IPlanCommand, {
18
20
  kind: "approve" | "revoke" | "authorize";
@@ -1,6 +1,6 @@
1
1
  import { Exception } from 'jg-exception';
2
2
  import { isSamePlanRevision } from './utilities.js';
3
- import { createCompletionLookup } from './reconciliation.js';
3
+ import { invalid } from './documents.js';
4
4
  const conflict = () => {
5
5
  throw new Exception('The HQ action conflicts with its recorded state', {
6
6
  code: 'JG_AGENT_HQ_ACTION_CONFLICT',
@@ -23,18 +23,19 @@ export const describePlan = (artifacts, pendingActionId = null) => {
23
23
  !!coordination.sequenceApproval &&
24
24
  !coordination.sequenceApproval.revokedBy &&
25
25
  isSamePlanRevision(coordination.sequenceApproval.revision, revision);
26
- 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));
27
31
  const workflow = coordination.revision;
28
- const invalidated = new Set(coordination.correspondences.flatMap((record) => record.invalidatedReceiptIds));
29
32
  const isWholePlanComplete = artifacts.milestones === null &&
30
- coordination.completions.some((receipt) => receipt.milestoneId === null &&
33
+ current.some((receipt) => receipt.milestoneId === null &&
31
34
  receipt.contractDigest === revision.planDigest &&
32
- receipt.revision.breakdownDigest === null &&
33
- !invalidated.has(receipt.id));
35
+ receipt.revision.breakdownDigest === null);
34
36
  const state = coordination.observedConflict ||
35
37
  pendingActionId ||
36
38
  workflow?.phase === 'blocked' ||
37
- workflow?.phase === 'reconciling' ||
38
39
  artifacts.parsed.some((milestone) => milestone.status === 'done' && !verified(milestone))
39
40
  ? 'blocked'
40
41
  : workflow?.phase === 'quiescing' ||
@@ -69,7 +70,6 @@ export const describePlan = (artifacts, pendingActionId = null) => {
69
70
  milestoneCount: artifacts.parsed.length,
70
71
  coordination: {
71
72
  schemaVersion: coordination.schemaVersion,
72
- comparisonCount: coordination.comparisons.length,
73
73
  finalized: coordination.finalized,
74
74
  planApproval: coordination.planApproval,
75
75
  sequenceApproval: coordination.sequenceApproval,
@@ -77,6 +77,14 @@ export const describePlan = (artifacts, pendingActionId = null) => {
77
77
  lastActionId: coordination.lastActionId,
78
78
  observedConflict: coordination.observedConflict,
79
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
+ })),
80
88
  revision: workflow
81
89
  ? {
82
90
  id: workflow.id,
@@ -91,11 +99,6 @@ export const describePlan = (artifacts, pendingActionId = null) => {
91
99
  createdAt: workflow.createdAt,
92
100
  hasUncertainEffects: workflow.hasUncertainEffects,
93
101
  hasCheckpoint: !!workflow.checkpoint,
94
- hasProposal: !!workflow.proposal,
95
- proposalId: workflow.proposal?.id ?? null,
96
- unmatchedCount: workflow.proposal?.confirmation
97
- ? 0
98
- : (workflow.proposal?.unmatchedSourceIds.length ?? 0),
99
102
  }
100
103
  : null,
101
104
  },
@@ -110,6 +113,7 @@ export const canExecutePlanUnit = (artifacts, milestoneId) => {
110
113
  const status = describePlan(artifacts);
111
114
  const execution = artifacts.coordination.execution;
112
115
  if (!execution ||
116
+ !artifacts.conformance.sequence ||
113
117
  !status.isPlanApproved ||
114
118
  !status.isFinalized ||
115
119
  ['blocked', 'completed', 'revising'].includes(status.state))
@@ -128,13 +132,17 @@ const revokeExecution = (coordination, action) => {
128
132
  };
129
133
  /**
130
134
  * Applies one explicit operator decision without native dispatch or filesystem mutation.
135
+ * A protocol 0.2 plan must pass the jg-plans check for the decision's stage.
131
136
  * @returns Updated current authority records.
132
137
  * @throws
133
138
  * - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
139
+ * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
134
140
  */
135
141
  export const updatePlanAuthority = (artifacts, command, runtimeEpoch) => {
136
142
  const coordination = structuredClone(artifacts.coordination);
137
143
  if (command.kind === 'approve') {
144
+ if (!artifacts.conformance[command.scope])
145
+ invalid();
138
146
  const status = describePlan(artifacts);
139
147
  if (command.scope === 'sequence' &&
140
148
  (artifacts.milestones === null || !status.isFinalized || !status.isPlanApproved))
@@ -166,6 +174,8 @@ export const updatePlanAuthority = (artifacts, command, runtimeEpoch) => {
166
174
  revokeExecution(coordination, command.action);
167
175
  }
168
176
  else {
177
+ if (!artifacts.conformance.sequence)
178
+ invalid();
169
179
  const status = describePlan(artifacts);
170
180
  if (coordination.revision &&
171
181
  coordination.revision.phase !== 'awaiting-approval' &&
@@ -1,5 +1,22 @@
1
1
  import { z } from 'zod';
2
2
  import { type IPlanMetadata, type IPlanStatus } from '../contracts/index.js';
3
+ import type { IPlanConformance } from './types.js';
4
+ /**
5
+ * Rejects a plan HQ cannot read or act on.
6
+ * @param cause The validation failure, when one exists.
7
+ * @throws
8
+ * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
9
+ */
10
+ export declare const invalid: (cause?: unknown) => never;
11
+ /**
12
+ * Checks a protocol 0.2 plan with jg-plans for the stages HQ gates. Plan approval needs plan.md
13
+ * to conform alone; finalization, sequence approval, authorization, and execution need it to
14
+ * conform with its milestones. Plans without the 0.2 marker always conform, as before.
15
+ * @param plan Exact plan.md source.
16
+ * @param milestones Exact milestones.md source, or null when absent.
17
+ * @returns The conformance of each stage.
18
+ */
19
+ export declare const observePlanConformance: (plan: string, milestones: string | null) => IPlanConformance;
3
20
  /**
4
21
  * Reads the persisted identity independently of an optional consumer metadata projection.
5
22
  * @throws
@@ -7,14 +24,12 @@ import { type IPlanMetadata, type IPlanStatus } from '../contracts/index.js';
7
24
  */
8
25
  export declare const observePlanId: (source: string) => string | null;
9
26
  /**
10
- * 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.
11
29
  * @throws
12
30
  * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
13
31
  */
14
- export declare const observePlanContract: (source: string, custom?: {
15
- body: string;
16
- metadata: IPlanMetadata;
17
- }) => {
32
+ export declare const observePlanContract: (source: string) => {
18
33
  body: string;
19
34
  metadata: IPlanMetadata;
20
35
  };
@@ -47,18 +62,6 @@ export declare const observeSequence: (source: string) => {
47
62
  plan_content_sha256: string;
48
63
  } | null;
49
64
  };
50
- /**
51
- * Missing identities are assigned once by the engine, then persisted by HQ's journal.
52
- * @throws
53
- * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
54
- */
55
- export declare const prepareSequenceIds: (source: string, expectedSha256: string) => string;
56
- /**
57
- * New requirements receive engine identities; exact verified correspondence retains its identity.
58
- * @throws
59
- * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
60
- */
61
- export declare const prepareReconciliationIds: (source: string, retained: Map<number, string>) => string;
62
65
  /**
63
66
  * Prepares only explicitly selected identity/progress markers, preserving all surrounding bytes.
64
67
  * @throws
@@ -1,6 +1,6 @@
1
1
  import { hashValue as fingerprintSource } from 'jg-crypto';
2
2
  import { Exception } from 'jg-exception';
3
- import { 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'];
@@ -10,13 +10,35 @@ const bindingSchema = z.object({
10
10
  plan_content_sha256: z.string().regex(/^[a-f0-9]{64}$/),
11
11
  });
12
12
  const metadataSchema = z.record(z.string(), z.json());
13
- const invalid = (cause) => {
13
+ /**
14
+ * Rejects a plan HQ cannot read or act on.
15
+ * @param cause The validation failure, when one exists.
16
+ * @throws
17
+ * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
18
+ */
19
+ export const invalid = (cause) => {
14
20
  throw new Exception('The HQ plan is invalid', {
15
21
  code: 'JG_AGENT_HQ_PLAN_INVALID',
16
22
  data: { kind: 'invalid-request' },
17
23
  cause,
18
24
  });
19
25
  };
26
+ /**
27
+ * Checks a protocol 0.2 plan with jg-plans for the stages HQ gates. Plan approval needs plan.md
28
+ * to conform alone; finalization, sequence approval, authorization, and execution need it to
29
+ * conform with its milestones. Plans without the 0.2 marker always conform, as before.
30
+ * @param plan Exact plan.md source.
31
+ * @param milestones Exact milestones.md source, or null when absent.
32
+ * @returns The conformance of each stage.
33
+ */
34
+ export const observePlanConformance = (plan, milestones) => {
35
+ if (parsePlan(plan).protocol !== '0.2')
36
+ return { plan: true, sequence: true };
37
+ return {
38
+ plan: checkPlan({ plan }).conforms,
39
+ sequence: checkPlan({ plan, ...(milestones === null ? {} : { milestones }) }).conforms,
40
+ };
41
+ };
20
42
  /** Metadata must be available as plain JSON; absence alone supplies an empty mapping. */
21
43
  const metadataOf = (document) => {
22
44
  if (!document.frontmatter)
@@ -38,28 +60,18 @@ export const observePlanId = (source) => {
38
60
  return typeof id === 'string' && id.trim().length > 0 ? id : null;
39
61
  };
40
62
  /**
41
- * 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.
42
65
  * @throws
43
66
  * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
44
67
  */
45
- export const observePlanContract = (source, custom) => {
68
+ export const observePlanContract = (source) => {
46
69
  const document = parsePlan(source);
47
70
  const raw = metadataOf(document);
48
71
  if (!document.body || ('id' in raw && !z.string().trim().min(1).safeParse(raw.id).success))
49
72
  return invalid();
50
- if (custom) {
51
- const parsed = PlanMetadataSchema.safeParse(custom.metadata);
52
- if (!parsed.success || custom.body !== document.body)
53
- return invalid(parsed.error);
54
- return { body: document.body, metadata: parsed.data };
55
- }
56
- const extensions = Object.fromEntries(Object.entries(raw).filter(([key]) => ![...administrativeKeys, 'scope', 'repositories', 'errorReservations'].includes(key)));
57
- const parsed = PlanMetadataSchema.safeParse({
58
- scope: 'scope' in raw ? raw.scope : 'local',
59
- repositories: 'repositories' in raw ? raw.repositories : [],
60
- errorReservations: 'errorReservations' in raw ? raw.errorReservations : [],
61
- extensions,
62
- });
73
+ const extensions = Object.fromEntries(Object.entries(raw).filter(([key]) => !administrativeKeys.includes(key)));
74
+ const parsed = PlanMetadataSchema.safeParse({ extensions });
63
75
  if (!parsed.success)
64
76
  return invalid(parsed.error);
65
77
  return { body: document.body, metadata: parsed.data };
@@ -180,52 +192,6 @@ export const observeSequence = (source) => {
180
192
  ]);
181
193
  return { entries, shared, metadata, binding };
182
194
  };
183
- /**
184
- * Missing identities are assigned once by the engine, then persisted by HQ's journal.
185
- * @throws
186
- * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
187
- */
188
- export const prepareSequenceIds = (source, expectedSha256) => {
189
- try {
190
- return preparePlanDocumentWrite(source, {
191
- document: 'milestones',
192
- expectedSha256,
193
- source,
194
- assignMissingIds: true,
195
- }).source;
196
- }
197
- catch (cause) {
198
- return invalid(cause);
199
- }
200
- };
201
- /**
202
- * New requirements receive engine identities; exact verified correspondence retains its identity.
203
- * @throws
204
- * - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
205
- */
206
- export const prepareReconciliationIds = (source, retained) => {
207
- const document = parseMilestones(source);
208
- const omissions = document.milestones.flatMap((entry) => retained.has(entry.ordinal)
209
- ? []
210
- : entry.idMarkers.map((marker) => ({ start: marker.lineStart, end: marker.lineEnd })));
211
- let candidate = retainRegions(source, [{ start: 0, end: source.length }], omissions);
212
- try {
213
- if (retained.size)
214
- candidate = preparePlanUpdate(candidate, {
215
- document: 'milestones',
216
- changes: [...retained].map(([ordinal, id]) => ({ select: { ordinal }, set: { id } })),
217
- }).source;
218
- return preparePlanDocumentWrite(source, {
219
- document: 'milestones',
220
- expectedSha256: fingerprintSource(source),
221
- source: candidate,
222
- assignMissingIds: true,
223
- }).source;
224
- }
225
- catch (cause) {
226
- return invalid(cause);
227
- }
228
- };
229
195
  /**
230
196
  * Prepares only explicitly selected identity/progress markers, preserving all surrounding bytes.
231
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
@@ -6,7 +6,7 @@ import { Exception, extractMessage, hasErrorCode, isException } from 'jg-excepti
6
6
  import { PlanCoordinationSchema, } from '../contracts/index.js';
7
7
  import { resolveWorkspaceTarget } from '../runtime/state/index.js';
8
8
  import { computeObservedPlanRevision, hashPlanContent, projectPlanMilestones, } from './utilities.js';
9
- import { observePlanContract, observeSkillsBinding, observeSequence } from './documents.js';
9
+ import { observePlanConformance, observePlanContract, observeSkillsBinding, observeSequence, } from './documents.js';
10
10
  const MAX_PLAN_BYTES = 1_048_576;
11
11
  /**
12
12
  * Reads one bounded regular artifact without following a file symlink.
@@ -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);
@@ -168,6 +166,8 @@ export const readPlanArtifacts = async (target, roots, parseContract) => {
168
166
  milestones: milestones === null ? null : hashPlanContent(milestones),
169
167
  coordination: coordinationText === null ? null : hashPlanContent(coordinationText),
170
168
  },
169
+ // observed, not enforced: reads and revisions continue while stage gates use the result
170
+ conformance: observePlanConformance(plan, milestones),
171
171
  };
172
172
  };
173
173
  /** Flushes fixed-name creation/removal before journal completion. */
@@ -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';