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.
- package/CHANGELOG.md +18 -0
- package/README.md +14 -14
- package/api/README.md +97 -65
- package/dist/actions/actions.js +15 -0
- package/dist/cli/cli.js +28 -5
- package/dist/cli/utilities.d.ts +3 -0
- package/dist/cli/utilities.js +13 -0
- 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 +9 -11
- package/dist/contracts/index.js +6 -8
- 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 +551 -1035
- package/dist/contracts/types.js +32 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/plans/admission.d.ts +6 -6
- package/dist/plans/admission.js +1 -1
- package/dist/plans/authority.d.ts +2 -0
- package/dist/plans/authority.js +23 -13
- package/dist/plans/documents.d.ts +20 -17
- package/dist/plans/documents.js +29 -63
- package/dist/plans/files.d.ts +2 -2
- package/dist/plans/files.js +5 -5
- 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 +36 -83
- 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 +5 -281
- package/dist/plans/types.js +2 -30
- package/dist/plans/utilities.js +2 -11
- package/dist/providers/claude/agents/agents.d.ts +16 -0
- package/dist/providers/claude/agents/agents.js +80 -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/claude.js +2 -0
- package/dist/providers/claude/history/history.model.js +2 -0
- package/dist/providers/claude/history/types.d.ts +115 -368
- package/dist/providers/claude/index.d.ts +1 -0
- package/dist/providers/claude/index.js +2 -0
- package/dist/providers/claude/transformers.js +14 -1
- package/dist/providers/codex/adapter.d.ts +1 -1
- package/dist/providers/codex/adapter.js +26 -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 +41 -3
- package/dist/providers/codex/types.d.ts +38 -1
- package/dist/providers/codex/types.js +15 -3
- 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.js +11 -3
- package/dist/runtime/state/index.d.ts +1 -1
- package/dist/runtime/state/index.js +1 -1
- package/dist/runtime/state/state.d.ts +15 -0
- package/dist/runtime/state/state.js +92 -1
- 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 +15 -0
- package/dist/snapshots/capture.js +158 -0
- package/dist/snapshots/database.d.ts +2 -0
- package/dist/snapshots/database.js +35 -55
- package/dist/snapshots/fences.d.ts +10 -0
- package/dist/snapshots/fences.js +51 -0
- package/dist/snapshots/index.d.ts +1 -0
- package/dist/snapshots/index.js +2 -0
- package/dist/snapshots/snapshots.d.ts +7 -3
- package/dist/snapshots/snapshots.js +31 -117
- package/dist/snapshots/snapshots.worker.js +5 -1
- package/dist/snapshots/types.d.ts +35 -3
- package/dist/snapshots/types.js +19 -4
- package/dist/storage/index.d.ts +2 -1
- package/dist/storage/index.js +2 -1
- package/dist/storage/schema/constants.d.ts +2 -0
- package/dist/storage/schema/constants.js +9 -0
- package/dist/storage/schema/index.d.ts +3 -0
- package/dist/storage/schema/index.js +6 -0
- package/dist/storage/schema/schema.d.ts +18 -0
- package/dist/storage/schema/schema.js +59 -0
- package/dist/storage/schema/types.d.ts +7 -0
- package/dist/storage/schema/types.js +8 -0
- package/dist/storage/storage.d.ts +1 -1
- package/dist/storage/storage.js +2 -2
- package/dist/storage/types.d.ts +0 -5
- package/dist/storage/types.js +0 -6
- 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.js +7 -35
- package/dist/store/schema.sql +91 -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.js +13 -7
- 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 +8 -4
- package/errors/README.md +3 -3
- package/package.json +2 -2
- package/dist/plans/reconciliation.d.ts +0 -34
- package/dist/plans/reconciliation.js +0 -246
package/dist/store/types.js
CHANGED
|
@@ -2,10 +2,10 @@ import { z } from 'zod';
|
|
|
2
2
|
import { DispatchScanSchema, } from '../collaboration/dispatch/index.js';
|
|
3
3
|
import { AgentIdentityQuerySchema, NativeToolBindingSchema, AgentSpawnReadSchema, } from '../collaboration/identity/index.js';
|
|
4
4
|
import { CollaborationRequestSchema, DispatchBlockedSchema, } from '../contracts/collaboration/index.js';
|
|
5
|
-
import { BrowserActionSchema, BrowserReceiptSchema, MAX_PAGE_SIZE, ThreadSummarySchema, ManagedThreadSchema, ErrorKindSchema, HqRequestSchema, } from '../contracts/index.js';
|
|
5
|
+
import { BrowserActionSchema, BrowserReceiptSchema, MAX_PAGE_SIZE, ThreadSummarySchema, ManagedThreadSchema, ErrorKindSchema, HqRequestSchema, SessionStateSchema, } from '../contracts/index.js';
|
|
6
6
|
import { EvidenceOriginsRequestSchema, } from '../sessions/evidence/index.js';
|
|
7
7
|
import { StorageDescriptorSchema } from '../storage/index.js';
|
|
8
|
-
import { PlanWriteIntentSchema, PlanProjectionSchema, PlanProjectionPageSchema,
|
|
8
|
+
import { PlanWriteIntentSchema, PlanProjectionSchema, PlanProjectionPageSchema, } from '../plans/index.js';
|
|
9
9
|
import { AdmissionSchema, NativeOutcomeSchema, NativeObservationSchema, ControlPageSchema, ApprovalPageRequestSchema, EventPageSchema, ApprovalRecordSchema, } from './control/index.js';
|
|
10
10
|
// worker messages are closed, bounded operations rather than arbitrary SQL
|
|
11
11
|
export const StoreCommandSchema = z.discriminatedUnion('kind', [
|
|
@@ -32,8 +32,7 @@ export const StoreCommandSchema = z.discriminatedUnion('kind', [
|
|
|
32
32
|
actionId: z.uuid(),
|
|
33
33
|
}),
|
|
34
34
|
z.strictObject({ kind: z.literal('evidence-origins'), request: EvidenceOriginsRequestSchema }),
|
|
35
|
-
z.strictObject({ kind: z.literal('storage-maintenance')
|
|
36
|
-
z.strictObject({ kind: z.literal('snapshot-plans'), after: z.string() }),
|
|
35
|
+
z.strictObject({ kind: z.literal('storage-maintenance') }),
|
|
37
36
|
z.strictObject({ kind: z.literal('snapshot-backup'), destination: z.string() }),
|
|
38
37
|
z.strictObject({
|
|
39
38
|
kind: z.literal('browser-read'),
|
|
@@ -58,11 +57,26 @@ export const StoreCommandSchema = z.discriminatedUnion('kind', [
|
|
|
58
57
|
nextCursor: z.string().max(16_384).nullable(),
|
|
59
58
|
observedAt: z.number().int(),
|
|
60
59
|
}),
|
|
60
|
+
z.strictObject({ kind: z.literal('plan-register'), directory: z.string() }),
|
|
61
61
|
z.strictObject({
|
|
62
|
-
kind: z.literal('
|
|
63
|
-
|
|
62
|
+
kind: z.literal('sessions-observe'),
|
|
63
|
+
provider: z.string(),
|
|
64
|
+
sessions: z
|
|
65
|
+
.array(z.strictObject({ nativeId: z.string().min(1), state: SessionStateSchema }))
|
|
66
|
+
.max(1024),
|
|
67
|
+
isComplete: z.boolean(),
|
|
68
|
+
}),
|
|
69
|
+
z.strictObject({ kind: z.literal('sessions-unknown'), provider: z.string() }),
|
|
70
|
+
z.strictObject({
|
|
71
|
+
kind: z.literal('sessions-states'),
|
|
72
|
+
provider: z.string(),
|
|
73
|
+
nativeIds: z.array(z.string()).max(MAX_PAGE_SIZE),
|
|
74
|
+
}),
|
|
75
|
+
z.strictObject({
|
|
76
|
+
kind: z.literal('session-transitions'),
|
|
77
|
+
afterSequence: z.number().int().nonnegative(),
|
|
78
|
+
limit: z.number().int().min(1).max(128),
|
|
64
79
|
}),
|
|
65
|
-
z.strictObject({ kind: z.literal('plan-revision-page'), page: PlanRevisionPageSchema }),
|
|
66
80
|
z.strictObject({ kind: z.literal('thread-plan-read'), threadId: z.uuid() }),
|
|
67
81
|
z.strictObject({ kind: z.literal('plan-threads'), directory: z.string() }),
|
|
68
82
|
z.strictObject({ kind: z.literal('queue-peek'), threadId: z.uuid() }),
|
package/docs/recovery.md
CHANGED
|
@@ -4,20 +4,24 @@ HQ supplies local capture, inspection and offline restore primitives. The Node s
|
|
|
4
4
|
|
|
5
5
|
## Capture
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
Capture runs while agents keep working. HQ-mediated plan writes wait for its coordination metadata lock, and each registered plan is copied under its own document locks. Keep the host's own connections from writing host tables until capture resolves. Capture includes committed WAL data, application tables, stored reports, action.key and registered plan companions. Prepared document writes and source mismatches stay as evidence. A plan edited outside HQ during capture is still copied consistently; when its copied revision differs from one its thread bindings recorded, the snapshot marks it plan-changed.
|
|
8
8
|
|
|
9
|
-
A successful snapshot has exact file hashes and a final completion marker. The database stamp binds its action-key fingerprint; inspection and runtime startup reject a mismatched key. Keep it private. It excludes repositories, native transcripts/authentication, external references and transient runtime credentials. Missing source plans and registered references outside the current allowed roots remain explicit diagnostics, without widening access. Inspection establishes complete local file/database evidence; hashes provide integrity rather than sender authentication.
|
|
9
|
+
A successful snapshot has exact file hashes and a final completion marker. The header records the package version that captured it, and the database stamp binds its schema, action-key fingerprint and writing package version; inspection and runtime startup reject a mismatched key or another schema. Keep it private. It excludes repositories, native transcripts/authentication, external references and transient runtime credentials. Missing source plans and registered references outside the current allowed roots remain explicit diagnostics, without widening access. Inspection establishes complete local file/database evidence; hashes provide integrity rather than sender authentication.
|
|
10
10
|
|
|
11
11
|
## Restore
|
|
12
12
|
|
|
13
13
|
Stop all connections to the proposed destination and choose a new recovery workspace. Restore validates source and staged copies and refuses every existing target. It creates separate state and plan recovery directories, a streamed recovery.jsonl inventory and recovered.json completion record. Never use output left incomplete by a crash. Caught failures clean only the output that operation created.
|
|
14
14
|
|
|
15
|
-
Start HQ with the returned stateRoot and explicit allowedRoots. Source root permissions are not imported. The runtime gets a new epoch; automation stays paused, dispatch is disabled, skill grants are revoked, approvals expire and native ownership is uncertain. Read stored reports without native histories. Inspect wait sets, continuation reservations and uncertain receipts without replaying input.
|
|
15
|
+
Start HQ with the returned stateRoot and explicit allowedRoots. Source root permissions are not imported. The runtime gets a new epoch; automation stays paused, dispatch is disabled, skill grants are revoked, approvals expire and native ownership is uncertain. Thread bindings of plans marked plan-changed lose their execution scope. Read stored reports without native histories. Inspect wait sets, continuation reservations and uncertain receipts without replaying input.
|
|
16
16
|
|
|
17
17
|
Recover repositories and native files separately. Source paths and plan bindings are retained as evidence. Compare the selected plan companions against current files before copying them into an explicitly chosen location; never blindly replace repository files. Rebind plan references and obtain fresh authority where needed. Reconcile a pending document intent only using its original ID and unchanged/desired byte guards. Reconcile native ownership and make current-revision host lifecycle decisions before enabling execution. The snapshot does not promise path translation or restore authentication.
|
|
18
18
|
|
|
19
|
+
## Rollback
|
|
20
|
+
|
|
21
|
+
Roll back by restoring an earlier snapshot into a new recovery workspace; never overwrite the current state root. A snapshot from another schema is refused with an error naming the package version that wrote it, so restore it with that version. Rollback accepts losing every change made after that snapshot, including host changes and later HQ receipts. Reconcile native ownership and obtain fresh authority before enabling work.
|
|
22
|
+
|
|
19
23
|
## Off-machine durability
|
|
20
24
|
|
|
21
25
|
The development helper examples/shared-storage.ts demonstrates a host-owned application table, maintenance, capture and offline restore using public exports. Capture already returns verified metadata, so the helper avoids an immediate extra full-database inspection. Its application transaction commits independently of capture. Inspect the restored values before starting a recovered runtime with explicitly chosen roots.
|
|
22
26
|
|
|
23
|
-
|
|
27
|
+
For off-machine copies, `packHqSnapshot` encrypts a snapshot into one AES-256-GCM archive with a 32-byte key the host supplies, and `unpackHqSnapshot` verifies the archive before writing a fresh snapshot directory to restore from. The archive carries action.key with the database. A lost key makes every archive packed with it unrecoverable, so keep the key outside the backups it protects. The host owns the key, scheduling, uploads, retention and the last successful backup status. Losing the disk can lose all changes after the last successful off-machine backup. Producing a local snapshot alone does not protect against disk failure.
|
package/errors/README.md
CHANGED
|
@@ -56,9 +56,9 @@ These contracts use the named codes below. An Exception's `data.kind` classifies
|
|
|
56
56
|
|
|
57
57
|
State safety rejects non-private ownership, symlinks and non-regular files. ACTION_KEY_UNAVAILABLE also rejects a valid-length key whose fingerprint differs from the database stamp, before opening a writer. Runtime ownership is never reclaimed automatically. Transport failure includes malformed, oversized or incomplete frames and bounded-request/lifecycle failures. Native history and subscription failures remain unavailable, never successful empty results. Claude control rejects missing or non-idle initialization, invalid native session identities and malformed lifecycle evidence. Failed delivery remains uncertain when no exact native rejection or acknowledgement establishes its outcome.
|
|
58
58
|
|
|
59
|
-
A nonempty SQLite schema requires exactly one matching `hq_schema` stamp. Missing, malformed or mismatched stamps use STORAGE_INVALID with the safe state-conflict classification before HQ changes the database. Read-only validation preserves uncheckpointed WAL state on rejection. Initialization failures roll back the complete HQ schema. Storage maintenance uses ACTION_CONFLICT for concurrent maintenance, calls from admitted work, active native execution or an unresolved plan write. Host callback errors propagate unchanged after admission is released.
|
|
59
|
+
A nonempty SQLite schema requires exactly one matching `hq_schema` stamp. Missing, malformed or mismatched stamps use STORAGE_INVALID with the safe state-conflict classification before HQ changes the database. Its message names the package version that wrote storage from another schema, or another jg-agent-hq version when the stamp records none; the CLI presents only that writer message. Read-only validation preserves uncheckpointed WAL state on rejection. Initialization failures roll back the complete HQ schema. Storage maintenance uses ACTION_CONFLICT for concurrent maintenance, calls from admitted work, active native execution or an unresolved plan write. Host callback errors propagate unchanged after admission is released.
|
|
60
60
|
|
|
61
|
-
Snapshot capture retains prepared document writes but uses ACTION_CONFLICT for
|
|
61
|
+
Snapshot capture retains prepared document writes and continues through native work, but uses ACTION_CONFLICT for concurrent maintenance, an expired metadata lock wait and document contention. Inspection and restore use STORAGE_INVALID for a snapshot from another schema. SNAPSHOT_INVALID classifies invalid selections or incomplete, corrupt, unsafe or occupied snapshot, archive or recovery paths as invalid-request, including an archive key that is not 32 bytes and an archive that fails authentication or lists entries its manifest does not. SNAPSHOT_FAILED classifies operational backup, copy, worker, lock-release and cleanup failures as operation-failed. Its stable message may carry a private extracted diagnostic suffix. These contracts belong only to trusted Node snapshot exports.
|
|
62
62
|
|
|
63
63
|
A native or worker startup failure whose cleanup could not be confirmed carries internal `cleanupUnconfirmed: true`. The runtime retains its owner record in that case rather than allowing a new host to assume its resources have stopped.
|
|
64
64
|
|
|
@@ -74,7 +74,7 @@ Input-file admission reuses REQUEST_INVALID for invalid media, malformed UTF-8 a
|
|
|
74
74
|
|
|
75
75
|
Native form replies reuse REQUEST_INVALID for content outside the exact requested schema or response kind. Stale, expired, cross-thread or already answered request identities use ACTION_CONFLICT. Native writes without matching consumption evidence remain submitted or uncertain; expiry never proves a response was rejected. Unsupported native request variants are denied on their own native channel without granting permission.
|
|
76
76
|
|
|
77
|
-
Plan validation rejects unsupported framing, duplicate or misplaced milestone IDs, invalid frontmatter boundaries, non-regular artifacts and oversized inputs. Plan operation failures retain safe operation diagnostics inside the trusted host. Document-lock contention uses ACTION_CONFLICT with reason document-locked. Document lock failures use PLAN_FAILED with the observed phase and a truthful not-applied or uncertain outcome. An applied write whose lock release fails keeps its prepared journal payload. A failed ledger acknowledgement is reconciled from durable state; an unavailable observation uses STORE_FAILED and keeps admission closed. Stale revisions, presentation hashes, replay payload conflicts, revoked authority and unresolved writes use the existing action-state conflict contract.
|
|
77
|
+
Plan validation rejects unsupported framing, duplicate or misplaced milestone IDs, finalization of a milestone without an ID, invalid frontmatter boundaries, non-regular artifacts and oversized inputs. Plan approval, finalization, sequence approval and authorization also reject a protocol 0.2 plan that fails the jg-plans check; `jg-plans check --directory <plan>` reports why. Reading such a plan is unaffected. Plan operation failures retain safe operation diagnostics inside the trusted host. Document-lock contention uses ACTION_CONFLICT with reason document-locked. Document lock failures use PLAN_FAILED with the observed phase and a truthful not-applied or uncertain outcome. An applied write whose lock release fails keeps its prepared journal payload. A failed ledger acknowledgement is reconciled from durable state; an unavailable observation uses STORE_FAILED and keeps admission closed. Stale revisions, presentation hashes, replay payload conflicts, revoked authority and unresolved writes use the existing action-state conflict contract. Unverified done evidence, live scope changes, stale runtime authority and unproven quiescence also use the action-state conflict contract. Failed native cleanup retains the checkpoint and closes the editing gate. Neither validation nor write recovery can grant native permissions. Whole-plan selection conflicts with a real breakdown, duplicate live implementation ownership, completed contracts and revoked implementation follow-up authority use the same action-state conflict contract. A valid sequence approval request for a plan without a sequence also conflicts.
|
|
78
78
|
|
|
79
79
|
Agent-tool admission reuses COLLABORATION_FORBIDDEN for an unknown/revoked bridge credential, stale native/runtime/turn binding or insufficient task membership. COLLABORATION_CONFLICT covers changed spawn identities and exhausted spawn capacity. Private credential parsing discards secret-bearing diagnostic causes. Credential setup/cleanup failures use TRANSPORT_FAILED. Native tool results and MCP failures contain only the existing safe public error classification and code. An admitted native spawn retains its durable failed/uncertain receipt; a tool timeout or lost client connection never proves native creation failed.
|
|
80
80
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "jg-agent-hq",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "4.0.0",
|
|
4
4
|
"description": "Native coding-agent session control, agent streams and durable collaboration for Node.js apps.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
"jg-crypto": "0.3.0",
|
|
52
52
|
"jg-exception": "^1.7.0",
|
|
53
53
|
"jg-fs": "1.7.0",
|
|
54
|
-
"jg-plans": "0.
|
|
54
|
+
"jg-plans": "0.3.0",
|
|
55
55
|
"jg-utilities": "1.7.0",
|
|
56
56
|
"zod": "^4.3.6"
|
|
57
57
|
},
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import type { IPlanCompletion, IPlanDraftMilestone, IPlanProposal, IPlanCorrespondence, IPlanCorrespondenceRecord, IPlanOperatorAction } from '../contracts/index.js';
|
|
2
|
-
import type { IPlanArtifacts } from './types.js';
|
|
3
|
-
/**
|
|
4
|
-
* Builds one memoized verification lookup, preserving original checks rather than asserting new ones.
|
|
5
|
-
* @returns A predicate for an exact contract or its operator-confirmed equivalent correspondence.
|
|
6
|
-
*/
|
|
7
|
-
export declare const createCompletionLookup: (completions: IPlanCompletion[], records: IPlanCorrespondenceRecord[]) => (entry: {
|
|
8
|
-
id: string | null;
|
|
9
|
-
contractDigest: string | null;
|
|
10
|
-
}) => boolean;
|
|
11
|
-
/**
|
|
12
|
-
* Creates stable prospective identities and exact matches without using ordinal as identity.
|
|
13
|
-
* @returns A single saved proposal containing every unmatched checkpoint entry.
|
|
14
|
-
* @throws
|
|
15
|
-
* - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
|
|
16
|
-
*/
|
|
17
|
-
export declare const proposeReconciliation: (artifacts: IPlanArtifacts, action: IPlanOperatorAction) => IPlanProposal;
|
|
18
|
-
/**
|
|
19
|
-
* Validates one complete explicit mapping, including omitted and split/merged correspondence.
|
|
20
|
-
* @returns Assigned drafts and retained evidence relationships, without granting approval.
|
|
21
|
-
* @throws
|
|
22
|
-
* - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
|
|
23
|
-
*/
|
|
24
|
-
export declare const confirmReconciliation: (artifacts: IPlanArtifacts, proposal: IPlanProposal, action: IPlanOperatorAction, decisions: IPlanCorrespondence[]) => {
|
|
25
|
-
drafts: IPlanDraftMilestone[];
|
|
26
|
-
records: IPlanCorrespondenceRecord[];
|
|
27
|
-
};
|
|
28
|
-
/**
|
|
29
|
-
* Prepares selected identity/progress through the document engine; requirement prose is unchanged.
|
|
30
|
-
* @returns The canonical sequence for explicit presentation and approval.
|
|
31
|
-
* @throws
|
|
32
|
-
* - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
|
|
33
|
-
*/
|
|
34
|
-
export declare const renderReconciledSequence: (content: string, drafts: IPlanDraftMilestone[]) => string;
|
|
@@ -1,246 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { Exception } from 'jg-exception';
|
|
3
|
-
import { getMilestoneContractDigest, hashPlanContent, isSamePlanRevision, parsePlanMilestones, } from './utilities.js';
|
|
4
|
-
import { prepareReconciliationIds, prepareSequenceMarkers } from './documents.js';
|
|
5
|
-
const conflict = () => {
|
|
6
|
-
throw new Exception('The HQ action conflicts with its recorded state', {
|
|
7
|
-
code: 'JG_AGENT_HQ_ACTION_CONFLICT',
|
|
8
|
-
data: {
|
|
9
|
-
kind: 'state-conflict',
|
|
10
|
-
},
|
|
11
|
-
});
|
|
12
|
-
};
|
|
13
|
-
const contractKey = (entry) => JSON.stringify([entry.id, entry.contractDigest]);
|
|
14
|
-
const matchKey = (entry) => JSON.stringify([entry.title, entry.sharedDigest, entry.contract]);
|
|
15
|
-
/**
|
|
16
|
-
* Builds one memoized verification lookup, preserving original checks rather than asserting new ones.
|
|
17
|
-
* @returns A predicate for an exact contract or its operator-confirmed equivalent correspondence.
|
|
18
|
-
*/
|
|
19
|
-
export const createCompletionLookup = (completions, records) => {
|
|
20
|
-
const invalidated = new Set(records.flatMap((record) => record.invalidatedReceiptIds));
|
|
21
|
-
const reopened = new Map();
|
|
22
|
-
records.forEach((record, index) => {
|
|
23
|
-
if (record.relation === 'reopened')
|
|
24
|
-
for (const target of record.targets)
|
|
25
|
-
reopened.set(target.id, { id: record.action.id, index });
|
|
26
|
-
});
|
|
27
|
-
const direct = new Set(completions
|
|
28
|
-
.filter((receipt) => !invalidated.has(receipt.id) &&
|
|
29
|
-
receipt.reopenActionId === (reopened.get(receipt.milestoneId ?? '')?.id ?? null))
|
|
30
|
-
.map((receipt) => JSON.stringify([receipt.milestoneId, receipt.contractDigest])));
|
|
31
|
-
const links = new Map();
|
|
32
|
-
for (const [recordIndex, record] of records.entries()) {
|
|
33
|
-
if (record.relation !== 'equivalent')
|
|
34
|
-
continue;
|
|
35
|
-
const sources = record.sources.filter((source) => source.status === 'done').map(contractKey);
|
|
36
|
-
if (sources.length !== record.sources.length)
|
|
37
|
-
continue;
|
|
38
|
-
for (const target of record.targets) {
|
|
39
|
-
if (target.status !== 'done' || recordIndex <= (reopened.get(target.id)?.index ?? -1))
|
|
40
|
-
continue;
|
|
41
|
-
const key = contractKey(target);
|
|
42
|
-
const groups = links.get(key) ?? [];
|
|
43
|
-
groups.push(sources);
|
|
44
|
-
links.set(key, groups);
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
const memo = new Map();
|
|
48
|
-
const visiting = new Set();
|
|
49
|
-
const verified = (key) => {
|
|
50
|
-
if (direct.has(key))
|
|
51
|
-
return true;
|
|
52
|
-
if (memo.has(key))
|
|
53
|
-
return memo.get(key);
|
|
54
|
-
if (visiting.has(key))
|
|
55
|
-
return false;
|
|
56
|
-
visiting.add(key);
|
|
57
|
-
const result = (links.get(key) ?? []).some((sources) => sources.every(verified));
|
|
58
|
-
visiting.delete(key);
|
|
59
|
-
memo.set(key, result);
|
|
60
|
-
return result;
|
|
61
|
-
};
|
|
62
|
-
return (entry) => !!entry.id &&
|
|
63
|
-
!!entry.contractDigest &&
|
|
64
|
-
verified(JSON.stringify([entry.id, entry.contractDigest]));
|
|
65
|
-
};
|
|
66
|
-
/**
|
|
67
|
-
* Creates stable prospective identities and exact matches without using ordinal as identity.
|
|
68
|
-
* @returns A single saved proposal containing every unmatched checkpoint entry.
|
|
69
|
-
* @throws
|
|
70
|
-
* - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
|
|
71
|
-
*/
|
|
72
|
-
export const proposeReconciliation = (artifacts, action) => {
|
|
73
|
-
const checkpoint = artifacts.coordination.revision?.checkpoint;
|
|
74
|
-
if (!checkpoint)
|
|
75
|
-
conflict();
|
|
76
|
-
const sources = checkpoint.entries;
|
|
77
|
-
const oldByContract = new Map();
|
|
78
|
-
const newCounts = new Map();
|
|
79
|
-
for (const entry of sources) {
|
|
80
|
-
const key = matchKey(entry);
|
|
81
|
-
const list = oldByContract.get(key) ?? [];
|
|
82
|
-
list.push(entry);
|
|
83
|
-
oldByContract.set(key, list);
|
|
84
|
-
}
|
|
85
|
-
for (const entry of artifacts.parsed) {
|
|
86
|
-
const key = matchKey(entry);
|
|
87
|
-
newCounts.set(key, (newCounts.get(key) ?? 0) + 1);
|
|
88
|
-
}
|
|
89
|
-
const verified = createCompletionLookup(artifacts.coordination.completions, artifacts.coordination.correspondences);
|
|
90
|
-
const matched = new Set();
|
|
91
|
-
const exactMatches = artifacts.parsed.map((entry) => {
|
|
92
|
-
const key = matchKey(entry);
|
|
93
|
-
const candidates = oldByContract.get(key) ?? [];
|
|
94
|
-
const candidate = candidates.length === 1 && newCounts.get(key) === 1 ? candidates[0] : null;
|
|
95
|
-
const exact = candidate && (candidate.status !== 'done' || verified(candidate)) ? candidate : null;
|
|
96
|
-
if (entry.id && exact && entry.id !== exact.id)
|
|
97
|
-
conflict();
|
|
98
|
-
return exact;
|
|
99
|
-
});
|
|
100
|
-
const retained = new Map(artifacts.parsed.flatMap((entry, index) => {
|
|
101
|
-
const exact = exactMatches[index];
|
|
102
|
-
return exact ? [[entry.ordinal, exact.id]] : [];
|
|
103
|
-
}));
|
|
104
|
-
const assigned = artifacts.milestones === null
|
|
105
|
-
? []
|
|
106
|
-
: parsePlanMilestones(prepareReconciliationIds(artifacts.milestones, retained));
|
|
107
|
-
const drafts = artifacts.parsed.map((entry, index) => {
|
|
108
|
-
const exact = exactMatches[index];
|
|
109
|
-
if (exact)
|
|
110
|
-
matched.add(exact.id);
|
|
111
|
-
const id = exact?.id ?? assigned[index].id;
|
|
112
|
-
return {
|
|
113
|
-
id,
|
|
114
|
-
ordinal: entry.ordinal,
|
|
115
|
-
title: entry.title,
|
|
116
|
-
status: exact?.status ?? entry.status,
|
|
117
|
-
contract: entry.contract,
|
|
118
|
-
sharedDigest: entry.sharedDigest,
|
|
119
|
-
contractDigest: getMilestoneContractDigest({ ...entry, id }),
|
|
120
|
-
matchedSourceId: exact?.id ?? null,
|
|
121
|
-
};
|
|
122
|
-
});
|
|
123
|
-
return {
|
|
124
|
-
id: action.id,
|
|
125
|
-
revision: artifacts.revision,
|
|
126
|
-
inspectionHash: artifacts.hashes.milestones,
|
|
127
|
-
drafts,
|
|
128
|
-
unmatchedSourceIds: sources
|
|
129
|
-
.filter((source) => !matched.has(source.id))
|
|
130
|
-
.map((source) => source.id),
|
|
131
|
-
confirmation: null,
|
|
132
|
-
};
|
|
133
|
-
};
|
|
134
|
-
/**
|
|
135
|
-
* Validates one complete explicit mapping, including omitted and split/merged correspondence.
|
|
136
|
-
* @returns Assigned drafts and retained evidence relationships, without granting approval.
|
|
137
|
-
* @throws
|
|
138
|
-
* - JG_AGENT_HQ_ACTION_CONFLICT: The HQ action conflicts with its recorded state
|
|
139
|
-
*/
|
|
140
|
-
export const confirmReconciliation = (artifacts, proposal, action, decisions) => {
|
|
141
|
-
const checkpoint = artifacts.coordination.revision?.checkpoint;
|
|
142
|
-
if (!checkpoint ||
|
|
143
|
-
proposal.inspectionHash !== artifacts.hashes.milestones ||
|
|
144
|
-
!isSamePlanRevision(proposal.revision, artifacts.revision))
|
|
145
|
-
conflict();
|
|
146
|
-
const sources = new Map(checkpoint.entries.map((entry) => [entry.id, entry]));
|
|
147
|
-
const drafts = structuredClone(proposal.drafts);
|
|
148
|
-
const targets = new Map(drafts.map((draft) => [draft.id, draft]));
|
|
149
|
-
const unmatched = new Set(proposal.unmatchedSourceIds);
|
|
150
|
-
const seenSources = new Set();
|
|
151
|
-
const seenTargets = new Set();
|
|
152
|
-
const verified = createCompletionLookup(artifacts.coordination.completions, artifacts.coordination.correspondences);
|
|
153
|
-
const records = [];
|
|
154
|
-
for (const decision of decisions) {
|
|
155
|
-
if (decision.sourceIds.some((id) => !unmatched.has(id) || seenSources.has(id)) ||
|
|
156
|
-
decision.targetIds.some((id) => !targets.has(id) || targets.get(id).matchedSourceId || seenTargets.has(id)))
|
|
157
|
-
conflict();
|
|
158
|
-
const previous = decision.sourceIds.map((id) => sources.get(id));
|
|
159
|
-
const next = decision.targetIds.map((id) => targets.get(id));
|
|
160
|
-
if (decision.relation === 'omitted'
|
|
161
|
-
? next.length !== 0 || decision.retainedPairs.length !== 0
|
|
162
|
-
: next.length === 0)
|
|
163
|
-
conflict();
|
|
164
|
-
if (decision.relation === 'requirements-changed' && decision.retainedPairs.length)
|
|
165
|
-
conflict();
|
|
166
|
-
if (decision.relation === 'equivalent' &&
|
|
167
|
-
previous.some((source) => source.status === 'done' && !verified(source)))
|
|
168
|
-
conflict();
|
|
169
|
-
if (previous.length === 1 &&
|
|
170
|
-
next.length === 1 &&
|
|
171
|
-
decision.relation === 'equivalent' &&
|
|
172
|
-
(decision.retainedPairs.length !== 1 ||
|
|
173
|
-
decision.retainedPairs[0].sourceId !== previous[0].id ||
|
|
174
|
-
decision.retainedPairs[0].targetId !== next[0].id))
|
|
175
|
-
conflict();
|
|
176
|
-
const retainedSources = new Set();
|
|
177
|
-
const retainedTargets = new Set();
|
|
178
|
-
for (const pair of decision.retainedPairs) {
|
|
179
|
-
if (!decision.sourceIds.includes(pair.sourceId) ||
|
|
180
|
-
!decision.targetIds.includes(pair.targetId) ||
|
|
181
|
-
retainedSources.has(pair.sourceId) ||
|
|
182
|
-
retainedTargets.has(pair.targetId))
|
|
183
|
-
conflict();
|
|
184
|
-
retainedSources.add(pair.sourceId);
|
|
185
|
-
retainedTargets.add(pair.targetId);
|
|
186
|
-
}
|
|
187
|
-
const allDone = previous.every((source) => source.status === 'done');
|
|
188
|
-
const allPending = previous.every((source) => source.status === 'pending');
|
|
189
|
-
for (const target of next) {
|
|
190
|
-
const retained = decision.retainedPairs.find((pair) => pair.targetId === target.id);
|
|
191
|
-
target.id = retained?.sourceId ?? target.id;
|
|
192
|
-
target.status =
|
|
193
|
-
decision.relation === 'equivalent'
|
|
194
|
-
? allDone
|
|
195
|
-
? 'done'
|
|
196
|
-
: allPending
|
|
197
|
-
? 'pending'
|
|
198
|
-
: 'in progress'
|
|
199
|
-
: 'pending';
|
|
200
|
-
target.contractDigest = getMilestoneContractDigest(target);
|
|
201
|
-
}
|
|
202
|
-
const invalidatedReceiptIds = decision.relation === 'reopened'
|
|
203
|
-
? artifacts.coordination.completions
|
|
204
|
-
.filter((receipt) => receipt.milestoneId !== null && decision.sourceIds.includes(receipt.milestoneId))
|
|
205
|
-
.map((receipt) => receipt.id)
|
|
206
|
-
: [];
|
|
207
|
-
records.push({
|
|
208
|
-
id: randomUUID(),
|
|
209
|
-
action,
|
|
210
|
-
revision: artifacts.revision,
|
|
211
|
-
sources: previous,
|
|
212
|
-
targets: next.map((target) => ({
|
|
213
|
-
id: target.id,
|
|
214
|
-
contractDigest: target.contractDigest,
|
|
215
|
-
status: target.status,
|
|
216
|
-
})),
|
|
217
|
-
relation: decision.relation,
|
|
218
|
-
invalidatedReceiptIds,
|
|
219
|
-
recordedAt: Date.now(),
|
|
220
|
-
});
|
|
221
|
-
for (const id of decision.sourceIds)
|
|
222
|
-
seenSources.add(id);
|
|
223
|
-
for (const id of decision.targetIds)
|
|
224
|
-
seenTargets.add(id);
|
|
225
|
-
}
|
|
226
|
-
if (seenSources.size !== unmatched.size ||
|
|
227
|
-
new Set(drafts.map((draft) => draft.id)).size !== drafts.length)
|
|
228
|
-
conflict();
|
|
229
|
-
return { drafts, records };
|
|
230
|
-
};
|
|
231
|
-
/**
|
|
232
|
-
* Prepares selected identity/progress through the document engine; requirement prose is unchanged.
|
|
233
|
-
* @returns The canonical sequence for explicit presentation and approval.
|
|
234
|
-
* @throws
|
|
235
|
-
* - JG_AGENT_HQ_PLAN_INVALID: The HQ plan is invalid
|
|
236
|
-
*/
|
|
237
|
-
export const renderReconciledSequence = (content, drafts) => {
|
|
238
|
-
const parsed = parsePlanMilestones(content);
|
|
239
|
-
if (parsed.length !== drafts.length ||
|
|
240
|
-
parsed.some((entry, index) => entry.ordinal !== drafts[index].ordinal))
|
|
241
|
-
throw new Exception('The HQ plan is invalid', {
|
|
242
|
-
code: 'JG_AGENT_HQ_PLAN_INVALID',
|
|
243
|
-
data: { kind: 'invalid-request' },
|
|
244
|
-
});
|
|
245
|
-
return prepareSequenceMarkers(content, drafts);
|
|
246
|
-
};
|