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
package/api/README.md CHANGED
@@ -22,7 +22,7 @@ All operations may expose the relevant intentional contracts in [errors](../erro
22
22
 
23
23
  `hq.storage` returns an independent `IStorageDescriptor` containing the canonical `databasePath`, `schemaHash`, `reservedPrefix` (`hq_`), and required `connectionSettings`: `foreignKeys` true, `busyTimeoutMs` 5000, `journalMode` wal, and `synchronous` full. Exported Node types are `IStorageDescriptor` and `IStorageMaintenanceOperation<T>`. No database handle, storage callback, raw SQL command or storage path is exposed by browser contracts or IPC.
24
24
 
25
- For node:sqlite, open the host connection with `new DatabaseSync(storage.databasePath, { timeout: storage.connectionSettings.busyTimeoutMs, enableForeignKeyConstraints: storage.connectionSettings.foreignKeys })`. These options enable foreign keys and a 5,000 ms busy timeout; the descriptor itself is not a DatabaseSync options object. See the [Node 24 SQLite API](https://nodejs.org/download/release/v24.15.0/docs/api/sqlite.html#new-databasesyncpath-options). Keep WAL mode and FULL synchronization; do not change database-wide settings while HQ is running. Hosts own their table prefix, definitions, connection lifetime and user_version. HQ-owned tables and indexes are reserved. A nonempty database requires the matching singleton hq_schema stamp; otherwise startup throws JG_AGENT_HQ_STORAGE_INVALID without changing the database. The stamp also binds the SHA-256 fingerprint of action.key; a different valid-length key fails with JG_AGENT_HQ_ACTION_KEY_UNAVAILABLE before a writer opens. Fresh initialization is transactional.
25
+ For node:sqlite, open the host connection with `new DatabaseSync(storage.databasePath, { timeout: storage.connectionSettings.busyTimeoutMs, enableForeignKeyConstraints: storage.connectionSettings.foreignKeys })`. These options enable foreign keys and a 5,000 ms busy timeout; the descriptor itself is not a DatabaseSync options object. See the [Node 24 SQLite API](https://nodejs.org/download/release/v24.15.0/docs/api/sqlite.html#new-databasesyncpath-options). Keep WAL mode and FULL synchronization; do not change database-wide settings while HQ is running. Hosts own their table prefix, definitions, connection lifetime and user_version. HQ-owned tables and indexes are reserved. A nonempty database requires the current singleton hq_schema stamp, which records the schema hash, the SHA-256 fingerprint of action.key and the package version that wrote the database. Startup rejects any other schema with JG_AGENT_HQ_STORAGE_INVALID before opening a writer; its message names that package version, or reports another jg-agent-hq version when the stamp records none. Rejected storage remains unchanged. A different valid-length key fails with JG_AGENT_HQ_ACTION_KEY_UNAVAILABLE before a writer opens. Fresh initialization is transactional.
26
26
 
27
27
  `await hq.withStorageMaintenance(operation)` passes the storage descriptor to the async operation and returns its result. It closes admission before draining accepted HQ operations, allows their awaited nested calls and required native evidence to finish, and checks for active native execution or prepared plan writes before invoking the callback. Concurrent maintenance, new HQ requests, browser host effects and shutdown conflict while maintenance is held. During the callback, native event persistence waits in its existing bounded lane, and an already accepted scheduled stop waits for release. The callback must not call HQ, start native work or leave transactions open. Its errors propagate unchanged; it owns rollback and reconciliation for its SQL effects. After success or failure, HQ admission resumes. Calls after shutdown use JG_AGENT_HQ_RUNTIME_NOT_RUNNING.
28
28
 
@@ -30,31 +30,35 @@ The host must coordinate every application connection that can write during main
30
30
 
31
31
  ## Snapshot and restore
32
32
 
33
- Import createHqSnapshot, inspectHqSnapshot and restoreHqSnapshot from jg-agent-hq in a trusted Node host. They are absent from browser contracts, IPC and agent tools. The exported types are IHqSnapshotInspection, IHqRestoreOptions and IHqRestoreResult.
33
+ Import createHqSnapshot, inspectHqSnapshot, restoreHqSnapshot, packHqSnapshot and unpackHqSnapshot from jg-agent-hq in a trusted Node host. They are absent from browser contracts, IPC and agent tools. The exported types are IHqSnapshotInspection, IHqRestoreOptions and IHqRestoreResult.
34
34
 
35
- | Operation | Contract |
36
- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
37
- | `createHqSnapshot(hq, destination)` | Pause all host writers, then capture a quiescent running runtime into an absent absolute destination under an existing canonical parent. Returns IHqSnapshotInspection. |
38
- | `inspectHqSnapshot(directory)` | Validate the complete private snapshot without changing it. Returns IHqSnapshotInspection. |
39
- | `restoreHqSnapshot({ snapshotDirectory, destination })` | Validate before creating an absent recovery destination, copy and validate staged files, then expose state and plan recovery directories. Returns IHqRestoreResult. All proposed destination connections must be stopped. |
35
+ | Operation | Contract |
36
+ | ------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
37
+ | `createHqSnapshot(hq, destination)` | Capture a running runtime while its agents keep working into an absent absolute destination under an existing canonical parent. Host connections must not write host tables until it resolves. Returns IHqSnapshotInspection. |
38
+ | `inspectHqSnapshot(directory)` | Validate the complete private snapshot without changing it. Returns IHqSnapshotInspection. |
39
+ | `packHqSnapshot(snapshotDirectory, archivePath, key)` | Inspect the snapshot, then encrypt it into one new private file at an absent absolute path under an existing canonical parent. Returns the snapshot's IHqSnapshotInspection. |
40
+ | `unpackHqSnapshot(archivePath, destination, key)` | Decrypt and verify an archive, then write it into an absent snapshot directory and inspect it. Returns IHqSnapshotInspection. |
41
+ | `restoreHqSnapshot({ snapshotDirectory, destination })` | Validate before creating an absent recovery destination, copy and validate staged files, then expose state and plan recovery directories. Returns IHqRestoreResult. All proposed destination connections must be stopped. |
40
42
 
41
- Capture holds exclusive HQ maintenance admission and the coordination metadata lock, then takes each registered plan's shared document locks in the existing order. Active native turns, unresolved native ownership or in-flight native mutations use ACTION_CONFLICT, without interruption. Concurrent maintenance and locked documents also conflict. Snapshot capture retains prepared document write intents and source mismatches; ordinary host schema maintenance continues to reject prepared writes. Host connections must stop writing for the complete capture; quiesce native background jobs and independent document writers as well. Uncoordinated writes, attached databases and external files are outside this coherence contract.
43
+ Capture runs as admitted HQ work, so host maintenance excludes it, and holds the coordination metadata lock throughout, so HQ-mediated plan writes and coordination.json wait for it under the lock's 120-second default. Native turns, ownership changes and evidence keep flowing: the store worker backs up the database through its own connection in bounded steps. Each registered plan is then copied under its own shared document locks, one plan at a time; a locked document conflicts. Host connections must not write host tables for the complete capture, because a write from another connection restarts or splits SQLite's backup. Prepared document write intents and source mismatches are retained. Attached databases and external files are outside this coherence contract.
42
44
 
43
- SQLite's worker-owned backup API includes committed WAL data and every table in the main database, including application tables and exact hq_report payloads. The resulting database needs no WAL sidecar. The snapshot also contains the private 32-byte action.key and every present registered plan.md, milestones.md and coordination.json. Capture binds the original canonical state root and checks the key against its startup hash, rejecting a key replaced while the runtime is open. The indexed hq_plan_registration records durable references from plans, task/grant scope and requests. Enumeration uses directory seek pages of 128; file copy and SHA-256 use 65,536-byte buffers. There is no repository scan, transcript copy or artifact cache.
45
+ SQLite's worker-owned backup API includes committed WAL data and every table in the main database, including application tables and exact hq_report payloads. The resulting database needs no WAL sidecar. The snapshot also contains the private 32-byte action.key and every present registered plan.md, milestones.md and coordination.json. Capture binds the original canonical state root and checks the key against its startup hash, rejecting a key replaced while the runtime is open. The indexed hq_plan_registration records durable references from plans, task/grant scope and requests. Enumeration reads directory seek pages of 128 from the captured database, so a plan registered after the backup belongs to the next capture; file copy and SHA-256 use 65,536-byte buffers. There is no repository scan, transcript copy or artifact cache.
44
46
 
45
- The one inventory format is manifest.jsonl: header, database, action-key and ordered plan records. Each plan's generated directory is `plans/<SHA-256 of source directory>`. Records retain exact source directory, observed plan ID/revision, companion byte counts/hashes and bounded diagnostics. Missing source plans, parser observations and corrupt coordination remain visible evidence; capture does not repair them or require checker conformance. Registered plans outside the runtime's current allowed roots retain an unavailable record without reading their files. A final complete.json binds the complete manifest hash and record count. Directories are private (0700), files are private (0600), and destinations are created exclusively. Runtime sockets, owner records, process IDs, bridge credentials and provider authentication are excluded.
47
+ The one inventory format is manifest.jsonl: header, database, action-key and ordered plan records. Each plan's generated directory is `plans/<SHA-256 of source directory>`. The header records the schema hash and the package version that captured it. Plan records retain the exact source directory, observed plan ID, the plan revision computed from the copied files, the distinct revisions the captured database's thread bindings record, companion byte counts/hashes and bounded diagnostics. A copied revision that differs from a recorded one adds the plan-changed diagnostic: the plan changed during capture or after its threads bound. Missing source plans, parser observations and corrupt coordination remain visible evidence; capture does not repair them or require checker conformance. Registered plans outside the runtime's current allowed roots retain an unavailable record without reading their files. A final complete.json binds the complete manifest hash and record count. Directories are private (0700), files are private (0600), and destinations are created exclusively. Runtime sockets, owner records, process IDs, bridge credentials and provider authentication are excluded.
46
48
 
47
- Inspection streams the inventory, verifies each listed regular file and every expected/absent companion, rejects links and unsafe paths, checks the current HQ schema stamp and database/key pairing, SQLite integrity/foreign keys, exact report hashes and complete registered-plan coverage. It rechecks captured plan identities and diagnostics. Full database verification runs in a dedicated worker. Inspection returns bounded directory/header/hash/count metadata; it does not load a growing inventory into memory. Hashes detect corruption and bind content; they do not authenticate a snapshot supplied by an untrusted party.
49
+ Inspection streams the inventory, verifies each listed regular file and every expected/absent companion, rejects links and unsafe paths, checks the current HQ schema stamp and database/key pairing, SQLite integrity/foreign keys, exact report hashes and complete registered-plan coverage. It rechecks captured plan identities, revisions and diagnostics. A snapshot whose header or database comes from another schema is refused with STORAGE_INVALID, naming the package version that wrote it, before any restore output is reserved. Full database verification runs in a dedicated worker. Inspection returns bounded directory, header, hash and count metadata, including changedPlanCount; it does not load a growing inventory into memory. Hashes detect corruption and bind content; they do not authenticate a snapshot supplied by an untrusted party.
48
50
 
49
51
  Restore leaves every existing destination untouched, including an empty directory, repository or live state root. Use a new directory. It validates the source before reserving that directory and validates the staged copy independently against the initially inspected manifest hash before changing recovery authority. On success, stateRoot points to destination/state, recoveryRoot to destination/plans, recovery.jsonl retains the source inventory and recovered.json records completion. Caught failures remove only the operation's newly created output. A crash can leave incomplete output; do not open it as a recovered runtime.
50
52
 
51
53
  Restored task and agent lifecycles are paused unless already stopped, automatic dispatch is disabled, all skill grants are revoked, live approvals expire and queued input loses readiness. Submitted actions retain uncertainty. Managed native identities become uncertain and require explicit ownership reconciliation. IDs, stored reports, waiting child sets/continuation reservations, delivery links, historical receipts and exact prepared document intents remain intact. No native operation runs during restore.
52
54
 
53
- Call createAgentHq with the returned stateRoot and an explicitly selected allowedRoots array. Runtime construction never imports source root permissions from the snapshot and always assigns a new epoch; stored execution and revision leases cannot authorize work in it. Native source workspace paths and plan bindings remain evidence and are not rewritten. Recover repository/native files separately. Inspect recovery.jsonl and copy selected companions into explicitly chosen plan locations only after comparing current files; restore never overwrites a source repository. Rebind task plan references and obtain fresh plan/execution authority where needed, reconcile pending document writes using their exact IDs/baselines, and make explicit current-revision lifecycle/native ownership decisions before enabling dispatch. Source paths outside the newly selected roots remain unavailable.
55
+ Thread bindings of plans marked plan-changed also lose their execution scope, so that work resumes only under fresh authority. Call createAgentHq with the returned stateRoot and an explicitly selected allowedRoots array. Runtime construction never imports source root permissions from the snapshot and always assigns a new epoch; stored execution and revision leases cannot authorize work in it. Native source workspace paths and plan bindings remain evidence and are not rewritten. Recover repository/native files separately. Inspect recovery.jsonl and copy selected companions into explicitly chosen plan locations only after comparing current files; restore never overwrites a source repository. Rebind task plan references and obtain fresh plan/execution authority where needed, reconcile pending document writes using their exact IDs/baselines, and make explicit current-revision lifecycle/native ownership decisions before enabling dispatch. Source paths outside the newly selected roots remain unavailable.
54
56
 
55
- These exports use SNAPSHOT_INVALID for incomplete, corrupt, unsafe or occupied snapshot/recovery selections and SNAPSHOT_FAILED for operational copy, backup, lock-release, worker or cleanup failures. Capture additionally exposes ACTION_CONFLICT for a busy checkpoint. Operational messages retain private diagnostic causes; no snapshot exception is exposed through public RPC.
57
+ These exports use SNAPSHOT_INVALID for incomplete, corrupt, unsafe or occupied snapshot, archive or recovery selections, for a key that is not 32 bytes and for an archive that fails authentication, and SNAPSHOT_FAILED for operational copy, backup, lock-release, worker or cleanup failures. Capture additionally exposes ACTION_CONFLICT while host maintenance runs, when the metadata lock wait expires or when a plan document is locked. Inspection/restore expose STORAGE_INVALID for a snapshot from another schema. Operational messages retain private diagnostic causes; no snapshot exception is exposed through public RPC.
56
58
 
57
- Snapshots are plaintext local state. The host owns encryption/key recovery, scheduling, uploads, retention and last-success status. A disk failure can lose every change after the last successful off-machine backup. A local snapshot alone provides no remote durability. See the [recovery workflow](../docs/recovery.md).
59
+ An archive is a fixed format identifier, a fresh 12-byte IV, the AES-256-GCM ciphertext of every snapshot file in manifest order, each behind its path and length, and the 16-byte authentication tag. The key is a 32-byte Buffer the host supplies and keeps; HQ never stores it. Unpacking decrypts the whole archive into a private temporary file beside the destination and verifies the tag before trusting any byte or creating the destination, so a wrong key, a modified byte or a truncation is refused with SNAPSHOT_INVALID and writes nothing. It then writes only the manifest's listed paths at exactly their listed sizes, refuses unlisted, repeated or missing entries, and runs inspectHqSnapshot on the result; any failure removes the destination and the temporary file. Packing removes a partial archive on failure. Both stream in 65,536-byte chunks.
60
+
61
+ Snapshot directories are plaintext local state; archives are the encrypted form for off-machine copies. The host owns the key and its recovery, scheduling, uploads, retention and last-success status. A disk failure can lose every change after the last successful off-machine backup. A local snapshot alone provides no remote durability. See the [recovery workflow](../docs/recovery.md).
58
62
 
59
63
  Native snapshot qualification on 2026-10-23 used Codex 0.164.0 (gpt-6.1-sol) and Claude Code 2.1.309 (claude-opus-5-5). Both produced exact HQ reports from controlled native sessions. Quiescent capture, offline restore and explicit root selection retained their report bytes/hashes, changed the runtime epoch, paused task dispatch and left both providers idle on the recovered runtime. Claude read-tool permissions received exact explicit replies. These observations do not establish a native version admission rule.
60
64
 
@@ -74,7 +78,7 @@ The socket accepts at most 32 simultaneous connections. Requests are bounded to
74
78
 
75
79
  Factories receive canonical allowed roots, the runtime epoch, a cancellation signal and runtime-owned event callbacks. They return `IAgentProvider`, which owns native protocol validation, processes, authentication, capabilities, history, skill invocation spelling and concrete session controls. Each operation receives a bounded `IProviderCall.signal`. Factories must clean up partial initialization before rejecting; `close()` must be idempotent and confirm that owned resources stopped. HQ retains ownership evidence when cleanup cannot be confirmed. Failed construction is not automatically replayed.
76
80
 
77
- `IAgentProviderEvents` carries normalized observations, items, deltas, prompts, outcomes and connection loss. `validateInput` rejects unsupported media/output options before admission and again at dispatch. `startTurn` receives content-bound `IProviderInputFile` bytes read by HQ. A turn-completed observation may carry a validated complete result whose state must match that observation. Registration binds provider identity. Echo each supplied request ID unchanged; HQ derives its action identity and verifies the exact receipt, runtime, provider, native session and workspace. A late create/fork/resume/unarchive/revert outcome also supplies verified native session metadata. Unknown control states cannot establish success or idle ownership. Callback metadata may grow additively; known identity and state fields remain validated. Native permission requests keep their exact reply channel and validation. An unsupported request is denied rather than approved.
81
+ `IAgentProviderEvents` carries normalized observations, items, deltas, prompts, outcomes, observed session states and connection loss. `session(nativeId, state)` reports the live state of a session another client drives inside the allowed workspaces; HQ ignores it for sessions it controls. `validateInput` rejects unsupported media/output options before admission and again at dispatch. `startTurn` receives content-bound `IProviderInputFile` bytes read by HQ. A turn-completed observation may carry a validated complete result whose state must match that observation. Registration binds provider identity. Echo each supplied request ID unchanged; HQ derives its action identity and verifies the exact receipt, runtime, provider, native session and workspace. A late create/fork/resume/unarchive/revert outcome also supplies verified native session metadata. Unknown control states cannot establish success or idle ownership. Callback metadata may grow additively; known identity and state fields remain validated. Native permission requests keep their exact reply channel and validation. An unsupported request is denied rather than approved.
78
82
 
79
83
  `{ kind: 'capabilities', provider, threadId? }` returns `IProviderCapabilities`. The optional managed thread must belong to that provider and an allowed workspace. The response includes provider/session scope, observation time, concrete operation support, and supported HQ input/configuration schemas. Each operation is `supported`, `unsupported`, `unavailable` or `unknown`, with a structured reason when support cannot be established. Supported settings describe whether a change is live or requires an idle restart. Configuration schemas describe typed session and turn settings, their live or idle-restart change mode, and native permission/sandbox choices. Model and effort values come from the native model catalog. Capabilities are observations, not permission grants or execution authority.
80
84
 
@@ -134,7 +138,7 @@ Import `HqRequestSchema`, `HqResponseSchema` and their inferred types from `jg-a
134
138
 
135
139
  Paged commands accept `limit` (default 32, maximum 128) and an opaque `cursor`. Continue with exactly the same command, target, filters and limit. The cursor binds those fields to the provider continuation. Codex requests descending creation order for threads, descending turns and ascending items. Claude orders discovery by creation time/native UUID descending and history by native chain position ascending. Workspace authorization is rechecked for each request, independently of cursor validation, before selected-thread items are fetched.
136
140
 
137
- Threads expose native state, `historyState` (`available` or `unavailable`), ownership (`external`, `managed` or `uncertain`) and nullable `managedId`. A managed thread uses its HQ name; an external thread retains its nullable native name. Timestamps use Unix milliseconds. Discovery projections are not authoritative transcript history and never cache a conversation body. Repeated Codex history reads go to its native APIs so a completed turn whose items have not flushed can be read again later. There is no resume-to-read behavior or Codex transcript-file parser.
141
+ Threads expose native state, the live session `state` described under [session states](#session-states), `historyState` (`available` or `unavailable`), ownership (`external`, `managed` or `uncertain`) and nullable `managedId`. A managed thread uses its HQ name; an external thread retains its nullable native name. Timestamps use Unix milliseconds. Discovery projections are not authoritative transcript history and never cache a conversation body. Repeated Codex history reads go to its native APIs so a completed turn whose items have not flushed can be read again later. There is no resume-to-read behavior or Codex transcript-file parser.
138
142
 
139
143
  ## Bounded session evidence
140
144
 
@@ -283,15 +287,15 @@ Partial text uses temporary live identities until the final native message UUID
283
287
 
284
288
  ## Native skill catalog
285
289
 
286
- `skills` accepts `threadId`, optional `search`, `limit` (default 32, maximum 128) and `cursor`. It operates on a controlled session and never adopts or resumes an external session. Codex uses native `skills/list` for that thread's authorized workspace; Claude uses that session's native initialization command list, which includes explicit-only skills. Its refresh endpoint omits those skills, so HQ does not use it. Close and explicitly resume the session to refresh Claude's catalog. Inactive or unsupported sessions report `unavailable`, with no successful-empty fallback. Native discovery errors produce `partial` and an `unavailableCount`. `observedAt` records when the native inventory was observed; it stays fixed for a Claude session and is null when unavailable.
290
+ `skills` accepts `threadId`, optional `search`, `limit` (default 32, maximum 128) and `cursor`. It operates on a controlled session and never adopts or resumes an external session. Codex uses native `skills/list` for that thread's authorized workspace, plus the skills in the operator's Codex extra roots; Claude uses that session's native initialization command list, which includes explicit-only skills. Its refresh endpoint omits those skills, so HQ does not use it. Close and explicitly resume the session to refresh Claude's catalog. Inactive or unsupported sessions report `unavailable`, with no successful-empty fallback. Native discovery errors produce `partial` and an `unavailableCount`. `observedAt` records when the native inventory was observed; it stays fixed for a Claude session and is null when unavailable.
287
291
 
288
- Rows contain an opaque `id`, native `name`, `description`, nullable `argumentHint`, `kind`, `path`, `scope`, `prerequisites` and `requiresExplicitInvocation`, plus native availability as `isEnabled`. Codex supplies skill identity, source/scope, enabled state and declared tool prerequisites. Claude supplies native command names, descriptions, argument hints and a built-in marker when available. Missing fields are null or `kind: 'unavailable'`; HQ does not inspect skill files to infer them. Declared prerequisites are metadata, not proof that an integration is connected. Invocation rules remain with the CLI, including explicit-only skills.
292
+ Rows contain an opaque `id`, native `name`, `description`, nullable `argumentHint`, `kind`, `path`, `scope`, `prerequisites` and `requiresExplicitInvocation`, plus native availability as `isEnabled`. Codex supplies skill identity, source/scope, enabled state and declared tool prerequisites. Claude supplies native command names, descriptions, argument hints and a built-in marker when available. Missing fields are null or `kind: 'unavailable'`; HQ does not inspect skill files to infer them. The one exception is Codex extra roots, which native discovery does not list: HQ reads each skill's single-line `name` and `description` frontmatter from `<root>/<directory>/SKILL.md`, reports it with scope `host`, skips linked directories and files, and counts unreadable entries in `unavailableCount`. A native skill with the same name takes precedence. Declared prerequisites are metadata, not proof that an integration is connected. Invocation rules remain with the CLI, including explicit-only skills.
289
293
 
290
- Both native inventory interfaces are unpaged. HQ accepts at most 4,096 native rows and 1 MiB of normalized catalog metadata per read, then provides stable ID seek pages guarded by the complete inventory revision and query. A changed inventory invalidates continuation. Only native metadata is read, never skill bodies or complete conversation histories. Concurrent reads for the same thread share their in-flight native request; Codex results are not retained as an HQ cache. Claude's native initialization metadata remains attached to its owned connection until that session closes. Native refresh and discovery caches remain provider-owned.
294
+ Both native inventory interfaces are unpaged. HQ accepts at most 4,096 native rows and 1 MiB of normalized catalog metadata per read, then provides stable ID seek pages guarded by the complete inventory revision and query. A changed inventory invalidates continuation. Only metadata is read, never skill bodies or complete conversation histories. Concurrent reads for the same thread share their in-flight native request; Codex results are not retained as an HQ cache. Claude's native initialization metadata remains attached to its owned connection until that session closes. Native refresh and discovery caches remain provider-owned.
291
295
 
292
296
  `skill-preview` accepts `threadId`, `skillId` and `arguments`. Its result is `ready`, `missing`, `disabled` or `unavailable`, with the selected metadata and exact text only when ready. Codex previews `$name arguments` and receives an explicit native skill selection containing its native name/path alongside that text. Claude previews `/name arguments` and performs native slash-command loading. Native same-name precedence applies. Preview never sends user input. Explicit message and queue actions share the established action ledger, ownership checks and delivery/uncertainty rules. They grant no tool permissions and do not expand the invoked workflow's authority.
293
297
 
294
- Trusted runtime construction also accepts `codexExtraSkillRoots?: string[]` and `claudeAdditionalDirectories?: string[]`. Paths must resolve to existing absolute directories. Codex receives process-local `skills/extraRoots/set`; Claude receives native `--add-dir` arguments, which also grant native file access to those directories. These inputs belong to the operator and cannot be changed through IPC commands. The installed `serve` command exposes repeated `--codex-extra-skill-root` and `--claude-additional-directory` flags. No global skill installation or coding-instruction change is performed.
298
+ Trusted runtime construction also accepts `codexExtraSkillRoots?: string[]` and `claudeAdditionalDirectories?: string[]`. Paths must resolve to existing absolute directories. Codex receives them as capability roots of each thread HQ starts, so other sessions on the shared daemon, including terminal sessions, never see them. Forks inherit them. A session Codex later reloads from disk loses native discovery of those skills, while explicit invocation through the HQ catalog still works, because it names the skill file. Claude receives native `--add-dir` arguments, which also grant native file access to those directories. These inputs belong to the operator and cannot be changed through IPC commands. The installed `serve` command exposes repeated `--codex-extra-skill-root` and `--claude-additional-directory` flags. No global skill installation or coding-instruction change is performed.
295
299
 
296
300
  ## Control reads and reconnect
297
301
 
@@ -315,13 +319,43 @@ Live item presentation is bounded to 128 items per cached thread, 32 windows and
315
319
 
316
320
  Items expose only normalized presentation fields. User/agent text, commands and file changes have explicit kinds. Unknown native kinds report `unsupported` without copying arbitrary payloads. Display text is bounded to 65,536 UTF-16 code units without splitting a surrogate pair; `isTruncated` reports omissions. An unsupported or oversized native transport frame fails explicitly.
317
321
 
322
+ ## Session states
323
+
324
+ Every session has a live state: `running`, `waiting` (on the operator), `idle`, `closed`, `failed` or `unknown`. A managed session reports it from its HQ record. A session another client drives is observed and listed with `ownership: 'external'`; HQ sends it no input. Hand it over with `thread-adopt` once it is closed in its terminal, which Codex reports as unloaded.
325
+
326
+ - **Codex.** The shared daemon broadcasts every thread's status. HQ records the states of sessions inside the allowed workspaces, reading each session's workspace once, and their items stay readable with `items`. Observation runs while the Codex connection is open; the connection opens on the first Codex request.
327
+ - **Claude.** While the runtime runs, HQ runs `claude agents --json` every 5 seconds, each run limited to 10 seconds and 65,536 bytes of output, and joins its entries to Claude discovery by `sessionId`. `busy` is running, `blocked` is waiting and `idle` is idle; an entry missing from a run is closed. A failed, late, oversized or malformed run changes nothing. Sessions HQ manages keep their managed records.
328
+
329
+ `{ kind: 'session-states', afterSequence?, limit? }` returns state transitions in sequence order after `afterSequence` (default 0), at most `limit` per page (default 32, maximum 128), with `hasMore`. Continue after the last returned `sequence`. Each transition has `sequence`, `provider`, nullable `nativeId`, nullable `threadId` (managed sessions only), `ownership`, nullable `previousState`, `state`, `reason` and `recordedAt`.
330
+
331
+ | Reason | When |
332
+ | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
333
+ | `opened` | A session became idle without completing a turn: it was created, adopted, resumed or first observed idle. |
334
+ | `turn-started` | A turn started. |
335
+ | `turn-completed` | A running or waiting session became idle. |
336
+ | `waiting-for-input` | The session waits on an approval, a question or input. |
337
+ | `operator-stopped` | An operator interrupt or close stopped a running or waiting managed session. |
338
+ | `failed` | The session failed. |
339
+ | `disappeared` | An observed session vanished while running or waiting, or the native connection or HQ ownership was lost and its state is unknown. |
340
+ | `closed` | An idle session closed. |
341
+
342
+ Transitions survive restarts. Each new transition deletes up to 128 transitions older than seven days, and closed observed sessions are forgotten after seven days. A managed session's stopping phase records no transition of its own.
343
+
344
+ When the Codex daemon restarts, HQ's connection ends: its sessions become uncertain, observed Codex sessions become unknown, and nothing is sent again. The provider reports unavailable until the next Codex read reconnects; recover uncertain sessions with `thread-recover`.
345
+
318
346
  ## Subscription observations
319
347
 
348
+ The usage metadata is optional, so a provider may omit it. Built-in adapters populate unknown metadata with null. Windows expose period (five-hour, seven-day or other), nativeKind, group and scope. Scope contains a nullable model with id/displayName and a nullable surface. Codex derives period from the actual duration; Claude normalizes recognized session and weekly groups to 300 and 10080 minutes. Primary/secondary remains the native position, not the period's identity. Existing bucket and window IDs remain stable.
349
+
350
+ credits contains independent bucket observations with hasCredits, isUnlimited and an exact nullable balance string. Its null value means unknown, never zero; do not add balances across buckets or assume a currency. resetCredits contains a nonnegative safe availableCount, independent of the provider's potentially capped reset detail list. Native account IDs and reset detail rows are not exposed. Credit/reset metadata can be available even when quota windows are unavailable; it grants no permission and provides no reset-redemption or purchase operation.
351
+
352
+ Codex prefers a valid nonempty rateLimitsByLimitId map and falls back to rateLimits when the map is absent, null or empty, without merging both views. A single rateLimits bucket without a native limitId uses `single` as its bucket ID. Missing or malformed optional credit/reset metadata becomes unknown while valid windows remain visible. Invalid quota-map content does not bypass boundary validation through the fallback.
353
+
320
354
  Usage retains actual bucket/window identities, optional native labels, reported used percentage, remaining percentage, window duration and reset time. Percentages are never estimated from token counts or summed across sessions. Reported usage above 100 is preserved; remaining percentage floors at zero. `ordinaryUsageAllowed` is nullable when the native response does not report permission.
321
355
 
322
- `available` means a usable observation exists. `exhausted` requires Codex's native permission/reached signal or a fully used Claude meter that the native response marks active. Neither label authorizes a model operation. `unavailable` covers missing windows or an observation that could not be obtained. Failed refreshes preserve a measured snapshot as `stale`, with its original `observedAt`. Observations older than 60 seconds or past a reported reset are stale. Codex account/rate-limit notifications trigger a coalesced refresh. Claude auth notifications discard account measurements and invalidate responses started for that account; rate-limit events mark the observation stale until the current or next structured refresh succeeds.
356
+ `available` means a usable observation exists. `exhausted` requires Codex's native permission/reached signal or a fully used Claude meter that the native response marks active. Neither label authorizes a model operation. `unavailable` covers missing windows or an observation that could not be obtained. Failed refreshes preserve a measured snapshot as `stale`, with its original `observedAt`. The complete prior observation, including credit/reset metadata and scopes, shares this freshness; an account change clears every field and invalidates responses started for the prior account. Observations older than 60 seconds or past a reported reset are stale. Codex account/rate-limit notifications trigger a coalesced refresh. Claude auth notifications discard account measurements and invalidate responses started for that account; rate-limit events mark the observation stale until the current or next structured refresh succeeds.
323
357
 
324
- Claude uses the experimental `get_usage` control with `skip_behaviors: true`, and validates the native `rate_limits.limits` rows rather than inferring quotas from session costs or reading credentials. The [published provider control types](https://app.unpkg.com/@anthropic-ai/claude-agent-sdk@0.3.301/files/sdk.d.ts) describe this protocol; HQ invokes the installed CLI directly. Independent model/surface windows stay separate. Null percentages are omitted; zero is retained when reported. Unsupported shapes are unavailable. Claude does not report a duration or ordinary-usage permission in this contract, so those fields remain null. No private OAuth endpoint, credential scrape or status-line execution is used.
358
+ Claude uses the experimental `get_usage` control with `skip_behaviors: true`, and validates the native `rate_limits.limits` rows rather than inferring quotas from session costs or reading credentials. The [published provider control types](https://app.unpkg.com/@anthropic-ai/claude-agent-sdk@0.3.301/files/sdk.d.ts) describe this protocol; HQ invokes the installed CLI directly. Independent model/surface windows stay separate. Null percentages are omitted; zero is retained when reported. Unsupported shapes are unavailable. Claude does not report ordinary-usage permission, so it remains null. Recognized session and weekly groups have normalized five-hour and seven-day periods; unknown groups retain their native identity with period other and a null duration. No private OAuth endpoint, credential scrape or status-line execution is used.
325
359
 
326
360
  Every usage read requests current native observations; the last successful snapshot is retained only to explain freshness after a failure. There is no TTL cache that suppresses a native refresh. Multiple simultaneous reads share one pending refresh.
327
361
 
@@ -331,31 +365,31 @@ Every usage read requests current native observations; the last successful snaps
331
365
 
332
366
  Output is one JSON line with `schemaVersion: 1`. Read output includes the command `kind` and `result`. Startup reports `kind: ready`. Confirmed shutdown reports `kind: stop` with `result.state: stopped`. Failure output goes to stderr with a safe error kind/message and exit status 1. The CLI never prints diagnostic causes or native payloads in an error response.
333
367
 
368
+ `jg-agent-hq session-states --state-root <directory> [--after-sequence <sequence>] [--limit <1..128>]` reads one page of session state transitions.
369
+
334
370
  `jg-agent-hq request --state-root <directory>` reads one complete HQ request from stdin, validates it, and prints the usual response. It accepts no extra target flags. This exposes action and reconnect operations without putting message text or question answers in command-line arguments. Its `stop` response acknowledges admission; use the dedicated `stop` command for confirmed shutdown.
335
371
 
336
372
  ## Plan coordination
337
373
 
338
- `computePlanRevision({ body, metadata, milestones })` is the pure Node API for execution identity. `metadata` contains `scope`, `repositories`, `errorReservations` and JSON-safe `extensions`. Reservation entries contain `repository`, `namespace`, inclusive `start`/`end`, `registryPath` and `purpose`; this API hashes them and does not allocate codes. Repository and reservation order is canonicalized; object keys use strict deterministic JSON. The exact parsed body, including its line endings, is contractual.
374
+ `computePlanRevision({ body, metadata, milestones })` is the pure Node API for execution identity. `metadata` contains JSON-safe `extensions`: every frontmatter field except the administrative ones. Object keys use strict deterministic JSON, so their order is not contractual; array order is. The exact parsed body, including its line endings, is contractual.
339
375
 
340
- Send `{ kind: 'plan', command }` through the existing local request API. Every command selects `target: { directory }`, an absolute directory inside an allowed workspace. The default profile uses jg-plans observations: absent HQ fields default to local scope and empty repository/reservation lists; unknown fields, including plan `id`, remain in `extensions`. Only `created_at`, `updated_at`, `revision` and `status` are administrative. Malformed, non-mapping or non-JSON metadata fails closed. No preferred-document conformance gate is imposed.
376
+ Send `{ kind: 'plan', command }` through the existing local request API. Every command selects `target: { directory }`, an absolute directory inside an allowed workspace. HQ reads plans through jg-plans observations and keeps every frontmatter field, including plan `id`, in `extensions`, except the administrative ones. Only `created_at`, `updated_at`, `revision` and `status` are administrative. Malformed, non-mapping or non-JSON metadata fails closed. Plans without `protocol: "0.2"` get no preferred-document conformance gate. A plan that declares protocol 0.2 must pass the jg-plans check at each stage that grants authority: plan approval needs plan.md to conform on its own, while finalization, sequence approval, authorization and execution checks need plan.md and milestones.md to conform together. A nonconforming plan stays readable, so `status`, inspection and revision workflows continue. `approve`, `finalize` and `authorize` reject it with `JG_AGENT_HQ_PLAN_INVALID`, and `check-execution` and admission stay closed.
341
377
 
342
- A trusted private host may supply `parsePlanContract({ directory, content })`. It must return exactly the body observed by jg-plans and valid HQ metadata. That host owns its alternative metadata profile and must put its contractual extension fields in `extensions`. It cannot exclude body prose. The private server resolves operator identity itself and never forwards browser-supplied roots, contract exclusions or metadata.
378
+ Milestone contracts retain every requirement byte outside observed status/identity lines, plus preamble and all intervening/trailing shared sections. Only recognized Overview table spans and the three valid `jg_skills` binding fields are excluded; other milestone metadata remains contractual. HQ does not regenerate Overview tables. Statuses must be exactly pending, in progress or done, and milestone IDs/order participate in sequence identity. Ordinal renumbering alone does not change a milestone's identity. jg-breakdown assigns every milestone ID through jg-plans; HQ never assigns one. When present, a skills binding must match the current plan id, revision and fingerprint excluding exactly the four administrative keys. A matching binding never grants HQ approval or execution permission.
343
379
 
344
- Milestone contracts retain every requirement byte outside observed status/identity lines, plus preamble and all intervening/trailing shared sections. Only recognized Overview table spans and the three valid `jg_skills` binding fields are excluded; other milestone metadata remains contractual. HQ does not regenerate Overview tables. Statuses must be exactly pending, in progress or done, and milestone IDs/order participate in sequence identity. Ordinal renumbering alone does not change a milestone's identity. Missing IDs are assigned explicitly by jg-plans and saved before application. When present, a skills binding must match the current plan id, revision and fingerprint excluding exactly the four administrative keys. A matching binding never grants HQ approval or execution permission.
345
-
346
- | Command kind | Required fields and result |
347
- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
348
- | `status` | `target`. Returns current execution revisions, full inspection hashes, `skillsBinding` (`absent`, `current` or `stale`), approval state and a bounded coordination summary and retained-evidence counts. |
349
- | `milestones` | `target`, optional `limit` (default 32, maximum 128) and `cursor`. Returns a bounded ordered seek page. |
350
- | `finalize` | `target`, `action`, `expected`. Assigns initial UUIDs or reconciles a checkpoint. Returns the complete canonical file, or a saved proposal needing one confirmation. Optional `confirmation: { proposalId, decisions }` resolves every unmatched source. |
351
- | `begin-revision` | `target`, `action`, `expected`, `intent: 'plan' \| 'breakdown'`, `threadIds`, `checkouts`. Closes execution admission and starts owned interruption/checkpoint work. |
352
- | `revision-invoke` | `target`, `action`, `expected`, `revisionId`, `skill: 'jg-plan' \| 'jg-breakdown'`. Explicitly opens the next native planning invocation after proven quiescence. It sends no model input itself. |
353
- | `complete` | `target`, `action`, `expected`, `milestoneId`, actual `checks` and selected `checkouts`. Retains the verified contract/check references and actual worktree fingerprints, then advances the marker. |
354
- | `reconciliation` | `target`, `collection: 'sources' \| 'drafts' \| 'evidence' \| 'correspondences'`, optional `limit` (32/128) and `cursor`. Returns retained evidence by indexed seek page. |
355
- | `approve` | `target`, `action`, `expected`, `scope: 'plan' \| 'sequence'`, `presentationHash`. The hash must match the exact presented plan or finalized sequence. Sequence approval also requires current plan approval. |
356
- | `revoke` | `target`, `action`, `expected`, `scope: 'plan' \| 'sequence' \| 'execution' \| 'all'`. Revoking a plan also revokes sequence and execution authority; revoking a sequence also revokes execution authority. |
357
- | `authorize` | `target`, `action`, `expected`, `mode: 'supervised' \| 'auto'`, selected unique `milestoneIds` (empty only for a plan without a breakdown). Records permission for this exact execution scope without starting an agent. |
358
- | `check-execution` | `target`, `expected`, `authorizationId`, nullable `milestoneId`, `mode`. Rejects missing, revoked, stale, wrong-mode or out-of-scope authority. It sends no native input. |
380
+ | Command kind | Required fields and result |
381
+ | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
382
+ | `status` | `target`. Returns current execution revisions, full inspection hashes, `skillsBinding` (`absent`, `current` or `stale`), approval state and a bounded coordination summary with the completion count and `unmatchedEvidence`: current receipts whose milestone ID no longer appears in the sequence. |
383
+ | `milestones` | `target`, optional `limit` (default 32, maximum 128) and `cursor`. Returns a bounded ordered seek page. |
384
+ | `register` | `target`. Records the directory so snapshots capture its plan files, after checking it is an allowed directory outside excluded archive/backup paths. It takes no document locks and reads no plan file, so the plan may not exist yet. Returns `{ directory }`. |
385
+ | `finalize` | `target`, `action`, `expected`. Requires every milestone to carry the ID jg-breakdown assigned, records the current revision and returns the unchanged milestone file. Receipts of a milestone the sequence no longer marks done stop counting. |
386
+ | `begin-revision` | `target`, `action`, `expected`, `intent: 'plan' \| 'breakdown'`, `threadIds`, `checkouts`. Closes execution admission and starts owned interruption/checkpoint work. |
387
+ | `revision-invoke` | `target`, `action`, `expected`, `revisionId`, `skill: 'jg-plan' \| 'jg-breakdown'`. Explicitly opens the next native planning invocation after proven quiescence. It sends no model input itself. |
388
+ | `complete` | `target`, `action`, `expected`, `milestoneId`, actual `checks` and selected `checkouts`. Retains the verified contract/check references and actual worktree fingerprints, then advances the marker. |
389
+ | `approve` | `target`, `action`, `expected`, `scope: 'plan' \| 'sequence'`, `presentationHash`. The hash must match the exact presented plan or finalized sequence. Sequence approval also requires current plan approval. |
390
+ | `revoke` | `target`, `action`, `expected`, `scope: 'plan' \| 'sequence' \| 'execution' \| 'all'`. Revoking a plan also revokes sequence and execution authority; revoking a sequence also revokes execution authority. |
391
+ | `authorize` | `target`, `action`, `expected`, `mode: 'supervised' \| 'auto'`, selected unique `milestoneIds` (empty only for a plan without a breakdown). Records permission for this exact execution scope without starting an agent. |
392
+ | `check-execution` | `target`, `expected`, `authorizationId`, nullable `milestoneId`, `mode`. Rejects missing, revoked, stale, wrong-mode or out-of-scope authority. It sends no native input. |
359
393
 
360
394
  `expected` is the exact `{ planDigest, breakdownDigest }` returned by inspection. Each mutating `action` has a UUID `id`, `operatorId` and `source: { kind: 'user-action' | 'user-message', reference }`. These are trusted local operator inputs. The module never infers approval from natural-language claims, an agent response or imported feedback. Its owner-only local IPC and files do not isolate hostile code executing as the same OS user. Native permissions remain separate action kinds with their own exact native request identities.
361
395
 
@@ -363,15 +397,15 @@ Milestones are optional. Finalizing a plan with no milestone file returns `conte
363
397
 
364
398
  Skills bindings are optional for generic HQ plans. When present, their syntax must be valid and their plan ID, revision and structural fingerprint must match before finalization or execution. A valid but stale binding remains visible in status: plan approval and explicit revision invocations remain available so jg-plan can retain the old sequence until jg-breakdown refreshes its coverage. Malformed bindings fail as invalid artifacts. A stale binding never supplies sequence approval or completion, even when semantic execution digests are unchanged.
365
399
 
366
- A first-use sequence has one `**Milestone ID:** <uuid>` immediately below each `**Status:**` line. Blank lines may separate the heading from its status; no intervening requirement prose is allowed. The initial finalizer rejects duplicate, malformed or misplaced IDs and inconsistent framing. It preserves existing Overview text and returns the complete canonical file for presentation before approval. A changed finalized contract goes through checkpoint reconciliation. A raw or changed sequence cannot inherit finalized status or sequence authority. A done marker remains visible but blocks execution without completion evidence.
400
+ Every milestone has one `**Milestone ID:** <uuid>`, written by jg-breakdown, immediately below its `**Status:**` line. Blank lines may separate the heading from its status; no intervening requirement prose is allowed. In a protocol 0.2 sequence, a milestone's `**Acceptance criteria:**` coverage line follows its ID line and is milestone contract prose. Finalization rejects a missing, duplicate, malformed or misplaced ID and inconsistent framing, changes no file and returns the complete file for presentation before approval. Outside a revision, a changed finalized contract must begin a revision before it is finalized again. A raw or changed sequence cannot inherit finalized status or sequence authority. A done marker remains visible but blocks execution without a current completion receipt for its milestone ID.
367
401
 
368
- The milestone contract includes its stable UUID, title without its ordinal, all requirement prose, shared sequence requirements and the approval statement. Status and identity marker lines are excluded from the prose; only the derived Overview table is excluded from shared text. Prose next to that table remains contractual. Sequence order is significant. Renumbering preserves execution identity; changed requirements, dependencies, scope, reservations or order require applicable approval. Full-file hashes preserve exact UTF-8 bytes and are distinct from semantic execution revisions. Administrative frontmatter excluded by the trusted contract parser, session labels, status advancement and coordination receipts do not change execution digests.
402
+ The milestone contract includes its stable UUID, title without its ordinal, all requirement prose, shared sequence requirements and the approval statement. Status and identity marker lines are excluded from the prose; only the derived Overview table is excluded from shared text. Prose next to that table remains contractual. Sequence order is significant. Renumbering preserves execution identity; changed requirements, dependencies, scope or order require applicable approval. Full-file hashes preserve exact UTF-8 bytes and are distinct from semantic execution revisions. Administrative frontmatter, session labels, status advancement and coordination receipts do not change execution digests.
369
403
 
370
404
  Plan and milestone artifacts are bounded to 1 MiB each; coordination evidence is bounded to 8 MiB and a sequence to 1,024 milestones. Reads do not scan planning trees. Milestone pages use ordinal seek ordering with unique ascending ordinals. Cursors bind the selected directory, page size, execution revisions and exact milestone inspection hash. Any changed artifact requires a fresh page; renumbering or status-only edits still preserve approval. A SQLite projection is rebuilt only when the selected milestone file's full hash changes. Every read verifies its source file; the projection is replaceable and never grants authority.
371
405
 
372
406
  Mutations acquire the HQ metadata lock at `<coordinationRoot>/.runtime/hq.lock` (`coordinationRoot` defaults to `stateRoot`), then the public jg-plans document locks in plan-before-milestones order. Use `serve --coordination-root <directory>` when coordination ownership is separate from runtime storage. Locks cover bounded observation, preparation, journaling and file application; no model turn or native stop wait holds them. A busy document lock becomes `JG_AGENT_HQ_ACTION_CONFLICT` with the safe `document-locked` reason. There is no automatic stale-lock takeover.
373
407
 
374
- SQLite persists exact prepared plan/milestone sources, assigned IDs and timestamps before application. A plan source of null means keep; milestone operations are explicitly keep, write with source, or remove. A null recorded before-plan hash permits only coordination work. Replay accepts only each recorded baseline or its exact desired state. Markdown is applied before coordination. Every HQ replacement uses jg-fs checked atomic writes with explicit 0600; absent targets are created exclusively and privately before content is written. Strict bounded, same-handle, single-link reads remain in HQ. Inspection alone never changes file permissions.
408
+ SQLite persists exact prepared plan/milestone sources and timestamps before application. A plan source of null means keep; milestone operations are explicitly keep, write with source, or remove. A null recorded before-plan hash permits only coordination work. Replay accepts only each recorded baseline or its exact desired state. Markdown is applied before coordination. Every HQ replacement uses jg-fs checked atomic writes with explicit 0600; absent targets are created exclusively and privately before content is written. Strict bounded, same-handle, single-link reads remain in HQ. Inspection alone never changes file permissions.
375
409
 
376
410
  After file durability succeeds, document locks must release successfully before SQLite marks the intent completed and clears its write bodies; HQ metadata ownership remains held through completion. A write, sync or release failure retains the prepared payload and closes admission. A crash after release and before completion is replayable. A failed completion acknowledgement is reconciled against the durable ledger: confirmed completion succeeds, an uncommitted intent stays pending, and an unknown outcome remains closed. Retry only the same original action and payload after inspection; changed files or payloads conflict. Nonparticipating writers still have a final comparison-to-replacement/removal race; these operations are not a multi-file transaction.
377
411
 
@@ -379,9 +413,7 @@ Accepted implementation input prepares aggregate and selected pending milestone
379
413
 
380
414
  Only accepted completion evidence advances a milestone to done. Aggregate done requires the complete current execution contract, applicable current approval/finalization and verified completion; administrative done markers alone do not provide them. Progress-only plan changes preserve revision and set updated_at once in the saved prepared source. An unchanged plan preserves its timestamp. The current finalization receipt retains the operator event, semantic revision, nullable canonical file hash and timestamp independently of write recovery bodies. Status reads expose pendingActionId for unresolved writes and never approve or resume work.
381
415
 
382
- `coordination.json` includes required `comparisons`, an array bounded to 1,024 records validated by `PlanComparisonSchema`. Each record binds `sourceRevision`, `targetDirectory`, `targetRevision`, a `compatible` or `contradiction` verdict, `reason`, `reviewedAt` and reviewer provenance (`provider`, `cliVersion`, nullable observed `model`, and native message `reference`). A trusted coordinator writes these records while holding the same metadata lock. Core operations preserve them; status exposes only `comparisonCount`. They never change execution digests or grant authority. The coordinator owns relevance, freshness, semantic judgments, bounded review reads and any execution gate, including contradictions. The standalone core does not assess compatibility.
383
-
384
- The installed `plan-status` and `plan-milestones` commands accept `--state-root` and `--directory`; the latter also accepts `--limit` and `--cursor`. Use `request` for the closed JSON mutation commands. The result is a tagged `status`, `milestones`, `reconciliation`, `reconciliation-required`, `finalized` or `execution-check` object within the outer `plan` response. A retried finalization returns current status when its finalized artifact no longer exists or has changed.
416
+ The installed `plan-status` and `plan-milestones` commands accept `--state-root` and `--directory`; the latter also accepts `--limit` and `--cursor`. Use `request` for the closed JSON mutation commands. The result is a tagged `status`, `milestones`, `registered`, `finalized` or `execution-check` object within the outer `plan` response. A retried finalization returns current status when its finalized artifact no longer exists or has changed.
385
417
 
386
418
  ### Revision and progress recovery
387
419
 
@@ -389,17 +421,17 @@ Begin revision before invoking a planning skill. Execution admission closes unde
389
421
 
390
422
  The local host supplies checkout evidence as `{ repository, directory, claimReference, paths }`. Paths are exact relative task paths. The core streams their contents, records link targets without following them, includes missing paths as deletions, and captures the current Git branch/HEAD. It does not stage or reset files and rejects traversal, parent-link escapes, `.git` and excluded archive/backup directories. Check commands and references are trusted operator evidence; this primitive does not execute arbitrary submitted commands or treat an imported agent claim as verification.
391
423
 
392
- After native `jg-plan` revises the contract and an explicitly requested `jg-breakdown` regenerates a needed sequence, close the planning controller before finalization. Only unique exact title and complete-contract matches retain identity automatically. Every unmatched checkpoint source, including done and partial work, appears in one saved proposal. Status exposes its nullable `coordination.revision.proposalId`; clients use the paged reconciliation reads to present correspondence and confirm that exact saved identity. Confirmation decisions use `sourceIds`, `targetIds`, `relation` (`equivalent`, `requirements-changed`, `omitted`, `reopened`) and explicit one-to-one `retainedPairs`. One source ID cannot be assigned to multiple targets. Grouped decisions retain split/merged evidence. A complete equivalent mapping preserves verified completion or partial status; rewording does not create new checks. A changed requirement gets fresh pending identity. Explicit reopening preserves evidence while invalidating its completion credit. Unverified done markers cannot become verified through an equivalent mapping.
424
+ After native `jg-plan` revises the contract and an explicitly requested `jg-breakdown` regenerates a needed sequence, close the planning controller before finalization. jg-breakdown owns milestone identity and progress: it keeps the ID and status of a milestone whose requirements still hold and assigns new IDs to new work. Finalization carries completion evidence by milestone ID, so rewording keeps a verified completion without new checks. A milestone the new sequence no longer marks done has its receipts reopened, and done credit returns only with a new completion. Evidence whose milestone ID left the sequence stays in coordination.json and appears in status as `unmatchedEvidence` until the ID returns. A done marker without a current receipt for its ID blocks the plan.
393
425
 
394
- A whole-plan checkpoint retains null milestones and an empty milestone inventory. If a revision removes a sequence because the remaining scope no longer needs one, every unmatched checkpoint milestone still requires explicit omission confirmation. Its verified evidence remains available; absence alone never resets progress or authorizes whole-plan execution.
426
+ A whole-plan checkpoint retains null milestones and an empty milestone inventory. When a revision removes a sequence because the remaining scope no longer needs one, its milestone evidence becomes unmatched; absence alone never resets progress, and whole-plan execution still needs plan approval and fresh authorization.
395
427
 
396
- The proposal and assigned identities are persisted before the canonical file is replaced. Retry the same action and payload after a partial write; do not regenerate UUIDs or confirm a different proposal. Present the complete canonical output before sequence approval. Applicable plan and sequence approvals are required again after digest changes. Approval does not resume work: send a fresh `authorize` with the intended mode and scope. Execution authority is also bound to the current runtime epoch.
428
+ Finalization is journaled like other plan writes; retry the same action and payload after a partial write. Present the complete milestone file before sequence approval. Applicable plan and sequence approvals are required again after digest changes. Approval does not resume work: send a fresh `authorize` with the intended mode and scope. Execution authority is also bound to the current runtime epoch.
397
429
 
398
430
  Guided native input adds `plan: { kind: 'execution', authorizationId, milestoneId, mode, revision }` or `{ kind: 'planning', revisionId, invocationId }` to its action envelope. The controller binds this context atomically to the managed thread. Planning starts with the exact authorized native skill. A live thread cannot switch scopes; close it before an explicit resume under a different scope. Queued input retains its original scope and cannot run under stale approval or during revision. Ordinary input on a bound thread retains that exact scope and remains subject to its current gate, including after revocation or completion. It cannot silently become unscoped input. Renaming and explicit replies to an existing native permission/question remain separate, revision-guarded controls; neither starts a new implementation turn or restores execution authority. Native permissions still require the exact pending request.
399
431
 
400
- Selected status/admission/queue observations detect external contract edits or milestone deletion, persist a closed gate and request exact bound-thread interruption. These observations grant no operator authority and report uncertain in-flight effects. The finalized baseline retains identities and completion evidence for explicit reconciliation of direct CLI edits. Invalid artifacts fail explicitly. No directory scan or filesystem watcher is used. Status projects Revising, approval/breakdown requirements, Ready, In progress, Completed and Blocked independently of provider process state.
432
+ Selected status/admission/queue observations detect external contract edits or milestone deletion, persist a closed gate and request exact bound-thread interruption. These observations grant no operator authority and report uncertain in-flight effects. The finalized baseline retains identities and progress, so a later revision checkpoint starts from them after direct CLI edits. Invalid artifacts fail explicitly. No directory scan or filesystem watcher is used. Status projects Revising, approval/breakdown requirements, Ready, In progress, Completed and Blocked independently of provider process state.
401
433
 
402
- Retained evidence pages bind their collection, page size and exact coordination hash. Reads do not load complete collections into the client; SQLite rebuilds the replaceable projection only when its selected authoritative file changes. The file has a hard size/record bound and rejects growth beyond it without discarding evidence.
434
+ coordination.json has a hard size and record bound and rejects growth beyond it without discarding evidence.
403
435
 
404
436
  ## Task collaboration
405
437
 
@@ -537,16 +569,14 @@ Native qualification on 2026-10-23 exercised all fourteen explicit workflows in
537
569
 
538
570
  ## Browser host integration
539
571
 
540
- `jg-agent-hq/contracts` exports closed `BrowserActionSchema`, `BrowserCommandSchema` and `BrowserReceiptSchema` contracts, plus browser session, repository and bounded plan read models. These schemas contain generic identities, not a deployment registry or private handler implementation. They do not expose native RPC, executables or provider configuration. Standalone IPC continues to support only its existing owned commands.
572
+ `jg-agent-hq/contracts` exports closed `BrowserActionSchema`, `BrowserCommandSchema` and `BrowserReceiptSchema` contracts, plus `BrowserThreadDetailSchema`, a bounded view of one managed thread with its plan context, pending approvals, live items and recent actions. These schemas contain generic identities, not a deployment registry or private handler implementation. They do not expose native RPC, executables or provider configuration. Standalone IPC continues to support only its existing owned commands.
541
573
 
542
- A trusted Node host calls `runtime.performBrowserAction(request, operatorId, execute)` after validating its signed operator identity. The host supplies one dispatcher function in process. It must validate every target against its registry, check operation-specific revisions/turns, and normalize approval provenance to that authenticated operator. Never accept a callback, operator identity or handler name from HTTP input. The request has a stable UUID, current runtime epoch and one closed command: native, plan, priority, error-reservation or publication-retry. The complete serialized request is limited to 2 MiB; nested native commands retain their tighter limits.
574
+ A trusted Node host calls `runtime.performBrowserAction(request, operatorId, execute)` after validating its signed operator identity. The host supplies one dispatcher function in process. It must validate every target against its registry, check operation-specific revisions/turns, and normalize approval provenance to that authenticated operator. Never accept a callback, operator identity or handler name from HTTP input. The request has a stable UUID, current runtime epoch and one closed command: native or plan. The complete serialized request is limited to 2 MiB; nested native commands retain their tighter limits.
543
575
 
544
576
  SQLite records an HMAC digest and receipt before invoking the dispatcher. The same UUID and identical normalized request returns the stored receipt without invoking it again. Changed payloads or operators conflict. New requests require the current epoch. Replaying a saved request after restart reconciles it without granting execution authority. Submitted receipts from another runtime become uncertain. Dispatcher failure also leaves the receipt uncertain because its effects may already have committed. This state never automatically resends an effect.
545
577
 
546
578
  The dispatcher receives a server-owned `nativeActionId`; use this ID for a native child action, preserving the validated runtime and command. `readBrowserAction(id, operatorId)` returns only that operator's receipt and joins its exact native receipt. Host acknowledgement means the handler completed, not that a native turn completed. An unknown or differently owned ID returns null. Host receipts retain admission metadata rather than arbitrary handler output. The selected joined native receipt includes its queued input and complete bounded final result; paged domain reads omit those bodies. At most 32 host jobs are admitted concurrently. Runtime close rejects new host work and waits for admitted work before closing its worker.
547
579
 
548
- `PublicationStatusSchema` is a browser-safe observation supplied by the host, independent of native execution and quota states. It contains the receipt UUID, state/reason, due/attempt/success timestamps, nullable pending and published commit hashes, and bounded queued/selected file counts. It contains no artifact bodies, paths, credentials or deployment configuration. `publication-retry` requires `publicationId` and `expectedCommit` (null before a commit exists). The host must compare both against its current receipt before acting and reconcile or retry only its recorded verified commit. The public runtime supplies no Git publisher, service installer or publication storage.
549
-
550
580
  Live reads accept `afterRevision`. A matching revision returns `unchanged: true` with an empty data array; retain the displayed window. A changed revision returns the complete bounded window. Revisions belong to one runtime. After reconnect to a new runtime, discard the revision and refresh native history. Token bodies stay in the existing bounded memory window and are never copied into lifecycle or browser-action tables.
551
581
 
552
582
  `thread-plan` accepts a managed `threadId` and returns its nullable `ActionPlanContextSchema`. The host verifies the thread's registered checkout before exposing it. It is read-only and grants no execution authority.
@@ -555,15 +585,17 @@ Live reads accept `afterRevision`. A matching revision returns `unchanged: true`
555
585
 
556
586
  The operation matrix describes the implemented native interfaces and their explicit unavailable surfaces. Executed qualification is narrower than every possible model, configuration and account state. Native versions below are observations, never admission rules.
557
587
 
558
- | Area | Executed evidence | Boundary |
559
- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
560
- | Provider integration | Public contract tests route a third provider, isolate unavailable providers and tolerate additive fields and future version labels. Native lifecycle, configuration, files, account and extension checks are listed in their sections above. | Each additional adapter needs its own native qualification. |
561
- | Directed collaboration | Codex 0.164.0 and Claude Code 2.1.309 completed both vendor directions. A parent yielded before its child started, then finished on its second turn. Same-vendor delegation answered a child clarification and finished with three parent turns and two child turns. | Reading, subscription and information messages grant no execution authority. |
562
- | Identity and native interaction | Both providers retained managed/native identities after compaction and reconnect with a fresh runtime epoch. Codex interruption and continuation passed. Claude AskUserQuestion and scoped MCP permission replies used exact native identities. | A timed-out compaction retained uncertain delivery even when completion later arrived; it was not resent. Explicit resume followed confirmed controller shutdown. |
563
- | Reports and recovery | Six final reports matched complete native outcomes byte for byte. A 46,464-byte report was found through indexed search and read in two chunks. After removing all eight qualification transcripts, offline recovery retained those reports and the host preference; tasks were paused and providers stayed idle. | Native transcripts, repository files and authentication remain separate recovery responsibilities. |
564
- | Optional skills | All fourteen explicit workflows ran in both providers, including verified delegation and standalone use. Skill-based parent returns ran in both directions. An unissued grant was rejected without creating its request. | Later approvals remain required. Claude signed publication used a disposable bare remote; the qualified Codex sandbox denied Git metadata writes. |
565
- | Host coverage | Linux x86_64 package checks passed on Node 24.15.0 and 24.22.1. Integrated delegation ran on the floor; identity, native interaction and recovery also ran on 24.22.1. | No macOS host was available for this run. Windows is outside the declared host contract. |
566
-
567
- The integrated delegation, identity and recovery checks used gpt-6.1-sol with medium effort and claude-opus-5-5 with medium effort in disposable workspaces on 2026-10-23. The [Node release index](https://nodejs.org/dist/index.json) identified 24.22.1 as the current LTS patch at qualification time. Local checks do not establish a published npm release or a deployed website.
588
+ | Area | Executed evidence | Boundary |
589
+ | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
590
+ | Provider integration | Public contract tests route a third provider, isolate unavailable providers and tolerate additive fields and future version labels. Native lifecycle, configuration, files, account and extension checks are listed in their sections above. | Each additional adapter needs its own native qualification. |
591
+ | Directed collaboration | Codex 0.164.0 and Claude Code 2.1.309 completed both vendor directions. A parent yielded before its child started, then finished on its second turn. Same-vendor delegation answered a child clarification and finished with three parent turns and two child turns. | Reading, subscription and information messages grant no execution authority. |
592
+ | Identity and native interaction | Both providers retained managed/native identities after compaction and reconnect with a fresh runtime epoch. Codex interruption and continuation passed. Claude AskUserQuestion and scoped MCP permission replies used exact native identities. | A timed-out compaction retained uncertain delivery even when completion later arrived; it was not resent. Explicit resume followed confirmed controller shutdown. |
593
+ | Reports and recovery | Six final reports matched complete native outcomes byte for byte. A 46,464-byte report was found through indexed search and read in two chunks. After removing all eight qualification transcripts, offline recovery retained those reports and the host preference; tasks were paused and providers stayed idle. | Native transcripts, repository files and authentication remain separate recovery responsibilities. |
594
+ | Optional skills | All fourteen explicit workflows ran in both providers, including verified delegation and standalone use. Skill-based parent returns ran in both directions. An unissued grant was rejected without creating its request. | Later approvals remain required. Claude signed publication used a disposable bare remote; the qualified Codex sandbox denied Git metadata writes. |
595
+ | Shared Codex daemon | Codex 0.164.0: a terminal `codex` session ran on the shared daemon and appeared in `thread/list`. Without subscribing, HQ saw its `thread/status/changed`; after rejoining with `thread/resume`, HQ received the terminal's live turn and item notifications. A thread HQ created appeared in the terminal's `codex resume` picker, and closing HQ's connection left the daemon and the terminal session running. The daemon confirmed HQ's interrupt and close. Per-thread skill roots, dynamic agent tools and output schemas worked on HQ threads, while another client's catalog and thread never saw the roots. Sessions read their own thread ID from `CODEX_THREAD_ID`. | A terminal started with `-c` overrides runs its thread in its own process (`source: cli`): it is listed, but a second writer is refused, so it cannot be followed live. The restart check ran against a separate app-server on its own socket rather than the shared daemon, which was serving other work: within one keepalive interval the session became uncertain and nothing was resent. A session Codex reloads from disk loses its capability roots. |
596
+ | Claude active sessions | Claude Code 2.1.310 answered `claude agents --json` in 0.16 s. Interactive entries carry `status` (`busy`, `idle`) and `pid`; background entries carry `id` and `state` (`blocked`). Sessions HQ starts in structured mode are listed as interactive under their HQ name and disappear after close. | The list describes running processes only; history still comes from transcripts. |
597
+ | Host coverage | Linux x86_64 package checks passed on Node 24.15.0 and 24.22.1. Integrated delegation ran on the floor; identity, native interaction and recovery also ran on 24.22.1. | No macOS host was available for this run. Windows is outside the declared host contract. |
598
+
599
+ The integrated delegation, identity and recovery checks used gpt-6.1-sol with medium effort and claude-opus-5-5 with medium effort in disposable workspaces on 2026-10-23. The shared-daemon and Claude active-session checks ran on 2026-10-25 with the installed CLIs' default models in disposable workspaces. The [Node release index](https://nodejs.org/dist/index.json) identified 24.22.1 as the current LTS patch at qualification time. Local checks do not establish a published npm release or a deployed website.
568
600
 
569
601
  Native model/output budgets also bound structured results. A generation that ends with incomplete JSON remains failed and creates no successful report; its bounded native result stays on the action receipt. The report byte limit does not increase the native model's output budget. Claude output schemas belong to session startup or explicit idle resume, as described in the configuration contract. Its unavailable steering, archive/revert, resource catalog and interactive authentication surfaces remain explicit in the operation matrix.
@@ -30,6 +30,8 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
30
30
  let lane = Promise.resolve();
31
31
  const eventCounts = new Map();
32
32
  const blockedProviders = new Set();
33
+ // providers whose connection reports the sessions other clients drive
34
+ const observingProviders = new Set();
33
35
  let closing = false;
34
36
  let unavailable = false;
35
37
  let eventFailure;
@@ -482,6 +484,16 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
482
484
  if (controlled.has(key(provider, nativeId)))
483
485
  live.markGap(key(provider, nativeId));
484
486
  },
487
+ session(provider, nativeId, state) {
488
+ observingProviders.add(provider);
489
+ // a session this runtime controls reports its transitions through its own thread state
490
+ if (controlled.has(key(provider, nativeId)))
491
+ return;
492
+ enqueue(provider, async () => {
493
+ await store.observeSessions(provider, [{ nativeId, state }], false);
494
+ onChange();
495
+ });
496
+ },
485
497
  delta(provider, nativeId, turnId, itemId, text) {
486
498
  if (controlled.has(key(provider, nativeId)))
487
499
  live.append(key(provider, nativeId), turnId, itemId, text);
@@ -569,6 +581,9 @@ export const createActions = (registry, store, roots, epoch, actionKey, skills,
569
581
  provider,
570
582
  ...(nativeId ? { nativeThreadId: nativeId } : {}),
571
583
  });
584
+ // only sessions observed through the lost connection lose their known state
585
+ if (!nativeId && observingProviders.has(provider))
586
+ await store.markSessionsUnknown(provider);
572
587
  onChange();
573
588
  for (const [id, prompt] of prompts)
574
589
  if (prompt.native.provider === provider &&
package/dist/cli/cli.js CHANGED
@@ -4,12 +4,12 @@ import { parseArgs } from 'node:util';
4
4
  import { setTimeout as wait } from 'node:timers/promises';
5
5
  import { Exception, hasErrorCode, isException } from 'jg-exception';
6
6
  import { HqRequestSchema } from '../contracts/index.js';
7
- import { toPublicError } from '../errors/index.js';
8
7
  import { requestAgentHq } from '../ipc/index.js';
9
8
  import { createAgentHq } from '../runtime/index.js';
10
9
  import { readRuntimeOwner } from '../runtime/state/index.js';
11
10
  import { serveAgentBridge } from '../agent-tools/mcp/index.js';
12
11
  import { AGENT_BRIDGE_FILE_ENV } from '../agent-tools/index.js';
12
+ import { toCliError } from './utilities.js';
13
13
  /** Runs the installed CLI without creating provider work merely to read history. */
14
14
  const main = async () => {
15
15
  if (process.argv[2] === 'agent-bridge') {
@@ -43,6 +43,7 @@ const main = async () => {
43
43
  topic: { type: 'string' },
44
44
  cursor: { type: 'string' },
45
45
  limit: { type: 'string' },
46
+ 'after-sequence': { type: 'string' },
46
47
  search: { type: 'string' },
47
48
  provider: { type: 'string' },
48
49
  help: { type: 'boolean', short: 'h' },
@@ -50,7 +51,7 @@ const main = async () => {
50
51
  });
51
52
  const [kind] = positionals;
52
53
  if (values.help || !kind || kind === 'help') {
53
- process.stdout.write('jg-agent-hq serve|status|stop|capabilities|threads|thread|turns|items|sessions|session-evidence|usage|account|models|configuration|mcp-servers|mcp-tools|mcp-resources|managed-thread-name|suggest-thread-name|skills|skill-preview|plan-status|plan-milestones|request --state-root <path> [--provider <provider-id>] [--workspace-root <path>] [--native-id <id>] [--limit <1..128>] [--cursor <cursor>] [--name <name>] [--topic <topic>] [--thread-id <id>] [--server-name <name>] [--skill-id <id>] [--arguments <text>] [--directory <path>]\nserve accepts repeated --codex-extra-skill-root and --claude-additional-directory.\nsession-evidence accepts --native-item-id and repeated --evidence-kind.\nrequest reads one validated HQ command as JSON from stdin.\n');
54
+ process.stdout.write('jg-agent-hq serve|status|stop|capabilities|threads|thread|turns|items|sessions|session-evidence|usage|account|models|configuration|mcp-servers|mcp-tools|mcp-resources|managed-thread-name|suggest-thread-name|skills|skill-preview|plan-status|plan-milestones|session-states|request --state-root <path> [--provider <provider-id>] [--workspace-root <path>] [--native-id <id>] [--limit <1..128>] [--cursor <cursor>] [--name <name>] [--topic <topic>] [--thread-id <id>] [--server-name <name>] [--skill-id <id>] [--arguments <text>] [--directory <path>] [--after-sequence <sequence>]\nserve accepts repeated --codex-extra-skill-root and --claude-additional-directory, and --coordination-root for a separate existing coordination directory.\nsession-evidence accepts --native-item-id and repeated --evidence-kind.\nrequest reads one validated HQ command as JSON from stdin.\n');
54
55
  return;
55
56
  }
56
57
  if (positionals.length !== 1 || !values['state-root'])
@@ -117,7 +118,8 @@ const main = async () => {
117
118
  values.cursor ||
118
119
  values.limit ||
119
120
  values.search ||
120
- values.provider)
121
+ values.provider ||
122
+ values['after-sequence'])
121
123
  throw new Exception('The HQ request is invalid', {
122
124
  code: 'JG_AGENT_HQ_REQUEST_INVALID',
123
125
  data: { kind: 'invalid-request' },
@@ -194,7 +196,28 @@ const main = async () => {
194
196
  process.stdout.write(`${JSON.stringify({ schemaVersion: 1, ...(await requestAgentHq(stateRoot, parsed.data)) })}\n`);
195
197
  return;
196
198
  }
197
- if (values.directory)
199
+ if (kind === 'session-states') {
200
+ const allowed = new Set(['state-root', 'after-sequence', 'limit']);
201
+ if (Object.keys(values).some((key) => !allowed.has(key)))
202
+ throw new Exception('The HQ request is invalid', {
203
+ code: 'JG_AGENT_HQ_REQUEST_INVALID',
204
+ data: { kind: 'invalid-request' },
205
+ });
206
+ const parsed = HqRequestSchema.safeParse({
207
+ kind: 'session-states',
208
+ afterSequence: values['after-sequence'] === undefined ? 0 : Number(values['after-sequence']),
209
+ limit: values.limit === undefined ? 32 : Number(values.limit),
210
+ });
211
+ if (!parsed.success)
212
+ throw new Exception('The HQ request is invalid', {
213
+ code: 'JG_AGENT_HQ_REQUEST_INVALID',
214
+ data: { kind: 'invalid-request' },
215
+ cause: parsed.error,
216
+ });
217
+ process.stdout.write(`${JSON.stringify({ schemaVersion: 1, ...(await requestAgentHq(stateRoot, parsed.data)) })}\n`);
218
+ return;
219
+ }
220
+ if (values.directory || values['after-sequence'])
198
221
  throw new Exception('The HQ request is invalid', {
199
222
  code: 'JG_AGENT_HQ_REQUEST_INVALID',
200
223
  data: { kind: 'invalid-request' },
@@ -281,6 +304,6 @@ try {
281
304
  await main();
282
305
  }
283
306
  catch (error) {
284
- process.stderr.write(`${JSON.stringify({ schemaVersion: 1, success: false, error: toPublicError(error) })}\n`);
307
+ process.stderr.write(`${JSON.stringify({ schemaVersion: 1, success: false, error: toCliError(error) })}\n`);
285
308
  process.exitCode = 1;
286
309
  }
@@ -0,0 +1,3 @@
1
+ import { toPublicError } from '../errors/index.js';
2
+ /** Presents static storage diagnoses without exposing diagnostic paths, suffixes or causes. */
3
+ export declare const toCliError: (error: unknown) => ReturnType<typeof toPublicError>;