@warpgogol/forge 10.1.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 (47) hide show
  1. package/CHANGELOG.md +15 -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/src/integration/drain.d.ts +6 -0
  6. package/dist/src/integration/drain.d.ts.map +1 -1
  7. package/dist/src/integration/drain.js +40 -0
  8. package/dist/src/integration/drain.js.map +1 -1
  9. package/dist/src/onboarding/init.d.ts.map +1 -1
  10. package/dist/src/onboarding/init.js +4 -0
  11. package/dist/src/onboarding/init.js.map +1 -1
  12. package/dist/src/onboarding/upgrade.d.ts.map +1 -1
  13. package/dist/src/onboarding/upgrade.js +77 -2
  14. package/dist/src/onboarding/upgrade.js.map +1 -1
  15. package/dist/src/sdk/cli-bridge.d.ts +26 -0
  16. package/dist/src/sdk/cli-bridge.d.ts.map +1 -0
  17. package/dist/src/sdk/cli-bridge.js +89 -0
  18. package/dist/src/sdk/cli-bridge.js.map +1 -0
  19. package/dist/src/sdk/hooks.d.ts +14 -0
  20. package/dist/src/sdk/hooks.d.ts.map +1 -0
  21. package/dist/src/sdk/hooks.js +35 -0
  22. package/dist/src/sdk/hooks.js.map +1 -0
  23. package/dist/src/sdk/loader.d.ts +2 -1
  24. package/dist/src/sdk/loader.d.ts.map +1 -1
  25. package/dist/src/sdk/loader.js +22 -7
  26. package/dist/src/sdk/loader.js.map +1 -1
  27. package/dist/src/sdk/types.d.ts +19 -2
  28. package/dist/src/sdk/types.d.ts.map +1 -1
  29. package/dist/src/sdk/types.js +2 -2
  30. package/dist/src/sdk/types.js.map +1 -1
  31. package/dist/src/utils/gitignore-entry.d.ts +3 -0
  32. package/dist/src/utils/gitignore-entry.d.ts.map +1 -0
  33. package/dist/src/utils/gitignore-entry.js +24 -0
  34. package/dist/src/utils/gitignore-entry.js.map +1 -0
  35. package/dist/src/utils/verifier-git.d.ts.map +1 -1
  36. package/dist/src/utils/verifier-git.js +18 -2
  37. package/dist/src/utils/verifier-git.js.map +1 -1
  38. package/package.json +3 -3
  39. package/src/integration/drain.ts +52 -0
  40. package/src/onboarding/init.ts +4 -0
  41. package/src/onboarding/upgrade.ts +84 -1
  42. package/src/sdk/cli-bridge.ts +94 -0
  43. package/src/sdk/hooks.ts +51 -0
  44. package/src/sdk/loader.ts +25 -8
  45. package/src/sdk/types.ts +30 -7
  46. package/src/utils/gitignore-entry.ts +24 -0
  47. package/src/utils/verifier-git.ts +17 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@warpgogol/forge",
3
- "version": "10.1.0",
3
+ "version": "10.1.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -309,8 +309,8 @@
309
309
  "default": "./dist/os/adversarial/adversarial.module.js"
310
310
  },
311
311
  "./sdk": {
312
- "types": "./dist/sdk/types.d.ts",
313
- "default": "./dist/sdk/types.js"
312
+ "types": "./dist/src/sdk/types.d.ts",
313
+ "default": "./dist/src/sdk/types.js"
314
314
  },
315
315
  "./sdk/context": {
316
316
  "types": "./dist/sdk/context.d.ts",
@@ -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
+ }
@@ -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 {
@@ -113,23 +132,27 @@ export interface PluginContext {
113
132
 
114
133
  /** Typed incompatibility error — fail-closed, no degraded modes. */
115
134
  export class PluginLoadError extends Error {
135
+ readonly kind: "forgerange-violation" | "manifest-invalid" | "capability-unknown" | "dependency-conflict" | "registration-refused";
136
+ readonly pluginId?: string;
116
137
  constructor(
117
- public readonly kind: "forgerange-violation" | "manifest-invalid" | "capability-unknown" | "dependency-conflict" | "registration-refused",
138
+ kind: "forgerange-violation" | "manifest-invalid" | "capability-unknown" | "dependency-conflict" | "registration-refused",
118
139
  message: string,
119
- public readonly pluginId?: string,
140
+ pluginId?: string,
120
141
  ) {
121
142
  super(message);
122
143
  this.name = "PluginLoadError";
144
+ this.kind = kind;
145
+ this.pluginId = pluginId;
123
146
  }
124
147
  }
125
148
 
126
149
  export class CapabilityViolation extends Error {
127
- constructor(
128
- public readonly capability: string,
129
- public readonly pluginId: string,
130
- detail: string,
131
- ) {
150
+ readonly capability: string;
151
+ readonly pluginId: string;
152
+ constructor(capability: string, pluginId: string, detail: string) {
132
153
  super(`capability violation: plugin "${pluginId}" has no ${capability} grant — ${detail}`);
133
154
  this.name = "CapabilityViolation";
155
+ this.capability = capability;
156
+ this.pluginId = pluginId;
134
157
  }
135
158
  }
@@ -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
+ }
@@ -8566,8 +8566,23 @@ export async function sessionIgnoreRulePaths(
8566
8566
  }
8567
8567
  }
8568
8568
  if (found.length === 0) return [];
8569
- const trackedSet = await tracked(found, root);
8570
- return trackedSet === null ? found : found.filter((p) => !trackedSet.has(p));
8569
+ // Inert-rule exclusion: git never reads `.gitignore` files inside
8570
+ // ignored directories — traversal stops at the excluded parent, so a
8571
+ // rule file under `node_modules/` (npm packages ship them routinely)
8572
+ // can hide nothing and is not session-authored dirt. `check-ignore`
8573
+ // reproduces git's own traversal verdict exactly; a failed read fails
8574
+ // closed (every candidate counts).
8575
+ let effective = found;
8576
+ const ci = await verifierGit(root, ["check-ignore", "--stdin", "-z"], {
8577
+ input: Buffer.from(found.map((p) => `${p}\0`).join(""), "utf8"),
8578
+ });
8579
+ if (ci.exitCode === 0 || ci.exitCode === 1) {
8580
+ const inert = new Set(ci.stdout.split("\0").filter((p) => p.length > 0));
8581
+ effective = found.filter((p) => !inert.has(p));
8582
+ }
8583
+ if (effective.length === 0) return [];
8584
+ const trackedSet = await tracked(effective, root);
8585
+ return trackedSet === null ? effective : effective.filter((p) => !trackedSet.has(p));
8571
8586
  }
8572
8587
 
8573
8588
  /**