@warpgogol/forge 10.1.0 → 10.1.2

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 (53) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/bin/cli.js +0 -0
  3. package/bin/cli.ts +17 -0
  4. package/dist/bin/cli.js +17 -0
  5. package/dist/bin/cli.js.map +1 -1
  6. package/dist/src/integration/drain.d.ts +6 -0
  7. package/dist/src/integration/drain.d.ts.map +1 -1
  8. package/dist/src/integration/drain.js +40 -0
  9. package/dist/src/integration/drain.js.map +1 -1
  10. package/dist/src/onboarding/init.d.ts.map +1 -1
  11. package/dist/src/onboarding/init.js +4 -0
  12. package/dist/src/onboarding/init.js.map +1 -1
  13. package/dist/src/onboarding/upgrade.d.ts.map +1 -1
  14. package/dist/src/onboarding/upgrade.js +77 -2
  15. package/dist/src/onboarding/upgrade.js.map +1 -1
  16. package/dist/src/sdk/cli-bridge.d.ts +26 -0
  17. package/dist/src/sdk/cli-bridge.d.ts.map +1 -0
  18. package/dist/src/sdk/cli-bridge.js +89 -0
  19. package/dist/src/sdk/cli-bridge.js.map +1 -0
  20. package/dist/src/sdk/context.d.ts +1 -0
  21. package/dist/src/sdk/context.d.ts.map +1 -1
  22. package/dist/src/sdk/context.js +87 -3
  23. package/dist/src/sdk/context.js.map +1 -1
  24. package/dist/src/sdk/hooks.d.ts +14 -0
  25. package/dist/src/sdk/hooks.d.ts.map +1 -0
  26. package/dist/src/sdk/hooks.js +35 -0
  27. package/dist/src/sdk/hooks.js.map +1 -0
  28. package/dist/src/sdk/loader.d.ts +2 -1
  29. package/dist/src/sdk/loader.d.ts.map +1 -1
  30. package/dist/src/sdk/loader.js +22 -7
  31. package/dist/src/sdk/loader.js.map +1 -1
  32. package/dist/src/sdk/types.d.ts +39 -2
  33. package/dist/src/sdk/types.d.ts.map +1 -1
  34. package/dist/src/sdk/types.js +2 -2
  35. package/dist/src/sdk/types.js.map +1 -1
  36. package/dist/src/utils/gitignore-entry.d.ts +3 -0
  37. package/dist/src/utils/gitignore-entry.d.ts.map +1 -0
  38. package/dist/src/utils/gitignore-entry.js +24 -0
  39. package/dist/src/utils/gitignore-entry.js.map +1 -0
  40. package/dist/src/utils/verifier-git.d.ts.map +1 -1
  41. package/dist/src/utils/verifier-git.js +18 -2
  42. package/dist/src/utils/verifier-git.js.map +1 -1
  43. package/package.json +497 -169
  44. package/src/integration/drain.ts +52 -0
  45. package/src/onboarding/init.ts +4 -0
  46. package/src/onboarding/upgrade.ts +84 -1
  47. package/src/sdk/cli-bridge.ts +94 -0
  48. package/src/sdk/context.ts +83 -3
  49. package/src/sdk/hooks.ts +51 -0
  50. package/src/sdk/loader.ts +25 -8
  51. package/src/sdk/types.ts +50 -7
  52. package/src/utils/gitignore-entry.ts +24 -0
  53. package/src/utils/verifier-git.ts +17 -2
@@ -31,6 +31,8 @@ import {
31
31
  type GitExec,
32
32
  defaultGitExec,
33
33
  } from "./gitops.ts";
34
+ import { invokeLifecycleHook, type HookInvocationError } from "../sdk/hooks.ts";
35
+ import type { LoadedPlugin } from "../sdk/loader.ts";
34
36
  import { acquireLease, type LeaseHandle } from "./lease.ts";
35
37
  import type { QueueStore } from "./store.ts";
36
38
  import { isTerminal, type IntegrationUnit, type QueueJournalEntry } from "./types.ts";
@@ -48,6 +50,10 @@ export interface DrainOptions {
48
50
  git?: GitExec;
49
51
  /** Test hook — a drain that evaluates without an evidence store round trip. */
50
52
  treeMaterializer?: (repoDir: string, treeDigest: string) => string;
53
+ /** Active plugins — lifecycle hooks fire around integration when present. */
54
+ plugins?: LoadedPlugin[];
55
+ /** Collector — afterIntegrate errors surface here (post-hoc, cannot veto). */
56
+ hookErrors?: HookInvocationError[];
51
57
  }
52
58
 
53
59
  export interface DrainReport {
@@ -210,6 +216,39 @@ async function processUnit(
210
216
  return;
211
217
  }
212
218
 
219
+ // Lifecycle veto — beforeIntegrate hooks execute against the green candidate.
220
+ // A throwing hook means the integration environment cannot vouch: the unit
221
+ // requeues under the same bounded infra semantics as evaluation failures —
222
+ // never a silent skip, never an unbounded hang.
223
+ if (options.plugins && options.plugins.length > 0) {
224
+ const before = await invokeLifecycleHook(options.plugins, "beforeIntegrate", {
225
+ unitId: unit.id,
226
+ data: { candidateCommit: replay.candidateCommit, governedRef },
227
+ });
228
+ if (before.errors.length > 0) {
229
+ unit.attempts += 1;
230
+ if (unit.attempts > MAX_INFRA_REQUEUE_ATTEMPTS) {
231
+ transition(
232
+ store,
233
+ unit,
234
+ {
235
+ status: "refused",
236
+ reason: {
237
+ nodeId: "core.integration.hooks",
238
+ summary: `beforeIntegrate hook failed ${unit.attempts} times: ${before.errors.map((e) => `${e.pluginId}: ${e.error}`).join("; ")}`,
239
+ violations: 0,
240
+ },
241
+ evidenceKey: "",
242
+ },
243
+ actor,
244
+ );
245
+ return;
246
+ }
247
+ transition(store, unit, { status: "queued" }, actor);
248
+ return;
249
+ }
250
+ }
251
+
213
252
  // Green evaluation — integrate the candidate into the governed ref (single write point).
214
253
  integrateCandidate(git, repoDir, governedRef, replay.candidateCommit);
215
254
  transition(
@@ -222,6 +261,19 @@ async function processUnit(
222
261
  },
223
262
  actor,
224
263
  );
264
+
265
+ // afterIntegrate is post-hoc notification — errors cannot veto a landed unit,
266
+ // so they surface loudly in the drain report instead.
267
+ if (options.plugins && options.plugins.length > 0) {
268
+ const after = await invokeLifecycleHook(options.plugins, "afterIntegrate", {
269
+ unitId: unit.id,
270
+ outcome: "integrated",
271
+ data: { commitSha: replay.candidateCommit, governedRef },
272
+ });
273
+ if (after.errors.length > 0) {
274
+ options.hookErrors = [...(options.hookErrors ?? []), ...after.errors];
275
+ }
276
+ }
225
277
  }
226
278
 
227
279
  /**
@@ -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
+ }
@@ -10,7 +10,7 @@ spawn, no git mutation. This is auditability, not a sandbox.
10
10
  <CHANGE_SUMMARY><item>RFC-1648 (WP-5): initial capability-enforcing context.</item></CHANGE_SUMMARY>
11
11
  */
12
12
 
13
- import { access, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
13
+ import { access, mkdir, readFile, readdir, readlink, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
14
14
  import { execFile } from "node:child_process";
15
15
  import { dirname, resolve as pathResolve } from "node:path";
16
16
  import { promisify } from "node:util";
@@ -29,6 +29,32 @@ export interface ContextHostServices {
29
29
  };
30
30
  }
31
31
 
32
+ /* Dual-use commands (tag/branch/config) are conservative-denied: listing refs
33
+ belongs to for-each-ref plumbing, config reads to file parsing. A security
34
+ boundary refuses false negatives at the cost of false-positive friction. */
35
+ const MUTATING_GIT_OPS = new Set(["commit", "push", "update-ref", "checkout", "reset", "rebase", "merge", "cherry-pick", "apply", "commit-tree", "tag", "branch", "am", "stash", "rm", "mv", "clean", "gc", "fetch", "pull", "clone", "init", "add", "notes", "replace", "filter-branch", "update-index", "write-tree", "symbolic-ref", "worktree", "reflog", "config"]);
36
+
37
+ /* Git global flags consuming a separate value token — the subcommand is the first
38
+ positional after these are skipped. `--flag=value` forms self-skip. */
39
+ const GIT_VALUE_FLAGS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env", "--exec-path"]);
40
+
41
+ export function gitSubcommand(args: string[]): string | undefined {
42
+ let i = 0;
43
+ while (i < args.length) {
44
+ const a = args[i];
45
+ if (GIT_VALUE_FLAGS.has(a)) {
46
+ i += 2;
47
+ continue;
48
+ }
49
+ if (a.startsWith("-")) {
50
+ i += 1;
51
+ continue;
52
+ }
53
+ return a;
54
+ }
55
+ return undefined;
56
+ }
57
+
32
58
  /** Build a capability-enforcing PluginContext for one activated plugin. */
33
59
  export function createPluginContext(manifest: PluginManifest, host: ContextHostServices): PluginContext {
34
60
  const caps = manifest.capabilities ?? {};
@@ -72,6 +98,40 @@ export function createPluginContext(manifest: PluginManifest, host: ContextHostS
72
98
  if (fsGrant === "none") deny("filesystem", "list with filesystem:none");
73
99
  return readdir(scoped(dir));
74
100
  },
101
+ async readlink(path) {
102
+ if (fsGrant === "none") deny("filesystem", "readlink with filesystem:none");
103
+ return readlink(scoped(path));
104
+ },
105
+ async symlink(target, linkPath) {
106
+ if (fsGrant !== "readwrite") deny("filesystem", `symlink with filesystem:${fsGrant}`);
107
+ // The link PATH is sandboxed; the link TARGET is not re-validated — scoped()
108
+ // is a textual check, so a link pointing outside the root escapes on follow.
109
+ // readwrite is a trusted-within-workspace grant (it can already overwrite
110
+ // forge.yaml and hooks); symlink creation is consistent with that trust level.
111
+ // Plugins needing strict containment must not receive readwrite.
112
+ await symlink(target, scoped(linkPath));
113
+ },
114
+ async unlink(path) {
115
+ if (fsGrant !== "readwrite") deny("filesystem", `unlink with filesystem:${fsGrant}`);
116
+ await unlink(scoped(path));
117
+ },
118
+ async readFileBytes(path) {
119
+ if (fsGrant === "none") deny("filesystem", "readFileBytes with filesystem:none");
120
+ return new Uint8Array(await readFile(scoped(path)));
121
+ },
122
+ async rename(from, to) {
123
+ if (fsGrant !== "readwrite") deny("filesystem", `rename with filesystem:${fsGrant}`);
124
+ await rename(scoped(from), scoped(to));
125
+ },
126
+ async rm(path, opts) {
127
+ if (fsGrant !== "readwrite") deny("filesystem", `rm with filesystem:${fsGrant}`);
128
+ await rm(scoped(path), { recursive: opts?.recursive ?? false, force: true });
129
+ },
130
+ async stat(path) {
131
+ if (fsGrant === "none") deny("filesystem", "stat with filesystem:none");
132
+ const st = await stat(scoped(path));
133
+ return { size: st.size, mtimeMs: st.mtimeMs, isDirectory: st.isDirectory() };
134
+ },
75
135
  },
76
136
  evidence: {
77
137
  consult: host.hooks?.evidenceConsult ?? (async () => ({ hit: false })),
@@ -91,8 +151,17 @@ export function createPluginContext(manifest: PluginManifest, host: ContextHostS
91
151
  },
92
152
  git: {
93
153
  async exec(args) {
94
- if (!caps.gitMutation && ["commit", "push", "update-ref", "checkout", "reset", "rebase", "merge", "cherry-pick", "apply"].some((m) => args[0] === m)) {
95
- deny("gitMutation", `mutating git op refused: git ${args[0]}`);
154
+ // Redirection flags escape the workspace scope for reads AND writes — refused outright.
155
+ for (const a of args) {
156
+ if (a === "-C" || a === "--git-dir" || a === "--work-tree" || a.startsWith("--git-dir=") || a.startsWith("--work-tree=")) {
157
+ deny("filesystem", `git scope redirection refused: ${a}`);
158
+ }
159
+ }
160
+ if (!caps.gitMutation) {
161
+ const subcommand = gitSubcommand(args);
162
+ if (subcommand && MUTATING_GIT_OPS.has(subcommand)) {
163
+ deny("gitMutation", `mutating git op refused: git ${subcommand}`);
164
+ }
96
165
  }
97
166
  const { stdout } = await execFileAsync("git", args, { cwd: host.workspaceRoot });
98
167
  return stdout;
@@ -122,6 +191,17 @@ export function createPluginContext(manifest: PluginManifest, host: ContextHostS
122
191
  return { status: res.status, body: await res.text() };
123
192
  },
124
193
  },
194
+ env: {
195
+ get(key) {
196
+ if (!(caps.envKeys ?? []).includes(key)) {
197
+ deny("env", `env key not declared in manifest envKeys: ${key}`);
198
+ }
199
+ return process.env[key];
200
+ },
201
+ declared(key) {
202
+ return (caps.envKeys ?? []).includes(key);
203
+ },
204
+ },
125
205
  log: {
126
206
  info: (msg) => console.log(`[${pid}] ${msg}`),
127
207
  warn: (msg) => console.warn(`[${pid}] ${msg}`),
@@ -0,0 +1,51 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Lifecycle-hook invocation surface (RFC-1648) — the only path through which plugin
5
+ hooks execute. Fail-loud per hook: a throwing hook surfaces as an error result,
6
+ never silently swallowed; one hook's failure does not prevent the remaining
7
+ implementations of the same hook from running (each is isolated, all errors
8
+ collected). Hook execution order is plugin load order — deterministic.
9
+ </purpose>
10
+ <CHANGE_SUMMARY><item>RFC-1648 WP-5 completion: initial invocation surface.</item></CHANGE_SUMMARY>
11
+ */
12
+
13
+ import type { HookPayload, LifecycleHook, PluginContext } from "./types.ts";
14
+ import type { LoadedPlugin } from "./loader.ts";
15
+
16
+ export interface HookInvocationError {
17
+ pluginId: string;
18
+ hook: LifecycleHook;
19
+ error: string;
20
+ }
21
+
22
+ export interface HookInvocationResult {
23
+ ran: number;
24
+ errors: HookInvocationError[];
25
+ }
26
+
27
+ /** Invoke one lifecycle hook across all active plugins — deterministic load order, isolated failures. */
28
+ export async function invokeLifecycleHook(
29
+ plugins: LoadedPlugin[],
30
+ hook: LifecycleHook,
31
+ payload: HookPayload = {},
32
+ ): Promise<HookInvocationResult> {
33
+ let ran = 0;
34
+ const errors: HookInvocationError[] = [];
35
+ for (const plugin of plugins) {
36
+ for (const hookModule of plugin.hooks) {
37
+ if (hookModule.hook !== hook) continue;
38
+ ran += 1;
39
+ try {
40
+ await hookModule.run(plugin.ctx as PluginContext, payload);
41
+ } catch (err) {
42
+ errors.push({
43
+ pluginId: plugin.manifest.id,
44
+ hook,
45
+ error: err instanceof Error ? err.message : String(err),
46
+ });
47
+ }
48
+ }
49
+ }
50
+ return { ran, errors };
51
+ }
package/src/sdk/loader.ts CHANGED
@@ -18,7 +18,7 @@ import { pathToFileURL } from "node:url";
18
18
  import { parse as parseYaml } from "yaml";
19
19
 
20
20
  import { createPluginContext, type ContextHostServices } from "./context.ts";
21
- import { LIFECYCLE_HOOKS, PluginLoadError, type CommandModule, type PluginContext, type PluginManifest } from "./types.ts";
21
+ import { LIFECYCLE_HOOKS, PluginLoadError, type CommandModule, type HookModule, type PluginContext, type PluginManifest } from "./types.ts";
22
22
 
23
23
  /** The running core version — plugins' forgeRange is checked against this. */
24
24
  export function coreVersion(): string {
@@ -65,12 +65,7 @@ export function verifyManifest(raw: unknown, pluginDir: string): PluginManifest
65
65
  throw new PluginLoadError("capability-unknown", `unknown capability declared: ${key}`, m.id);
66
66
  }
67
67
  }
68
- const hooks = m.registers?.hooks ?? [];
69
- for (const h of hooks) {
70
- if (!LIFECYCLE_HOOKS.includes(h as never)) {
71
- throw new PluginLoadError("manifest-invalid", `unknown lifecycle hook: ${h}`, m.id);
72
- }
73
- }
68
+ // registers.hooks entries are module paths — validated at load, not here.
74
69
  void pluginDir;
75
70
  return { schema: "forge:plugin-manifest/v1", ...m } as PluginManifest;
76
71
  }
@@ -79,6 +74,7 @@ export interface LoadedPlugin {
79
74
  manifest: PluginManifest;
80
75
  ctx: PluginContext;
81
76
  commands: CommandModule[];
77
+ hooks: HookModule[];
82
78
  skillsDir: string | null;
83
79
  dir: string;
84
80
  }
@@ -141,8 +137,29 @@ export async function loadPlugin(entry: string, consumerRoot: string, host: Cont
141
137
  commands.push(command);
142
138
  }
143
139
 
140
+ // Register lifecycle-hook modules — fail-closed: each module's declared hook
141
+ // must be in the closed vocabulary; duplicates within one plugin refuse.
142
+ const hooks: HookModule[] = [];
143
+ const seenHooks = new Set<string>();
144
+ for (const hookPath of manifest.registers.hooks ?? []) {
145
+ const abs = join(dir, hookPath);
146
+ if (!existsSync(abs)) {
147
+ throw new PluginLoadError("registration-refused", `hook module missing: ${hookPath}`, manifest.id);
148
+ }
149
+ const mod = (await import(pathToFileURL(abs).href)) as { default?: HookModule; hook?: HookModule };
150
+ const hookMod = mod.default ?? mod.hook;
151
+ if (!hookMod || typeof hookMod.run !== "function" || !LIFECYCLE_HOOKS.includes(hookMod.hook)) {
152
+ throw new PluginLoadError("registration-refused", `hook module ${hookPath} does not implement HookModule`, manifest.id);
153
+ }
154
+ if (seenHooks.has(hookMod.hook)) {
155
+ throw new PluginLoadError("registration-refused", `duplicate hook implementation: ${hookMod.hook}`, manifest.id);
156
+ }
157
+ seenHooks.add(hookMod.hook);
158
+ hooks.push(hookMod);
159
+ }
160
+
144
161
  const skillsDir = manifest.registers.skills ? join(dir, manifest.registers.skills) : null;
145
- return { manifest, ctx, commands, skillsDir, dir };
162
+ return { manifest, ctx, commands, hooks, skillsDir, dir };
146
163
  }
147
164
 
148
165
  /** Plugin dependency resolution — refuse-on-conflict across the active set. */
package/src/sdk/types.ts CHANGED
@@ -54,6 +54,25 @@ export interface CommandModule {
54
54
  export type LifecycleHook = "onActivate" | "onDeactivate" | "beforeIntegrate" | "afterIntegrate";
55
55
  export const LIFECYCLE_HOOKS: readonly LifecycleHook[] = ["onActivate", "onDeactivate", "beforeIntegrate", "afterIntegrate"];
56
56
 
57
+ /**
58
+ * Hook module — self-describing like CommandModule: the default export names
59
+ * the hook it implements and carries the handler. `registers.hooks` entries are
60
+ * module paths relative to the plugin dir; fail-closed: the module's declared
61
+ * hook must be in the closed vocabulary, and duplicate hook implementations
62
+ * within one plugin refuse registration.
63
+ */
64
+ export interface HookModule {
65
+ hook: LifecycleHook;
66
+ run(ctx: PluginContext, payload: HookPayload): Promise<void>;
67
+ }
68
+
69
+ /** Payload passed to lifecycle hooks — the integration payload carries the unit id and outcome. */
70
+ export interface HookPayload {
71
+ unitId?: string;
72
+ outcome?: string;
73
+ data?: Record<string, unknown>;
74
+ }
75
+
57
76
  // ---- SDK ports — the ONLY platform access surface for plugin code. ----
58
77
 
59
78
  export interface WorkspaceIOPort {
@@ -61,6 +80,15 @@ export interface WorkspaceIOPort {
61
80
  writeFile(path: string, content: string): Promise<void>;
62
81
  exists(path: string): Promise<boolean>;
63
82
  list(dir: string, pattern?: string): Promise<string[]>;
83
+ /* Symlink primitives — atomic deploy swaps and artifact layouts are link-based;
84
+ readFile follows links and can never observe the link itself. */
85
+ readlink(path: string): Promise<string>;
86
+ symlink(target: string, linkPath: string): Promise<void>;
87
+ unlink(path: string): Promise<void>;
88
+ readFileBytes(path: string): Promise<Uint8Array>;
89
+ rename(from: string, to: string): Promise<void>;
90
+ rm(path: string, opts?: { recursive?: boolean }): Promise<void>;
91
+ stat(path: string): Promise<{ size: number; mtimeMs: number; isDirectory: boolean }>;
64
92
  }
65
93
 
66
94
  export interface EvidenceAccessPort {
@@ -109,27 +137,42 @@ export interface PluginContext {
109
137
  network: NetworkPort;
110
138
  log: LoggerPort;
111
139
  paths: PathResolverPort;
140
+ env: EnvPort;
141
+ }
142
+
143
+ /* Env access is allowlist-enforced: the manifest's envKeys declares exactly which
144
+ variables the plugin may read — secrets-adjacent access stays transparent and
145
+ auditable at the manifest surface, never a blanket process.env passthrough. */
146
+ export interface EnvPort {
147
+ /** Declared key → value or undefined; undeclared key → CapabilityViolation. */
148
+ get(key: string): string | undefined;
149
+ /** Whether the key is declared in the manifest — no leakage of presence vs value. */
150
+ declared(key: string): boolean;
112
151
  }
113
152
 
114
153
  /** Typed incompatibility error — fail-closed, no degraded modes. */
115
154
  export class PluginLoadError extends Error {
155
+ readonly kind: "forgerange-violation" | "manifest-invalid" | "capability-unknown" | "dependency-conflict" | "registration-refused";
156
+ readonly pluginId?: string;
116
157
  constructor(
117
- public readonly kind: "forgerange-violation" | "manifest-invalid" | "capability-unknown" | "dependency-conflict" | "registration-refused",
158
+ kind: "forgerange-violation" | "manifest-invalid" | "capability-unknown" | "dependency-conflict" | "registration-refused",
118
159
  message: string,
119
- public readonly pluginId?: string,
160
+ pluginId?: string,
120
161
  ) {
121
162
  super(message);
122
163
  this.name = "PluginLoadError";
164
+ this.kind = kind;
165
+ this.pluginId = pluginId;
123
166
  }
124
167
  }
125
168
 
126
169
  export class CapabilityViolation extends Error {
127
- constructor(
128
- public readonly capability: string,
129
- public readonly pluginId: string,
130
- detail: string,
131
- ) {
170
+ readonly capability: string;
171
+ readonly pluginId: string;
172
+ constructor(capability: string, pluginId: string, detail: string) {
132
173
  super(`capability violation: plugin "${pluginId}" has no ${capability} grant — ${detail}`);
133
174
  this.name = "CapabilityViolation";
175
+ this.capability = capability;
176
+ this.pluginId = pluginId;
134
177
  }
135
178
  }
@@ -0,0 +1,24 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>Ensure a .gitignore entry exists — idempotent, line-exact, append-only.
4
+ Generated-artifact writers (skills tree, forge state) use this so generated
5
+ output never counts as worktree dirt. Never reorders or rewrites existing lines.</purpose>
6
+ <CHANGE_SUMMARY><item>RFC-1648 WP-5-depth: initial — skills-tree untracking support.</item></CHANGE_SUMMARY>
7
+ */
8
+
9
+ import { existsSync, readFileSync, writeFileSync, appendFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+
12
+ /** Ensure `entry` appears as a line in `<workspaceRoot>/.gitignore`; returns true when added. */
13
+ export function ensureGitignoreEntry(workspaceRoot: string, entry: string): boolean {
14
+ const gitignorePath = join(workspaceRoot, ".gitignore");
15
+ if (!existsSync(gitignorePath)) {
16
+ writeFileSync(gitignorePath, `${entry}\n`, "utf8");
17
+ return true;
18
+ }
19
+ const existing = readFileSync(gitignorePath, "utf8");
20
+ if (existing.split("\n").some((line) => line.trim() === entry)) return false;
21
+ const sep = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
22
+ appendFileSync(gitignorePath, `${sep}${entry}\n`, "utf8");
23
+ return true;
24
+ }