jg-agent-hq 3.0.0 → 4.0.1
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.
- package/CHANGELOG.md +14 -0
- package/README.md +13 -13
- package/api/README.md +91 -102
- package/dist/actions/actions.js +15 -0
- package/dist/cli/cli.js +26 -35
- package/dist/cli/utilities.d.ts +1 -1
- package/dist/cli/utilities.js +8 -25
- package/dist/collaboration/dispatch/types.d.ts +2 -2
- package/dist/contracts/actions/types.d.ts +4 -4
- package/dist/contracts/browser/index.d.ts +1 -3
- package/dist/contracts/browser/index.js +1 -3
- package/dist/contracts/browser/types.d.ts +15 -1447
- package/dist/contracts/browser/types.js +3 -112
- package/dist/contracts/index.d.ts +7 -9
- package/dist/contracts/index.js +5 -7
- package/dist/contracts/plans/index.d.ts +4 -6
- package/dist/contracts/plans/index.js +2 -4
- package/dist/contracts/plans/types.d.ts +38 -905
- package/dist/contracts/plans/types.js +13 -139
- package/dist/contracts/sessions/index.d.ts +2 -0
- package/dist/contracts/sessions/index.js +2 -0
- package/dist/contracts/sessions/types.d.ts +101 -0
- package/dist/contracts/sessions/types.js +43 -0
- package/dist/contracts/types.d.ts +461 -1047
- package/dist/contracts/types.js +8 -0
- package/dist/index.d.ts +2 -4
- package/dist/index.js +1 -3
- package/dist/plans/admission.d.ts +6 -6
- package/dist/plans/admission.js +1 -1
- package/dist/plans/authority.js +15 -13
- package/dist/plans/documents.d.ts +3 -17
- package/dist/plans/documents.js +6 -62
- package/dist/plans/files.d.ts +2 -2
- package/dist/plans/files.js +2 -4
- package/dist/plans/finalization.d.ts +6 -8
- package/dist/plans/finalization.js +25 -26
- package/dist/plans/index.d.ts +2 -3
- package/dist/plans/index.js +1 -2
- package/dist/plans/plans.d.ts +8 -8
- package/dist/plans/plans.js +33 -82
- package/dist/plans/projections.d.ts +2 -2
- package/dist/plans/projections.js +44 -82
- package/dist/plans/revisions.d.ts +4 -5
- package/dist/plans/revisions.js +5 -44
- package/dist/plans/types.d.ts +0 -281
- package/dist/plans/types.js +2 -30
- package/dist/plans/utilities.js +2 -11
- package/dist/providers/claude/agents/agents.d.ts +19 -0
- package/dist/providers/claude/agents/agents.js +83 -0
- package/dist/providers/claude/agents/constants.d.ts +3 -0
- package/dist/providers/claude/agents/constants.js +4 -0
- package/dist/providers/claude/agents/index.d.ts +1 -0
- package/dist/providers/claude/agents/index.js +2 -0
- package/dist/providers/claude/agents/types.d.ts +14 -0
- package/dist/providers/claude/agents/types.js +9 -0
- package/dist/providers/claude/history/history.model.js +2 -0
- package/dist/providers/claude/history/types.d.ts +92 -368
- package/dist/providers/claude/index.d.ts +1 -0
- package/dist/providers/claude/index.js +2 -0
- package/dist/providers/codex/adapter.d.ts +1 -1
- package/dist/providers/codex/adapter.js +28 -3
- package/dist/providers/codex/codex.js +51 -18
- package/dist/providers/codex/events.d.ts +2 -1
- package/dist/providers/codex/events.js +8 -3
- package/dist/providers/codex/index.d.ts +1 -1
- package/dist/providers/codex/index.js +1 -1
- package/dist/providers/codex/rpc.d.ts +9 -4
- package/dist/providers/codex/rpc.js +109 -47
- package/dist/providers/codex/skill-roots/constants.d.ts +4 -0
- package/dist/providers/codex/skill-roots/constants.js +7 -0
- package/dist/providers/codex/skill-roots/index.d.ts +2 -0
- package/dist/providers/codex/skill-roots/index.js +4 -0
- package/dist/providers/codex/skill-roots/skill-roots.d.ts +35 -0
- package/dist/providers/codex/skill-roots/skill-roots.js +93 -0
- package/dist/providers/codex/transformers.d.ts +3 -1
- package/dist/providers/codex/transformers.js +12 -1
- package/dist/providers/codex/types.d.ts +11 -0
- package/dist/providers/codex/types.js +6 -1
- package/dist/providers/codex/websocket/constants.d.ts +11 -0
- package/dist/providers/codex/websocket/constants.js +18 -0
- package/dist/providers/codex/websocket/index.d.ts +1 -0
- package/dist/providers/codex/websocket/index.js +2 -0
- package/dist/providers/codex/websocket/websocket.d.ts +7 -0
- package/dist/providers/codex/websocket/websocket.js +219 -0
- package/dist/providers/index.d.ts +2 -2
- package/dist/providers/index.js +1 -1
- package/dist/providers/process.d.ts +2 -2
- package/dist/providers/process.js +37 -4
- package/dist/providers/registry/registry.js +2 -1
- package/dist/providers/types.d.ts +25 -2
- package/dist/runtime/runtime.d.ts +0 -2
- package/dist/runtime/runtime.js +11 -5
- package/dist/runtime/state/state.d.ts +1 -1
- package/dist/runtime/state/state.js +2 -2
- package/dist/runtime/types.d.ts +0 -2
- package/dist/runtime/types.js +0 -3
- package/dist/sessions/sessions.js +2 -0
- package/dist/snapshots/archive/archive.d.ts +29 -0
- package/dist/snapshots/archive/archive.js +342 -0
- package/dist/snapshots/archive/constants.d.ts +5 -0
- package/dist/snapshots/archive/constants.js +8 -0
- package/dist/snapshots/archive/index.d.ts +1 -0
- package/dist/snapshots/archive/index.js +2 -0
- package/dist/snapshots/artifacts.d.ts +10 -1
- package/dist/snapshots/artifacts.js +38 -13
- package/dist/snapshots/capture.d.ts +3 -2
- package/dist/snapshots/capture.js +29 -13
- package/dist/snapshots/database.d.ts +2 -2
- package/dist/snapshots/database.js +30 -14
- package/dist/snapshots/fences.d.ts +4 -9
- package/dist/snapshots/fences.js +9 -22
- package/dist/snapshots/index.d.ts +1 -2
- package/dist/snapshots/index.js +2 -3
- package/dist/snapshots/snapshots.d.ts +6 -5
- package/dist/snapshots/snapshots.js +13 -13
- package/dist/snapshots/snapshots.worker.js +1 -1
- package/dist/snapshots/types.d.ts +26 -5
- package/dist/snapshots/types.js +15 -4
- package/dist/storage/schema/constants.d.ts +2 -2
- package/dist/storage/schema/constants.js +9 -3
- package/dist/storage/schema/index.d.ts +2 -3
- package/dist/storage/schema/index.js +4 -3
- package/dist/storage/schema/schema.d.ts +10 -8
- package/dist/storage/schema/schema.js +22 -36
- package/dist/storage/schema/types.d.ts +1 -11
- package/dist/storage/schema/types.js +2 -2
- package/dist/storage/storage.d.ts +1 -1
- package/dist/storage/storage.js +2 -2
- package/dist/store/collaboration/collaboration.model.d.ts +2 -2
- package/dist/store/control/types.d.ts +16 -16
- package/dist/store/plans/plans.model.d.ts +3 -105
- package/dist/store/plans/plans.model.js +6 -46
- package/dist/store/schema.d.ts +0 -2
- package/dist/store/schema.js +6 -25
- package/dist/store/schema.sql +90 -16
- package/dist/store/sessions/index.d.ts +1 -0
- package/dist/store/sessions/index.js +2 -0
- package/dist/store/sessions/sessions.model.d.ts +28 -0
- package/dist/store/sessions/sessions.model.js +105 -0
- package/dist/store/store.d.ts +0 -2
- package/dist/store/store.js +13 -9
- package/dist/store/store.worker.js +16 -11
- package/dist/store/types.d.ts +134 -513
- package/dist/store/types.js +21 -7
- package/docs/recovery.md +6 -16
- package/errors/README.md +30 -36
- package/package.json +1 -1
- package/dist/plans/reconciliation.d.ts +0 -34
- package/dist/plans/reconciliation.js +0 -246
- package/dist/storage/schema/v1-to-v2.sql +0 -1
- package/dist/storage/schema/v1.sql +0 -538
- package/dist/storage/upgrade/index.d.ts +0 -2
- package/dist/storage/upgrade/index.js +0 -2
- package/dist/storage/upgrade/types.d.ts +0 -61
- package/dist/storage/upgrade/types.js +0 -42
- package/dist/storage/upgrade/upgrade.d.ts +0 -33
- package/dist/storage/upgrade/upgrade.js +0 -196
- package/dist/storage/upgrade/upgrade.worker.d.ts +0 -1
- package/dist/storage/upgrade/upgrade.worker.js +0 -220
package/api/README.md
CHANGED
|
@@ -22,76 +22,43 @@ 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
|
|
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
|
|
|
29
29
|
The host must coordinate every application connection that can write during maintenance. A shared file gives SQLite transaction isolation, not an atomic transaction spanning host SQL and HQ API calls. HQ does not expose its worker connection. Snapshot scheduling and remote backup operations belong to the host application.
|
|
30
30
|
|
|
31
|
-
## Offline storage upgrade
|
|
32
|
-
|
|
33
|
-
Import `upgradeHqStorage`, `IHqStorageUpgradeOptions` and `IHqStorageUpgradeResult` from the Node root. This operation is absent from browser contracts, IPC and agent tools.
|
|
34
|
-
|
|
35
|
-
```ts
|
|
36
|
-
interface IHqStorageUpgradeOptions {
|
|
37
|
-
stateRoot: string;
|
|
38
|
-
backupDirectory: string;
|
|
39
|
-
allowedRoots: string[];
|
|
40
|
-
coordinationRoot?: string;
|
|
41
|
-
}
|
|
42
|
-
interface IHqStorageUpgradeResult {
|
|
43
|
-
stateRoot: string;
|
|
44
|
-
state: 'upgraded' | 'current';
|
|
45
|
-
fromVersion: number;
|
|
46
|
-
toVersion: number;
|
|
47
|
-
fromSchemaHash: string;
|
|
48
|
-
toSchemaHash: string;
|
|
49
|
-
backupDirectory: string | null;
|
|
50
|
-
}
|
|
51
|
-
// upgradeHqStorage(options): Promise<IHqStorageUpgradeResult>
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
Stop HQ and its native children, close independent application database writers and pause independent plan writers first. Supply existing canonical absolute state/workspace paths and an absent backup directory beneath an existing private canonical parent. The backup must not overlap the source state or any registered plan source. coordinationRoot defaults to stateRoot. A separate coordinationRoot may be a normal project directory; its .runtime lock directory remains private. Inputs are trusted operator selections; stored roots never grant access. Existing live, dead, incomplete or unverifiable lifetime owners block the operation and are never automatically reclaimed.
|
|
55
|
-
|
|
56
|
-
The installed CLI invokes the same API directly without a controller, listening socket or provider:
|
|
57
|
-
|
|
58
|
-
```sh
|
|
59
|
-
jg-agent-hq upgrade-storage --state-root /path/to/state --backup-directory /private/backups/before-upgrade --workspace-root /path/to/workspace --workspace-root /path/to/other-workspace --coordination-root /path/to/coordination
|
|
60
|
-
```
|
|
61
|
-
|
|
62
|
-
At least one --workspace-root is required; --coordination-root is optional. Other command flags are rejected, and --backup-directory is rejected on other commands. Success writes one stdout JSON line `{ schemaVersion: 1, kind: 'upgrade-storage', result }`. Failure retains exit 1 and stderr `{ schemaVersion: 1, success: false, error: { kind, message } }`. Only the four canonical storage upgrade/version messages bypass generic CLI classifications; private causes, paths and diagnostic suffixes are removed. `serve` presents the same explicit-upgrade-required message on legacy state. Help documents this operator path.
|
|
63
|
-
|
|
64
|
-
Read-only classification rejects unsupported/corrupt state before a writer or backup reservation. A current version returns current with backupDirectory null, without DDL, backup reservation or startup reconciliation. For version 1, lifetime ownership and the metadata lock protect a BEGIN IMMEDIATE checkpoint. A separate read-only connection captures the same complete format-1 snapshot as createHqSnapshot, including host tables, the private key, exact reports and registered companions. Full verification precedes DDL. Migration updates version/hash in one transaction, verifies integrity/foreign keys and preserves application objects, user_version, keys, receipts, queues, grants and collaboration state. Migration grants no authority and starts no native work.
|
|
65
|
-
|
|
66
|
-
The dedicated worker has no whole-operation size deadline. The caller waits for actual exit before lifetime ownership is released. A pre-commit failure rolls back; once a backup verifies, it remains the operator's recovery deliverable even if migration fails. Post-commit, acknowledgement or cleanup uncertainty uses JG_AGENT_HQ_STORAGE_UPGRADE_UNCERTAIN with trusted Node phase/backup diagnostics. A lost worker result may identify only the requested backup path; inspect its completion evidence before using it. Never automatically reverse or replay it. An explicit retry reads the durable stamp and returns current if committed. Process death can leave ownership requiring deliberate inspection. Keep the verified backup and follow the [recovery procedure](../docs/recovery.md); no down-migration is supplied.
|
|
67
|
-
|
|
68
31
|
## Snapshot and restore
|
|
69
32
|
|
|
70
|
-
Import createHqSnapshot, inspectHqSnapshot and
|
|
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.
|
|
71
34
|
|
|
72
|
-
| Operation | Contract
|
|
73
|
-
| ------------------------------------------------------- |
|
|
74
|
-
| `createHqSnapshot(hq, destination)` |
|
|
75
|
-
| `inspectHqSnapshot(directory)` | Validate the complete private snapshot without changing it. Returns IHqSnapshotInspection.
|
|
76
|
-
| `
|
|
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. |
|
|
77
42
|
|
|
78
|
-
Capture
|
|
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.
|
|
79
44
|
|
|
80
|
-
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
|
|
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.
|
|
81
46
|
|
|
82
|
-
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>`.
|
|
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.
|
|
83
48
|
|
|
84
|
-
Inspection streams the inventory, verifies each listed regular file and every expected/absent companion, rejects links and unsafe paths, checks
|
|
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.
|
|
85
50
|
|
|
86
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.
|
|
87
52
|
|
|
88
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.
|
|
89
54
|
|
|
90
|
-
|
|
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.
|
|
91
56
|
|
|
92
|
-
These exports use SNAPSHOT_INVALID for incomplete, corrupt, unsafe or occupied snapshot
|
|
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.
|
|
93
58
|
|
|
94
|
-
|
|
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).
|
|
95
62
|
|
|
96
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.
|
|
97
64
|
|
|
@@ -111,7 +78,7 @@ The socket accepts at most 32 simultaneous connections. Requests are bounded to
|
|
|
111
78
|
|
|
112
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.
|
|
113
80
|
|
|
114
|
-
`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.
|
|
115
82
|
|
|
116
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.
|
|
117
84
|
|
|
@@ -171,7 +138,7 @@ Import `HqRequestSchema`, `HqResponseSchema` and their inferred types from `jg-a
|
|
|
171
138
|
|
|
172
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.
|
|
173
140
|
|
|
174
|
-
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.
|
|
175
142
|
|
|
176
143
|
## Bounded session evidence
|
|
177
144
|
|
|
@@ -320,15 +287,15 @@ Partial text uses temporary live identities until the final native message UUID
|
|
|
320
287
|
|
|
321
288
|
## Native skill catalog
|
|
322
289
|
|
|
323
|
-
`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.
|
|
324
291
|
|
|
325
|
-
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.
|
|
326
293
|
|
|
327
|
-
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
|
|
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.
|
|
328
295
|
|
|
329
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.
|
|
330
297
|
|
|
331
|
-
Trusted runtime construction also accepts `codexExtraSkillRoots?: string[]` and `claudeAdditionalDirectories?: string[]`. Paths must resolve to existing absolute directories. Codex receives
|
|
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.
|
|
332
299
|
|
|
333
300
|
## Control reads and reconnect
|
|
334
301
|
|
|
@@ -352,13 +319,37 @@ Live item presentation is bounded to 128 items per cached thread, 32 windows and
|
|
|
352
319
|
|
|
353
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.
|
|
354
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`. An ephemeral session, which Codex doesn't save, such as a helper session Codex starts itself, is never observed. 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, `waiting` (an interactive session's question or permission prompt) and `blocked` (a background session) are 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
|
+
|
|
355
346
|
## Subscription observations
|
|
356
347
|
|
|
357
|
-
The
|
|
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.
|
|
358
349
|
|
|
359
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.
|
|
360
351
|
|
|
361
|
-
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
|
|
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.
|
|
362
353
|
|
|
363
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.
|
|
364
355
|
|
|
@@ -374,31 +365,31 @@ Every usage read requests current native observations; the last successful snaps
|
|
|
374
365
|
|
|
375
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.
|
|
376
367
|
|
|
368
|
+
`jg-agent-hq session-states --state-root <directory> [--after-sequence <sequence>] [--limit <1..128>]` reads one page of session state transitions.
|
|
369
|
+
|
|
377
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.
|
|
378
371
|
|
|
379
372
|
## Plan coordination
|
|
380
373
|
|
|
381
|
-
`computePlanRevision({ body, metadata, milestones })` is the pure Node API for execution identity. `metadata` contains
|
|
382
|
-
|
|
383
|
-
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. 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.
|
|
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.
|
|
384
375
|
|
|
385
|
-
|
|
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.
|
|
386
377
|
|
|
387
|
-
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.
|
|
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.
|
|
388
379
|
|
|
389
|
-
| Command kind | Required fields and result
|
|
390
|
-
| ----------------- |
|
|
391
|
-
| `status` | `target`. Returns current execution revisions, full inspection hashes, `skillsBinding` (`absent`, `current` or `stale`), approval state and a bounded coordination summary and
|
|
392
|
-
| `milestones` | `target`, optional `limit` (default 32, maximum 128) and `cursor`. Returns a bounded ordered seek page.
|
|
393
|
-
| `
|
|
394
|
-
| `
|
|
395
|
-
| `revision
|
|
396
|
-
| `
|
|
397
|
-
| `
|
|
398
|
-
| `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.
|
|
399
|
-
| `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.
|
|
400
|
-
| `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.
|
|
401
|
-
| `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. |
|
|
402
393
|
|
|
403
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.
|
|
404
395
|
|
|
@@ -406,15 +397,15 @@ Milestones are optional. Finalizing a plan with no milestone file returns `conte
|
|
|
406
397
|
|
|
407
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.
|
|
408
399
|
|
|
409
|
-
|
|
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.
|
|
410
401
|
|
|
411
|
-
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
|
|
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.
|
|
412
403
|
|
|
413
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.
|
|
414
405
|
|
|
415
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.
|
|
416
407
|
|
|
417
|
-
SQLite persists exact prepared plan/milestone sources
|
|
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.
|
|
418
409
|
|
|
419
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.
|
|
420
411
|
|
|
@@ -422,9 +413,7 @@ Accepted implementation input prepares aggregate and selected pending milestone
|
|
|
422
413
|
|
|
423
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.
|
|
424
415
|
|
|
425
|
-
`
|
|
426
|
-
|
|
427
|
-
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.
|
|
428
417
|
|
|
429
418
|
### Revision and progress recovery
|
|
430
419
|
|
|
@@ -432,17 +421,17 @@ Begin revision before invoking a planning skill. Execution admission closes unde
|
|
|
432
421
|
|
|
433
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.
|
|
434
423
|
|
|
435
|
-
After native `jg-plan` revises the contract and an explicitly requested `jg-breakdown` regenerates a needed sequence, close the planning controller before finalization.
|
|
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.
|
|
436
425
|
|
|
437
|
-
A whole-plan checkpoint retains null milestones and an empty milestone inventory.
|
|
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.
|
|
438
427
|
|
|
439
|
-
|
|
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.
|
|
440
429
|
|
|
441
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.
|
|
442
431
|
|
|
443
|
-
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
|
|
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.
|
|
444
433
|
|
|
445
|
-
|
|
434
|
+
coordination.json has a hard size and record bound and rejects growth beyond it without discarding evidence.
|
|
446
435
|
|
|
447
436
|
## Task collaboration
|
|
448
437
|
|
|
@@ -580,16 +569,14 @@ Native qualification on 2026-10-23 exercised all fourteen explicit workflows in
|
|
|
580
569
|
|
|
581
570
|
## Browser host integration
|
|
582
571
|
|
|
583
|
-
`jg-agent-hq/contracts` exports closed `BrowserActionSchema`, `BrowserCommandSchema` and `BrowserReceiptSchema` contracts, plus
|
|
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.
|
|
584
573
|
|
|
585
|
-
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
|
|
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.
|
|
586
575
|
|
|
587
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.
|
|
588
577
|
|
|
589
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.
|
|
590
579
|
|
|
591
|
-
`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.
|
|
592
|
-
|
|
593
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.
|
|
594
581
|
|
|
595
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.
|
|
@@ -598,15 +585,17 @@ Live reads accept `afterRevision`. A matching revision returns `unchanged: true`
|
|
|
598
585
|
|
|
599
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.
|
|
600
587
|
|
|
601
|
-
| Area | Executed evidence
|
|
602
|
-
| ------------------------------- |
|
|
603
|
-
| 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.
|
|
604
|
-
| 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.
|
|
605
|
-
| 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.
|
|
606
|
-
| 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.
|
|
607
|
-
| 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.
|
|
608
|
-
|
|
|
609
|
-
|
|
610
|
-
|
|
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`, `waiting`, `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.
|
|
611
600
|
|
|
612
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.
|
package/dist/actions/actions.js
CHANGED
|
@@ -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 &&
|