@warpgogol/forge 10.0.0 → 10.1.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.
Files changed (136) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/bin/cli.ts +17 -0
  3. package/dist/bin/cli.js +17 -0
  4. package/dist/bin/cli.js.map +1 -1
  5. package/dist/os/rfc/probe-batch.d.ts.map +1 -1
  6. package/dist/os/rfc/probe-batch.js +13 -6
  7. package/dist/os/rfc/probe-batch.js.map +1 -1
  8. package/dist/src/contract/core-nodes.d.ts +8 -0
  9. package/dist/src/contract/core-nodes.d.ts.map +1 -0
  10. package/dist/src/contract/core-nodes.js +101 -0
  11. package/dist/src/contract/core-nodes.js.map +1 -0
  12. package/dist/src/contract/evaluator.d.ts +48 -0
  13. package/dist/src/contract/evaluator.d.ts.map +1 -0
  14. package/dist/src/contract/evaluator.js +158 -0
  15. package/dist/src/contract/evaluator.js.map +1 -0
  16. package/dist/src/contract/evidence-store.d.ts +17 -0
  17. package/dist/src/contract/evidence-store.d.ts.map +1 -0
  18. package/dist/src/contract/evidence-store.js +113 -0
  19. package/dist/src/contract/evidence-store.js.map +1 -0
  20. package/dist/src/contract/executors/zero-deps.d.ts +3 -0
  21. package/dist/src/contract/executors/zero-deps.d.ts.map +1 -0
  22. package/dist/src/contract/executors/zero-deps.js +88 -0
  23. package/dist/src/contract/executors/zero-deps.js.map +1 -0
  24. package/dist/src/contract/fingerprint.d.ts +34 -0
  25. package/dist/src/contract/fingerprint.d.ts.map +1 -0
  26. package/dist/src/contract/fingerprint.js +153 -0
  27. package/dist/src/contract/fingerprint.js.map +1 -0
  28. package/dist/src/contract/graph.d.ts +23 -0
  29. package/dist/src/contract/graph.d.ts.map +1 -0
  30. package/dist/src/contract/graph.js +158 -0
  31. package/dist/src/contract/graph.js.map +1 -0
  32. package/dist/src/contract/migration-map.d.ts +51 -0
  33. package/dist/src/contract/migration-map.d.ts.map +1 -0
  34. package/dist/src/contract/migration-map.js +130 -0
  35. package/dist/src/contract/migration-map.js.map +1 -0
  36. package/dist/src/contract/types.d.ts +108 -0
  37. package/dist/src/contract/types.d.ts.map +1 -0
  38. package/dist/src/contract/types.js +23 -0
  39. package/dist/src/contract/types.js.map +1 -0
  40. package/dist/src/integration/drain.d.ts +37 -0
  41. package/dist/src/integration/drain.d.ts.map +1 -0
  42. package/dist/src/integration/drain.js +235 -0
  43. package/dist/src/integration/drain.js.map +1 -0
  44. package/dist/src/integration/enqueue.d.ts +30 -0
  45. package/dist/src/integration/enqueue.d.ts.map +1 -0
  46. package/dist/src/integration/enqueue.js +64 -0
  47. package/dist/src/integration/enqueue.js.map +1 -0
  48. package/dist/src/integration/gitops.d.ts +33 -0
  49. package/dist/src/integration/gitops.d.ts.map +1 -0
  50. package/dist/src/integration/gitops.js +128 -0
  51. package/dist/src/integration/gitops.js.map +1 -0
  52. package/dist/src/integration/lease.d.ts +16 -0
  53. package/dist/src/integration/lease.d.ts.map +1 -0
  54. package/dist/src/integration/lease.js +140 -0
  55. package/dist/src/integration/lease.js.map +1 -0
  56. package/dist/src/integration/materialize.d.ts +7 -0
  57. package/dist/src/integration/materialize.d.ts.map +1 -0
  58. package/dist/src/integration/materialize.js +34 -0
  59. package/dist/src/integration/materialize.js.map +1 -0
  60. package/dist/src/integration/store.d.ts +21 -0
  61. package/dist/src/integration/store.d.ts.map +1 -0
  62. package/dist/src/integration/store.js +131 -0
  63. package/dist/src/integration/store.js.map +1 -0
  64. package/dist/src/integration/types.d.ts +71 -0
  65. package/dist/src/integration/types.d.ts.map +1 -0
  66. package/dist/src/integration/types.js +18 -0
  67. package/dist/src/integration/types.js.map +1 -0
  68. package/dist/src/onboarding/init.d.ts.map +1 -1
  69. package/dist/src/onboarding/init.js +4 -0
  70. package/dist/src/onboarding/init.js.map +1 -1
  71. package/dist/src/onboarding/upgrade.d.ts.map +1 -1
  72. package/dist/src/onboarding/upgrade.js +77 -2
  73. package/dist/src/onboarding/upgrade.js.map +1 -1
  74. package/dist/src/sdk/cli-bridge.d.ts +26 -0
  75. package/dist/src/sdk/cli-bridge.d.ts.map +1 -0
  76. package/dist/src/sdk/cli-bridge.js +89 -0
  77. package/dist/src/sdk/cli-bridge.js.map +1 -0
  78. package/dist/src/sdk/context.d.ts +13 -0
  79. package/dist/src/sdk/context.d.ts.map +1 -0
  80. package/dist/src/sdk/context.js +128 -0
  81. package/dist/src/sdk/context.js.map +1 -0
  82. package/dist/src/sdk/hooks.d.ts +14 -0
  83. package/dist/src/sdk/hooks.d.ts.map +1 -0
  84. package/dist/src/sdk/hooks.js +35 -0
  85. package/dist/src/sdk/hooks.js.map +1 -0
  86. package/dist/src/sdk/loader.d.ts +26 -0
  87. package/dist/src/sdk/loader.d.ts.map +1 -0
  88. package/dist/src/sdk/loader.js +170 -0
  89. package/dist/src/sdk/loader.js.map +1 -0
  90. package/dist/src/sdk/scan.d.ts +16 -0
  91. package/dist/src/sdk/scan.d.ts.map +1 -0
  92. package/dist/src/sdk/scan.js +126 -0
  93. package/dist/src/sdk/scan.js.map +1 -0
  94. package/dist/src/sdk/skills-gen.d.ts +27 -0
  95. package/dist/src/sdk/skills-gen.d.ts.map +1 -0
  96. package/dist/src/sdk/skills-gen.js +87 -0
  97. package/dist/src/sdk/skills-gen.js.map +1 -0
  98. package/dist/src/sdk/types.d.ts +141 -0
  99. package/dist/src/sdk/types.d.ts.map +1 -0
  100. package/dist/src/sdk/types.js +34 -0
  101. package/dist/src/sdk/types.js.map +1 -0
  102. package/dist/src/utils/gitignore-entry.d.ts +3 -0
  103. package/dist/src/utils/gitignore-entry.d.ts.map +1 -0
  104. package/dist/src/utils/gitignore-entry.js +24 -0
  105. package/dist/src/utils/gitignore-entry.js.map +1 -0
  106. package/dist/src/utils/verifier-git.d.ts.map +1 -1
  107. package/dist/src/utils/verifier-git.js +18 -2
  108. package/dist/src/utils/verifier-git.js.map +1 -1
  109. package/os/rfc/probe-batch.ts +13 -6
  110. package/package.json +17 -1
  111. package/src/contract/core-nodes.ts +111 -0
  112. package/src/contract/evaluator.ts +207 -0
  113. package/src/contract/evidence-store.ts +119 -0
  114. package/src/contract/executors/zero-deps.ts +92 -0
  115. package/src/contract/fingerprint.ts +176 -0
  116. package/src/contract/graph.ts +181 -0
  117. package/src/contract/migration-map.ts +174 -0
  118. package/src/contract/types.ts +125 -0
  119. package/src/integration/drain.ts +323 -0
  120. package/src/integration/enqueue.ts +92 -0
  121. package/src/integration/gitops.ts +174 -0
  122. package/src/integration/lease.ts +144 -0
  123. package/src/integration/materialize.ts +40 -0
  124. package/src/integration/store.ts +153 -0
  125. package/src/integration/types.ts +79 -0
  126. package/src/onboarding/init.ts +4 -0
  127. package/src/onboarding/upgrade.ts +84 -1
  128. package/src/sdk/cli-bridge.ts +94 -0
  129. package/src/sdk/context.ts +135 -0
  130. package/src/sdk/hooks.ts +51 -0
  131. package/src/sdk/loader.ts +187 -0
  132. package/src/sdk/scan.ts +132 -0
  133. package/src/sdk/skills-gen.ts +104 -0
  134. package/src/sdk/types.ts +158 -0
  135. package/src/utils/gitignore-entry.ts +24 -0
  136. package/src/utils/verifier-git.ts +17 -2
@@ -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
+ }
@@ -0,0 +1,40 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Candidate tree materialization (Werkstatt RFC-1647) — the contract graph evaluates
5
+ the exact content that would integrate. The frozen candidate tree object is
6
+ expanded into an ephemeral filesystem root via git archive; callers own cleanup.
7
+ </purpose>
8
+ <non-goals>
9
+ <item>No caching of materializations — evaluation frequency is human-scale.</item>
10
+ </non-goals>
11
+ <CHANGE_SUMMARY>
12
+ <item>RFC-1647 (WP-4): initial materializer.</item>
13
+ </CHANGE_SUMMARY>
14
+ */
15
+
16
+ import { execFileSync } from "node:child_process";
17
+ import { mkdtempSync, rmSync } from "node:fs";
18
+ import { tmpdir } from "node:os";
19
+ import { join } from "node:path";
20
+
21
+ export interface MaterializedTree {
22
+ root: string;
23
+ cleanup(): void;
24
+ }
25
+
26
+ /** Expand a git tree object into a fresh ephemeral directory. */
27
+ export function materializeTree(repoDir: string, treeDigest: string): MaterializedTree {
28
+ const root = mkdtempSync(join(tmpdir(), "forge-candidate-"));
29
+ // git archive writes a tar of the tree to stdout — expand in place.
30
+ execFileSync("sh", ["-c", `git archive "${treeDigest}" | tar -x -C "${root}"`], {
31
+ cwd: repoDir,
32
+ stdio: ["ignore", "pipe", "pipe"],
33
+ });
34
+ return {
35
+ root,
36
+ cleanup() {
37
+ rmSync(root, { recursive: true, force: true });
38
+ },
39
+ };
40
+ }
@@ -0,0 +1,153 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Queue persistence (Werkstatt RFC-1647) — atomic enqueue via staging plus a single
5
+ journal append; append-only journal as the source of truth with bounded fold via
6
+ checkpoints; unit records immutable once terminal. A journal entry referencing a
7
+ missing or incomplete unit record is proof of crash-mid-enqueue and is discarded
8
+ as never-enqueued.
9
+ </purpose>
10
+ <non-goals>
11
+ <item>No lease or drain logic — persistence only.</item>
12
+ </non-goals>
13
+ <CHANGE_SUMMARY>
14
+ <item>RFC-1647 (WP-4): initial queue store.</item>
15
+ </CHANGE_SUMMARY>
16
+ */
17
+
18
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, unlinkSync, writeSync } from "node:fs";
19
+ import { randomBytes } from "node:crypto";
20
+ import { join } from "node:path";
21
+
22
+ import type { IntegrationUnit, QueueJournalEntry } from "./types.ts";
23
+
24
+ function atomicWrite(path: string, content: string): void {
25
+ mkdirSync(join(path, ".."), { recursive: true });
26
+ const tmp = join(join(path, ".."), `.tmp-${randomBytes(8).toString("hex")}`);
27
+ const fd = openSync(tmp, "w");
28
+ try {
29
+ writeSync(fd, content);
30
+ } finally {
31
+ closeSync(fd);
32
+ }
33
+ renameSync(tmp, path);
34
+ }
35
+
36
+ export interface QueueStore {
37
+ /**
38
+ * Atomic enqueue: the unit record is staged, then becomes visible through one
39
+ * atomic journal append. Either the unit exists complete in the queue or not
40
+ * at all — partial units are impossible by construction.
41
+ */
42
+ enqueue(unit: IntegrationUnit): void;
43
+ appendJournal(entry: QueueJournalEntry): void;
44
+ readUnit(id: string): IntegrationUnit | null;
45
+ writeUnit(unit: IntegrationUnit): void;
46
+ /** All live units folded from journal + records — never-enqueued partial entries discarded. */
47
+ units(): IntegrationUnit[];
48
+ journal(): QueueJournalEntry[];
49
+ checkpoint(): void;
50
+ queueDir: string;
51
+ }
52
+
53
+ export function createQueueStore(queueDir: string): QueueStore {
54
+ const unitsDir = join(queueDir, "units");
55
+ const journalPath = join(queueDir, "journal.log");
56
+ const checkpointPath = join(queueDir, "checkpoint.json");
57
+ mkdirSync(unitsDir, { recursive: true });
58
+
59
+ function unitPath(id: string): string {
60
+ return join(unitsDir, `${id}.json`);
61
+ }
62
+
63
+ function appendJournal(entry: QueueJournalEntry): void {
64
+ mkdirSync(queueDir, { recursive: true });
65
+ const fd = openSync(journalPath, "a");
66
+ try {
67
+ writeSync(fd, JSON.stringify(entry) + "\n");
68
+ } finally {
69
+ closeSync(fd);
70
+ }
71
+ }
72
+
73
+ function readJournalRaw(): QueueJournalEntry[] {
74
+ if (!existsSync(journalPath)) return [];
75
+ return readFileSync(journalPath, "utf8")
76
+ .split("\n")
77
+ .filter((l) => l.trim().length > 0)
78
+ .map((l) => JSON.parse(l) as QueueJournalEntry);
79
+ }
80
+
81
+ function readUnit(id: string): IntegrationUnit | null {
82
+ try {
83
+ return JSON.parse(readFileSync(unitPath(id), "utf8")) as IntegrationUnit;
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+
89
+ function writeUnit(unit: IntegrationUnit): void {
90
+ atomicWrite(unitPath(unit.id), JSON.stringify(unit, null, 2));
91
+ }
92
+
93
+ function units(): IntegrationUnit[] {
94
+ // Fold the journal: a unit is live when its enqueued entry resolves to a
95
+ // complete record. Entries referencing missing/incomplete records are proof
96
+ // of crash-mid-enqueue — discarded as never-enqueued.
97
+ const entries = readJournalRaw();
98
+ const ids: string[] = [];
99
+ for (const e of entries) {
100
+ if (e.transition === "enqueued" && !ids.includes(e.unitId)) {
101
+ if (readUnit(e.unitId) != null) ids.push(e.unitId);
102
+ }
103
+ }
104
+ return ids.map((id) => readUnit(id)!).filter(Boolean);
105
+ }
106
+
107
+ return {
108
+ queueDir,
109
+ enqueue(unit) {
110
+ // Stage the complete record first, then the single atomic journal append
111
+ // that makes it visible. Reverse order would expose a referencing entry
112
+ // without a record; this order makes crash-mid-enqueue detectable and
113
+ // discardable.
114
+ writeUnit(unit);
115
+ appendJournal({
116
+ schema: "forge:queue-journal/v1",
117
+ unitId: unit.id,
118
+ transition: "enqueued",
119
+ at: new Date().toISOString(),
120
+ actor: `session:${unit.source.sessionId}`,
121
+ });
122
+ },
123
+ appendJournal,
124
+ readUnit,
125
+ writeUnit,
126
+ units,
127
+ journal: readJournalRaw,
128
+ checkpoint() {
129
+ // Fold-on-read stays bounded by checkpoint spacing, not journal age.
130
+ const snapshot = {
131
+ at: new Date().toISOString(),
132
+ units: units().map((u) => ({ id: u.id, state: u.state })),
133
+ };
134
+ atomicWrite(checkpointPath, JSON.stringify(snapshot, null, 2));
135
+ },
136
+ };
137
+ }
138
+
139
+ /** Garbage-collect staging residue older than crash windows — safe because incomplete units are never visible. */
140
+ export function cleanStagingResidue(queueDir: string): number {
141
+ const staging = join(queueDir, "staging");
142
+ if (!existsSync(staging)) return 0;
143
+ let removed = 0;
144
+ for (const entry of readdirSync(staging)) {
145
+ try {
146
+ unlinkSync(join(staging, entry));
147
+ removed += 1;
148
+ } catch {
149
+ // concurrent writer — leave it
150
+ }
151
+ }
152
+ return removed;
153
+ }
@@ -0,0 +1,79 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Transactional integration queue types (Werkstatt RFC-1647) — immutable units,
5
+ the unit state machine, drain leases, and the append-only queue journal.
6
+ Mutable bookkeeping is separated from evidence per RFC-1646.
7
+ </purpose>
8
+ <non-goals>
9
+ <item>No drain/store logic — types only.</item>
10
+ </non-goals>
11
+ <CHANGE_SUMMARY>
12
+ <item>RFC-1647 (WP-4): initial queue contracts.</item>
13
+ </CHANGE_SUMMARY>
14
+ */
15
+
16
+ /** Immutable unit of integration — frozen at enqueue, never mutated. */
17
+ export interface IntegrationUnit {
18
+ schema: "forge:integration-unit/v1";
19
+ /** uuidv7-style time-ordered id. */
20
+ id: string;
21
+ /** Frozen session tree — git tree object id is the content digest. */
22
+ treeDigest: string;
23
+ /** Governed ref digest at enqueue time. */
24
+ baseRef: string;
25
+ source: {
26
+ sessionId: string;
27
+ /** Informational only. */
28
+ worktreePath: string;
29
+ /** RFC/ADR/friction anchors. */
30
+ governanceIds: string[];
31
+ };
32
+ /** Commit chain preserved for replay, oldest first — squash is forbidden. */
33
+ commitChain: string[];
34
+ enqueuedAt: string;
35
+ state: UnitState;
36
+ /** Crash-recovery counter, not retry-of-failure. */
37
+ attempts: number;
38
+ }
39
+
40
+ export type UnitState =
41
+ | { status: "queued" }
42
+ | { status: "evaluating"; leaseId: string; since: string }
43
+ | { status: "integrated"; commitSha: string; evidenceKey: string }
44
+ | { status: "refused"; reason: RefusalReason; evidenceKey: string }
45
+ | { status: "conflicted"; conflictingPaths: string[] }
46
+ | { status: "cancelled"; by: string };
47
+
48
+ export interface RefusalReason {
49
+ /** The blocking contract node — one explanation path. */
50
+ nodeId: string;
51
+ summary: string;
52
+ violations: number;
53
+ }
54
+
55
+ export interface DrainLease {
56
+ leaseId: string;
57
+ workerPid: number;
58
+ /** Same-machine fencing, inheriting the v9 machine-local trust model. */
59
+ hostBootId: string;
60
+ acquiredAt: string;
61
+ /** Expiry = heartbeat + leaseTtl. */
62
+ heartbeatAt: string;
63
+ }
64
+
65
+ export interface QueueJournalEntry {
66
+ schema: "forge:queue-journal/v1";
67
+ unitId: string;
68
+ transition: "enqueued" | "evaluating" | "integrated" | "refused" | "conflicted" | "cancelled" | "requeued";
69
+ at: string;
70
+ /** drain:<leaseId> | session:<id> | operator */
71
+ actor: string;
72
+ detail?: Record<string, string>;
73
+ }
74
+
75
+ export type TerminalStatus = "integrated" | "refused" | "conflicted" | "cancelled";
76
+
77
+ export function isTerminal(state: UnitState): boolean {
78
+ return state.status === "integrated" || state.status === "refused" || state.status === "conflicted" || state.status === "cancelled";
79
+ }
@@ -35,6 +35,7 @@ import { resolveWorkspaceTypes } from "./workspace-discovery.ts";
35
35
  import { defaultForgeConfig, loadForgeConfig, resolveForgeRoot, type ForgeConfig } from "../config/forge-config.ts";
36
36
  import { listStackProfiles, detectStack } from "../profiles/stack-profile.ts";
37
37
  import { scaffoldTrustBoundary } from "./trust-boundary.ts";
38
+ import { ensureGitignoreEntry } from "../utils/gitignore-entry.ts";
38
39
 
39
40
  export interface SkippedSkill {
40
41
  name: string;
@@ -271,6 +272,9 @@ export function runInit(
271
272
  }
272
273
 
273
274
  // 3. Copy forge skills to .agents/skills/<name>/ for IDE discovery
275
+ // RFC-1648: the skills tree is a generated view — untracked by construction,
276
+ // so the writer self-ensures gitignore coverage (nothing tracked to drift).
277
+ ensureGitignoreEntry(workspaceRoot, `${config.paths.skillsDir}/`);
274
278
  const agentsSkillsDir = path.join(workspaceRoot, config.paths.skillsDir);
275
279
  for (const skill of FORGE_SKILLS) {
276
280
  const srcPath = path.join(forgeRoot, skill.path);
@@ -48,6 +48,7 @@ scaffold (CODEOWNERS + forge-policy workflow) and reference docs.</item>
48
48
  </CHANGE_SUMMARY>
49
49
  */
50
50
 
51
+ import { ensureGitignoreEntry } from "../utils/gitignore-entry.ts";
51
52
  import type { WorkspaceIO } from "../types.ts";
52
53
  import { resolveIo } from "../utils/io.ts";
53
54
  import { hasGeneratedMarker, mergeEditableGenerated } from "../utils/index.ts";
@@ -75,6 +76,7 @@ import {
75
76
  pruneStaleSkillDirs,
76
77
  listFilesRecursive,
77
78
  type PruneResult,
79
+ writeSkillMarkerSync,
78
80
  } from "./skill-markers.ts";
79
81
  import {
80
82
  planPrettierignore,
@@ -282,6 +284,8 @@ async function syncForgeSkills(
282
284
  ): Promise<{ updated: string[]; knowledgeConflicts: string[] }> {
283
285
  const updated: string[] = [];
284
286
  const knowledgeConflicts: string[] = [];
287
+ // RFC-1648: generated view — untracked by construction (see init.ts).
288
+ if (!dryRun) ensureGitignoreEntry(workspaceRoot, `${skillsDir}/`);
285
289
  const agentsSkillsDir = path.join(workspaceRoot, skillsDir);
286
290
 
287
291
  for (const skill of FORGE_SKILLS) {
@@ -400,6 +404,71 @@ async function syncSharedConventions(
400
404
  return { updated: ["_shared"] };
401
405
  }
402
406
 
407
+ /**
408
+ * RFC-1648: sync plugin-contributed skills into the generated tree. Sources are
409
+ * active plugins' skillsDirs resolved through the standard SDK loader — one
410
+ * code path for npm and project-local species. Name conflicts with forge or
411
+ * pack skills skip (the first writer wins, conflict is reported, never merged).
412
+ */
413
+ async function syncPluginSkills(
414
+ workspaceRoot: string,
415
+ skillsDir: string,
416
+ dryRun: boolean,
417
+ io: WorkspaceIO,
418
+ alreadyWritten: Set<string>,
419
+ ): Promise<{ updated: string[]; skipped: SkippedSkill[] }> {
420
+ const updated: string[] = [];
421
+ const skipped: SkippedSkill[] = [];
422
+ const agentsSkillsDir = path.join(workspaceRoot, skillsDir);
423
+ let plugins: Array<{ manifest: { id: string }; skillsDir: string | null }> = [];
424
+ try {
425
+ const { loadConsumerPlugins } = await import("../sdk/cli-bridge.ts");
426
+ const loaded = await loadConsumerPlugins(workspaceRoot);
427
+ plugins = loaded.plugins;
428
+ } catch {
429
+ return { updated, skipped };
430
+ }
431
+ for (const plugin of plugins) {
432
+ if (!plugin.skillsDir) continue;
433
+ let entries: Array<{ name: string; isDirectory: boolean }> = [];
434
+ try {
435
+ const raw = await io.readdir(plugin.skillsDir);
436
+ entries = raw.map((e) => ({ name: e.name, isDirectory: e.isDirectory }));
437
+ } catch {
438
+ continue;
439
+ }
440
+ for (const entry of entries) {
441
+ if (!entry.isDirectory) continue;
442
+ const skillSrcDir = path.join(plugin.skillsDir, entry.name);
443
+ if (!(await io.exists(path.join(skillSrcDir, "SKILL.md")))) continue;
444
+ if (alreadyWritten.has(entry.name)) {
445
+ skipped.push({ name: entry.name, reason: `conflict — already provided (plugin ${plugin.manifest.id})` });
446
+ continue;
447
+ }
448
+ const destDir = path.join(agentsSkillsDir, entry.name);
449
+ if (!dryRun) {
450
+ const written: string[] = [];
451
+ const walk = async (dir: string, rel: string): Promise<void> => {
452
+ for (const e of await io.readdir(dir)) {
453
+ const r = rel ? `${rel}/${e.name}` : e.name;
454
+ if (e.isDirectory) await walk(path.join(dir, e.name), r);
455
+ else {
456
+ await io.mkdir(path.dirname(path.join(destDir, r)));
457
+ await io.copyFile(path.join(dir, e.name), path.join(destDir, r));
458
+ written.push(r);
459
+ }
460
+ }
461
+ };
462
+ await walk(skillSrcDir, "");
463
+ writeSkillMarkerSync(destDir, written);
464
+ }
465
+ alreadyWritten.add(entry.name);
466
+ updated.push(entry.name);
467
+ }
468
+ }
469
+ return { updated, skipped };
470
+ }
471
+
403
472
  async function syncPackSkills(
404
473
  workspaceRoot: string,
405
474
  config: ForgeConfig,
@@ -520,9 +589,22 @@ async function reconcileGeneratedSurface(
520
589
  io,
521
590
  );
522
591
 
592
+ const alreadyWritten = new Set([
593
+ ...forgeSkillsResult.updated,
594
+ ...packResult.updated,
595
+ ]);
596
+ const pluginResult = await syncPluginSkills(
597
+ workspaceRoot,
598
+ config.paths.skillsDir,
599
+ dryRun,
600
+ io,
601
+ alreadyWritten,
602
+ );
603
+
523
604
  const currentSyncSet = new Set([
524
605
  ...forgeSkillsResult.updated,
525
606
  ...packResult.updated,
607
+ ...pluginResult.updated,
526
608
  ...sharedKnowledgeResult.updated,
527
609
  ...sharedConventionsResult.updated,
528
610
  ]);
@@ -562,6 +644,7 @@ async function reconcileGeneratedSurface(
562
644
  updated: [
563
645
  ...forgeSkillsResult.updated,
564
646
  ...packResult.updated,
647
+ ...pluginResult.updated,
565
648
  ...sharedKnowledgeResult.updated,
566
649
  ...sharedConventionsResult.updated,
567
650
  ],
@@ -570,7 +653,7 @@ async function reconcileGeneratedSurface(
570
653
  ...packResult.knowledgeConflicts,
571
654
  ...sharedKnowledgeResult.knowledgeConflicts,
572
655
  ],
573
- skipped: packResult.skipped,
656
+ skipped: [...packResult.skipped, ...pluginResult.skipped],
574
657
  prune,
575
658
  prettierignore,
576
659
  warnings,
@@ -0,0 +1,94 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Plugin-CLI bridge (Werkstatt RFC-1648) — consumer plugins discovered from the
5
+ workspace forge.yaml `plugins:` entries load through the standard SDK loader and
6
+ their commands adapt into the CLI registry as first-class commands. One species:
7
+ npm-published and project-local plugins take the identical path. A plugin failing
8
+ any load phase is entirely absent — partial activation impossible — and the load
9
+ failure surfaces as a loud CLI diagnostic, never silent absence.
10
+ </purpose>
11
+ <non-goals><item>No compile cache — plugins ship compiled dist per RFC-1648.</item></non-goals>
12
+ <CHANGE_SUMMARY><item>WP-5/WP-6: initial bridge.</item></CHANGE_SUMMARY>
13
+ */
14
+
15
+ import { existsSync, readFileSync } from "node:fs";
16
+ import { join } from "node:path";
17
+
18
+ import { parse as parseYaml } from "yaml";
19
+
20
+ import type { ForgeCommandDefinition, ForgeCommandInput, ForgeCommandResult, ForgeRuntimeContext } from "../types.ts";
21
+ import { loadPlugin, type LoadedPlugin } from "./loader.ts";
22
+ import type { CommandModule, PluginContext } from "./types.ts";
23
+
24
+ /** Read consumer plugin entries from forge.yaml — absent section means no plugins. */
25
+ export function discoverPluginEntries(workspaceRoot: string): string[] {
26
+ const configPath = join(workspaceRoot, "forge.yaml");
27
+ if (!existsSync(configPath)) return [];
28
+ try {
29
+ const config = parseYaml(readFileSync(configPath, "utf8")) as { plugins?: unknown };
30
+ if (!config.plugins) return [];
31
+ if (Array.isArray(config.plugins)) return config.plugins.filter((p): p is string => typeof p === "string");
32
+ if (typeof config.plugins === "object") return Object.keys(config.plugins);
33
+ return [];
34
+ } catch {
35
+ return [];
36
+ }
37
+ }
38
+
39
+ /** Adapt one SDK command into the CLI registry shape. */
40
+ export function adaptCommand(cmd: CommandModule, ctx: PluginContext, pluginId: string): ForgeCommandDefinition {
41
+ return {
42
+ name: cmd.id,
43
+ description: `[${pluginId}] ${cmd.description}`,
44
+ scope: "workspace",
45
+ async execute(input: ForgeCommandInput, _runtime: ForgeRuntimeContext): Promise<ForgeCommandResult> {
46
+ const args = (input.flags ?? {}) as Record<string, unknown>;
47
+ try {
48
+ const result = await cmd.run(ctx, args);
49
+ const diagnostics = (result.violations ?? []).map((v) => ({
50
+ ruleId: v.ruleId,
51
+ severity: v.severity === "blocking" ? ("error" as const) : ("warning" as const),
52
+ message: v.message,
53
+ file: v.file,
54
+ }));
55
+ return {
56
+ data: { status: result.status, violations: result.violations, ...result.data },
57
+ summary: result.message ?? `${cmd.id}: ${result.status}`,
58
+ exitCode: result.status === "pass" ? 0 : 1,
59
+ diagnostics,
60
+ } as ForgeCommandResult;
61
+ } catch (err) {
62
+ return {
63
+ summary: `${cmd.id}: executor error — ${err instanceof Error ? err.message : String(err)}`,
64
+ exitCode: 1,
65
+ };
66
+ }
67
+ },
68
+ };
69
+ }
70
+
71
+ export interface PluginLoadReport {
72
+ loaded: Array<{ pluginId: string; commands: string[] }>;
73
+ failed: Array<{ entry: string; error: string }>;
74
+ }
75
+
76
+ /**
77
+ * Discover and load all consumer plugins — fail-closed per plugin, but one
78
+ * plugin's failure never blocks the others (each failure is reported loudly).
79
+ */
80
+ export async function loadConsumerPlugins(workspaceRoot: string): Promise<{ plugins: LoadedPlugin[]; report: PluginLoadReport }> {
81
+ const entries = discoverPluginEntries(workspaceRoot);
82
+ const plugins: LoadedPlugin[] = [];
83
+ const report: PluginLoadReport = { loaded: [], failed: [] };
84
+ for (const entry of entries) {
85
+ try {
86
+ const loaded = await loadPlugin(entry, workspaceRoot, { workspaceRoot });
87
+ plugins.push(loaded);
88
+ report.loaded.push({ pluginId: loaded.manifest.id, commands: loaded.commands.map((c) => c.id) });
89
+ } catch (err) {
90
+ report.failed.push({ entry, error: err instanceof Error ? err.message : String(err) });
91
+ }
92
+ }
93
+ return { plugins, report };
94
+ }