@warpgogol/forge 9.7.1 → 10.1.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/AGENTS.md +50 -27
- package/CHANGELOG.md +39 -0
- package/bin/cli.js +0 -0
- package/dist/os/codebase/handlers/codebase-measure-symbols.d.ts.map +1 -1
- package/dist/os/codebase/handlers/codebase-measure-symbols.js +35 -4
- package/dist/os/codebase/handlers/codebase-measure-symbols.js.map +1 -1
- package/dist/os/core/core.module.d.ts.map +1 -1
- package/dist/os/core/core.module.js +1 -69
- package/dist/os/core/core.module.js.map +1 -1
- package/dist/os/core/handlers/assets-helpers.d.ts.map +1 -1
- package/dist/os/core/handlers/assets-helpers.js +2 -3
- package/dist/os/core/handlers/assets-helpers.js.map +1 -1
- package/dist/os/core/handlers/determinism-check.d.ts.map +1 -1
- package/dist/os/core/handlers/determinism-check.js +2 -3
- package/dist/os/core/handlers/determinism-check.js.map +1 -1
- package/dist/os/core/handlers/release-prepare.d.ts.map +1 -1
- package/dist/os/core/handlers/release-prepare.js +2 -4
- package/dist/os/core/handlers/release-prepare.js.map +1 -1
- package/dist/os/flow/handlers/flow-peers.js +1 -1
- package/dist/os/flow/handlers/flow-peers.js.map +1 -1
- package/dist/os/{mission → flow}/open-missions.d.ts +1 -2
- package/dist/os/flow/open-missions.d.ts.map +1 -0
- package/dist/os/flow/open-missions.js +37 -0
- package/dist/os/flow/open-missions.js.map +1 -0
- package/dist/os/flow/preflight.js +1 -1
- package/dist/os/flow/preflight.js.map +1 -1
- package/dist/os/rfc/probe-batch.d.ts.map +1 -1
- package/dist/os/rfc/probe-batch.js +13 -6
- package/dist/os/rfc/probe-batch.js.map +1 -1
- package/dist/src/command-modules.d.ts.map +1 -1
- package/dist/src/command-modules.js +0 -2
- package/dist/src/command-modules.js.map +1 -1
- package/dist/src/contract/core-nodes.d.ts +8 -0
- package/dist/src/contract/core-nodes.d.ts.map +1 -0
- package/dist/src/contract/core-nodes.js +101 -0
- package/dist/src/contract/core-nodes.js.map +1 -0
- package/dist/src/contract/evaluator.d.ts +48 -0
- package/dist/src/contract/evaluator.d.ts.map +1 -0
- package/dist/src/contract/evaluator.js +158 -0
- package/dist/src/contract/evaluator.js.map +1 -0
- package/dist/src/contract/evidence-store.d.ts +17 -0
- package/dist/src/contract/evidence-store.d.ts.map +1 -0
- package/dist/src/contract/evidence-store.js +113 -0
- package/dist/src/contract/evidence-store.js.map +1 -0
- package/dist/src/contract/executors/zero-deps.d.ts +3 -0
- package/dist/src/contract/executors/zero-deps.d.ts.map +1 -0
- package/dist/src/contract/executors/zero-deps.js +88 -0
- package/dist/src/contract/executors/zero-deps.js.map +1 -0
- package/dist/src/contract/fingerprint.d.ts +34 -0
- package/dist/src/contract/fingerprint.d.ts.map +1 -0
- package/dist/src/contract/fingerprint.js +153 -0
- package/dist/src/contract/fingerprint.js.map +1 -0
- package/dist/src/contract/graph.d.ts +23 -0
- package/dist/src/contract/graph.d.ts.map +1 -0
- package/dist/src/contract/graph.js +158 -0
- package/dist/src/contract/graph.js.map +1 -0
- package/dist/src/contract/migration-map.d.ts +51 -0
- package/dist/src/contract/migration-map.d.ts.map +1 -0
- package/dist/src/contract/migration-map.js +130 -0
- package/dist/src/contract/migration-map.js.map +1 -0
- package/dist/src/contract/types.d.ts +108 -0
- package/dist/src/contract/types.d.ts.map +1 -0
- package/dist/src/contract/types.js +23 -0
- package/dist/src/contract/types.js.map +1 -0
- package/dist/src/index.d.ts +0 -2
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +0 -2
- package/dist/src/index.js.map +1 -1
- package/dist/src/integration/drain.d.ts +31 -0
- package/dist/src/integration/drain.d.ts.map +1 -0
- package/dist/src/integration/drain.js +195 -0
- package/dist/src/integration/drain.js.map +1 -0
- package/dist/src/integration/enqueue.d.ts +30 -0
- package/dist/src/integration/enqueue.d.ts.map +1 -0
- package/dist/src/integration/enqueue.js +64 -0
- package/dist/src/integration/enqueue.js.map +1 -0
- package/dist/src/integration/gitops.d.ts +33 -0
- package/dist/src/integration/gitops.d.ts.map +1 -0
- package/dist/src/integration/gitops.js +128 -0
- package/dist/src/integration/gitops.js.map +1 -0
- package/dist/src/integration/lease.d.ts +16 -0
- package/dist/src/integration/lease.d.ts.map +1 -0
- package/dist/src/integration/lease.js +140 -0
- package/dist/src/integration/lease.js.map +1 -0
- package/dist/src/integration/materialize.d.ts +7 -0
- package/dist/src/integration/materialize.d.ts.map +1 -0
- package/dist/src/integration/materialize.js +34 -0
- package/dist/src/integration/materialize.js.map +1 -0
- package/dist/src/integration/store.d.ts +21 -0
- package/dist/src/integration/store.d.ts.map +1 -0
- package/dist/src/integration/store.js +131 -0
- package/dist/src/integration/store.js.map +1 -0
- package/dist/src/integration/types.d.ts +71 -0
- package/dist/src/integration/types.d.ts.map +1 -0
- package/dist/src/integration/types.js +18 -0
- package/dist/src/integration/types.js.map +1 -0
- package/dist/src/onboarding/doctor.d.ts +0 -5
- package/dist/src/onboarding/doctor.d.ts.map +1 -1
- package/dist/src/onboarding/doctor.js +6 -79
- package/dist/src/onboarding/doctor.js.map +1 -1
- package/dist/src/onboarding/npm-token-check.d.ts +1 -1
- package/dist/src/onboarding/npm-token-check.d.ts.map +1 -1
- package/dist/src/onboarding/npm-token-check.js +2 -2
- package/dist/src/onboarding/npm-token-check.js.map +1 -1
- package/dist/src/sdk/context.d.ts +13 -0
- package/dist/src/sdk/context.d.ts.map +1 -0
- package/dist/src/sdk/context.js +128 -0
- package/dist/src/sdk/context.js.map +1 -0
- package/dist/src/sdk/loader.d.ts +25 -0
- package/dist/src/sdk/loader.d.ts.map +1 -0
- package/dist/src/sdk/loader.js +155 -0
- package/dist/src/sdk/loader.js.map +1 -0
- package/dist/src/sdk/scan.d.ts +16 -0
- package/dist/src/sdk/scan.d.ts.map +1 -0
- package/dist/src/sdk/scan.js +126 -0
- package/dist/src/sdk/scan.js.map +1 -0
- package/dist/src/sdk/skills-gen.d.ts +27 -0
- package/dist/src/sdk/skills-gen.d.ts.map +1 -0
- package/dist/src/sdk/skills-gen.js +87 -0
- package/dist/src/sdk/skills-gen.js.map +1 -0
- package/dist/src/sdk/types.d.ts +124 -0
- package/dist/src/sdk/types.d.ts.map +1 -0
- package/dist/src/sdk/types.js +34 -0
- package/dist/src/sdk/types.js.map +1 -0
- package/dist/src/utils/hash.d.ts +1 -0
- package/dist/src/utils/hash.d.ts.map +1 -1
- package/dist/src/utils/hash.js +4 -0
- package/dist/src/utils/hash.js.map +1 -1
- package/dist/{os/mission → src/utils}/lockfile.d.ts +1 -18
- package/dist/src/utils/lockfile.d.ts.map +1 -0
- package/dist/src/utils/lockfile.js +70 -0
- package/dist/src/utils/lockfile.js.map +1 -0
- package/os/codebase/handlers/codebase-measure-symbols.ts +32 -4
- package/os/core/core.module.ts +3 -76
- package/os/core/handlers/assets-helpers.ts +2 -4
- package/os/core/handlers/determinism-check.ts +2 -3
- package/os/core/handlers/lifecycle-handlers.test.ts +529 -0
- package/os/core/handlers/release-prepare.ts +2 -4
- package/os/correctness/gate/trust-boundary-cx18.test.ts +1 -1
- package/os/flow/handlers/flow-peers.ts +1 -1
- package/os/flow/open-missions.ts +45 -0
- package/os/flow/preflight.ts +1 -1
- package/os/flow/tests/release-lines.test.ts +136 -0
- package/os/flow/tests/state-roots.test.ts +1 -48
- package/os/rfc/handlers/validate-corpus.test.ts +149 -0
- package/os/rfc/probe-batch.test.ts +253 -0
- package/os/rfc/probe-batch.ts +13 -6
- package/os/rfc/verifier/rfc-1391/ac10-operating-model-policy.acceptance.test.ts +63 -0
- package/package.json +177 -506
- package/src/command-modules.ts +0 -2
- package/src/contract/core-nodes.ts +111 -0
- package/src/contract/evaluator.ts +207 -0
- package/src/contract/evidence-store.ts +119 -0
- package/src/contract/executors/zero-deps.ts +92 -0
- package/src/contract/fingerprint.ts +176 -0
- package/src/contract/graph.ts +181 -0
- package/src/contract/migration-map.ts +174 -0
- package/src/contract/types.ts +125 -0
- package/src/index.ts +0 -2
- package/src/integration/drain.ts +271 -0
- package/src/integration/enqueue.ts +92 -0
- package/src/integration/gitops.ts +174 -0
- package/src/integration/lease.ts +144 -0
- package/src/integration/materialize.ts +40 -0
- package/src/integration/store.ts +153 -0
- package/src/integration/types.ts +79 -0
- package/src/onboarding/doctor.ts +9 -96
- package/src/onboarding/npm-token-check.ts +3 -3
- package/src/sdk/context.ts +135 -0
- package/src/sdk/loader.ts +170 -0
- package/src/sdk/scan.ts +132 -0
- package/src/sdk/skills-gen.ts +104 -0
- package/src/sdk/types.ts +135 -0
- package/src/tests/pkg-health-self-scan.test.ts +29 -0
- package/src/tests/rfc-evidence-sync.test.ts +369 -0
- package/src/tests/skill-agents-sync.test.ts +192 -0
- package/src/utils/hash.ts +5 -0
- package/src/utils/lockfile.ts +78 -0
- package/dist/os/core/handlers/forge-autonomy-validate.d.ts +0 -25
- package/dist/os/core/handlers/forge-autonomy-validate.d.ts.map +0 -1
- package/dist/os/core/handlers/forge-autonomy-validate.js +0 -208
- package/dist/os/core/handlers/forge-autonomy-validate.js.map +0 -1
- package/dist/os/mission/handlers/archive.d.ts +0 -4
- package/dist/os/mission/handlers/archive.d.ts.map +0 -1
- package/dist/os/mission/handlers/archive.js +0 -583
- package/dist/os/mission/handlers/archive.js.map +0 -1
- package/dist/os/mission/importer-block.d.ts +0 -19
- package/dist/os/mission/importer-block.d.ts.map +0 -1
- package/dist/os/mission/importer-block.js +0 -124
- package/dist/os/mission/importer-block.js.map +0 -1
- package/dist/os/mission/index.d.ts +0 -2
- package/dist/os/mission/index.d.ts.map +0 -1
- package/dist/os/mission/index.js +0 -15
- package/dist/os/mission/index.js.map +0 -1
- package/dist/os/mission/lockfile.d.ts.map +0 -1
- package/dist/os/mission/lockfile.js +0 -138
- package/dist/os/mission/lockfile.js.map +0 -1
- package/dist/os/mission/mission.module.d.ts +0 -3
- package/dist/os/mission/mission.module.d.ts.map +0 -1
- package/dist/os/mission/mission.module.js +0 -63
- package/dist/os/mission/mission.module.js.map +0 -1
- package/dist/os/mission/open-missions.d.ts.map +0 -1
- package/dist/os/mission/open-missions.js +0 -42
- package/dist/os/mission/open-missions.js.map +0 -1
- package/dist/os/mission/types.d.ts +0 -23
- package/dist/os/mission/types.d.ts.map +0 -1
- package/dist/os/mission/types.js +0 -19
- package/dist/os/mission/types.js.map +0 -1
- package/dist/os/werkstatt/handlers/lock.d.ts +0 -10
- package/dist/os/werkstatt/handlers/lock.d.ts.map +0 -1
- package/dist/os/werkstatt/handlers/lock.js +0 -153
- package/dist/os/werkstatt/handlers/lock.js.map +0 -1
- package/dist/os/werkstatt/handlers/schema.d.ts +0 -33
- package/dist/os/werkstatt/handlers/schema.d.ts.map +0 -1
- package/dist/os/werkstatt/handlers/schema.js +0 -42
- package/dist/os/werkstatt/handlers/schema.js.map +0 -1
- package/dist/os/werkstatt/handlers/werkstatt-lock-recover.d.ts +0 -15
- package/dist/os/werkstatt/handlers/werkstatt-lock-recover.d.ts.map +0 -1
- package/dist/os/werkstatt/handlers/werkstatt-lock-recover.js +0 -171
- package/dist/os/werkstatt/handlers/werkstatt-lock-recover.js.map +0 -1
- package/dist/os/werkstatt/handlers/werkstatt-lock-status.d.ts +0 -18
- package/dist/os/werkstatt/handlers/werkstatt-lock-status.d.ts.map +0 -1
- package/dist/os/werkstatt/handlers/werkstatt-lock-status.js +0 -51
- package/dist/os/werkstatt/handlers/werkstatt-lock-status.js.map +0 -1
- package/dist/os/werkstatt/handlers/werkstatt-operation-validate.d.ts +0 -11
- package/dist/os/werkstatt/handlers/werkstatt-operation-validate.d.ts.map +0 -1
- package/dist/os/werkstatt/handlers/werkstatt-operation-validate.js +0 -86
- package/dist/os/werkstatt/handlers/werkstatt-operation-validate.js.map +0 -1
- package/dist/os/werkstatt/handlers/workspace-deps.d.ts +0 -12
- package/dist/os/werkstatt/handlers/workspace-deps.d.ts.map +0 -1
- package/dist/os/werkstatt/handlers/workspace-deps.js +0 -42
- package/dist/os/werkstatt/handlers/workspace-deps.js.map +0 -1
- package/dist/os/werkstatt/index.d.ts +0 -7
- package/dist/os/werkstatt/index.d.ts.map +0 -1
- package/dist/os/werkstatt/index.js +0 -18
- package/dist/os/werkstatt/index.js.map +0 -1
- package/dist/os/werkstatt/werkstatt.module.d.ts +0 -3
- package/dist/os/werkstatt/werkstatt.module.d.ts.map +0 -1
- package/dist/os/werkstatt/werkstatt.module.js +0 -91
- package/dist/os/werkstatt/werkstatt.module.js.map +0 -1
- package/os/core/handlers/forge-autonomy-validate.ts +0 -276
- package/os/correctness/gate/trust-boundary-cx19.test.ts +0 -514
- package/os/mission/handlers/archive.test.ts +0 -764
- package/os/mission/handlers/archive.ts +0 -711
- package/os/mission/handlers/ship-inflight-degraded.test.ts +0 -105
- package/os/mission/importer-block.ts +0 -119
- package/os/mission/index.ts +0 -15
- package/os/mission/lockfile.ts +0 -152
- package/os/mission/mission.module.ts +0 -68
- package/os/mission/open-missions.ts +0 -50
- package/os/mission/types.ts +0 -42
- package/os/werkstatt/handlers/lock.ts +0 -168
- package/os/werkstatt/handlers/schema.ts +0 -47
- package/os/werkstatt/handlers/werkstatt-lock-recover.ts +0 -206
- package/os/werkstatt/handlers/werkstatt-lock-status.ts +0 -82
- package/os/werkstatt/handlers/werkstatt-operation-validate.ts +0 -112
- package/os/werkstatt/handlers/workspace-deps.ts +0 -56
- package/os/werkstatt/index.ts +0 -39
- package/os/werkstatt/werkstatt.module.ts +0 -95
- package/src/tests/doctor-autonomy.test.ts +0 -246
- package/src/tests/forge-autonomy-validate.test.ts +0 -159
- package/src/tests/werkstatt-lock.test.ts +0 -357
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/*
|
|
2
|
+
<MODULE_CONTRACT>
|
|
3
|
+
<purpose>
|
|
4
|
+
On-demand drain worker (Werkstatt RFC-1647) — strict FIFO, single logical writer:
|
|
5
|
+
lease, rebase-materialize the frozen unit onto the current head, evaluate the
|
|
6
|
+
candidate tree through the contract graph, integrate or refuse, loop until the
|
|
7
|
+
queue is empty, exit. Never a daemon. Idempotent recovery: lease expiry plus
|
|
8
|
+
state-machine re-entry; integration verified by commit existence before
|
|
9
|
+
re-creation — no orphan states.
|
|
10
|
+
</purpose>
|
|
11
|
+
<non-goals>
|
|
12
|
+
<item>No parallelism, no speculative pre-evaluation — strict FIFO v1.</item>
|
|
13
|
+
</non-goals>
|
|
14
|
+
<CHANGE_SUMMARY>
|
|
15
|
+
<item>RFC-1647 (WP-4): initial drain worker.</item>
|
|
16
|
+
</CHANGE_SUMMARY>
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { evaluateGraph, type EvaluationReport } from "../contract/evaluator.ts";
|
|
20
|
+
import type { ContractGraph } from "../contract/graph.ts";
|
|
21
|
+
import type { EvidenceStore } from "../contract/evidence-store.ts";
|
|
22
|
+
import type { Executor } from "../contract/evaluator.ts";
|
|
23
|
+
import type { ChangeUnit } from "../contract/types.ts";
|
|
24
|
+
|
|
25
|
+
import {
|
|
26
|
+
commitExists,
|
|
27
|
+
commitTreeEquals,
|
|
28
|
+
integrateCandidate,
|
|
29
|
+
replayChainOntoHead,
|
|
30
|
+
resolveRef,
|
|
31
|
+
type GitExec,
|
|
32
|
+
defaultGitExec,
|
|
33
|
+
} from "./gitops.ts";
|
|
34
|
+
import { acquireLease, type LeaseHandle } from "./lease.ts";
|
|
35
|
+
import type { QueueStore } from "./store.ts";
|
|
36
|
+
import { isTerminal, type IntegrationUnit, type QueueJournalEntry } from "./types.ts";
|
|
37
|
+
|
|
38
|
+
/** Bound on infra-failure requeues before terminal refusal — poison-pill protection. */
|
|
39
|
+
export const MAX_INFRA_REQUEUE_ATTEMPTS = 5;
|
|
40
|
+
|
|
41
|
+
export interface DrainOptions {
|
|
42
|
+
store: QueueStore;
|
|
43
|
+
repoDir: string;
|
|
44
|
+
governedRef: string;
|
|
45
|
+
graph: ContractGraph;
|
|
46
|
+
evidenceStore: EvidenceStore;
|
|
47
|
+
executors: Record<string, Executor>;
|
|
48
|
+
git?: GitExec;
|
|
49
|
+
/** Test hook — a drain that evaluates without an evidence store round trip. */
|
|
50
|
+
treeMaterializer?: (repoDir: string, treeDigest: string) => string;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface DrainReport {
|
|
54
|
+
status: "drained" | "drain-in-progress" | "empty";
|
|
55
|
+
processed: Array<{ unitId: string; terminal: string }>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function journal(store: QueueStore, entry: Omit<QueueJournalEntry, "schema" | "at">): void {
|
|
59
|
+
store.appendJournal({
|
|
60
|
+
schema: "forge:queue-journal/v1",
|
|
61
|
+
at: new Date().toISOString(),
|
|
62
|
+
...entry,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function transition(
|
|
67
|
+
store: QueueStore,
|
|
68
|
+
unit: IntegrationUnit,
|
|
69
|
+
state: IntegrationUnit["state"],
|
|
70
|
+
actor: string,
|
|
71
|
+
): void {
|
|
72
|
+
unit.state = state;
|
|
73
|
+
store.writeUnit(unit);
|
|
74
|
+
journal(store, {
|
|
75
|
+
unitId: unit.id,
|
|
76
|
+
transition: state.status === "evaluating" ? "evaluating" : (state.status as QueueJournalEntry["transition"]),
|
|
77
|
+
actor,
|
|
78
|
+
detail: state.status === "refused" ? { nodeId: state.reason.nodeId, summary: state.reason.summary } : undefined,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Re-entry normalization: a unit in non-terminal state after lease expiry is
|
|
84
|
+
* either already landed (verify by commit existence — idempotency by
|
|
85
|
+
* verification, not assumption) or safely reprocessable. Returns true when the
|
|
86
|
+
* unit still needs processing.
|
|
87
|
+
*/
|
|
88
|
+
function normalizeForReentry(
|
|
89
|
+
git: GitExec,
|
|
90
|
+
store: QueueStore,
|
|
91
|
+
repoDir: string,
|
|
92
|
+
unit: IntegrationUnit,
|
|
93
|
+
governedRef: string,
|
|
94
|
+
actor: string,
|
|
95
|
+
): boolean {
|
|
96
|
+
if (isTerminal(unit.state)) return false;
|
|
97
|
+
if (unit.state.status === "evaluating") {
|
|
98
|
+
// Did the in-flight integration actually land? The governed ref tip equality
|
|
99
|
+
// is the verification — tree digest preimage, never assumption.
|
|
100
|
+
try {
|
|
101
|
+
const tip = resolveRef(git, repoDir, governedRef);
|
|
102
|
+
if (commitExists(git, repoDir, tip) && commitTreeEquals(git, repoDir, tip, unit.treeDigest)) {
|
|
103
|
+
transition(store, unit, { status: "integrated", commitSha: tip, evidenceKey: "recovered-by-verification" }, actor);
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
} catch {
|
|
107
|
+
// unverifiable — fall through to requeue
|
|
108
|
+
}
|
|
109
|
+
unit.attempts += 1;
|
|
110
|
+
transition(store, unit, { status: "queued" }, actor);
|
|
111
|
+
}
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function processUnit(
|
|
116
|
+
options: DrainOptions,
|
|
117
|
+
lease: LeaseHandle,
|
|
118
|
+
unit: IntegrationUnit,
|
|
119
|
+
): Promise<void> {
|
|
120
|
+
const { store, repoDir, governedRef, graph, evidenceStore, executors } = options;
|
|
121
|
+
const git = options.git ?? defaultGitExec;
|
|
122
|
+
const actor = `drain:${lease.lease.leaseId}`;
|
|
123
|
+
|
|
124
|
+
transition(store, unit, { status: "evaluating", leaseId: lease.lease.leaseId, since: new Date().toISOString() }, actor);
|
|
125
|
+
|
|
126
|
+
// Rebase-materialize against the ACTUAL current head — the single-writer
|
|
127
|
+
// guarantee makes this stable inside the drain.
|
|
128
|
+
const headSha = resolveRef(git, repoDir, governedRef);
|
|
129
|
+
const replay = replayChainOntoHead(git, repoDir, headSha, unit.commitChain);
|
|
130
|
+
|
|
131
|
+
if (!replay.ok) {
|
|
132
|
+
// Terminal conflicted — the owning session rebases and re-enqueues a NEW unit.
|
|
133
|
+
transition(store, unit, { status: "conflicted", conflictingPaths: replay.conflictingPaths }, actor);
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// The graph evaluates the candidate tree — the exact content that would
|
|
138
|
+
// integrate, never the session's private tree.
|
|
139
|
+
const changeUnit: ChangeUnit = {
|
|
140
|
+
id: `unit-${unit.id}`,
|
|
141
|
+
treeDigest: replay.candidateTree,
|
|
142
|
+
baseRef: governedRef,
|
|
143
|
+
createdAt: new Date().toISOString(),
|
|
144
|
+
frozenRefs: { [governedRef]: headSha },
|
|
145
|
+
metadata: { integrationUnit: unit.id },
|
|
146
|
+
};
|
|
147
|
+
const treeRoot = options.treeMaterializer
|
|
148
|
+
? options.treeMaterializer(repoDir, replay.candidateTree)
|
|
149
|
+
: repoDir;
|
|
150
|
+
|
|
151
|
+
let report: EvaluationReport;
|
|
152
|
+
try {
|
|
153
|
+
report = await evaluateGraph({
|
|
154
|
+
graph,
|
|
155
|
+
store: evidenceStore,
|
|
156
|
+
changeUnit,
|
|
157
|
+
executors,
|
|
158
|
+
treeRoot,
|
|
159
|
+
});
|
|
160
|
+
} catch (err) {
|
|
161
|
+
// Evaluation infrastructure failure is NOT a verdict — requeue for a later drain.
|
|
162
|
+
// Bounded: a poison-pill unit must not hang the queue forever — after the bound,
|
|
163
|
+
// terminal refusal carries the error as evidence of an unhealthy system.
|
|
164
|
+
unit.attempts += 1;
|
|
165
|
+
if (unit.attempts > MAX_INFRA_REQUEUE_ATTEMPTS) {
|
|
166
|
+
transition(
|
|
167
|
+
store,
|
|
168
|
+
unit,
|
|
169
|
+
{
|
|
170
|
+
status: "refused",
|
|
171
|
+
reason: {
|
|
172
|
+
nodeId: "core.integration.infra",
|
|
173
|
+
summary: `evaluation infrastructure failed ${unit.attempts} times: ${err instanceof Error ? err.message : String(err)}`,
|
|
174
|
+
violations: 0,
|
|
175
|
+
},
|
|
176
|
+
evidenceKey: "",
|
|
177
|
+
},
|
|
178
|
+
actor,
|
|
179
|
+
);
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
transition(store, unit, { status: "queued" }, actor);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (!report.blockingPassed) {
|
|
187
|
+
const blocking = report.nodes.find((n) => {
|
|
188
|
+
const node = graph.nodes[n.nodeId];
|
|
189
|
+
return node?.severity === "blocking" && n.verdict.status !== "pass" && n.verdict.status !== "uncacheable-pass";
|
|
190
|
+
});
|
|
191
|
+
const violations =
|
|
192
|
+
blocking?.verdict.status === "fail" ? blocking.verdict.violations.length : 1;
|
|
193
|
+
transition(
|
|
194
|
+
store,
|
|
195
|
+
unit,
|
|
196
|
+
{
|
|
197
|
+
status: "refused",
|
|
198
|
+
reason: {
|
|
199
|
+
nodeId: blocking?.nodeId ?? "core.unknown",
|
|
200
|
+
summary:
|
|
201
|
+
blocking?.verdict.status === "error"
|
|
202
|
+
? `executor error: ${blocking.verdict.message}`
|
|
203
|
+
: `${violations} blocking violation(s)`,
|
|
204
|
+
violations,
|
|
205
|
+
},
|
|
206
|
+
evidenceKey: blocking?.evidenceKey ?? "",
|
|
207
|
+
},
|
|
208
|
+
actor,
|
|
209
|
+
);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Green evaluation — integrate the candidate into the governed ref (single write point).
|
|
214
|
+
integrateCandidate(git, repoDir, governedRef, replay.candidateCommit);
|
|
215
|
+
transition(
|
|
216
|
+
store,
|
|
217
|
+
unit,
|
|
218
|
+
{
|
|
219
|
+
status: "integrated",
|
|
220
|
+
commitSha: replay.candidateCommit,
|
|
221
|
+
evidenceKey: report.nodes.find((n) => n.evidenceKey)?.evidenceKey ?? "",
|
|
222
|
+
},
|
|
223
|
+
actor,
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Drain the queue once, strict FIFO, exiting when empty. A second concurrent
|
|
229
|
+
* drain reports drain-in-progress and exits 0 — it never double-processes.
|
|
230
|
+
*/
|
|
231
|
+
export async function drainQueue(options: DrainOptions): Promise<DrainReport> {
|
|
232
|
+
const git = options.git ?? defaultGitExec;
|
|
233
|
+
const lease = acquireLease(options.store.queueDir);
|
|
234
|
+
if (!lease) {
|
|
235
|
+
return { status: "drain-in-progress", processed: [] };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const processed: Array<{ unitId: string; terminal: string }> = [];
|
|
239
|
+
try {
|
|
240
|
+
for (;;) {
|
|
241
|
+
lease.heartbeat(); // per-unit boundary — fresh heartbeat each iteration
|
|
242
|
+
const live = options.store
|
|
243
|
+
.units()
|
|
244
|
+
.filter((u) => !isTerminal(u.state))
|
|
245
|
+
.sort((a, b) => a.enqueuedAt.localeCompare(b.enqueuedAt) || a.id.localeCompare(b.id));
|
|
246
|
+
|
|
247
|
+
if (live.length === 0) {
|
|
248
|
+
store_checkpoint(options.store);
|
|
249
|
+
return { status: processed.length > 0 ? "drained" : "empty", processed };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const unit = live[0]!;
|
|
253
|
+
if (!normalizeForReentry(git, options.store, options.repoDir, unit, options.governedRef, `drain:${lease.lease.leaseId}`)) {
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
await processUnit(options, lease, unit);
|
|
257
|
+
const final = options.store.readUnit(unit.id);
|
|
258
|
+
processed.push({ unitId: unit.id, terminal: final?.state.status ?? "unknown" });
|
|
259
|
+
}
|
|
260
|
+
} finally {
|
|
261
|
+
lease.release();
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function store_checkpoint(store: QueueStore): void {
|
|
266
|
+
try {
|
|
267
|
+
store.checkpoint();
|
|
268
|
+
} catch {
|
|
269
|
+
// checkpoint failure never blocks a drain verdict
|
|
270
|
+
}
|
|
271
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/*
|
|
2
|
+
<MODULE_CONTRACT>
|
|
3
|
+
<purpose>
|
|
4
|
+
Enqueue path + read-only observability surfaces (Werkstatt RFC-1647) — sessions
|
|
5
|
+
freeze their work into immutable units and enqueue atomically; queue state is
|
|
6
|
+
inspectable at all times through read-only surfaces consuming frozen state only.
|
|
7
|
+
The conflicted-recovery contract names itself verbatim: the owning session
|
|
8
|
+
rebases onto the current head and re-enqueues a NEW unit — units are immutable,
|
|
9
|
+
re-enqueue is a new id.
|
|
10
|
+
</purpose>
|
|
11
|
+
<non-goals>
|
|
12
|
+
<item>No drain triggers as daemons — enqueueing commands may trigger an on-demand drain.</item>
|
|
13
|
+
</non-goals>
|
|
14
|
+
<CHANGE_SUMMARY>
|
|
15
|
+
<item>RFC-1647 (WP-4): initial enqueue + observability.</item>
|
|
16
|
+
</CHANGE_SUMMARY>
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { randomBytes } from "node:crypto";
|
|
20
|
+
|
|
21
|
+
import type { QueueStore } from "./store.ts";
|
|
22
|
+
import { isTerminal, type IntegrationUnit, type QueueJournalEntry } from "./types.ts";
|
|
23
|
+
|
|
24
|
+
/** uuidv7-style time-ordered id — millisecond prefix keeps FIFO sort stable. */
|
|
25
|
+
export function newUnitId(now = Date.now()): string {
|
|
26
|
+
const timeHex = now.toString(16).padStart(12, "0");
|
|
27
|
+
const rand = randomBytes(8).toString("hex");
|
|
28
|
+
return `${timeHex}-${rand}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface EnqueueInput {
|
|
32
|
+
treeDigest: string;
|
|
33
|
+
baseRef: string;
|
|
34
|
+
sessionId: string;
|
|
35
|
+
worktreePath: string;
|
|
36
|
+
governanceIds: string[];
|
|
37
|
+
commitChain: string[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Freeze-and-enqueue: the unit either exists complete in the queue or not at all. */
|
|
41
|
+
export function enqueueUnit(store: QueueStore, input: EnqueueInput): IntegrationUnit {
|
|
42
|
+
const unit: IntegrationUnit = {
|
|
43
|
+
schema: "forge:integration-unit/v1",
|
|
44
|
+
id: newUnitId(),
|
|
45
|
+
treeDigest: input.treeDigest,
|
|
46
|
+
baseRef: input.baseRef,
|
|
47
|
+
source: {
|
|
48
|
+
sessionId: input.sessionId,
|
|
49
|
+
worktreePath: input.worktreePath,
|
|
50
|
+
governanceIds: input.governanceIds,
|
|
51
|
+
},
|
|
52
|
+
commitChain: input.commitChain,
|
|
53
|
+
enqueuedAt: new Date().toISOString(),
|
|
54
|
+
state: { status: "queued" },
|
|
55
|
+
attempts: 0,
|
|
56
|
+
};
|
|
57
|
+
store.enqueue(unit);
|
|
58
|
+
return unit;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface QueueView {
|
|
62
|
+
units: Array<{
|
|
63
|
+
id: string;
|
|
64
|
+
status: string;
|
|
65
|
+
enqueuedAt: string;
|
|
66
|
+
sessionId: string;
|
|
67
|
+
terminal: boolean;
|
|
68
|
+
}>;
|
|
69
|
+
journalTail: QueueJournalEntry[];
|
|
70
|
+
liveLease: boolean;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Read-only queue state — consumes frozen records and the append-only journal only. */
|
|
74
|
+
export function inspectQueue(store: QueueStore, journalTailLines = 20): QueueView {
|
|
75
|
+
const units = store.units().map((u) => ({
|
|
76
|
+
id: u.id,
|
|
77
|
+
status: u.state.status,
|
|
78
|
+
enqueuedAt: u.enqueuedAt,
|
|
79
|
+
sessionId: u.source.sessionId,
|
|
80
|
+
terminal: isTerminal(u.state),
|
|
81
|
+
}));
|
|
82
|
+
const journal = store.journal();
|
|
83
|
+
return {
|
|
84
|
+
units,
|
|
85
|
+
journalTail: journal.slice(-journalTailLines),
|
|
86
|
+
liveLease: false, // lease state is operational, not evidence — callers may probe separately
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Verbatim recovery path named in every conflicted terminal — the agent contract. */
|
|
91
|
+
export const CONFLICTED_RECOVERY_INSTRUCTION =
|
|
92
|
+
"This unit is terminally conflicted and is never retried in place. The owning session rebases its worktree onto the current head, resolves the named paths, freezes the result as a NEW unit and re-enqueues it — units are immutable, re-enqueue is a new id.";
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/*
|
|
2
|
+
<MODULE_CONTRACT>
|
|
3
|
+
<purpose>
|
|
4
|
+
Git operations substrate for the integration queue (Werkstatt RFC-1647) — pure
|
|
5
|
+
plumbing, no worktrees: commit-chain replay via merge-tree --write-tree with the
|
|
6
|
+
replayed commit's parent as merge-base (exact cherry-pick semantics), commit
|
|
7
|
+
materialization via commit-tree into the repo's own object store. Squash is
|
|
8
|
+
forbidden: the chain replays commit-by-commit preserving messages, authorship
|
|
9
|
+
and governance trailers. Objects never leave the main object store, so the
|
|
10
|
+
candidate survives independent of any scratch lifetime.
|
|
11
|
+
</purpose>
|
|
12
|
+
<non-goals>
|
|
13
|
+
<item>No evaluation or verdict logic — git mechanics only.</item>
|
|
14
|
+
</non-goals>
|
|
15
|
+
<CHANGE_SUMMARY>
|
|
16
|
+
<item>RFC-1647 (WP-4): plumbing-only — merge-tree/commit-tree, zero worktrees.</item>
|
|
17
|
+
</CHANGE_SUMMARY>
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
21
|
+
|
|
22
|
+
export interface GitExec {
|
|
23
|
+
(args: string[], cwd: string): string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const defaultGitExec: GitExec = (args, cwd) =>
|
|
27
|
+
execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
|
|
28
|
+
|
|
29
|
+
export function resolveRef(git: GitExec, repoDir: string, ref: string): string {
|
|
30
|
+
return git(["rev-parse", ref], repoDir).trim();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function treeOfCommit(git: GitExec, repoDir: string, commitSha: string): string {
|
|
34
|
+
return git(["rev-parse", `${commitSha}^{tree}`], repoDir).trim();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function commitExists(git: GitExec, repoDir: string, sha: string): boolean {
|
|
38
|
+
try {
|
|
39
|
+
git(["cat-file", "-e", sha], repoDir);
|
|
40
|
+
return true;
|
|
41
|
+
} catch {
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function commitTreeEquals(git: GitExec, repoDir: string, sha: string, treeDigest: string): boolean {
|
|
47
|
+
try {
|
|
48
|
+
return treeOfCommit(git, repoDir, sha) === treeDigest;
|
|
49
|
+
} catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ReplayResult {
|
|
55
|
+
ok: true;
|
|
56
|
+
candidateCommit: string;
|
|
57
|
+
candidateTree: string;
|
|
58
|
+
replayedCount: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface ReplayConflict {
|
|
62
|
+
ok: false;
|
|
63
|
+
conflictingPaths: string[];
|
|
64
|
+
atCommit: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface MergeTreeOutcome {
|
|
68
|
+
conflicted: boolean;
|
|
69
|
+
tree: string | null;
|
|
70
|
+
conflictedPaths: string[];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* One merge-tree execution, exit status as the conflict signal. Output format:
|
|
75
|
+
* first line the tree oid; on conflict a section of conflicted-file records
|
|
76
|
+
* whose lines carry the path as the last whitespace-separated token.
|
|
77
|
+
*/
|
|
78
|
+
function runMergeTree(repoDir: string, base: string, ours: string, theirs: string): MergeTreeOutcome {
|
|
79
|
+
const res = spawnSync("git", ["merge-tree", "--write-tree", "--merge-base", base, ours, theirs], {
|
|
80
|
+
cwd: repoDir,
|
|
81
|
+
encoding: "utf8",
|
|
82
|
+
});
|
|
83
|
+
const out = res.stdout ?? "";
|
|
84
|
+
const lines = out.split("\n");
|
|
85
|
+
const tree = lines[0]?.trim() || null;
|
|
86
|
+
const conflicted = res.status !== 0;
|
|
87
|
+
const conflictedPaths = conflicted
|
|
88
|
+
? [
|
|
89
|
+
...new Set(
|
|
90
|
+
lines
|
|
91
|
+
.slice(1)
|
|
92
|
+
.map((l) => l.trim())
|
|
93
|
+
.filter((l) => /^\d+ \d+ [0-9a-f]{7,40} \d+\t?.+/i.test(l) || l.includes("\t"))
|
|
94
|
+
.map((l) => l.split(/\s+/).pop() ?? "")
|
|
95
|
+
.filter(Boolean),
|
|
96
|
+
),
|
|
97
|
+
]
|
|
98
|
+
: [];
|
|
99
|
+
return { conflicted, tree, conflictedPaths };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function commitMeta(git: GitExec, repoDir: string, commit: string): { message: string; authorName: string; authorEmail: string; authorDate: string } {
|
|
103
|
+
const sep = "@@META@@";
|
|
104
|
+
const message = git(["log", "-1", "--format=%B", commit], repoDir);
|
|
105
|
+
const meta = git(["log", "-1", `--format=${sep}%an${sep}%ae${sep}%aI`, commit], repoDir).trim().split(sep).filter(Boolean);
|
|
106
|
+
return {
|
|
107
|
+
message: message.trimEnd(),
|
|
108
|
+
authorName: meta[1] ?? "integration-queue",
|
|
109
|
+
authorEmail: meta[2] ?? "queue@localhost",
|
|
110
|
+
authorDate: meta[3] ?? new Date().toISOString(),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Rebase-materialize: replay the chain commit-by-commit onto the current head
|
|
116
|
+
* using merge-tree with the commit's parent as merge-base — exact cherry-pick
|
|
117
|
+
* tree semantics, no worktree, no checkout. Each step materializes its own
|
|
118
|
+
* commit object (never squashed). First conflict stops the replay and names
|
|
119
|
+
* the conflicting paths per-commit.
|
|
120
|
+
*/
|
|
121
|
+
export function replayChainOntoHead(
|
|
122
|
+
git: GitExec,
|
|
123
|
+
repoDir: string,
|
|
124
|
+
headSha: string,
|
|
125
|
+
commitChain: string[],
|
|
126
|
+
): ReplayResult | ReplayConflict {
|
|
127
|
+
let tip = headSha;
|
|
128
|
+
let replayed = 0;
|
|
129
|
+
|
|
130
|
+
for (const commit of commitChain) {
|
|
131
|
+
const parent = git(["rev-parse", `${commit}^`], repoDir).trim();
|
|
132
|
+
const outcome = runMergeTree(repoDir, parent, tip, commit);
|
|
133
|
+
if (outcome.conflicted || !outcome.tree) {
|
|
134
|
+
return {
|
|
135
|
+
ok: false,
|
|
136
|
+
conflictingPaths: outcome.conflictedPaths.length > 0 ? outcome.conflictedPaths : ["(conflict — paths unparsed)"],
|
|
137
|
+
atCommit: commit,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const meta = commitMeta(git, repoDir, commit);
|
|
142
|
+
const env = {
|
|
143
|
+
...process.env,
|
|
144
|
+
GIT_AUTHOR_NAME: meta.authorName,
|
|
145
|
+
GIT_AUTHOR_EMAIL: meta.authorEmail,
|
|
146
|
+
GIT_AUTHOR_DATE: meta.authorDate,
|
|
147
|
+
GIT_COMMITTER_NAME: meta.authorName,
|
|
148
|
+
GIT_COMMITTER_EMAIL: meta.authorEmail,
|
|
149
|
+
};
|
|
150
|
+
const newCommit = execFileSync("git", ["commit-tree", outcome.tree, "-p", tip, "-m", meta.message], {
|
|
151
|
+
cwd: repoDir,
|
|
152
|
+
encoding: "utf8",
|
|
153
|
+
env,
|
|
154
|
+
}).trim();
|
|
155
|
+
tip = newCommit;
|
|
156
|
+
replayed += 1;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const candidateTree = treeOfCommit(git, repoDir, tip);
|
|
160
|
+
return { ok: true, candidateCommit: tip, candidateTree, replayedCount: replayed };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Integrate the candidate into the governed ref — the single write point.
|
|
165
|
+
* update-ref is atomic; the candidate commits already live in this object store.
|
|
166
|
+
*/
|
|
167
|
+
export function integrateCandidate(
|
|
168
|
+
git: GitExec,
|
|
169
|
+
repoDir: string,
|
|
170
|
+
governedRef: string,
|
|
171
|
+
candidateCommit: string,
|
|
172
|
+
): void {
|
|
173
|
+
git(["update-ref", governedRef, candidateCommit], repoDir);
|
|
174
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/*
|
|
2
|
+
<MODULE_CONTRACT>
|
|
3
|
+
<purpose>
|
|
4
|
+
Drain lease machinery (Werkstatt RFC-1647) — atomic acquisition, heartbeat, expiry
|
|
5
|
+
and reclaim, same-machine boot-id fencing inheriting the v9 machine-local trust
|
|
6
|
+
model. Lease is per-unit-processing, re-acquired with a fresh heartbeat at each
|
|
7
|
+
unit boundary; heartbeat cadence strictly less than half the TTL. Worst-case
|
|
8
|
+
duplicate work is one unit evaluation, never one corruption.
|
|
9
|
+
</purpose>
|
|
10
|
+
<non-goals>
|
|
11
|
+
<item>No multi-host fencing — v1 is single-machine scope by design.</item>
|
|
12
|
+
</non-goals>
|
|
13
|
+
<CHANGE_SUMMARY>
|
|
14
|
+
<item>RFC-1647 (WP-4): initial lease machinery.</item>
|
|
15
|
+
</CHANGE_SUMMARY>
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeSync } from "node:fs";
|
|
19
|
+
import { randomBytes } from "node:crypto";
|
|
20
|
+
import { join } from "node:path";
|
|
21
|
+
|
|
22
|
+
import type { DrainLease } from "./types.ts";
|
|
23
|
+
|
|
24
|
+
/** Lease TTL in ms — minutes-scale per RFC; heartbeat cadence must be < ttl/2. */
|
|
25
|
+
export const LEASE_TTL_MS = 5 * 60 * 1000;
|
|
26
|
+
export const HEARTBEAT_CADENCE_MS = 60 * 1000; // < LEASE_TTL_MS / 2 — fixed relationship
|
|
27
|
+
|
|
28
|
+
function hostBootId(): string {
|
|
29
|
+
try {
|
|
30
|
+
return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
|
|
31
|
+
} catch {
|
|
32
|
+
// Non-Linux fallback: machine+process start is the best available fence in v1 scope.
|
|
33
|
+
return `unknown-${process.pid}`;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface LeaseHandle {
|
|
38
|
+
lease: DrainLease;
|
|
39
|
+
heartbeat(): void;
|
|
40
|
+
release(): void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function readLease(path: string): DrainLease | null {
|
|
44
|
+
try {
|
|
45
|
+
return JSON.parse(readFileSync(path, "utf8")) as DrainLease;
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function isExpired(lease: DrainLease, now: number, ttlMs: number): boolean {
|
|
52
|
+
return new Date(lease.heartbeatAt).getTime() + ttlMs < now;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function isLiveHolder(lease: DrainLease): boolean {
|
|
56
|
+
if (lease.hostBootId !== hostBootId()) return false; // different boot — holder is gone
|
|
57
|
+
try {
|
|
58
|
+
process.kill(lease.workerPid, 0);
|
|
59
|
+
return true;
|
|
60
|
+
} catch {
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Acquire the drain lease atomically. Returns null when a live unexpired lease
|
|
67
|
+
* is held — the caller reports drain-in-progress and exits 0. Expired or dead
|
|
68
|
+
* leases are reclaimed; re-entry safety is the drain's idempotency contract.
|
|
69
|
+
*/
|
|
70
|
+
export function acquireLease(queueDir: string, ttlMs = LEASE_TTL_MS): LeaseHandle | null {
|
|
71
|
+
mkdirSync(queueDir, { recursive: true });
|
|
72
|
+
const leasePath = join(queueDir, "lease.json");
|
|
73
|
+
const now = Date.now();
|
|
74
|
+
|
|
75
|
+
const existing = readLease(leasePath);
|
|
76
|
+
if (existing && !isExpired(existing, now, ttlMs) && isLiveHolder(existing)) {
|
|
77
|
+
return null; // held by a live worker — never double-process
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Atomic take: write to a unique temp and rename — the rename is atomic on
|
|
81
|
+
// POSIX, and concurrent racers converge on one winner's file. Losers detect
|
|
82
|
+
// the loss by re-reading: the lease on disk names a different leaseId.
|
|
83
|
+
const lease: DrainLease = {
|
|
84
|
+
leaseId: randomBytes(8).toString("hex"),
|
|
85
|
+
workerPid: process.pid,
|
|
86
|
+
hostBootId: hostBootId(),
|
|
87
|
+
acquiredAt: new Date(now).toISOString(),
|
|
88
|
+
heartbeatAt: new Date(now).toISOString(),
|
|
89
|
+
};
|
|
90
|
+
const tmp = join(queueDir, `.lease-${lease.leaseId}`);
|
|
91
|
+
const fd = openSync(tmp, "w");
|
|
92
|
+
try {
|
|
93
|
+
writeSync(fd, JSON.stringify(lease, null, 2));
|
|
94
|
+
} finally {
|
|
95
|
+
closeSync(fd);
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
renameSync(tmp, leasePath);
|
|
99
|
+
} catch {
|
|
100
|
+
try {
|
|
101
|
+
unlinkSync(tmp);
|
|
102
|
+
} catch {
|
|
103
|
+
// best effort
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
// Verify the win — a concurrent racer's rename may have landed after ours.
|
|
107
|
+
const onDisk = readLease(leasePath);
|
|
108
|
+
if (!onDisk || onDisk.leaseId !== lease.leaseId) return null;
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
lease,
|
|
112
|
+
heartbeat() {
|
|
113
|
+
const current = readLease(leasePath);
|
|
114
|
+
if (!current || current.leaseId !== lease.leaseId) return; // lost — heartbeating another's lease is worse than expiry
|
|
115
|
+
const updated = { ...current, heartbeatAt: new Date().toISOString() };
|
|
116
|
+
const htmp = join(queueDir, `.lease-hb-${lease.leaseId}`);
|
|
117
|
+
const hfd = openSync(htmp, "w");
|
|
118
|
+
try {
|
|
119
|
+
writeSync(hfd, JSON.stringify(updated, null, 2));
|
|
120
|
+
} finally {
|
|
121
|
+
closeSync(hfd);
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
renameSync(htmp, leasePath);
|
|
125
|
+
} catch {
|
|
126
|
+
try {
|
|
127
|
+
unlinkSync(htmp);
|
|
128
|
+
} catch {
|
|
129
|
+
// best effort
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
release() {
|
|
134
|
+
const current = readLease(leasePath);
|
|
135
|
+
if (current?.leaseId === lease.leaseId) {
|
|
136
|
+
try {
|
|
137
|
+
unlinkSync(leasePath);
|
|
138
|
+
} catch {
|
|
139
|
+
// already gone
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|