@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
@@ -39,6 +39,7 @@ import { existsSync } from 'node:fs';
39
39
  import { dirname, join, resolve as resolvePath } from 'node:path';
40
40
  import { fileURLToPath } from 'node:url';
41
41
  import { buildHitlResponseMessage, extractHitlEnvelope, validateResponseStructurally, } from './hitl.js';
42
+ import { collectAuthorizedHitlResponse } from './hitl-authorization.js';
42
43
  import { digestDecisionContext } from '../audit/operator-decision.js';
43
44
  /** Default audit log — writes to stderr as JSONL. Replace with a file/HTTP sink in production. */
44
45
  export class StderrHitlAuditLog {
@@ -162,6 +163,7 @@ export async function driveHitlPromptsForTask(opts) {
162
163
  const ctx = inferEventContext(event);
163
164
  await driveOnePrompt({
164
165
  envelope,
166
+ authorization: opts.authorization,
165
167
  client: opts.client,
166
168
  adapter: opts.adapter,
167
169
  auditLog,
@@ -222,12 +224,9 @@ export async function driveOnePrompt(opts) {
222
224
  try {
223
225
  for (let attempt = 0; attempt < maxRetries; attempt++) {
224
226
  let response;
227
+ let authorization;
225
228
  try {
226
- response = await opts.adapter.collect(opts.envelope, {
227
- ...(opts.taskId !== undefined ? { taskId: opts.taskId } : {}),
228
- ...(opts.contextId !== undefined ? { contextId: opts.contextId } : {}),
229
- signal: controller.signal,
230
- });
229
+ ({ response, authorization } = await collectAuthorizedHitlResponse(opts, controller.signal));
231
230
  }
232
231
  catch (err) {
233
232
  if (controller.signal.aborted) {
@@ -312,6 +311,7 @@ export async function driveOnePrompt(opts) {
312
311
  ...(opts.taskId !== undefined ? { task_id: opts.taskId } : {}),
313
312
  ...(opts.contextId !== undefined ? { context_id: opts.contextId } : {}),
314
313
  outcome: 'responded',
314
+ ...(authorization ? { authorization } : {}),
315
315
  response_digest: digestDecisionContext(response),
316
316
  duration_ms: Date.now() - startedAt,
317
317
  });
@@ -459,6 +459,8 @@ function recordForEntry(cwd, entry, graphName, dependencyGraph, privacy, schemaV
459
459
  ...(entry.activation ? { activation: entry.activation } : {}),
460
460
  ...(entry.bound_to ? { bound_to: entry.bound_to } : {}),
461
461
  ...(entry.ruleEnforcement ? { enforcement: entry.ruleEnforcement } : {}),
462
+ ...(entry.rulePrecedence ? { precedence: entry.rulePrecedence } : {}),
463
+ ...(entry.ruleOverridable === undefined ? {} : { overridable: entry.ruleOverridable }),
462
464
  ...(entry.rulePaths ? { paths: entry.rulePaths } : {}),
463
465
  ...(entry.governedPaths ? { aiwg_governed_paths: entry.governedPaths } : {}),
464
466
  ...(entry.ruleSummary !== undefined ? { summary: entry.ruleSummary } : {}),
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { createHash } from 'node:crypto';
5
5
  import { BUILTIN_GRAPH_CONFIGS, INDEX_EXTRACTOR_VERSION, getGraphIndexDir } from './types.js';
6
- export const FRAMEWORK_RELATIONS_REVISION = 4;
6
+ export const FRAMEWORK_RELATIONS_REVISION = 5;
7
7
  const REVISION = FRAMEWORK_RELATIONS_REVISION;
8
8
  const sha256 = (value) => createHash('sha256').update(value).digest('hex');
9
9
  /** No absolute paths, git revision or mtimes enter the portable digest. */
@@ -30,6 +30,8 @@ import { collectGraphIndexFiles, findArtifactFiles, indexPathFor } from './index
30
30
  import { acquireDirectoryLock } from './prebuilt-build-lock.js';
31
31
  import { graphIndexDigest, indexAdapterRegistry, recordIndexVerification } from './index-adapters.js';
32
32
  import { loadMemoryRecord } from '../memory/maintenance-record.js';
33
+ import { extractCapability } from './index-capability.js';
34
+ export { extractCapability } from './index-capability.js';
33
35
  import { extractTemplateReferences, isTemplateReference } from './template-references.js';
34
36
  import { createDependencyResolver, extractFlowDependencies } from './index-dependencies.js';
35
37
  function absoluteEntryPath(cwd, entryPath, graph) {
@@ -81,6 +83,8 @@ export function extractRuleBindings(data, body = '') {
81
83
  const enforcement = typeof data.enforcement === 'string' ? data.enforcement
82
84
  : body.match(/^\*\*Enforcement Level\*\*:\s*([A-Za-z]+)/m)?.[1];
83
85
  return {
86
+ rulePrecedence: typeof data.precedence === 'string' ? data.precedence : 'medium',
87
+ ruleOverridable: typeof data.overridable === 'boolean' ? data.overridable : true,
84
88
  ...(enforcement ? { ruleEnforcement: enforcement.trim().toLowerCase() } : {}),
85
89
  ...(Array.isArray(data.paths) ? { rulePaths: data.paths.filter((value) => typeof value === 'string') } : {}),
86
90
  ...(typeof data.activation === 'string' ? { activation: data.activation } : {}),
@@ -158,7 +162,9 @@ function addDependencyEdge(depGraph, entries, sourcePath, targetPath, type) {
158
162
  /**
159
163
  * Extract title from content (first # heading or frontmatter title)
160
164
  */
161
- function extractTitle(data, body) {
165
+ function extractTitle(data, body, type) {
166
+ if (type === 'agent' && typeof data.name === 'string' && data.name.trim())
167
+ return data.name.trim();
162
168
  if (typeof data.title === 'string')
163
169
  return data.title;
164
170
  const headingMatch = body.match(/^#\s+(.+)$/m);
@@ -559,30 +565,6 @@ export function extractTriggers(body, frontmatter) {
559
565
  }
560
566
  return [...new Set(phrases)];
561
567
  }
562
- /**
563
- * Extract a capability summary for a skill/agent/command/rule.
564
- *
565
- * Prefers the frontmatter `description` field (used uniformly across
566
- * AIWG SKILL.md / agent files). Falls back to the first non-heading
567
- * paragraph of the body. Capped at 240 chars so the index stays
568
- * token-tight when surfaced via `aiwg index discover`.
569
- *
570
- * @implements #1214
571
- */
572
- export function extractCapability(data, body) {
573
- if (typeof data.description === 'string' && data.description.trim().length > 0) {
574
- return data.description.trim().slice(0, 240);
575
- }
576
- // Fallback: first non-empty paragraph that isn't a heading.
577
- const stripped = body.replace(/^---\n[\s\S]*?\n---\n/, '');
578
- for (const block of stripped.split(/\n\s*\n/)) {
579
- const trimmed = block.trim();
580
- if (!trimmed || trimmed.startsWith('#'))
581
- continue;
582
- return trimmed.replace(/\s+/g, ' ').slice(0, 240);
583
- }
584
- return undefined;
585
- }
586
568
  /**
587
569
  * Extract a SkillScriptSpec from skill frontmatter (#1227).
588
570
  *
@@ -896,7 +878,7 @@ function extractIndexArtifact(job, bindingOnly, warnings = []) {
896
878
  const physicalType = inferType({ ...data, type: undefined }, relativePath);
897
879
  const runbook = flow || decision || gatePack ? null : parseRunbookDoc(data, body, relativePath);
898
880
  const schemaDoc = inferredType === 'schema' ? parseSchemaDoc(content, relativePath) : null;
899
- const title = flow?.name ?? decision?.name ?? gatePack?.name ?? schemaDoc?.title ?? extractTitle(data, body);
881
+ const title = flow?.name ?? decision?.name ?? gatePack?.name ?? schemaDoc?.title ?? extractTitle(data, body, inferredType);
900
882
  const phase = typeof data.phase === 'string' ? data.phase : inferPhase(relativePath);
901
883
  const type = flow?.type ?? decision?.type ?? gatePack?.type ?? (runbook ? 'runbook' : inferredType);
902
884
  // Binding resolution consumes only identity and title. Keep the same canonical
@@ -923,7 +905,7 @@ function extractIndexArtifact(job, bindingOnly, warnings = []) {
923
905
  // Declarative processes have no trigger phrases — they rely on their
924
906
  // capability and structure-aware search terms.
925
907
  const triggers = isDiscoverable && !flow ? extractTriggers(body, data) : undefined;
926
- const capability = flow?.capability ?? decision?.capability ?? gatePack?.capability ?? schemaDoc?.capability ?? runbook?.capability ?? (isDiscoverable ? extractCapability(data, body) : undefined);
908
+ const capability = flow?.capability ?? decision?.capability ?? gatePack?.capability ?? schemaDoc?.capability ?? runbook?.capability ?? (isDiscoverable ? extractCapability(data, body, type === 'template' ? extractCanonicalName(data, relativePath) : undefined) : undefined);
927
909
  const kind = flow?.kind ?? decision?.kind ?? gatePack?.kind ?? runbook?.kind;
928
910
  const sourceType = runbook && physicalType !== 'runbook' ? physicalType : undefined;
929
911
  const searchTerms = flow?.searchTerms ?? decision?.searchTerms ?? gatePack?.searchTerms ?? schemaDoc?.searchTerms ?? runbook?.searchTerms;
@@ -0,0 +1,24 @@
1
+ // Derive discovery capabilities from usable prose, with safe title fallbacks for templates.
2
+ function usableText(value) {
3
+ if (typeof value !== 'string')
4
+ return undefined;
5
+ const text = value.trim();
6
+ if (!text || /\{\{[^}]*\}\}|^#/.test(text))
7
+ return undefined;
8
+ return text.replace(/\s+/g, ' ').slice(0, 240);
9
+ }
10
+ export function extractCapability(data, body, fallbackTitle) {
11
+ const description = usableText(data.description);
12
+ if (description)
13
+ return description;
14
+ const stripped = body.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '');
15
+ for (const block of stripped.split(/\r?\n\s*\r?\n/)) {
16
+ const text = usableText(block);
17
+ if (text)
18
+ return text;
19
+ }
20
+ // Strip heading markers before considering a title; never surface a raw heading.
21
+ const heading = stripped.match(/^\s*#{1,6}\s+(.+?)(?:\s+#+)?\s*$/m)?.[1];
22
+ return usableText(data.title) ?? usableText(heading) ?? usableText(fallbackTitle);
23
+ }
24
+ //# sourceMappingURL=index-capability.js.map
@@ -2,7 +2,7 @@
2
2
  import * as path from 'node:path';
3
3
  import { diagnoseFacetActivations } from './discover-facets.js';
4
4
  import { buildRunHint, DISCOVER_TYPE_ORDER, discoveryIdForEntry, normalizeIndexedPath, scopeRank, showHintForDiscoverResult, } from './query-engine-entries.js';
5
- import { boundRuleDescriptor, compoundGoverningRules, governingRuleFields, governingRuleStats, RULE_CHECK_OBLIGATION, statsText, } from './query-engine-rules.js';
5
+ import { ruleOrderingFields, boundRuleDescriptor, compoundGoverningRules, governingRuleFields, governingRuleStats, RULE_CHECK_OBLIGATION, statsText, } from './query-engine-rules.js';
6
6
  import { tokenize } from './query-engine-scoring.js';
7
7
  import { ensureRelations, loadRelations } from './relations.js';
8
8
  import { templateRelationFields } from './query-engine-templates.js';
@@ -47,13 +47,14 @@ export async function emitDiscoverResults(context) {
47
47
  const relations = resourceSource === 'local' && (!params.graph || params.graph === 'framework')
48
48
  ? prebuiltRelations ?? (readOnly ? loadRelations(cwd, cwd, false)
49
49
  : await ensureRelations(cwd, cwd, { verbose: params.verbose, selection: prebuiltSelection, reconciled: frameworkReconciled })) : undefined;
50
+ const orderingFor = (entry) => ruleOrderingFields(cwd, aiwgRoot ?? cwd, entry, resourceSource === 'local' ? resolvePath(entry) : undefined);
50
51
  const governing = scored.map(result => compoundGoverningRules(entries, result.entry, relations ?? undefined, params.phrase));
51
52
  const responseRules = new Map();
52
53
  for (const item of governing.flat()) {
53
54
  const key = `${item.rule.type}:${item.rule.path}`, prior = responseRules.get(key);
54
55
  responseRules.set(key, { rule: item.rule, applicability: [...new Set([...(prior?.applicability ?? []), ...item.applicability])] });
55
56
  }
56
- const responseFields = governingRuleFields([...responseRules.values()]);
57
+ const responseFields = governingRuleFields([...responseRules.values()], orderingFor);
57
58
  const responseRuleStats = governingRuleStats([...responseRules.values()]);
58
59
  const includePaths = params.includePaths ?? true;
59
60
  const facetActivations = diagnoseFacetActivations(params.phrase);
@@ -121,10 +122,11 @@ export async function emitDiscoverResults(context) {
121
122
  type: r.entry.type,
122
123
  name: r.entry.name,
123
124
  title: r.entry.title,
125
+ ...orderingFor(r.entry),
124
126
  ...templateRelationFields(r.entry, ruleRelations, 3, includePaths),
125
127
  score: Math.round(r.score * 100) / 100,
126
128
  ranking: rankingDiagnostic(r.entry, r.score, r.facetDiagnostics),
127
- ...governingRuleFields(governing[resultIndex]),
129
+ ...governingRuleFields(governing[resultIndex], orderingFor),
128
130
  triggers: r.entry.triggers ?? [],
129
131
  capability: r.entry.capability ?? r.entry.summary,
130
132
  kernel: r.entry.kernel ?? false,
@@ -194,6 +196,9 @@ export async function emitDiscoverResults(context) {
194
196
  const topTrigger = topTriggerMatch?.value ??
195
197
  (r.entry.triggers && r.entry.triggers.length > 0 ? r.entry.triggers[0] : '');
196
198
  console.log(`${i + 1}. ${r.entry.title}`);
199
+ const ordering = orderingFor(r.entry);
200
+ if ('precedence' in ordering)
201
+ console.log(` precedence: ${ordering.precedence} | overridable: ${ordering.overridable} | source: ${ordering.precedence_source} | project context: ${ordering.project_context}`);
197
202
  console.log(` type: ${r.entry.type} score: ${score}${flags ? ` flags: ${flags}` : ''}`);
198
203
  console.log(` ${includePaths ? 'path' : 'id'}: ${locator}`);
199
204
  if (r.entry.name) {
@@ -1,4 +1,9 @@
1
1
  // Resolve governing rules and shape bound-rule checks and summaries.
2
+ import fs from 'node:fs';
3
+ import { parseRuleFrontmatter } from '../rules/activation.mjs';
4
+ import { resolveRulePrecedence } from '../rules/precedence.mjs';
5
+ import { loadRulePinConfigs } from '../rules/pins.mjs';
6
+ import { ruleOrderingAliases } from '../rules/project-precedence.js';
2
7
  import { minimatch } from 'minimatch';
3
8
  import * as path from 'node:path';
4
9
  import { inferRuleActivation } from '../rules/activation.mjs';
@@ -36,7 +41,7 @@ export function relationshipRules(entries, target, relations) {
36
41
  const asMetadata = (id) => {
37
42
  const rule = relations.index.rules[id];
38
43
  return { path: rule.path, type: rule.type, name: rule.name, activation: rule.activation ?? undefined,
39
- bound_to: rule.bound_to, ruleSummary: rule.summary, ruleEnforcement: rule.enforcement ?? undefined, rulePaths: rule.paths, triggers: rule.triggers };
44
+ bound_to: rule.bound_to, ruleSummary: rule.summary, ruleEnforcement: rule.enforcement ?? undefined, rulePrecedence: rule.precedence, ruleOverridable: rule.overridable, rulePaths: rule.paths, triggers: rule.triggers };
40
45
  };
41
46
  const key = `${target.type}:${discoveryIdForEntry(target)}`;
42
47
  const shipped = Object.hasOwn(relations.index.targets, key)
@@ -49,7 +54,7 @@ export function relationshipRules(entries, target, relations) {
49
54
  export const RULE_CHECK_OBLIGATION = 'Before governed work, fetch and follow every required rule below; a discovery summary is not the full rule.';
50
55
  export function relationMetadata(relations) {
51
56
  return Object.values(relations.index.rules).map(rule => ({ path: rule.path, type: rule.type, name: rule.name,
52
- activation: rule.activation ?? undefined, ruleSummary: rule.summary, ruleEnforcement: rule.enforcement ?? undefined,
57
+ activation: rule.activation ?? undefined, ruleSummary: rule.summary, ruleEnforcement: rule.enforcement ?? undefined, rulePrecedence: rule.precedence, ruleOverridable: rule.overridable,
53
58
  bound_to: rule.bound_to, rulePaths: rule.paths, triggers: rule.triggers }));
54
59
  }
55
60
  /** Post-ranking enrichment: relationship lookup never loads the full metadata index. */
@@ -81,13 +86,13 @@ export function compoundGoverningRules(entries, target, relations, phrase = '',
81
86
  }
82
87
  if (includeMatches) {
83
88
  const query = phrase.toLowerCase();
84
- const queryPaths = (phrase.replace(/\\/g, '/').match(/[\w@./*?-]+/g) ?? []).map(value => value.replace(/[.,;:!?]+$/, ''));
85
89
  const corpus = relations ? relationMetadata(relations) : [];
86
90
  const rules = new Map([...corpus, ...entries.filter(entry => ['rule', 'behavior'].includes(entry.type))]
87
91
  .map(rule => [`${rule.type}:${rule.path}`, rule]));
88
92
  for (const rule of rules.values()) {
93
+ // Search prose is never path context; only declared governed paths activate path rules.
89
94
  for (const glob of rule.rulePaths ?? [])
90
- for (const candidate of [...queryPaths.filter(value => /[./*?]/.test(value) || value === glob), ...(target.governedPaths ?? [])]) {
95
+ for (const candidate of target.governedPaths ?? []) {
91
96
  if (minimatch(candidate, glob, { dot: true, nonegate: true, nocomment: true })
92
97
  || ((target.governedPaths ?? []).includes(candidate) && minimatch(glob, candidate, { dot: true, nonegate: true, nocomment: true })))
93
98
  add(rule, `path:${candidate}`);
@@ -108,8 +113,9 @@ export function compoundGoverningRules(entries, target, relations, phrase = '',
108
113
  }
109
114
  return [...found.values()].sort((a, b) => (a.rule.name ?? a.rule.path).localeCompare(b.rule.name ?? b.rule.path) || a.rule.path.localeCompare(b.rule.path));
110
115
  }
111
- export function boundRuleDescriptor(rule) {
116
+ export function boundRuleDescriptor(rule, ordering) {
112
117
  return { name: rule.name ?? path.basename(rule.path, '.md'), activation: rule.activation ?? null, enforcement: rule.ruleEnforcement ?? null,
118
+ precedence: rule.rulePrecedence ?? 'medium', overridable: rule.ruleOverridable ?? true, precedence_source: 'rule', project_context: false, ...ordering,
113
119
  summary: (rule.ruleSummary ?? '').replace(/\s+/g, ' ').trim(), show_command: `aiwg show ${rule.type} ${rule.name ?? path.basename(rule.path, '.md')} --body` };
114
120
  }
115
121
  /** Counts unique attached contracts; every emitted check is required irrespective of severity. */
@@ -123,10 +129,10 @@ export function governingRuleStats(governing) {
123
129
  }
124
130
  return stats;
125
131
  }
126
- export function governingRuleFields(governing) {
132
+ export function governingRuleFields(governing, ordering) {
127
133
  if (!governing.length)
128
134
  return {};
129
- return { bound_rules: governing.map(({ rule }) => boundRuleDescriptor(rule)), rule_stats: governingRuleStats(governing),
135
+ return { bound_rules: governing.map(({ rule }) => boundRuleDescriptor(rule, ordering?.(rule))), rule_stats: governingRuleStats(governing),
130
136
  required_rule_checks: governing.map(({ rule, applicability }) => ({ rule_id: discoveryIdForEntry(rule),
131
137
  applicability, fetch_command: `aiwg show ${rule.type} ${discoveryIdForEntry(rule)} --body` })), rule_check_obligation: RULE_CHECK_OBLIGATION };
132
138
  }
@@ -149,11 +155,11 @@ export function relationshipRuleStats(entries, target, relations) {
149
155
  }
150
156
  return stats;
151
157
  }
152
- export async function showBindings(entries, target, content, params, read, relations) {
158
+ export async function showBindings(entries, target, content, params, read, relations, ordering) {
153
159
  const governing = compoundGoverningRules(entries, target, relations, '', false, false);
154
160
  const rules = governing.map(item => item.rule);
155
161
  const boundRules = await Promise.all(rules.map(async (rule) => ({
156
- ...boundRuleDescriptor(rule),
162
+ ...boundRuleDescriptor(rule, ordering?.(rule)),
157
163
  ...((params.boundRuleBodies || params.withRuleBodies) ? { content: await read(rule) } : {}),
158
164
  })));
159
165
  // Parse the selected rule for reverse lookup, including corpus-only rules.
@@ -182,7 +188,7 @@ export async function showBindings(entries, target, content, params, read, relat
182
188
  if (boundRules.length) {
183
189
  // Cards already print these stats in the header; body/section output has no header.
184
190
  const stats = params.body || params.sections?.length ? `${statsText(governingRuleStats(governing))}\n\n` : '';
185
- text += `\n## Bound rules\n\n${RULE_CHECK_OBLIGATION}\n\n${stats}` + boundRules.map(rule => `- **${rule.name}** [${rule.activation ?? 'unknown'} / ${rule.enforcement ?? 'unknown'}]: ${rule.summary} (\`${rule.show_command}\`)`
191
+ text += `\n## Bound rules\n\n${RULE_CHECK_OBLIGATION}\n\n${stats}` + boundRules.map(rule => `- **${rule.name}** [${rule.activation ?? 'unknown'} / ${rule.enforcement ?? 'unknown'}; precedence ${rule.precedence}; overridable ${rule.overridable}; source ${rule.precedence_source}]: ${rule.summary} (\`${rule.show_command}\`)`
186
192
  + ('content' in rule ? `\n\n${rule.content}` : '')).join('\n') + '\n';
187
193
  }
188
194
  if (Object.keys(boundTo).length) {
@@ -192,10 +198,22 @@ export async function showBindings(entries, target, content, params, read, relat
192
198
  if (boundTargets.size)
193
199
  text += '\nResolved targets: ' + [...boundTargets.values()].map(target => `${target.type} ${target.name ?? target.id}`).join(', ') + '\n';
194
200
  return { fields: {
195
- ...governingRuleFields(governing),
201
+ ...governingRuleFields(governing, ordering),
196
202
  ...(['rule', 'behavior'].includes(target.type) ? { bound_to: boundTo, bound_targets: [...boundTargets.values()] } : {}),
197
203
  ...(boundRules.length ? { bound_rules: boundRules } : {}),
198
204
  ...(Object.keys(boundTo).length ? { bound_to: boundTo } : {}),
199
205
  }, text };
200
206
  }
207
+ /** Cards use canonical source when available, so a stale index cannot weaken a rule. */
208
+ export function ruleOrderingFields(cwd, root, entry, file) {
209
+ if (!['rule', 'behavior'].includes(entry.type))
210
+ return {};
211
+ let ordering = { precedence: entry.rulePrecedence, overridable: entry.ruleOverridable };
212
+ if (file && fs.existsSync(file)) {
213
+ const parsed = parseRuleFrontmatter(fs.readFileSync(file, 'utf8'));
214
+ // Discovery preserves legacy binding syntax; ordering itself is validated below.
215
+ ordering = parsed.data && typeof parsed.data === 'object' ? parsed.data : {};
216
+ }
217
+ return resolveRulePrecedence({ ...ordering, name: entry.name, id: discoveryIdForEntry(entry) }, loadRulePinConfigs(cwd), ruleOrderingAliases(file ?? path.resolve(root, entry.path), root, cwd));
218
+ }
201
219
  //# sourceMappingURL=query-engine-rules.js.map
@@ -226,16 +226,16 @@ export function scoreEntryDetailed(entry, text, opts = {}) {
226
226
  });
227
227
  return finish(1.001, 1.001);
228
228
  }
229
- if (nearNameMatch(text, entry.name)) {
229
+ if (nearNameMatch(text, entry.name) || verbose?.names(entry.name)) {
230
230
  matches.push({
231
231
  field: 'name',
232
- match: 'near-name',
232
+ match: verbose?.names(entry.name) ? 'contained-phrase' : 'near-name',
233
233
  value: entry.name,
234
234
  contribution: 0.951,
235
- matched_tokens: tokens,
236
- query_token_coverage: 1,
235
+ matched_tokens: verbose?.names(entry.name) ? tokenize(entry.name) : tokens,
236
+ query_token_coverage: verbose?.names(entry.name) ? tokenize(entry.name).length / tokens.length : 1,
237
237
  });
238
- return finish(0.951);
238
+ return finish(0.951, verbose?.names(entry.name) ? 0.951 : undefined);
239
239
  }
240
240
  }
241
241
  // Searchable text — joined once so per-token includes() is cheap
@@ -1,3 +1,6 @@
1
+ import { resolveRulePrecedence } from '../rules/precedence.mjs';
2
+ import { loadRulePinConfigs } from '../rules/pins.mjs';
3
+ import { ruleOrderingAliases } from '../rules/project-precedence.js';
1
4
  // Render show metadata cards, sections, and companion resources.
2
5
  import * as fs from 'node:fs';
3
6
  import * as path from 'node:path';
@@ -146,6 +149,7 @@ export async function emitShowCard(cwd, aiwgRoot, entry, filePath, source, param
146
149
  title: entry.title, path: filePath, description: String(data.description ?? data.summary ?? flow?.description ?? entry.capability ?? entry.ruleSummary ?? entry.summary ?? ''),
147
150
  capability: owner ? { kind, name: owner[2] } : null, installed, kernel: entry.kernel ?? false,
148
151
  ...(['rule', 'behavior'].includes(entry.type) ? {
152
+ ...resolveRulePrecedence({ ...data, name: entry.name, id: discoveryIdForEntry(entry) }, loadRulePinConfigs(cwd), ruleOrderingAliases(filePath, aiwgRoot ?? cwd, cwd)),
149
153
  activation: localPin ? 'kernel' : entry.activation ?? data.activation ?? null, enforcement: data.enforcement ?? entry.ruleEnforcement ?? null,
150
154
  bound_to: data.bound_to ?? entry.bound_to ?? {},
151
155
  } : {}),
@@ -190,7 +194,7 @@ export async function emitShowCard(cwd, aiwgRoot, entry, filePath, source, param
190
194
  if (pinNote)
191
195
  lines.push(pinNote);
192
196
  if ('activation' in card)
193
- lines.push(`Activation: ${card.activation} | enforcement: ${card.enforcement}`, `Bound targets: ${JSON.stringify(card.bound_to)}`);
197
+ lines.push(`Activation: ${card.activation} | enforcement: ${card.enforcement}`, `Precedence: ${card.precedence} | overridable: ${card.overridable} | source: ${card.precedence_source} | project context: ${card.project_context}`, `Bound targets: ${JSON.stringify(card.bound_to)}`);
194
198
  lines.push(...templateRelationLines(extra));
195
199
  lines.push(contentNotice, bindings.text || RULE_CHECK_OBLIGATION, '\n## Outline', ...card.outline.map(section => `- ${section.heading} (${section.bytes} bytes, ${section.lines} lines)`), '\n## Resources', ...resources.map(resource => `- ${resource.path} (${resource.bytes} bytes)`), '\n## Drill in', ...Object.values(card.drill_in).flat().map(command => `- ${command}`));
196
200
  if (card.resource)
@@ -13,7 +13,7 @@ export function resolveMetadataPath(cwd, aiwgRoot, entry) {
13
13
  if (path.isAbsolute(entry.path))
14
14
  return entry.path;
15
15
  const normalizedPath = normalizeIndexedPath(entry.path);
16
- if (aiwgRoot && normalizedPath.startsWith('agentic/code/')) {
16
+ if (aiwgRoot && (entry.indexScope === 'packaged' || normalizedPath.startsWith('agentic/code/'))) {
17
17
  return path.join(aiwgRoot, normalizedPath);
18
18
  }
19
19
  if (entry.indexScope === 'user' && normalizedPath.startsWith('~/.aiwg/')) {
@@ -5,7 +5,7 @@ import { isArtifactInstalled } from './query-engine-installation.js';
5
5
  import { findCorpusArtifact } from './query-engine-corpus.js';
6
6
  import { buildRunHint, DEFAULT_ARTIFACT_SEARCH_BACKEND, discoveryIdForEntry, normalizeIndexedPath, } from './query-engine-entries.js';
7
7
  import { findShowMatches } from './query-engine-matching.js';
8
- import { showBindings } from './query-engine-rules.js';
8
+ import { showBindings, ruleOrderingFields } from './query-engine-rules.js';
9
9
  import { emitShowCard } from './query-engine-show-card.js';
10
10
  import { templateRelationFields } from './query-engine-templates.js';
11
11
  import { fortemiRecordForEntry, loadShowEntries, resolveMetadataPath } from './query-engine-show-load.js';
@@ -67,7 +67,7 @@ export async function showArtifact(cwd, params) {
67
67
  ? `Run \`aiwg use ${corpusMatch.bundleId}\` to install this ${corpusMatch.bundleKind} into the workspace.`
68
68
  : 'Run `aiwg index build --graph framework` to refresh the artifact index.';
69
69
  const fallbackEntry = { path: path.relative(aiwgRoot, corpusMatch.path), type: corpusMatch.type, name: needle, title: needle };
70
- const bindings = await showBindings(entries, fallbackEntry, content, params, rule => fs.readFile(resolveMetadataPath(cwd, aiwgRoot, rule), 'utf8'), relations);
70
+ const bindings = await showBindings(entries, fallbackEntry, content, params, rule => fs.readFile(resolveMetadataPath(cwd, aiwgRoot, rule), 'utf8'), relations, rule => ruleOrderingFields(cwd, aiwgRoot ?? cwd, rule, resolveMetadataPath(cwd, aiwgRoot, rule)));
71
71
  await emitShowCard(cwd, aiwgRoot, fallbackEntry, corpusMatch.path, content, params, bindings, { uninstalled: !installed, installed, hint: installHint,
72
72
  ...(localPin ? { local_pin: localPin } : {}), ...templateRelationFields(fallbackEntry, relations) }, true);
73
73
  return;
@@ -169,7 +169,7 @@ export async function showArtifact(cwd, params) {
169
169
  webReleaseOptions: params.webReleaseOptions, offline: params.offline,
170
170
  });
171
171
  return resolved.bytes.toString('utf8');
172
- }, relations);
172
+ }, relations, rule => ruleOrderingFields(cwd, aiwgRoot ?? cwd, rule, resourceSource === 'local' ? resolvePath(rule) : undefined));
173
173
  const providerModels = resourceSource === 'local' ? await loadProviderModelMetadata(cwd, aiwgRoot) : null;
174
174
  await emitShowCard(cwd, aiwgRoot, entry, filePath, content, params, bindings, {
175
175
  ...templateRelationFields(entry, relations),
@@ -25,9 +25,15 @@ export function templateRelationFields(entry, reader, limit = Infinity, includeP
25
25
  }) };
26
26
  }
27
27
  export function templateRelationLines(fields) {
28
- return Object.entries(fields).filter(([, items]) => items?.length).flatMap(([key, items]) => [
29
- `\n## ${key === 'templates' ? 'Templates' : 'Used by'}`,
30
- ...items.map(item => `- ${item.name} (${item.type}): ${item.title} — \`${item.show_command}\``),
31
- ]);
28
+ // Cards also carry strings such as run_hint and hint; only relations are lists.
29
+ return ['templates', 'used_by'].flatMap(key => {
30
+ const items = fields[key];
31
+ if (!Array.isArray(items) || !items.length)
32
+ return [];
33
+ return [
34
+ `\n## ${key === 'templates' ? 'Templates' : 'Used by'}`,
35
+ ...items.map(item => `- ${item.name} (${item.type}): ${item.title} — \`${item.show_command}\``),
36
+ ];
37
+ });
32
38
  }
33
39
  //# sourceMappingURL=query-engine-templates.js.map
@@ -1,12 +1,25 @@
1
1
  // Calibrate verbose-query evidence around the leading intent and weighted token coverage.
2
+ function namedSubject(text, tokenize) {
3
+ // A command/skill named in the request is more specific than authoring vocabulary.
4
+ // Limit this to the leading clause so examples and trailing context cannot redirect it.
5
+ const leading = text.split(/[.!?;:\n]/, 1)[0];
6
+ const explicit = leading.match(/\b(?:command|skill)\s+(?:called|named)\s+[`"']?([a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)\b/i);
7
+ const before = leading.match(/\b([a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)[`"']?\s+(?:command|skill)\b/i);
8
+ const after = leading.match(/\b(?:command|skill)\s+(?:called\s+|named\s+)?[`"']?([a-z][a-z0-9]*(?:[-_][a-z0-9]+)*)\b/i);
9
+ return [explicit?.[1], before?.[1], after?.[1]].find(value => value && tokenize(value).length)
10
+ ?.toLowerCase().replace(/[-_]+/g, ' ');
11
+ }
2
12
  export function verboseQueryProfile(text, tokens, tokenize) {
3
- // Short capability phrases retain their established lexical scores.
4
- if (tokens.length <= 8)
13
+ const subject = namedSubject(text, tokenize);
14
+ const subjectTokens = new Set(subject ? tokenize(subject) : []);
15
+ const named = subjectTokens.size > 0;
16
+ // Short capability phrases retain their established lexical scores unless they name a subject.
17
+ if (tokens.length <= 8 && !named)
5
18
  return undefined;
6
19
  const prose = text.replace(/(`+)[\s\S]*?\1/g, ' ');
7
20
  const proseTokens = new Set(tokenize(prose));
8
- const leading = new Set(tokenize(prose.split(/[.!?;:\n]/, 1)[0]).slice(0, 8));
9
- const contextCount = tokens.filter(token => proseTokens.has(token) && !leading.has(token)).length;
21
+ const leading = named ? subjectTokens : new Set(tokenize(prose.split(/[.!?;:\n]/, 1)[0]).slice(0, 8));
22
+ const contextCount = tokens.filter(token => (named || proseTokens.has(token)) && !leading.has(token)).length;
10
23
  // Context gets at most a quarter of the leading clause's total weight.
11
24
  // Code-only words carry still less signal, but remain discoverable.
12
25
  const contextWeight = Math.min(0.25, Math.max(1, leading.size) / (4 * Math.max(1, contextCount)));
@@ -15,6 +28,7 @@ export function verboseQueryProfile(text, tokens, tokenize) {
15
28
  const mass = (hits) => hits.reduce((sum, token) => sum + (weights.get(token) ?? 0), 0);
16
29
  const total = mass(tokens);
17
30
  return {
31
+ names: (name) => named && name.toLowerCase().replace(/[-_\s]+/g, ' ').trim() === subject,
18
32
  weight: (hits) => mass(hits) / Math.max(1, hits.length),
19
33
  coverage: (matches) => {
20
34
  const hits = [...new Set(matches.flatMap(match => match.matched_tokens ?? tokens))];
@@ -68,6 +68,7 @@ export function buildRelations(entries) {
68
68
  index.rules[id] = {
69
69
  name: rule.name ?? slug(rule), path: rule.path, type: rule.type,
70
70
  activation: rule.activation ?? null, enforcement: rule.ruleEnforcement ?? null,
71
+ precedence: rule.rulePrecedence ?? 'medium', overridable: rule.ruleOverridable ?? true,
71
72
  summary: rule.ruleSummary ?? '', capability: capability?.id ?? null,
72
73
  ...(rule.rulePaths ? { paths: rule.rulePaths } : {}),
73
74
  ...(rule.triggers?.length ? { triggers: rule.triggers } : {}),
@@ -110,7 +110,7 @@ export const INDEX_VERSION = '1.0.0';
110
110
  * making the serialized index schema incompatible; a mismatch simply forces a
111
111
  * one-time content re-extraction during the next incremental build.
112
112
  */
113
- export const INDEX_EXTRACTOR_VERSION = '2026.11.06.1';
113
+ export const INDEX_EXTRACTOR_VERSION = '2026.11.10.1';
114
114
  /**
115
115
  * Built-in graph definitions
116
116
  */
@@ -26,7 +26,8 @@ export async function writeCheckpointHandoff(frameworkRoot, checkpointsDir, reco
26
26
  links: record.artifacts.length ? record.artifacts.map(path => `- ${path}`).join('\n')
27
27
  : '- [TODO: Link relevant artifacts and references.]',
28
28
  };
29
- const handoff = template.replace(/\{\{(\w+)\}\}/g, (match, key) => fields[key] ?? match);
29
+ const body = template.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '');
30
+ const handoff = body.replace(/\{\{(\w+)\}\}/g, (match, key) => fields[key] ?? match);
30
31
  const prompt = [
31
32
  `Continue checkpoint ${record.id}${record.name ? ` (${record.name})` : ''} in ${record.cwd}.`,
32
33
  'Read WORKSPACE.md and AIWG.md if present, then read the handoff:',
@@ -74,7 +74,9 @@ export function parseGuidedSetupFlags(args, command) {
74
74
  throw new Error('--workspace, --monorepo, --package and --scan-roots are available on setup.');
75
75
  }
76
76
  // The strict helpers honor the bare -- terminator, including malformed later occurrences.
77
- const enabled = NEW_FLAGS.some(name => value(name) !== undefined) || tokenStdin || verify || remove;
77
+ // Init opts into planning only through its documented selectors; Jev options are answers.
78
+ const enabled = command === 'init' ? ['--scope', '--intent', '--credential'].some(name => value(name) !== undefined)
79
+ : NEW_FLAGS.some(name => value(name) !== undefined) || tokenStdin || verify || remove;
78
80
  return { jev: jev ?? (remove ? 'decline' : undefined) ?? (tokenStdin || region || endpoint || verify ? 'enable' : undefined), jevOptions, scope, intent, monorepo, packageRoot, workspaces: workspaces.length ? workspaces : undefined,
79
81
  scanRoots: scanRoots.length ? scanRoots : undefined, credentials, enabled };
80
82
  }
@@ -4,7 +4,8 @@ import path from 'node:path';
4
4
  import { isDeepStrictEqual } from 'node:util';
5
5
  import { lt, valid } from 'semver';
6
6
  import { managedClaudeHooks } from '../../extensions/claude-hooks-installer.js';
7
- import { AIWG_MANAGED_HOOKS } from '../../extensions/muse-managed-hooks.js';
7
+ import { verifiedHookCommand } from '../../extensions/verified-hook-command.js';
8
+ import { managedMuseHooks } from '../../extensions/muse-managed-hooks.js';
8
9
  import { managedHookScriptState } from '../../extensions/managed-hook-script-state.js';
9
10
  import { managedFactoryHooks } from '../../smiths/hook-bridge/factory-translator.js';
10
11
  import { readFactoryDocument } from '../../smiths/hook-bridge/factory-hook-config.js';
@@ -41,7 +42,7 @@ function groups(doc, event) {
41
42
  return Array.isArray(hooks?.[event]) ? hooks[event] : [];
42
43
  }
43
44
  async function staleHooks(projectRoot, frameworkRoot, provider) {
44
- if (!['claude', 'muse', 'factory'].includes(provider))
45
+ if (!['claude', 'muse', 'factory', 'codex'].includes(provider))
45
46
  return [];
46
47
  const file = provider === 'claude' ? '.claude/settings.json' : `.${provider}/hooks.json`;
47
48
  let doc;
@@ -53,7 +54,18 @@ async function staleHooks(projectRoot, frameworkRoot, provider) {
53
54
  return [{ name: `${provider} managed hooks`, file, reason: 'unreadable' }];
54
55
  }
55
56
  const stale = [];
56
- if (provider === 'factory') {
57
+ if (provider === 'codex') {
58
+ const { sources } = await loadHookSources(frameworkRoot);
59
+ const source = sources.find(hook => hook.id === 'aiwg-prompt-discovery');
60
+ if (!source?.args?.[0])
61
+ return [];
62
+ const expected = verifiedHookCommand(projectRoot, '.codex/hooks/aiwg-prompt-discovery.cjs', await fs.readFile(source.args[0]));
63
+ const candidates = groups(doc, 'UserPromptSubmit').flatMap(group => group.hooks || [])
64
+ .filter(hook => hook._aiwg_id === source.id);
65
+ if (!candidates.some(hook => hook.command === expected && hook.statusMessage === 'AIWG prompt discovery'))
66
+ stale.push({ name: `UserPromptSubmit → ${source.id}`, file, reason: candidates.length ? 'outdated' : 'missing' });
67
+ }
68
+ else if (provider === 'factory') {
57
69
  for (const hook of managedFactoryHooks()) {
58
70
  const candidates = groups(doc, hook.event).flatMap(group => Array.isArray(group?.hooks) ? group.hooks : [])
59
71
  .filter(entry => entry && (entry._aiwg_id === hook.id || entry.command === hook.command));
@@ -74,7 +86,7 @@ async function staleHooks(projectRoot, frameworkRoot, provider) {
74
86
  return [];
75
87
  throw error;
76
88
  }
77
- for (const hook of managedClaudeHooks(sourceFiles)) {
89
+ for (const hook of managedClaudeHooks(sourceFiles, projectRoot, source)) {
78
90
  const candidates = groups(doc, hook.event).flatMap(group => Array.isArray(group?.hooks) ? group.hooks : [])
79
91
  .filter(entry => entry && (entry._aiwg_id === hook.hookId ||
80
92
  (typeof entry.command === 'string' && entry.command.includes(hook.script))));
@@ -93,7 +105,7 @@ async function staleHooks(projectRoot, frameworkRoot, provider) {
93
105
  recorded = sidecar.hooks;
94
106
  }
95
107
  catch { /* The live document still proves canonical registrations without a sidecar. */ }
96
- for (const hook of AIWG_MANAGED_HOOKS) {
108
+ for (const hook of managedMuseHooks(projectRoot, await fs.readFile(path.join(frameworkRoot, 'agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs')))) {
97
109
  const deployed = groups(doc, hook.event);
98
110
  if (deployed.some(group => isDeepStrictEqual(group, hook.group)))
99
111
  continue;
@@ -77,7 +77,7 @@ export const rulesHandler = {
77
77
  const { ruleInventory } = await import('../../rules/inventory.js');
78
78
  const report = await ruleInventory(ctx.cwd, ctx.frameworkRoot, { scope: scope, capability: list('--capability'), activation, enforcement: tier, provider: values.get('--provider'), bodies: flags.has('--bodies') });
79
79
  return { exitCode: 0, rawOutput: true, message: json ? JSON.stringify(report, null, 2) :
80
- [`Scope: ${report.scope} (${report.scope_description})`, 'Per-rule delivery and session loading: unknown.', ...report.rules.map(rule => `${rule.capability}/${rule.name} [${rule.effective_activation ?? 'unconfigured'}, ${rule.enforcement ?? 'unknown'}]: ${rule.summary ?? '(no summary)'}; ${rule.fetch_command ?? 'fetch ID unknown'}${rule.content ? `\n${rule.content}` : ''}`), ...report.warnings, ...(!report.rules.length ? ['No matching rules.'] : [])].join('\n') };
80
+ [`Scope: ${report.scope} (${report.scope_description})`, 'Per-rule delivery and session loading: unknown.', ...report.rules.map(rule => `${rule.capability}/${rule.name} [${rule.effective_activation ?? 'unconfigured'}, ${rule.enforcement ?? 'unknown'}; precedence: ${rule.precedence}; overridable: ${rule.overridable}; source: ${rule.precedence_source}; project context: ${rule.project_context}]: ${rule.summary ?? '(no summary)'}; ${rule.fetch_command ?? 'fetch ID unknown'}${rule.content ? `\n${rule.content}` : ''}`), ...report.warnings, ...(!report.rules.length ? ['No matching rules.'] : [])].join('\n') };
81
81
  }
82
82
  if (values.has('--scope') || values.has('--activation') || values.has('--provider') || flags.has('--bodies'))
83
83
  throw new Error('Inventory filters are only valid for rules inventory');
@@ -19,10 +19,13 @@ import { providerDeploymentLockEnvironment } from '../../providers/deployment-lo
19
19
  // Embedded deployers use process-wide console/environment APIs. Serialize the
20
20
  // complete invocation (including import), and restore them even after failure.
21
21
  let deploymentQueue = Promise.resolve();
22
- function reportFlueWarnings(message, sink = console) {
23
- for (const line of message.split(/\r?\n/))
22
+ function reportDeploymentWarnings(message, sink = console) {
23
+ for (const line of message.split(/\r?\n/)) {
24
24
  if (line.startsWith('Flue (experimental):'))
25
25
  sink.warn(line);
26
+ else if (/^Removing .+ \((?:critical )?rule retired because /.test(line))
27
+ process.stderr.write(`${line}\n`);
28
+ }
26
29
  }
27
30
  /**
28
31
  * Default script runner implementation
@@ -137,7 +140,7 @@ export class DefaultScriptRunner {
137
140
  }
138
141
  else {
139
142
  if (options.capture && code === 0 && scriptPath === 'tools/agents/deploy-agents.mjs') {
140
- reportFlueWarnings(Buffer.concat(capturedStderr).toString());
143
+ reportDeploymentWarnings(Buffer.concat(capturedStderr).toString());
141
144
  }
142
145
  resolve({
143
146
  exitCode: code ?? 0,
@@ -197,7 +200,7 @@ export class DefaultScriptRunner {
197
200
  const message = Buffer.concat(diagnostics).toString().trim()
198
201
  || (exitCode ? `Deployment script exited with code ${exitCode}: ${path.basename(fullPath)}` : '');
199
202
  if (exitCode === 0 && options.capture)
200
- reportFlueWarnings(message, previousConsole);
203
+ reportDeploymentWarnings(message, previousConsole);
201
204
  return exitCode || message ? { exitCode, message } : { exitCode };
202
205
  }
203
206
  catch (error) {