@aiwg/cli 2026.11.3 → 2026.11.5

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 (169) hide show
  1. package/agentic/code/addons/aiwg-hooks/canonical/aiwg-prompt-discovery.yaml +3 -2
  2. package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +12 -9
  3. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +2 -0
  4. package/agentic/code/addons/composition-engine/lib/runtime.mjs +5 -26
  5. package/agentic/code/addons/composition-engine/schemas/flow-graph.schema.json +22 -0
  6. package/agentic/code/providers/capability-matrix.yaml +85 -18
  7. package/agentic/code/providers/model-capabilities.v1.json +35 -27
  8. package/dist/src/a2a/hitl-authorization.js +46 -0
  9. package/dist/src/a2a/hitl-driver.js +5 -5
  10. package/dist/src/artifacts/browser-export.js +2 -0
  11. package/dist/src/artifacts/framework-source-digest.js +1 -1
  12. package/dist/src/artifacts/index-builder.js +9 -27
  13. package/dist/src/artifacts/index-capability.js +24 -0
  14. package/dist/src/artifacts/query-engine-discover-output.js +8 -3
  15. package/dist/src/artifacts/query-engine-rules.js +29 -11
  16. package/dist/src/artifacts/query-engine-scoring.js +5 -5
  17. package/dist/src/artifacts/query-engine-show-card.js +5 -1
  18. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  19. package/dist/src/artifacts/query-engine-show.js +3 -3
  20. package/dist/src/artifacts/query-engine-templates.js +10 -4
  21. package/dist/src/artifacts/query-engine-verbose.js +18 -4
  22. package/dist/src/artifacts/relations-builder.js +1 -0
  23. package/dist/src/artifacts/types.js +1 -1
  24. package/dist/src/cli/handlers/checkpoint-handoff.js +2 -1
  25. package/dist/src/cli/handlers/guided-setup.js +3 -1
  26. package/dist/src/cli/handlers/refresh-managed-deployment.js +17 -5
  27. package/dist/src/cli/handlers/rules.js +1 -1
  28. package/dist/src/cli/handlers/script-runner.js +7 -4
  29. package/dist/src/cli/handlers/sessions.js +1 -1
  30. package/dist/src/cli/handlers/steward-format.js +12 -0
  31. package/dist/src/cli/handlers/steward.js +1 -1
  32. package/dist/src/cli/handlers/use.js +14 -6
  33. package/dist/src/cli/handlers/utility-doctor.js +9 -2
  34. package/dist/src/cli/handlers/workspace.js +1 -1
  35. package/dist/src/cli/services/deployment-probe-scope.js +40 -0
  36. package/dist/src/cli/services/deployment-verification.js +4 -5
  37. package/dist/src/config/aiwg-config.js +6 -0
  38. package/dist/src/config/authorization-cli.js +61 -3
  39. package/dist/src/config/cli-help.js +1 -1
  40. package/dist/src/config/cli.js +4 -2
  41. package/dist/src/config/host-resource-runtime.mjs +1 -1
  42. package/dist/src/config/user-registry.js +9 -1
  43. package/dist/src/config/worker-owner-lock.js +90 -10
  44. package/dist/src/decision/graph-flow-adapter.js +1 -1
  45. package/dist/src/effects/authorization-grant.js +50 -0
  46. package/dist/src/effects/authorization-store.js +130 -0
  47. package/dist/src/effects/index.js +2 -0
  48. package/dist/src/effects/ledger.js +1 -0
  49. package/dist/src/effects/lifecycle.js +1 -1
  50. package/dist/src/effects/reader.js +4 -0
  51. package/dist/src/effects/records.js +4 -0
  52. package/dist/src/effects/schema.js +2 -0
  53. package/dist/src/extensions/claude-hooks-installer.js +7 -7
  54. package/dist/src/extensions/manifest.js +6 -0
  55. package/dist/src/extensions/muse-managed-hooks.js +11 -0
  56. package/dist/src/extensions/project-local-discovery.js +21 -1
  57. package/dist/src/extensions/project-local-scaffold.js +19 -7
  58. package/dist/src/extensions/user-hook-diagnostics.js +32 -0
  59. package/dist/src/extensions/verified-hook-command.js +32 -0
  60. package/dist/src/lint/rule-conflicts.js +52 -0
  61. package/dist/src/lint/runner.js +3 -0
  62. package/dist/src/mcp/cli.mjs +3 -1
  63. package/dist/src/mcp/elicitation.mjs +30 -0
  64. package/dist/src/mcp/grok-build-config.mjs +1 -1
  65. package/dist/src/mcp/muse-native-config.mjs +1 -0
  66. package/dist/src/mcp/server.mjs +2 -0
  67. package/dist/src/mcp/tools/authorization.mjs +78 -0
  68. package/dist/src/models/factory-models.js +144 -0
  69. package/dist/src/models/model-capabilities.v1.json +35 -27
  70. package/dist/src/models/model-discovery.js +7 -3
  71. package/dist/src/models/worker-installation.d.mts +2 -0
  72. package/dist/src/models/worker-installation.mjs +11 -2
  73. package/dist/src/models/worker-invocation-policy.js +25 -1
  74. package/dist/src/models/wrapper-enforcement.js +1 -1
  75. package/dist/src/policy/authorization-capture.js +64 -0
  76. package/dist/src/policy/authorization-operations.js +108 -0
  77. package/dist/src/policy/hitl-check.js +3 -2
  78. package/dist/src/policy/hitl-consume.js +14 -0
  79. package/dist/src/policy/hitl-durable-store.js +60 -0
  80. package/dist/src/policy/hitl-durable.js +60 -0
  81. package/dist/src/policy/hitl-receipt.js +5 -0
  82. package/dist/src/policy/hitl.js +44 -6
  83. package/dist/src/policy/repo-access.js +3 -1
  84. package/dist/src/process/bounded-child-process.mjs +49 -39
  85. package/dist/src/providers/capability-matrix.yaml +85 -18
  86. package/dist/src/providers/deployment-ownership.d.mts +1 -0
  87. package/dist/src/providers/deployment-ownership.mjs +29 -3
  88. package/dist/src/providers/deployment-preservation.mjs +44 -3
  89. package/dist/src/providers/grok-build-acp.js +13 -5
  90. package/dist/src/providers/grok-build-dispatch.js +35 -2
  91. package/dist/src/providers/grok-build-headless.js +171 -77
  92. package/dist/src/providers/grok-build-inspect.js +1 -0
  93. package/dist/src/providers/grok-build-paths.js +2 -0
  94. package/dist/src/providers/muse-paths.js +4 -2
  95. package/dist/src/providers/provider-context-contracts.js +12 -4
  96. package/dist/src/providers/provider-definition-schema.js +6 -0
  97. package/dist/src/providers/provider-seeds-1.js +3 -3
  98. package/dist/src/providers/provider-seeds-2.js +6 -4
  99. package/dist/src/providers/provider-seeds-3.js +6 -6
  100. package/dist/src/rules/activation.d.mts +2 -0
  101. package/dist/src/rules/activation.mjs +16 -7
  102. package/dist/src/rules/inline-budget.d.mts +2 -1
  103. package/dist/src/rules/inline-budget.mjs +4 -2
  104. package/dist/src/rules/inventory.js +3 -0
  105. package/dist/src/rules/precedence.d.mts +6 -0
  106. package/dist/src/rules/precedence.mjs +49 -0
  107. package/dist/src/rules/project-precedence.js +73 -0
  108. package/dist/src/rules/rule-frontmatter.schema.json +15 -0
  109. package/dist/src/serve/a2a-terminal-observer.js +12 -3
  110. package/dist/src/serve/mission-hitl.js +20 -1
  111. package/dist/src/serve/worker-stdin-frame.mjs +1 -1
  112. package/dist/src/sessions/adapters/grok-build-fallback.js +33 -0
  113. package/dist/src/sessions/adapters/grok-build-native-records.js +134 -0
  114. package/dist/src/sessions/adapters/grok-build-native.js +237 -98
  115. package/dist/src/sessions/adapters/grok-build.js +95 -32
  116. package/dist/src/sessions/grok-build-cli-output.js +113 -0
  117. package/dist/src/sessions/grok-build-cli.js +4 -28
  118. package/dist/src/sessions/normalization.js +1 -1
  119. package/dist/src/smiths/context-pipeline/bridge-ownership.js +4 -3
  120. package/dist/src/smiths/context-pipeline/finalization.js +5 -0
  121. package/dist/src/smiths/context-pipeline/generator.js +1 -1
  122. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +20 -17
  123. package/dist/src/smiths/context-pipeline/workspace-doctor.js +6 -1
  124. package/dist/src/smiths/context-pipeline/workspace-document.js +6 -0
  125. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -12
  126. package/dist/src/smiths/hook-bridge/codex-translator.js +11 -14
  127. package/dist/src/smiths/hook-bridge/codex-trust.js +7 -2
  128. package/dist/src/smiths/hook-bridge/copilot-translator.js +2 -1
  129. package/dist/src/smiths/hook-bridge/factory-trust.js +2 -2
  130. package/dist/src/smiths/hook-bridge/grok-build-translator.js +3 -1
  131. package/dist/src/smiths/hook-bridge/hermes-prompt-discovery.js +81 -0
  132. package/dist/src/smiths/hook-bridge/hermes-translator.js +5 -3
  133. package/dist/src/smiths/hook-bridge/hermes-trust.js +65 -0
  134. package/dist/src/smiths/hook-bridge/index.js +3 -1
  135. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +3 -2
  136. package/package.json +7 -1
  137. package/tools/agents/deploy-agents.mjs +9 -8
  138. package/tools/agents/deploy-options.mjs +3 -0
  139. package/tools/agents/providers/base-frontmatter.mjs +3 -2
  140. package/tools/agents/providers/base-inventory.mjs +3 -1
  141. package/tools/agents/providers/base-kernel-skills.mjs +11 -5
  142. package/tools/agents/providers/claude-post-deploy.mjs +1 -1
  143. package/tools/agents/providers/codex-post-deploy.mjs +1 -1
  144. package/tools/agents/providers/generic.mjs +66 -0
  145. package/tools/agents/providers/grok-build.mjs +34 -41
  146. package/tools/agents/providers/model-wrapper.mjs +2 -5
  147. package/tools/agents/providers/muse-hooks.mjs +13 -11
  148. package/tools/agents/providers/muse-prompt-discovery.mjs +5 -1
  149. package/tools/agents/providers/muse.mjs +2 -1
  150. package/tools/agents/providers/openclaw.mjs +2 -1
  151. package/tools/agents/providers/rule-deployment-commit.mjs +3 -0
  152. package/tools/agents/providers/rule-deployment-prepare.mjs +7 -5
  153. package/tools/agents/providers/rule-deployment-state.mjs +14 -6
  154. package/tools/agents/providers/rule-projection.mjs +39 -4
  155. package/tools/agents/providers/rule-startup.mjs +11 -10
  156. package/tools/agents/providers/skill-copy-prune.mjs +12 -0
  157. package/tools/agents/providers/staged-directory-reference.mjs +14 -0
  158. package/tools/agents/providers/stale-artifact-prune.mjs +24 -10
  159. package/tools/agents/providers/user-hooks.mjs +26 -0
  160. package/tools/cli/authorization-health.mjs +20 -0
  161. package/tools/cli/workspace-status.mjs +7 -0
  162. package/tools/commands/deploy-prompts-codex.mjs +15 -1
  163. package/tools/ralph-external/lib/claude-adapter.mjs +2 -0
  164. package/tools/ralph-external/lib/factory-adapter.mjs +6 -2
  165. package/tools/ralph-external/lib/worker-inputs.mjs +20 -1
  166. package/tools/ralph-external/lib/worker-isolation.mjs +1 -0
  167. package/tools/ralph-external/lib/worker-termination.mjs +21 -12
  168. package/tools/ralph-external/session-launcher.mjs +22 -17
  169. package/vscode-extension/schemas/aiwg.config.v1.json +20 -0
@@ -54,7 +54,7 @@ import path from 'node:path';
54
54
  import { randomUUID } from 'node:crypto';
55
55
  import { importImpl } from '../../_resolve-impl.mjs';
56
56
  import { stripJsonComments } from './base.mjs';
57
- import { deployPromptDiscovery } from './muse-prompt-discovery.mjs';
57
+ import { museHooksForTarget, deployPromptDiscovery } from './muse-prompt-discovery.mjs';
58
58
  import { resolveMuseXdgSkillsDir, museXdgSkillsDirRemediation } from './muse-paths.mjs';
59
59
 
60
60
  const { AIWG_MANAGED_HOOKS } = await importImpl(import.meta.url, 'extensions/muse-managed-hooks.js');
@@ -185,9 +185,9 @@ export const MUSE_HOOK_EVENTS = [
185
185
  export { AIWG_MANAGED_HOOKS };
186
186
 
187
187
  /** Canonical group payloads keyed by hook id, for merge/prune identity. */
188
- function managedGroupsById() {
188
+ function managedGroupsById(desired = AIWG_MANAGED_HOOKS) {
189
189
  const out = new Map();
190
- for (const hook of AIWG_MANAGED_HOOKS) out.set(hook.id, { event: hook.event, group: hook.group });
190
+ for (const hook of desired) out.set(hook.id, { event: hook.event, group: hook.group });
191
191
  return out;
192
192
  }
193
193
 
@@ -306,13 +306,15 @@ function readHooksSidecar(sidecarPath) {
306
306
  * byte-identical to the canonical set) are preserved untouched. Managed
307
307
  * groups are replaced with the canonical payload, repairing drift.
308
308
  */
309
- export function mergeManagedHooks(existingDoc, sidecar) {
310
- const byId = managedGroupsById();
309
+ export function mergeManagedHooks(existingDoc, sidecar, desired = AIWG_MANAGED_HOOKS) {
310
+ const byId = managedGroupsById(desired);
311
+ const legacy = managedGroupsById();
311
312
  const recorded = new Map();
312
313
  for (const entry of sidecar.hooks || []) {
313
314
  if (entry && typeof entry.id === 'string') recorded.set(entry.id, entry);
314
315
  }
315
316
  const identities = managedIdentities(byId, recorded);
317
+ for (const [key, id] of managedIdentities(legacy, new Map())) identities.set(key, id);
316
318
 
317
319
  // A group is AIWG-managed when its identity matches the current set or a
318
320
  // sidecar-recorded payload. Returns the hook id or null.
@@ -323,7 +325,7 @@ export function mergeManagedHooks(existingDoc, sidecar) {
323
325
  const existingHooks = (existingDoc && existingDoc.hooks) || {};
324
326
 
325
327
  // Preserve original event order; managed events are refreshed in place.
326
- const desiredEvents = new Set([...AIWG_MANAGED_HOOKS.map((h) => h.event)]);
328
+ const desiredEvents = new Set([...desired.map((h) => h.event)]);
327
329
  const eventOrder = [...Object.keys(existingHooks)];
328
330
  for (const event of desiredEvents) {
329
331
  if (!eventOrder.includes(event)) eventOrder.push(event);
@@ -341,7 +343,7 @@ export function mergeManagedHooks(existingDoc, sidecar) {
341
343
  operatorGroups.push(group);
342
344
  }
343
345
  }
344
- const desiredHere = AIWG_MANAGED_HOOKS.filter((h) => h.event === event);
346
+ const desiredHere = desired.filter((h) => h.event === event);
345
347
  const nextGroups = [...operatorGroups];
346
348
  for (const hook of desiredHere) {
347
349
  nextGroups.push(hook.group);
@@ -368,10 +370,10 @@ export function mergeManagedHooks(existingDoc, sidecar) {
368
370
  return { doc: merged, changed, plan };
369
371
  }
370
372
 
371
- function buildHooksSidecar() {
373
+ function buildHooksSidecar(desired = AIWG_MANAGED_HOOKS) {
372
374
  return {
373
375
  version: 1,
374
- hooks: AIWG_MANAGED_HOOKS.map((h) => ({ id: h.id, event: h.event, group: h.group })),
376
+ hooks: desired.map((h) => ({ id: h.id, event: h.event, group: h.group })),
375
377
  };
376
378
  }
377
379
 
@@ -389,7 +391,7 @@ export function deployMuseHooks(targetDir, opts = {}) {
389
391
 
390
392
  const { doc: existingDoc, raw: existingRaw, existed } = readHooksDoc(hooksPath);
391
393
  const sidecar = readHooksSidecar(sidecarPath);
392
- const { doc: merged, changed, plan } = mergeManagedHooks(existingDoc, sidecar);
394
+ const { doc: merged, changed, plan } = mergeManagedHooks(existingDoc, sidecar, museHooksForTarget(opts.logicalOutputPath?.(targetDir) || targetDir, opts.scope));
393
395
 
394
396
  const beforeText = existed ? existingRaw : '(no .muse/hooks.json — will be created)';
395
397
  const afterText = canonicalJson(merged);
@@ -418,7 +420,7 @@ export function deployMuseHooks(targetDir, opts = {}) {
418
420
  fs.mkdirSync(path.dirname(hooksPath), { recursive: true });
419
421
  const backupPath = backupIfHandEdited(hooksPath, existingDoc, existingRaw, existed);
420
422
  atomicWrite(hooksPath, afterText);
421
- atomicWrite(sidecarPath, canonicalJson(buildHooksSidecar()));
423
+ atomicWrite(sidecarPath, canonicalJson(buildHooksSidecar(museHooksForTarget(opts.logicalOutputPath?.(targetDir) || targetDir, opts.scope))));
422
424
  log(`Muse hooks: merged ${plan.length} managed change(s) into ${hooksPath}`);
423
425
  if (backupPath) log(` backup (comments/formatting not preserved): ${backupPath}`);
424
426
  for (const step of plan) log(` ${step}`);
@@ -5,7 +5,7 @@ import { fileURLToPath } from 'node:url';
5
5
 
6
6
  import { importImpl } from '../../_resolve-impl.mjs';
7
7
 
8
- export const { promptDiscoveryHook } = await importImpl(import.meta.url, 'extensions/muse-managed-hooks.js');
8
+ export const { promptDiscoveryHook, managedMuseHooks } = await importImpl(import.meta.url, 'extensions/muse-managed-hooks.js');
9
9
 
10
10
  export function deployPromptDiscovery(targetDir) {
11
11
  const directory = path.join(targetDir, '.muse', 'hooks');
@@ -16,3 +16,7 @@ export function deployPromptDiscovery(targetDir) {
16
16
  fs.copyFileSync(fileURLToPath(new URL('../../../agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs', import.meta.url)),
17
17
  path.join(directory, 'aiwg-prompt-discovery.cjs'));
18
18
  }
19
+
20
+ export function museHooksForTarget(targetDir, scope) {
21
+ return managedMuseHooks(targetDir, fs.readFileSync(fileURLToPath(new URL('../../../agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs', import.meta.url))), scope);
22
+ }
@@ -50,6 +50,7 @@ import {
50
50
  museXdgSkillsDirRemediation,
51
51
  } from './muse-paths.mjs';
52
52
  import { importImpl } from '../../_resolve-impl.mjs';
53
+ const { MUSE_STANDARD_SKILLS_PATH } = await importImpl(import.meta.url, 'providers/muse-paths.js');
53
54
  const { captureDeploymentOutputs, recordDeploymentOutputs } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
54
55
  import { assertMuseUserSettingsPath, deployMuseHooks, deployMuseMcp } from './muse-hooks.mjs';
55
56
 
@@ -72,7 +73,7 @@ export const kernelSkillsPath = '.agents/skills';
72
73
 
73
74
  // Opt-in standard-tier mirror (only with --copy-all): siblings of the
74
75
  // project skills root, never the user XDG root and never ~/.agents/skills.
75
- const STANDARD_MIRROR_SUBDIR = '.agents/.aiwg/skills';
76
+ const STANDARD_MIRROR_SUBDIR = MUSE_STANDARD_SKILLS_PATH;
76
77
 
77
78
  export const support = {
78
79
  agents: 'indexed',
@@ -542,12 +542,13 @@ async function deploySelected(opts) {
542
542
  // sit inert on disk (no discover-first, no rule routing — the agent treats
543
543
  // `address-issues` as a generic query). Preserves operator content outside
544
544
  // the AIWG-managed section.
545
+ // Include kernel-only skill passes: both workspace files are startup context.
545
546
  // Run once, only from the batch whose srcRoot actually contains the framework
546
547
  // template (the repo/framework root). `aiwg use` invokes deploy() once per
547
548
  // framework AND per addon with different srcRoots; addon batches would warn
548
549
  // "template not found". The idempotent skip in createAgentsMdFromTemplate also
549
550
  // guards against double-injection across batches.
550
- if (!commandsOnly && !skillsOnly && !rulesOnly) {
551
+ if (!commandsOnly && !rulesOnly && (!skillsOnly || opts.kernelOnly)) {
551
552
  const templatePath = path.join(
552
553
  srcRoot, 'agentic', 'code', 'frameworks', 'sdlc-complete', 'templates', 'openclaw', 'AGENTS.md.aiwg-template',
553
554
  );
@@ -22,6 +22,7 @@ import {
22
22
  walk,
23
23
  } from './rule-delivery-surface.mjs';
24
24
  import { prepareRuleDeployment } from './rule-deployment-prepare.mjs';
25
+ import { ruleRemovalReason } from './rule-projection.mjs';
25
26
  import {
26
27
  captureAnchors,
27
28
  capturePreimage,
@@ -82,6 +83,8 @@ export function commitRuleDeploymentPlan(plan) {
82
83
  promoteDirectories(to, from, rel => delegated(from, rel));
83
84
  const after = new Set(walk(to).map(file => path.relative(to, file)).filter(rel => !delegated(from, rel)));
84
85
  for (const rel of before.keys()) if (!delegated(from, rel) && !after.has(rel)) {
86
+ const reason = ruleRemovalReason(path.join(from, rel));
87
+ if (reason) console.warn(`Removing ${path.join(from, rel)}${reason}`);
85
88
  fs.rmSync(path.join(from, rel), { force: true });
86
89
  // A pruned managed skill must disappear as a directory too. Remove
87
90
  // only empty parents absent from the staged result; preserve siblings.
@@ -44,10 +44,11 @@ import {
44
44
  stagedCleanups,
45
45
  verifyInputPool,
46
46
  } from './rule-deployment-state.mjs';
47
- import { inlineStartup, projectRules } from './rule-projection.mjs';
47
+ import { ruleRemovalReason, inlineStartup, projectRules } from './rule-projection.mjs';
48
48
  const { captureDeploymentOutputs, recordDeploymentOutputs } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
49
49
  const { preserveDeploymentOutputs } = await importImpl(import.meta.url, 'providers/deployment-preservation.mjs');
50
50
  import { retireInlineStartup } from './rule-startup.mjs';
51
+ import { createStagedDirectoryReference } from './staged-directory-reference.mjs';
51
52
 
52
53
  /** Stage only provider/context output, never the user's source tree. On failure
53
54
  * no staged output (including skills and behaviors) reaches the prior deployment. */
@@ -130,7 +131,7 @@ export async function prepareRuleDeployment(original, provider, deploy) {
130
131
  // The projector helpers execute installed code but receive the snapshot as data.
131
132
  for (const rel of ['tools', 'dist', 'node_modules', 'src']) {
132
133
  const from = path.join(corpusRoot, rel), to = path.join(snapshotRoot, rel);
133
- if (fs.existsSync(from)) fs.symlinkSync(from, to, 'dir');
134
+ if (fs.existsSync(from)) createStagedDirectoryReference(from, to);
134
135
  }
135
136
  }
136
137
  // Keep standalone fixture/bundle snapshots from inheriting the installed
@@ -258,8 +259,9 @@ export async function prepareRuleDeployment(original, provider, deploy) {
258
259
  kernel = to;
259
260
  }
260
261
  // Codex's legacy prompt helper is home-global. Give it an isolated home and
261
- // promote only its output after validation.
262
- if (provider.name === 'codex' && (original.deployCommands || original.commandsOnly)) mount(path.join(os.homedir(), '.codex', 'prompts'), path.join(home, '.codex', 'prompts'));
262
+ // promote only its output after validation. Kernel upgrades also need the
263
+ // legacy prompt preimages so ownership can adopt known October bytes.
264
+ if (provider.name === 'codex' && (original.deployCommands || original.commandsOnly || original.kernelOnly)) mount(path.join(os.homedir(), '.codex', 'prompts'), path.join(home, '.codex', 'prompts'));
263
265
  let hermesLegacySkills;
264
266
  let legacyCodexSkills;
265
267
  if (provider.name === 'hermes') {
@@ -425,7 +427,7 @@ export async function prepareRuleDeployment(original, provider, deploy) {
425
427
  const file = path.join(to, rel);
426
428
  if (before.get(rel) !== fileDigest(file)) console.log(`[dry-run] Would write ${normalize(file)}`);
427
429
  }
428
- for (const rel of before.keys()) if (!delegated(from, rel) && !after.has(rel)) console.log(`[dry-run] Would remove ${path.join(from, rel)}`);
430
+ for (const rel of before.keys()) if (!delegated(from, rel) && !after.has(rel)) console.log(`[dry-run] Would remove ${path.join(from, rel)}${ruleRemovalReason(path.join(from, rel))}`);
429
431
  }
430
432
  for (const name of rootNames) {
431
433
  const file = path.join(stage, name);
@@ -5,6 +5,7 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { resolveAiwgRoot } from './base.mjs';
7
7
  import { fileDigest, resolveProjectAiwgDir, trackTemporaryDirectory } from './rule-delivery-surface.mjs';
8
+ import { createStagedDirectoryReference } from './staged-directory-reference.mjs';
8
9
 
9
10
  // Plans contain only JSON values and a scratch directory. The preparing process
10
11
  // owns that directory until disposal; cross-process transfer needs a separate lease.
@@ -32,10 +33,11 @@ export function capturePreimage(file, ancestors = new Set()) {
32
33
  }
33
34
  if (stat.isFile()) return { kind: 'file', mode, digest: fileDigest(file) };
34
35
  if (stat.isDirectory()) return { kind: 'directory', mode, entries: fs.readdirSync(file).sort().map(name => [name, capturePreimage(path.join(file, name), new Set([...ancestors, path.resolve(file)]))]) };
35
- throw new Error(`Unsupported deployment preimage: ${file}`);
36
+ // Runtime IPC and other opaque entries are sealed by type, never read/copied.
37
+ return { kind: 'special', mode, type: stat.mode & fs.constants.S_IFMT };
36
38
  }
37
- // cpSync materializes links; compare its output with the recursively resolved
38
- // content while retaining the original link-shaped preimage for commit drift.
39
+ // Materialize regular content only. Retain link/special-shaped live preimages
40
+ // for commit drift, but omit dangling links and opaque entries from the stage.
39
41
  export function materializeInput(from, to, ancestors = new Set(), parentReady = false) {
40
42
  let stat;
41
43
  try { stat = fs.statSync(from); } catch (error) {
@@ -54,11 +56,14 @@ export function materializeInput(from, to, ancestors = new Set(), parentReady =
54
56
  } else if (stat.isFile()) {
55
57
  if (!parentReady) fs.mkdirSync(path.dirname(to), { recursive: true });
56
58
  fs.copyFileSync(from, to); fs.chmodSync(to, stat.mode & 0o7777);
57
- } else throw new Error(`Unsupported deployment input: ${from}`);
59
+ }
58
60
  }
59
61
  export function materializedPreimage(state) {
60
62
  if (state.kind === 'symlink') return materializedPreimage(state.resolved);
61
- if (state.kind === 'directory') return { ...state, entries: state.entries.map(([name, child]) => [name, materializedPreimage(child)]) };
63
+ if (state.kind === 'special') return { kind: 'missing' };
64
+ if (state.kind === 'directory') return { ...state, entries: state.entries
65
+ .map(([name, child]) => [name, materializedPreimage(child)])
66
+ .filter(([, child]) => child.kind !== 'missing') };
62
67
  return state;
63
68
  }
64
69
  export function snapshotPreimages(paths) {
@@ -161,7 +166,7 @@ export function createRuleDeploymentInputPool(srcRoot) {
161
166
  }
162
167
  for (const rel of ['tools', 'dist', 'node_modules', 'src']) {
163
168
  const from = path.join(corpusRoot, rel), to = path.join(snapshotRoot, rel);
164
- if (fs.existsSync(from)) { fs.symlinkSync(from, to, 'dir'); trustedExec.push(from); }
169
+ if (fs.existsSync(from)) { createStagedDirectoryReference(from, to); trustedExec.push(from); }
165
170
  }
166
171
  }
167
172
  setPoolWritable(snapshotRoot, false);
@@ -231,6 +236,9 @@ export function validPreimageState(state) {
231
236
  if (!state || typeof state !== 'object' || Array.isArray(state) || typeof state.kind !== 'string') return false;
232
237
  if (state.kind === 'missing') return Object.keys(state).length === 1;
233
238
  if (!Number.isSafeInteger(state.mode) || state.mode < 0) return false;
239
+ if (state.kind === 'special') return Object.keys(state).length === 3 && Number.isSafeInteger(state.type)
240
+ && state.type === (state.type & fs.constants.S_IFMT)
241
+ && ![fs.constants.S_IFREG, fs.constants.S_IFDIR, fs.constants.S_IFLNK].includes(state.type);
234
242
  if (state.kind === 'file') return Object.keys(state).length === 3 && /^[a-f0-9]{64}$/.test(state.digest);
235
243
  if (state.kind === 'symlink') return Object.keys(state).length === 4 && typeof state.target === 'string' && validPreimageState(state.resolved);
236
244
  return state.kind === 'directory' && Object.keys(state).length === 3 && Array.isArray(state.entries) && state.entries.every(entry =>
@@ -10,9 +10,17 @@ import { writeContextFileSync } from './context-write.mjs';
10
10
  export { inlineStartup } from './rule-startup.mjs';
11
11
  const { parseRuleFrontmatter } = await importImpl(import.meta.url, 'rules/activation.mjs');
12
12
  const { renderCoreStartup } = await importImpl(import.meta.url, 'rules/core-startup.mjs');
13
+ const { deploymentOwner } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
13
14
  const read = file => fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
14
15
  const walk = dir => fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry =>
15
16
  entry.isDirectory() ? walk(path.join(dir, entry.name)) : [path.join(dir, entry.name)]) : [];
17
+ const deployedRule = file => parseRuleFrontmatter(read(file).replace(/^<!-- aiwg:managed[^\n]*-->\r?\n/, ''));
18
+ export function ruleRemovalReason(file) {
19
+ if (!/[/\\](?:rules|rule|instructions)[/\\].*\.(?:md|mdc)$/.test(file)) return '';
20
+ const parsed = deployedRule(file);
21
+ const level = parsed.data?.enforcement === 'critical' ? 'critical rule' : 'rule';
22
+ return ` (${level} retired because the selected deployment no longer projects its source at this path)`;
23
+ }
16
24
  const put = (file, content) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, content); };
17
25
  export const nativeRuleLoader = name => ['claude', 'cursor', 'grok-build', 'windsurf', 'opencode'].includes(name);
18
26
  export const nativePathLoader = name => ['claude', 'cursor', 'windsurf'].includes(name);
@@ -57,18 +65,44 @@ export function projectRules(opts, provider) {
57
65
  const extension = provider.name === 'cursor' ? '.mdc' : '.md';
58
66
  const managed = content => addManagedMarker(content, opts.deployVersion, opts.deploySource || 'bundled');
59
67
  const deployedSources = new Map();
68
+ const owner = deploymentOwner(opts);
69
+ const selectedSource = rule => !opts.bundleOnly || rule.file.startsWith(`${opts.srcRoot}${path.sep}`);
70
+ const manifestPath = path.join(rulesDir, '.aiwg-manifest.json');
71
+ const manifest = fs.existsSync(manifestPath) ? JSON.parse(read(manifestPath)) : { managed: {} };
72
+ const previousManaged = opts.ownershipBefore
73
+ ? JSON.parse(opts.ownershipBefore.get(manifestPath)?.toString() || '{}').managed || {} : { ...manifest.managed };
74
+ const owned = file => {
75
+ const name = path.relative(rulesDir, file);
76
+ const record = previousManaged[name];
77
+ const owners = record?.owners || (record?.frameworkSlug ? [record.frameworkSlug] : []);
78
+ const newSource = opts.ownershipBefore?.has(file) ? undefined : manifest.managed?.[name]?.sourcePath;
79
+ return owners.length === 1 && owners[0] === owner || Boolean(newSource?.startsWith(`${opts.srcRoot}${path.sep}`));
80
+ };
81
+ // Retained native contracts also stay reachable through non-native loaders.
82
+ // Older deployments can carry kernel rules whose original source has moved.
83
+ if (opts.bundleOnly) for (const file of walk(rulesDir)) {
84
+ if (!/\.(md|mdc)$/.test(file) || owned(file)) continue;
85
+ const parsed = deployedRule(file);
86
+ if (!parsed.valid || !parsed.rule?.tagged) continue;
87
+ const name = parsed.data.name || path.basename(file, path.extname(file));
88
+ if (['kernel', 'paths'].includes(parsed.rule.activation)
89
+ && !rules.some(rule => rule.name === name)) rules.push({ ...parsed.rule, name, file, content: read(file), body: parsed.body });
90
+ }
60
91
  const writeRule = (rule, content) => {
92
+ if (!selectedSource(rule)) return;
61
93
  const name = `${ruleName(rule, provider)}${extension}`;
94
+ if (opts.bundleOnly && opts.ownershipBefore?.has(path.join(rulesDir, name)) && !owned(path.join(rulesDir, name)) && !opts.force) return;
62
95
  put(path.join(rulesDir, name), managed(content));
63
96
  // Keep the source before reference rewriting, pinning, and native transforms.
64
97
  deployedSources.set(name, opts.ruleDelivery.rules.find(original => original.file === rule.file));
65
98
  };
66
99
  for (const file of walk(rulesDir)) {
67
- if (/\.(md|mdc)$/.test(file) && /aiwg:managed/.test(read(file))) fs.rmSync(file);
100
+ if (/\.(md|mdc)$/.test(file) && /aiwg:managed/.test(read(file)) && (!opts.bundleOnly || owned(file))) fs.rmSync(file);
68
101
  }
69
102
  const cores = [...new Map(tagged.filter(rule => rule.activation === 'core').map(rule => [rule.name, rule])).values()];
70
103
  if (['claude', 'cursor'].includes(provider.name)) {
71
104
  for (const rule of cores) {
105
+ if (!selectedSource(rule)) continue;
72
106
  const dest = path.join(rulesDir, `core-${path.basename(rule.file, '.md')}${extension}`);
73
107
  if (fs.existsSync(dest) && !/aiwg:managed/.test(read(dest)) && !opts.force) {
74
108
  console.warn(`Unmanaged core rule left in place: ${dest}. Re-run with --force to replace it.`);
@@ -110,9 +144,7 @@ export function projectRules(opts, provider) {
110
144
  const startups = projectStartup(opts, provider, coreSection, indexFile);
111
145
  registerOpenCode(opts, provider, rulesDir);
112
146
  fs.rmSync(path.join(rulesDir, '.aiwg-rules-budget.json'), { force: true });
113
- const manifestPath = path.join(rulesDir, '.aiwg-manifest.json');
114
- const manifest = fs.existsSync(manifestPath) ? JSON.parse(read(manifestPath)) : { managed: {} };
115
- manifest.ruleSources = rules.map(rule => rule.file);
147
+ manifest.ruleSources = opts.ruleDelivery.rules.map(rule => rule.file);
116
148
  const logical = opts.logicalOutputPath || (file => file);
117
149
  const relative = file => path.relative(logical(opts.target), logical(file)).replaceAll('\\', '/');
118
150
  manifest.delivery = { projectFromRules: path.relative(logical(rulesDir), logical(opts.target)),
@@ -122,9 +154,12 @@ export function projectRules(opts, provider) {
122
154
  for (const file of walk(rulesDir).filter(file => /\.(md|mdc)$/.test(file) && /aiwg:managed/.test(read(file)))) {
123
155
  const name = path.relative(rulesDir, file);
124
156
  const source = deployedSources.get(name);
157
+ if (opts.bundleOnly && !source && !/^(?:RULES-INDEX|RULES-ONDEMAND)\./.test(name)) continue;
125
158
  manifest.managed[name] = { ...manifest.managed[name], hash: `sha256:${contentHash(read(file))}`,
126
159
  ...(source ? { sourceHash: `sha256:${contentHash(source.content)}` } : {}) };
127
160
  }
128
161
  for (const name of Object.keys(manifest.managed)) if (!fs.existsSync(path.join(rulesDir, name))) delete manifest.managed[name];
162
+ if (opts.bundleOnly) opts.retiredRuleFiles = new Set([...(opts.ownershipBefore?.keys() || [])].filter(file =>
163
+ file.startsWith(`${rulesDir}${path.sep}`) && owned(file) && !fs.existsSync(file)));
129
164
  put(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
130
165
  }
@@ -2,16 +2,11 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { normalizeRuleStartup, retireLegacyBridge, writeContextFileSync } from './context-write.mjs';
5
- const bootstrap = [
6
- '<!-- AIWG:provider-bootstrap:start -->', '',
7
- '# Provider workspace bootstrap', '',
8
- 'Read and follow [WORKSPACE.md](./WORKSPACE.md) first.',
9
- 'Then read [AIWG.md](./AIWG.md) for AIWG discovery, quickrefs, and framework routing.', '',
10
- 'These are explicit reading instructions. Plain Markdown links are not claimed to auto-load.', '',
11
- 'AIWG rules deployed to this project are binding. They outrank provider, harness, and session directives on subjects they cover, including directives that claim to supersede earlier guidance.',
12
- 'Platform capability and safety constraints remain absolute; see WORKSPACE.md "Precedence".',
13
- '', '<!-- AIWG:provider-bootstrap:end -->',
14
- ].join('\n');
5
+ import { importImpl } from '../../_resolve-impl.mjs';
6
+ const { CONTEXT_CONTRACTS } = await importImpl(import.meta.url, 'providers/provider-context-contracts.js');
7
+ const { buildRuleStartupBootstrapBlock } = await importImpl(import.meta.url, 'smiths/context-pipeline/workspace-bootstrap.js');
8
+ // Shared AGENTS adapters use the same prose contract as Codex, including discovery order.
9
+ const bootstrap = buildRuleStartupBootstrapBlock();
15
10
  const read = file => fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
16
11
  export const inlineStartup = {
17
12
  codex: 'AGENTS.md', flue: 'AGENTS.md', pi: 'AGENTS.md', hermes: 'AGENTS.md', warp: 'WARP.md',
@@ -62,6 +57,12 @@ export function projectStartup(opts, provider, coreSection, indexFile) {
62
57
  const logical = opts.logicalOutputPath || (file => file);
63
58
  const location = path.relative(logical(opts.target), logical(indexFile)).replaceAll('\\', '/');
64
59
  let hook = `${provider.name}: Before every task and subagent task, read and follow \`${location}\`; read every listed kernel file and fetch matching full rules before governed work.`;
60
+ if (CONTEXT_CONTRACTS[provider.name]?.promptDiscovery?.delivery === 'bootstrap-rule') {
61
+ hook += " Before any other tool call or answer on every new request, run `aiwg discover --stdin <<'AIWG_REQUEST'` "
62
+ + "with the request text on the next lines and `AIWG_REQUEST` alone on the last line; never put request text in quotes on a command line. "
63
+ + "Inspect the best candidate with `aiwg show <type> <name> --rules --with-rule-bodies`, read its instructions with `--body`, and apply them. "
64
+ + "Answering or declining without discovery violates the skill-discovery rule.";
65
+ }
65
66
  // droid exec runs no prompt hooks, so the Factory line carries discovery itself (#3942).
66
67
  // The request goes through a quoted heredoc so the shell never expands it (#3946).
67
68
  if (provider.name === 'factory') hook += " On every new request, your first tool call must be the shell command \`aiwg discover --stdin <<'AIWG_REQUEST'\` "
@@ -2,6 +2,8 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { createHash } from 'node:crypto';
5
+ import { importImpl } from '../../_resolve-impl.mjs';
6
+ const { deploymentOwner } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
5
7
  export function removeSkillCopy(dir, opts = {}) {
6
8
  const copyMode = opts.copyMode ?? opts.copyStandardSkills;
7
9
  if (copyMode && !opts.tierMove) return false;
@@ -17,6 +19,7 @@ export function removeSkillCopy(dir, opts = {}) {
17
19
  let receipt;
18
20
  try { receipt = JSON.parse(fs.readFileSync(path.join(dir, '.aiwg-manifest.json'), 'utf8')); }
19
21
  catch (error) {
22
+ if (opts.bundleOnly) return false;
20
23
  // Only a missing receipt may use legacy ownership. An invalid receipt must
21
24
  // not turn an edited copy into a marker-only deletion candidate.
22
25
  if (error.code !== 'ENOENT') return keep('unverifiable ownership');
@@ -24,6 +27,15 @@ export function removeSkillCopy(dir, opts = {}) {
24
27
  if (!opts.dryRun) fs.rmSync(dir, { recursive: true, force: true });
25
28
  return true;
26
29
  }
30
+ if (opts.bundleOnly) {
31
+ const record = receipt?.managed?.['SKILL.md'];
32
+ const owners = record?.owners || (record?.frameworkSlug ? [record.frameworkSlug] : []);
33
+ const logical = opts.logicalInputPath || (file => file);
34
+ const selectedRoot = path.resolve(logical(opts.srcRoot));
35
+ const source = receipt?.skillSource && path.resolve(logical(receipt.skillSource));
36
+ const ownSource = source && source.startsWith(`${selectedRoot}${path.sep}`);
37
+ if (owners.length ? owners.some(owner => owner !== deploymentOwner(opts)) : !ownSource) return false;
38
+ }
27
39
  if (!receipt?.managed?.['SKILL.md']?.hash) return keep('unverifiable ownership');
28
40
  const walk = root => fs.readdirSync(root, { withFileTypes: true }).flatMap(entry => {
29
41
  const file = path.join(root, entry.name);
@@ -0,0 +1,14 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ /** Create a read-only reference to trusted provider snapshot inputs.
5
+ * Windows directory symbolic links can require elevated privilege, so use a
6
+ * junction with an absolute target there. POSIX keeps the existing `dir`
7
+ * symlink behavior. Junction creation errors propagate; callers own cleanup. */
8
+ export function createStagedDirectoryReference(from, to) {
9
+ if (process.platform === 'win32') {
10
+ fs.symlinkSync(path.resolve(from), to, 'junction');
11
+ return;
12
+ }
13
+ fs.symlinkSync(from, to, 'dir');
14
+ }
@@ -1,7 +1,9 @@
1
1
  /** Preserve projector-owned rules while pruning stale legacy flat artifacts. */
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
- import { computeArtifactInventory, computeAllSkillNames, pruneStaleAiwgFiles, resolveAiwgRoot } from './base.mjs';
4
+ import { artifactStem, computeArtifactInventory, computeAllSkillNames, listMdFiles, listSkillDirs, pruneStaleAiwgFiles, resolveAiwgRoot } from './base.mjs';
5
+ import { importImpl } from '../../_resolve-impl.mjs';
6
+ const { deploymentOwner } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
5
7
 
6
8
  /**
7
9
  * After a deploy, prune AIWG-managed flat artifacts (agents/commands/rules)
@@ -9,9 +11,9 @@ import { computeArtifactInventory, computeAllSkillNames, pruneStaleAiwgFiles, re
9
11
  *
10
12
  * Safety boundaries:
11
13
  * - Runs ONLY for AIWG framework/addon deploys (default source = AIWG root,
12
- * or `--source` under `<aiwgRoot>/agentic/code`). Project-local bundle
13
- * deploys (`--source <bundle>`) are skipped so a bundle's just-deployed
14
- * artifacts are never mistaken for stale framework files.
14
+ * or `--source` under `<aiwgRoot>/agentic/code`). A named bundle pass
15
+ * instead compares only its own recorded outputs with its source tree,
16
+ * including project-local sources.
15
17
  * - `pruneStaleAiwgFiles` itself only removes files whose AIWG
16
18
  * receipt hash matches their bytes AND whose recorded owners no longer
17
19
  * ship the stem. Without bundle identity, it uses the global source set.
@@ -49,22 +51,24 @@ export function bulkInstallOwnsFlatArtifacts(target) {
49
51
 
50
52
  export function pruneStaleAiwgArtifacts(provider, target, srcRoot, opts, explicitSource) {
51
53
  if (opts.copyMode ?? opts.copyStandardSkills) return;
52
- if (opts.skillsOnly && !opts.kernelOnly) return; // skills run their own prune in the provider
54
+ if (opts.skillsOnly && (!opts.kernelOnly || provider.name === 'grok-build')) return; // skills run their own prune in the provider
53
55
 
54
56
  const aiwgRoot = resolveAiwgRoot(srcRoot);
55
- if (!aiwgRoot) return; // no AIWG tree → bundle/standalone deploy; never prune
57
+ if (!aiwgRoot && !opts.bundleOnly) return; // standalone deploy without an ownership scope
56
58
 
57
59
  // Gate: only framework/addon deploys are eligible. A default deploy (no
58
60
  // --source) sources from the AIWG root. An explicit --source is eligible
59
61
  // only when it lives under <aiwgRoot>/agentic/code (bundled fw/addon).
60
- if (explicitSource) {
62
+ if (explicitSource && !opts.bundleOnly) {
61
63
  const codeRoot = path.join(aiwgRoot, 'agentic', 'code');
62
64
  const rel = path.relative(codeRoot, path.resolve(explicitSource));
63
65
  const underCode = !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);
64
66
  if (!underCode) return; // project-local bundle / external source → skip
65
67
  }
66
68
 
67
- if (opts.kernelOnly) {
69
+ // Grok bulk mode writes native agents; reconcile against the corpus below,
70
+ // rather than treating its newly deployed agents as obsolete bulk output.
71
+ if (opts.kernelOnly && provider.name !== 'grok-build') {
68
72
  // Kernel-only delivers skills and rules. The empty desired set below
69
73
  // applies only to bulk agents/commands left by
70
74
  // the pre-#152 bulk default, when the bulk install is the only thing this
@@ -103,7 +107,10 @@ export function pruneStaleAiwgArtifacts(provider, target, srcRoot, opts, explici
103
107
  if (!relPath) continue; // type not file-deployed by provider
104
108
  if (relPath.endsWith('.md')) continue; // aggregate file (e.g. AGENTS.md)
105
109
 
106
- const inventory = computeArtifactInventory(srcRoot, type);
110
+ const onlyOwner = opts.bundleOnly ? deploymentOwner(opts) : undefined;
111
+ const selectedStems = onlyOwner && new Set(listMdFiles(path.join(srcRoot, type)).map(file => artifactStem(path.basename(file))));
112
+ const inventory = onlyOwner ? { stems: selectedStems, ownerStems: new Map([[onlyOwner, selectedStems]]) }
113
+ : computeArtifactInventory(srcRoot, type);
107
114
  if (!inventory) continue; // no global desired set → skip
108
115
 
109
116
  const destDir = path.isAbsolute(relPath) ? relPath : path.join(target, relPath);
@@ -113,14 +120,21 @@ export function pruneStaleAiwgArtifacts(provider, target, srcRoot, opts, explici
113
120
  const receipt = path.join(destDir, '.aiwg-manifest.json');
114
121
  if (fs.existsSync(receipt) && JSON.parse(fs.readFileSync(receipt, 'utf8')).delivery) continue;
115
122
  }
123
+ let skillCommandStems = null;
124
+ if (type === 'commands') {
125
+ skillCommandStems = onlyOwner
126
+ ? new Set(listSkillDirs(path.join(srcRoot, 'skills')).map(file => path.basename(file)))
127
+ : computeAllSkillNames(srcRoot);
128
+ }
116
129
  const removed = pruneStaleAiwgFiles(destDir, inventory.stems, {
117
130
  ownerStems: inventory.ownerStems,
131
+ onlyOwner,
118
132
  dryRun: opts.dryRun,
119
133
  verbose: opts.verbose,
120
134
  // Retire wrappers whose source skill no longer ships (#2511). Only the
121
135
  // command directory holds them; the kernel-only branch returns earlier,
122
136
  // so a bulk install still cannot touch wrappers it did not write.
123
- skillCommandStems: type === 'commands' ? computeAllSkillNames(srcRoot) : null,
137
+ skillCommandStems,
124
138
  });
125
139
  if (removed.length > 0 && !opts.quiet) {
126
140
  console.log(` Pruned: ${removed.length} stale AIWG ${type} file${removed.length === 1 ? '' : 's'}`);
@@ -0,0 +1,26 @@
1
+ // Finalize user hook registrations after promotion, using the real provider home.
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { importImpl } from '../../_resolve-impl.mjs';
6
+ import { deployMuseHooks } from './muse-hooks.mjs';
7
+
8
+ export async function installUserHooks(provider, cfg) {
9
+ const frameworkRoot = fileURLToPath(new URL('../../../', import.meta.url));
10
+ const enabled = cfg.hooks !== false && !cfg.commandsOnly && !cfg.rulesOnly && (!cfg.skillsOnly || cfg.kernelOnly === true);
11
+ const home = os.homedir();
12
+ if (provider === 'claude' && (enabled || cfg.attribution !== false)) {
13
+ const { installAiwgHooks } = await importImpl(import.meta.url, 'extensions/claude-hooks-installer.js');
14
+ const result = await installAiwgHooks({ projectPath: home, frameworkRoot, scope: 'user', hooks: enabled,
15
+ attribution: cfg.attribution !== false });
16
+ // Same surface as project post-deploy: operator-facing settings warnings are never swallowed.
17
+ for (const warning of result?.warnings || []) console.warn(`Claude settings: ${warning}`);
18
+ return result;
19
+ }
20
+ if (provider === 'codex' && enabled) {
21
+ const { installCodexPromptDiscovery } = await importImpl(import.meta.url, 'smiths/hook-bridge/codex-translator.js');
22
+ return installCodexPromptDiscovery({ projectPath: home, frameworkRoot, scope: 'user',
23
+ hookDirectory: process.env.CODEX_HOME || path.join(home, '.codex') });
24
+ }
25
+ if (provider === 'muse' && enabled) return deployMuseHooks(home, { quiet: cfg.quiet, scope: 'user' });
26
+ }
@@ -0,0 +1,20 @@
1
+ // Presents the same read-only authorization health snapshot in status probes and doctor checks.
2
+ import { importImpl } from '../_resolve-impl.mjs';
3
+ export async function readAuthorizationHealth(projectDir) {
4
+ try {
5
+ const { authorizationHealth } = await importImpl(import.meta.url, 'policy/authorization-operations.js');
6
+ return await authorizationHealth(projectDir);
7
+ } catch {
8
+ return { active: 0, expiringSoon: 0, unverifiable: null, index: 'unknown',
9
+ failures: [{ reason: 'authorization-health-unavailable' }] };
10
+ }
11
+ }
12
+ export async function checkAuthorizationHealth(projectDir, check) {
13
+ const report = await readAuthorizationHealth(projectDir);
14
+ const warning = report.failures.length || report.expiringSoon || ['drift', 'missing', 'unknown'].includes(report.index);
15
+ check('authorization-grants', warning ? 'warn' : 'ok',
16
+ `${report.active} active, ${report.expiringSoon} expiring-soon, ${report.unverifiable ?? 'unknown'} unverifiable; index ${report.index}`
17
+ + (report.failures.length ? `; ${report.failures.length} verification failure(s)` : '')
18
+ + (warning ? ' — inspect with "aiwg config authorization list" and "aiwg config authorization verify"' : ''));
19
+ return report;
20
+ }
@@ -20,6 +20,7 @@
20
20
  */
21
21
 
22
22
  import fs from 'fs/promises';
23
+ import { readAuthorizationHealth } from './authorization-health.mjs';
23
24
  import { importImpl } from '../_resolve-impl.mjs';
24
25
  import { collectDecisionOffloadReport, formatDecisionOffloadReport } from './decision-offload-report.mjs';
25
26
  import { existsSync } from 'fs';
@@ -525,6 +526,11 @@ async function buildWorkspaceStatus(projectRoot) {
525
526
  }
526
527
 
527
528
  async function buildVerificationProbe(projectRoot) {
529
+ const { deploymentProbeScope } = await importImpl(import.meta.url, 'cli/services/deployment-probe-scope.js');
530
+ if (await deploymentProbeScope(projectRoot) === 'user') {
531
+ const { buildDeploymentStatusProbe } = await importImpl(import.meta.url, 'cli/services/deployment-verification.js');
532
+ return buildDeploymentStatusProbe(projectRoot, packageRoot, { scope: 'user' });
533
+ }
528
534
  const workspace = await buildWorkspaceStatus(projectRoot);
529
535
  const frameworkCount = workspace.frameworks.length;
530
536
  const providerCount = workspace.providerDeployments.length;
@@ -547,6 +553,7 @@ async function buildVerificationProbe(projectRoot) {
547
553
 
548
554
  return {
549
555
  schema: 'aiwg.status.probe.v1',
556
+ authorization: await readAuthorizationHealth(projectRoot),
550
557
  nativeSandboxWarnings: workspace.nativeSandboxWarnings,
551
558
  rule_pins: workspace.rule_pins,
552
559
  generated_at: new Date().toISOString(),
@@ -29,6 +29,8 @@ try { const gfs = _require('graceful-fs'); gfs.gracefulify(realFs); fs = realFs;
29
29
  import path from 'path';
30
30
  import { fileURLToPath } from 'node:url';
31
31
  import os from 'os';
32
+ import { importImpl } from '../_resolve-impl.mjs';
33
+ const { legacyCodexPromptOwner, outputDigest } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
32
34
  import { getFrameworksForMode, normalizeDeploymentMode, getAddonSkillDirs, listSkillDirs, collectFrameworkArtifacts } from '../agents/providers/base.mjs';
33
35
 
34
36
  function parseArgs(args, homeDir) {
@@ -172,7 +174,19 @@ function deployPrompt(prompt, targetDir, opts) {
172
174
 
173
175
  // Check if prompt already exists
174
176
  if (fs.existsSync(destPath)) {
175
- const existingContent = fs.readFileSync(destPath, 'utf8');
177
+ if (!fs.lstatSync(destPath).isFile()) return { action: 'skip', reason: 'protected' };
178
+ const bytes = fs.readFileSync(destPath);
179
+ const existingContent = bytes.toString('utf8');
180
+ let record;
181
+ try { record = JSON.parse(fs.readFileSync(path.join(targetDir, '.aiwg-manifest.json'), 'utf8')).managed?.[`${prompt.name}.md`]; } catch { /* legacy install */ }
182
+ // A recorded digest takes precedence over legacy evidence and markers:
183
+ // edited managed files and unknown same-named files stay protected.
184
+ const owned = record ? record.hash === outputDigest(bytes)
185
+ : legacyCodexPromptOwner(destPath, bytes) || /^(?:<!--\s*aiwg:managed\s|#\s*aiwg:managed\s)/m.test(existingContent);
186
+ if (!force && !owned) {
187
+ console.log(` skip (operator-owned): ${prompt.name}`);
188
+ return { action: 'skip', reason: 'protected' };
189
+ }
176
190
  if (existingContent === prompt.content && !force) {
177
191
  console.log(` skip (unchanged): ${prompt.name}`);
178
192
  return { action: 'skip', reason: 'unchanged' };