@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
@@ -1,75 +1,106 @@
1
1
  /** Bounded Grok Build headless transport. The caller owns task authorization. */
2
2
  import { signalChild } from '../process/signal-child.mjs';
3
3
  import { spawn } from 'node:child_process';
4
+ /** Failed runs retain redacted partial output and observed accounting. */
5
+ export class GrokHeadlessError extends Error {
6
+ result;
7
+ constructor(message, result) {
8
+ super(message);
9
+ this.result = result;
10
+ this.name = 'GrokHeadlessError';
11
+ }
12
+ }
4
13
  const MAX_TIMEOUT_MS = 10 * 60_000;
5
14
  const DEFAULT_TIMEOUT_MS = 2 * 60_000;
6
15
  const DEFAULT_MAX_OUTPUT = 8 * 1024 * 1024;
7
- // grok 1.0.50 --output-format streaming-json: ACP session updates.
8
- // See docs/providers/grok-build-cli-evidence.md; json is a separate result object.
16
+ // Captured 1.0.77 headless events; this is not the agent-stdio ACP contract.
9
17
  const STREAM_EVENT_TYPES = new Set(['text', 'thought', 'tool_call', 'tool_call_update',
10
18
  'usage', 'plan', 'available_commands', 'end', 'error']);
19
+ const MESSAGE_EVENT_TYPES = new Set(['system', 'assistant', 'user', 'result', 'error']);
11
20
  export function redactGrokOutput(value, env = process.env) {
12
21
  let redacted = value
22
+ .replace(/("(?:api[_-]?key|access[_-]?token|authorization)"\s*:\s*)"(?:\\.|[^"\\])*"/gi, '$1"[REDACTED]"')
13
23
  .replace(/\b(Bearer\s+)[A-Za-z0-9._~+/-]+/gi, '$1[REDACTED]')
14
24
  .replace(/\b(xai-[A-Za-z0-9_-]{8,})\b/g, '[REDACTED]')
15
25
  .replace(/\b((?:api[_-]?key|access[_-]?token|authorization)\s*[:=]\s*)[^\s,}"']+/gi, '$1[REDACTED]');
16
26
  for (const key of ['XAI_API_KEY', 'GROK_CODE_XAI_API_KEY']) {
17
27
  const secret = env[key];
18
- if (secret && secret.length >= 4)
28
+ if (secret && secret.length >= 4) {
19
29
  redacted = redacted.split(secret).join('[REDACTED]');
30
+ redacted = redacted.split(JSON.stringify(secret).slice(1, -1)).join('[REDACTED]');
31
+ }
20
32
  }
21
33
  return redacted;
22
34
  }
23
- function scrubEvent(event, env) {
24
- // JSON roundtrip scrubs nested provider event payloads before any callback.
25
- return JSON.parse(redactGrokOutput(JSON.stringify(event), env));
35
+ function scrub(value, env) {
36
+ if (typeof value === 'string')
37
+ return redactGrokOutput(value, env);
38
+ if (Array.isArray(value))
39
+ return value.map(item => scrub(item, env));
40
+ if (value && typeof value === 'object') {
41
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [redactGrokOutput(key, env),
42
+ /^(?:api[_-]?key|access[_-]?token|authorization)$/i.test(key) ? '[REDACTED]' : scrub(item, env)]));
43
+ }
44
+ return value;
26
45
  }
27
- function isTerminal(event) {
28
- return event.type === 'end' || event.type === 'error';
46
+ function record(value) {
47
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
29
48
  }
30
49
  function isError(event) {
31
50
  return event.type === 'error' || event.is_error === true || event.error != null
32
- || (event.type === 'end' && event.stopReason !== 'end_turn')
51
+ || (Array.isArray(event.errors) && event.errors.length > 0)
52
+ || (event.type === 'result' && event.subtype !== 'success')
33
53
  || (['tool_call', 'tool_call_update'].includes(String(event.type)) && event.status === 'failed');
34
54
  }
35
- function stopProcess(child) {
55
+ function signalProcess(child, signal) {
36
56
  if (Number.isSafeInteger(child.pid) && child.pid > 0 && process.platform !== 'win32') {
37
57
  try {
38
- process.kill(-child.pid, 'SIGTERM');
58
+ process.kill(-child.pid, signal);
39
59
  return;
40
60
  }
41
61
  catch { /* process already exited */ }
42
62
  }
43
- signalChild(child, 'SIGTERM');
63
+ signalChild(child, signal);
44
64
  }
45
65
  export async function runGrokHeadless(options) {
46
66
  if (!options.prompt.trim())
47
67
  throw new Error('Grok Build prompt is required');
48
68
  const format = options.format ?? 'streaming-json';
49
- if (!['plain', 'json', 'streaming-json'].includes(format))
69
+ if (!['plain', 'json', 'streaming-json', 'streaming-messages-json'].includes(format))
50
70
  throw new Error(`Unsupported Grok output format: ${format}`);
51
- const timeoutMs = Math.min(Math.max(options.timeoutMs ?? DEFAULT_TIMEOUT_MS, 1), MAX_TIMEOUT_MS);
71
+ for (const key of ['timeoutMs', 'maxOutputBytes']) {
72
+ if (options[key] !== undefined && (!Number.isFinite(options[key]) || options[key] <= 0)) {
73
+ throw new Error(`Grok Build ${key} must be a positive finite number`);
74
+ }
75
+ }
76
+ const timeoutMs = Math.min(options.timeoutMs ?? DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS);
52
77
  const maxBytes = Math.min(Math.max(options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT, 1024), DEFAULT_MAX_OUTPUT);
53
78
  const env = options.env ?? process.env;
54
- const args = [...(options.prefixArgs ?? []), ...(options.disableSubagents ? ['--no-subagents'] : []), '-p', options.prompt, '--output-format', format];
79
+ // 1.0.77: workflow can spawn children even when spawn_subagent is disabled.
80
+ const args = [...(options.prefixArgs ?? []), '--no-auto-update', '--allow', 'Bash(aiwg discover *)', ...(options.disableSubagents ? ['--no-subagents', '--disallowed-tools', 'workflow'] : []), '-p', options.prompt, '--output-format', format];
81
+ const streaming = format === 'streaming-json' || format === 'streaming-messages-json';
55
82
  return new Promise((resolve, reject) => {
56
83
  const child = spawn(options.command ?? 'grok', args, {
57
- cwd: options.cwd,
58
- env,
59
- stdio: ['ignore', 'pipe', 'pipe'],
60
- detached: process.platform !== 'win32',
61
- shell: false,
84
+ cwd: options.cwd, env, stdio: ['ignore', 'pipe', 'pipe'],
85
+ detached: process.platform !== 'win32', shell: false,
62
86
  });
87
+ // Stateful decoders preserve code points split across pipe reads.
88
+ child.stdout.setEncoding('utf8');
89
+ child.stderr.setEncoding('utf8');
63
90
  let stdout = '';
64
91
  let stderr = '';
65
92
  let pending = '';
66
93
  let bytes = 0;
94
+ let stderrBytes = 0;
67
95
  let settled = false;
96
+ let closed = false;
97
+ let exitCode;
98
+ let exitSignal = null;
68
99
  let terminalSeen = false;
69
100
  let terminalError = false;
70
101
  const events = [];
71
102
  let drainTimer;
72
- const finish = (error, code = 0) => {
103
+ const finish = (error, code = exitCode ?? 0) => {
73
104
  if (settled)
74
105
  return;
75
106
  settled = true;
@@ -77,86 +108,126 @@ export async function runGrokHeadless(options) {
77
108
  if (drainTimer)
78
109
  clearTimeout(drainTimer);
79
110
  options.signal?.removeEventListener('abort', abort);
80
- if (error) {
81
- stopProcess(child);
82
- reject(error);
83
- return;
111
+ if (format === 'json') {
112
+ try {
113
+ const parsed = JSON.parse(stdout);
114
+ if (!record(parsed) || typeof parsed.text !== 'string')
115
+ throw new Error('Invalid result');
116
+ const safe = scrub(parsed, env);
117
+ events.push(safe);
118
+ if (isError(safe) || safe.stopReason !== 'end_turn')
119
+ error ??= new Error('Grok Build returned a JSON error result');
120
+ }
121
+ catch {
122
+ error ??= new Error('Invalid Grok Build JSON error result');
123
+ }
84
124
  }
85
- const cleanStdout = redactGrokOutput(stdout, env);
86
- const cleanStderr = redactGrokOutput(stderr, env);
87
- if (code !== 0 || terminalError) {
88
- reject(new Error(`Grok Build headless failed (exit ${code}): ${cleanStderr || 'provider error event'}`));
89
- return;
125
+ if (code !== 0 || exitSignal || terminalError) {
126
+ error ??= new Error(`Grok Build headless failed (exit ${code}${exitSignal ? `, signal ${exitSignal}` : ''}): ${stderr || 'provider error event'}`);
127
+ }
128
+ if (streaming && !terminalSeen)
129
+ error ??= new Error(`Grok Build ${format} ended without a terminal event`);
130
+ const result = { format, text: redactGrokOutput(stdout, env), events,
131
+ exitCode: code, stderr: redactGrokOutput(stderr, env) };
132
+ // Terminal totals supersede per-turn usage; never sum cumulative frames.
133
+ for (const event of events) {
134
+ const reason = event.stopReason ?? event.stop_reason;
135
+ if (typeof reason === 'string')
136
+ result.stopReason = reason;
137
+ for (const key of ['usage', 'modelUsage']) {
138
+ const value = event[key] ?? (key === 'usage' && record(event.message) ? event.message.usage : undefined);
139
+ if (record(value))
140
+ result[key] = value;
141
+ }
142
+ for (const key of ['num_turns', 'total_cost_usd', 'total_cost_usd_ticks']) {
143
+ if (typeof event[key] === 'number' && Number.isFinite(event[key]))
144
+ result[key] = event[key];
145
+ }
90
146
  }
91
- if (format === 'streaming-json' && !terminalSeen) {
92
- reject(new Error('Grok Build streaming-json ended without a terminal event'));
147
+ const complete = () => {
148
+ if (error)
149
+ reject(new GrokHeadlessError(redactGrokOutput(error.message, env), result));
150
+ else
151
+ resolve(result);
152
+ };
153
+ if (closed) {
154
+ complete();
93
155
  return;
94
156
  }
95
- if (format === 'json') {
96
- try {
97
- const parsed = JSON.parse(cleanStdout);
98
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)
99
- || typeof parsed.text !== 'string' || isError(parsed)
100
- || parsed.stopReason !== 'end_turn')
101
- throw new Error('Grok Build returned a JSON error result');
102
- events.push(parsed);
103
- }
104
- catch (cause) {
105
- reject(cause instanceof Error ? cause : new Error('Invalid Grok Build JSON result'));
157
+ // Bound cleanup even for a child ignoring TERM or descendants holding pipes.
158
+ signalProcess(child, 'SIGTERM');
159
+ setTimeout(() => {
160
+ signalProcess(child, 'SIGKILL');
161
+ child.stdout.destroy();
162
+ child.stderr.destroy();
163
+ complete();
164
+ }, 150);
165
+ };
166
+ const abort = () => finish(new Error('Grok Build headless aborted'), 1);
167
+ const timer = setTimeout(() => finish(new Error(`Grok Build headless timed out after ${timeoutMs}ms`), 1), timeoutMs);
168
+ const drain = () => {
169
+ drainTimer ??= setTimeout(() => {
170
+ if (streaming && pending.trim()) {
171
+ finish(new Error(`Invalid trailing Grok Build ${format} event`));
106
172
  return;
107
173
  }
108
- }
109
- resolve({ format, text: cleanStdout, events, exitCode: code, stderr: cleanStderr });
174
+ finish();
175
+ }, 300);
110
176
  };
111
- const abort = () => finish(new Error('Grok Build headless aborted'));
112
- const timer = setTimeout(() => finish(new Error(`Grok Build headless timed out after ${timeoutMs}ms`)), timeoutMs);
113
177
  options.signal?.addEventListener('abort', abort, { once: true });
114
178
  if (options.signal?.aborted)
115
179
  abort();
116
- child.on('error', error => finish(new Error(`Grok Build headless launch failed: ${error.message}`)));
180
+ child.on('error', error => finish(new Error(`Grok Build headless launch failed: ${error.message}`), 1));
117
181
  const acceptEvent = (event) => {
118
182
  if (settled)
119
183
  return;
120
- if (!event || typeof event !== 'object' || Array.isArray(event)
121
- || typeof event.type !== 'string' || !STREAM_EVENT_TYPES.has(event.type)) {
122
- finish(new Error('Invalid Grok Build streaming-json event'));
184
+ const types = format === 'streaming-messages-json' ? MESSAGE_EVENT_TYPES : STREAM_EVENT_TYPES;
185
+ if (!record(event) || typeof event.type !== 'string' || !types.has(event.type)) {
186
+ finish(new Error(`Invalid Grok Build ${format} event`));
123
187
  return;
124
188
  }
125
- // ACP end is always last. Failure is latched across the whole stream.
126
189
  if (terminalSeen) {
127
190
  finish(new Error('Grok Build event after terminal event'));
128
191
  return;
129
192
  }
130
- const safe = scrubEvent(event, env);
193
+ if (['assistant', 'user'].includes(event.type) && (!record(event.message) || !Array.isArray(event.message.content))) {
194
+ finish(new Error('Invalid Grok Build message envelope'));
195
+ return;
196
+ }
197
+ const safe = scrub(event, env);
131
198
  events.push(safe);
132
- options.onEvent?.(safe);
133
- if (isError(safe))
199
+ const terminal = event.type === 'error' || event.type === (format === 'streaming-messages-json' ? 'result' : 'end');
200
+ if (isError(safe) || (terminal && (safe.stopReason ?? safe.stop_reason) !== 'end_turn'))
134
201
  terminalError = true;
135
- if (isTerminal(safe)) {
202
+ if (terminal) {
136
203
  terminalSeen = true;
137
- // Some builds leave background work attached after end. Allow a
138
- // short drain, then terminate the process group.
139
- drainTimer ??= setTimeout(() => {
140
- if (pending.trim()) {
141
- finish(new Error('Invalid trailing Grok Build streaming-json event'));
142
- return;
143
- }
144
- stopProcess(child);
145
- finish(undefined, terminalError ? 1 : 0);
146
- }, 300);
204
+ drain();
205
+ }
206
+ try {
207
+ options.onEvent?.(safe);
208
+ }
209
+ catch (cause) {
210
+ finish(new Error(`Grok Build event callback failed: ${cause instanceof Error ? cause.message : String(cause)}`));
147
211
  }
148
212
  };
149
- child.stdout.on('data', (chunk) => {
213
+ child.stdout.on('data', (part) => {
150
214
  if (settled)
151
215
  return;
152
- bytes += chunk.length;
216
+ bytes += Buffer.byteLength(part);
153
217
  if (bytes > maxBytes) {
154
218
  finish(new Error(`Grok Build headless output exceeded ${maxBytes} bytes`));
155
219
  return;
156
220
  }
157
- const part = chunk.toString('utf8');
158
221
  stdout += part;
159
- if (format !== 'streaming-json')
222
+ if (format === 'json') {
223
+ // A complete result can arrive without a newline or process exit.
224
+ try {
225
+ if (record(JSON.parse(stdout)))
226
+ drain();
227
+ }
228
+ catch { /* wait for the remainder */ }
229
+ }
230
+ if (!streaming)
160
231
  return;
161
232
  pending += part;
162
233
  let end;
@@ -170,26 +241,49 @@ export async function runGrokHeadless(options) {
170
241
  event = JSON.parse(line);
171
242
  }
172
243
  catch {
173
- finish(new Error('Invalid Grok Build streaming-json event'));
244
+ finish(new Error(`Invalid Grok Build ${format} event`));
174
245
  return;
175
246
  }
176
247
  acceptEvent(event);
177
248
  if (settled)
178
249
  return;
179
250
  }
251
+ // Parse complete newline-free frames now so background work cannot hold us.
252
+ if (pending.trim()) {
253
+ let event;
254
+ try {
255
+ event = JSON.parse(pending);
256
+ }
257
+ catch {
258
+ return;
259
+ }
260
+ pending = '';
261
+ acceptEvent(event);
262
+ }
180
263
  });
181
- child.stderr.on('data', (chunk) => {
182
- stderr += chunk.toString('utf8');
183
- if (Buffer.byteLength(stderr) > maxBytes)
264
+ child.stderr.on('data', (part) => {
265
+ if (settled)
266
+ return;
267
+ stderrBytes += Buffer.byteLength(part);
268
+ if (stderrBytes > maxBytes) {
184
269
  finish(new Error(`Grok Build stderr exceeded ${maxBytes} bytes`));
270
+ return;
271
+ }
272
+ stderr += part;
185
273
  });
274
+ child.on('exit', (code, signal) => { exitCode = code ?? 1; exitSignal = signal; });
186
275
  child.on('close', code => {
187
- if (format === 'streaming-json' && pending.trim()) {
276
+ closed = true;
277
+ if (settled)
278
+ return;
279
+ if (streaming && pending.trim()) {
280
+ const line = pending;
281
+ pending = '';
188
282
  try {
189
- acceptEvent(JSON.parse(pending));
283
+ acceptEvent(JSON.parse(line));
190
284
  }
191
285
  catch {
192
- finish(new Error('Invalid trailing Grok Build streaming-json event'));
286
+ finish(new Error(`Invalid trailing Grok Build ${format} event`));
193
287
  return;
194
288
  }
195
289
  }
@@ -169,6 +169,7 @@ export function runGrokInspect(envOrOptions = process.env) {
169
169
  const args = argSets[i];
170
170
  const wantsJson = args.length > 1 && args[1] === '--json';
171
171
  const result = spawnSync(binary, [...args], {
172
+ stdio: ['ignore', 'pipe', 'pipe'],
172
173
  encoding: 'utf8',
173
174
  env,
174
175
  cwd,
@@ -12,6 +12,8 @@
12
12
  */
13
13
  import { homedir } from 'node:os';
14
14
  import * as path from 'node:path';
15
+ /** Project-only opt-in bulk mirror, shared by the registry and deployment adapter. */
16
+ export const GROK_BUILD_STANDARD_SKILLS_PATH = '.grok/.aiwg/skills';
15
17
  export const GROK_HOME_ENV = 'GROK_HOME';
16
18
  export function isGrokFilesystemRoot(resolved, pathFlavor = path) {
17
19
  return pathFlavor.parse(resolved).root === resolved;
@@ -4,8 +4,8 @@
4
4
  * Muse Code's documented user skill root is `$XDG_CONFIG_HOME/muse/skills`
5
5
  * (default `~/.config/muse/skills` when XDG_CONFIG_HOME is unset). The
6
6
  * project skill root (`<repo>/.agents/skills`) is static provider metadata
7
- * on the `muse` skillNamespace; this module resolves only the XDG user root
8
- * at deploy time.
7
+ * on the `muse` skillNamespace; this module shares the project bulk mirror
8
+ * path and resolves the XDG user root at deploy time.
9
9
  *
10
10
  * Unlike Grok Bot (AIWG_GROKBOT_SKILLS_DIR, fail-closed until configured),
11
11
  * the Muse user root is documented, so an unset XDG_CONFIG_HOME falls back
@@ -21,6 +21,8 @@
21
21
  */
22
22
  import { homedir } from 'node:os';
23
23
  import * as path from 'node:path';
24
+ /** Project-only opt-in bulk mirror, shared by the registry and deployment adapter. */
25
+ export const MUSE_STANDARD_SKILLS_PATH = '.agents/.aiwg/skills';
24
26
  /** Muse's documented user skills subtree below the XDG config root. */
25
27
  export const MUSE_XDG_SKILLS_SUBDIR = path.join('muse', 'skills');
26
28
  /**
@@ -1,3 +1,4 @@
1
+ import { resolveHermesHomePath } from './hermes-home.js';
1
2
  const VERIFIED_ON = '2026-07-21';
2
3
  export const CONTEXT_CONTRACTS = {
3
4
  flue: {
@@ -32,6 +33,7 @@ export const CONTEXT_CONTRACTS = {
32
33
  verification: { method: 'official AGENTS.md discovery chain; no Markdown include claimed', source: 'https://developers.openai.com/codex/guides/agents-md', lastVerified: VERIFIED_ON },
33
34
  },
34
35
  copilot: {
36
+ promptDiscovery: { delivery: 'bootstrap-rule', files: ['.github/copilot-instructions.md'] },
35
37
  startupFiles: ['.github/copilot-instructions.md', 'AGENTS.md', 'CLAUDE.md'], precedence: ['personal', 'repository', 'organization; CLI combines applicable files'],
36
38
  loadMode: 'native-include', includeSyntax: '@WORKSPACE.md\n@AIWG.md', configRegistration: null,
37
39
  bootstrapTargets: ['.github/copilot-instructions.md', 'AGENTS.md'], maxContextBytes: null, recommendedMaxLines: null, nestedContext: true, support: 'supported',
@@ -72,6 +74,7 @@ export const CONTEXT_CONTRACTS = {
72
74
  },
73
75
  },
74
76
  'grok-build': {
77
+ promptDiscovery: { delivery: 'bootstrap-rule', files: ['AGENTS.md'] },
75
78
  // config.toml is configuration (MCP/plugins/permissions), not a startup/context file.
76
79
  // Hierarchical instructions: AGENTS.md + .grok/rules/*.md, root-to-cwd, deeper wins.
77
80
  startupFiles: ['AGENTS.md', '.grok/rules/*.md'],
@@ -90,6 +93,9 @@ export const CONTEXT_CONTRACTS = {
90
93
  },
91
94
  },
92
95
  hermes: {
96
+ promptDiscovery: { delivery: 'hook-bridge', event: 'pre_llm_call', optIn: true, files: [
97
+ resolveHermesHomePath('config.yaml'), resolveHermesHomePath('agent-hooks', 'aiwg-prompt-discovery.cjs'),
98
+ ] },
93
99
  startupFiles: ['.hermes.md', 'AGENTS.md'], precedence: ['provider/system', '.hermes.md', 'AGENTS.md'],
94
100
  loadMode: 'prose-directive', includeSyntax: null, configRegistration: null,
95
101
  bootstrapTargets: ['.hermes.md', 'AGENTS.md'], maxContextBytes: null, recommendedMaxLines: 30, nestedContext: false, support: 'degraded',
@@ -118,7 +124,9 @@ export const CONTEXT_CONTRACTS = {
118
124
  openclaw: {
119
125
  startupFiles: ['~/.openclaw/config.yaml'], precedence: ['provider/system', 'home configuration'],
120
126
  loadMode: 'unsupported', includeSyntax: null, configRegistration: null,
121
- bootstrapTargets: [], maxContextBytes: null, recommendedMaxLines: null, nestedContext: false, support: 'degraded',
127
+ // Default active workspace; the deployment adapter resolves profile/config overrides.
128
+ bootstrapTargets: ['~/.openclaw/workspace/AGENTS.md', '~/.openclaw/workspace/SOUL.md'],
129
+ maxContextBytes: null, recommendedMaxLines: null, nestedContext: false, support: 'degraded',
122
130
  verification: { method: 'AIWG home-scope adapter contract; no verified project startup file', source: 'agentic/code/providers/capability-matrix.yaml', lastVerified: VERIFIED_ON },
123
131
  },
124
132
  openhuman: {
@@ -162,9 +170,9 @@ export const CONTEXT_CONTRACTS = {
162
170
  verification: { method: 'AIWG Windsurf/Devin topology contract; provider-native rules retained', source: 'src/providers/provider-definitions.ts', lastVerified: VERIFIED_ON },
163
171
  },
164
172
  generic: {
165
- startupFiles: [], precedence: ['host policy'], loadMode: 'unsupported', includeSyntax: null, configRegistration: null,
166
- bootstrapTargets: [], maxContextBytes: null, recommendedMaxLines: null, nestedContext: false, support: 'unsupported',
167
- verification: { method: 'No provider selected; no startup-file claim', source: 'src/providers/provider-definitions.ts', lastVerified: VERIFIED_ON },
173
+ startupFiles: ['AGENTS.md'], precedence: ['host policy'], loadMode: 'prose-directive', includeSyntax: null, configRegistration: null,
174
+ bootstrapTargets: ['AGENTS.md'], maxContextBytes: null, recommendedMaxLines: null, nestedContext: false, support: 'degraded',
175
+ verification: { method: 'Portable Markdown adapter; host must explicitly load AGENTS.md; no automatic startup-file claim', source: 'tools/agents/providers/generic.mjs', lastVerified: VERIFIED_ON },
168
176
  },
169
177
  };
170
178
  //# sourceMappingURL=provider-context-contracts.js.map
@@ -93,6 +93,12 @@ export const ProviderDefinitionSchema = z.object({
93
93
  includeSyntax: z.string().nullable(),
94
94
  configRegistration: z.object({ file: z.string().min(1), key: z.string().min(1) }).nullable(),
95
95
  bootstrapTargets: z.array(z.string().min(1)),
96
+ promptDiscovery: z.object({
97
+ delivery: z.enum(['bootstrap-rule', 'hook-bridge']),
98
+ files: z.array(z.string().min(1)).min(1),
99
+ event: z.string().min(1).optional(),
100
+ optIn: z.boolean().optional(),
101
+ }).optional(),
96
102
  maxContextBytes: integer().positive().nullable(),
97
103
  recommendedMaxLines: integer().positive().nullable(),
98
104
  nestedContext: z.boolean(),
@@ -162,8 +162,8 @@ export const BUILT_IN_SEEDS_1 = [
162
162
  agents: '.github/agents',
163
163
  commands: '.github/commands',
164
164
  skills: '.github/.aiwg/skills',
165
- rules: '.github/copilot-rules',
166
- behaviors: '.github/copilot-rules',
165
+ rules: '.github/instructions',
166
+ behaviors: '.github/instructions',
167
167
  },
168
168
  kernelSkills: '.github/skills',
169
169
  contextDiscovery: {
@@ -179,7 +179,7 @@ export const BUILT_IN_SEEDS_1 = [
179
179
  agents: '.github/agents',
180
180
  commands: '.github/agents',
181
181
  skills: '.github/skills',
182
- rules: '.github/copilot-rules',
182
+ rules: '.github/instructions',
183
183
  fileExtension: '.md',
184
184
  configFile: 'copilot-instructions.md',
185
185
  aggregated: false,
@@ -1,4 +1,6 @@
1
1
  import { resolveHermesHomePath } from './hermes-home.js';
2
+ import { GROK_BUILD_STANDARD_SKILLS_PATH } from './grok-build-paths.js';
3
+ import { MUSE_STANDARD_SKILLS_PATH } from './muse-paths.js';
2
4
  export const BUILT_IN_SEEDS_2 = [
3
5
  {
4
6
  id: 'grok-build',
@@ -26,7 +28,7 @@ export const BUILT_IN_SEEDS_2 = [
26
28
  artifacts: {
27
29
  agents: '.grok/agents',
28
30
  commands: null,
29
- skills: '.grok/skills',
31
+ skills: GROK_BUILD_STANDARD_SKILLS_PATH,
30
32
  rules: '.grok/rules',
31
33
  behaviors: null,
32
34
  },
@@ -133,11 +135,11 @@ export const BUILT_IN_SEEDS_2 = [
133
135
  paths: {
134
136
  deployTarget: 'mixed',
135
137
  artifacts: {
136
- // Skills are native; rule files are reached through the AGENTS.md
137
- // hook. Agents and commands remain indexed through discover/show.
138
+ // Bulk skills use an opt-in mirror; kernel skills stay native. Rule files
139
+ // use the AGENTS.md hook. Agents/commands stay indexed via discover/show.
138
140
  agents: null,
139
141
  commands: null,
140
- skills: '.agents/skills',
142
+ skills: MUSE_STANDARD_SKILLS_PATH,
141
143
  rules: '.muse/rules',
142
144
  behaviors: null,
143
145
  },
@@ -233,7 +233,7 @@ export const BUILT_IN_SEEDS_3 = [
233
233
  status: 'stable',
234
234
  aliases: [],
235
235
  builtIn: true,
236
- surfaces: { primary: 'generic', compatibility: [], precedence: ['agents/', 'skills/', 'rules/'], related: [] },
236
+ surfaces: { primary: 'generic', compatibility: [], precedence: ['AGENTS.md', 'agents/', '.agents/skills/', 'skills/', 'rules/'], related: [] },
237
237
  detection: {
238
238
  env: [],
239
239
  process: [],
@@ -248,9 +248,9 @@ export const BUILT_IN_SEEDS_3 = [
248
248
  rules: 'rules',
249
249
  behaviors: null,
250
250
  },
251
- kernelSkills: null,
252
- configFile: 'README.md',
253
- contextFiles: { aiwgMd: true, agentsMd: false, claudeMdHook: false, hookFile: null, contextFile: 'README.md' },
251
+ kernelSkills: '.agents/skills',
252
+ configFile: 'AGENTS.md',
253
+ contextFiles: { aiwgMd: true, agentsMd: true, claudeMdHook: false, hookFile: null, contextFile: 'AGENTS.md' },
254
254
  },
255
255
  smithPaths: {
256
256
  agents: 'agents',
@@ -258,7 +258,7 @@ export const BUILT_IN_SEEDS_3 = [
258
258
  skills: 'skills',
259
259
  rules: 'rules',
260
260
  fileExtension: '.md',
261
- configFile: 'README.md',
261
+ configFile: 'AGENTS.md',
262
262
  aggregated: false,
263
263
  },
264
264
  skillNamespace: {
@@ -271,7 +271,7 @@ export const BUILT_IN_SEEDS_3 = [
271
271
  agentFormat: 'generic-markdown',
272
272
  hookBridge: null,
273
273
  mcpInjection: null,
274
- contextAggregation: null,
274
+ contextAggregation: 'agents-md',
275
275
  ruleFormat: 'markdown',
276
276
  },
277
277
  matrixRef: null,
@@ -4,6 +4,8 @@ export interface RuleBindings { skills: string[]; agents: string[]; flows: strin
4
4
  export interface RuleFrontmatter extends Record<string, unknown> {
5
5
  activation: RuleActivation;
6
6
  tagged: boolean;
7
+ precedence: 'critical' | 'high' | 'medium' | 'low';
8
+ overridable: boolean;
7
9
  summary?: string;
8
10
  bound_to: RuleBindings;
9
11
  paths?: string[];
@@ -51,6 +51,8 @@ export function validateRuleFrontmatter(data) {
51
51
  ...data,
52
52
  activation: tagged ? data.activation : inferRuleActivation(data.enforcement),
53
53
  tagged,
54
+ precedence: data.precedence ?? 'medium',
55
+ overridable: data.overridable ?? true,
54
56
  ...(typeof data.summary === 'string' ? { summary: data.summary.trim() } : {}),
55
57
  bound_to: { skills: [], agents: [], flows: [], ...data.bound_to },
56
58
  } } : {}),
@@ -98,22 +100,29 @@ export function coreBodyPath(ruleFile) {
98
100
  return ruleFile.replace(/\.md$/, '.core.md');
99
101
  }
100
102
 
103
+ /** Normalize Markdown line endings before enforcing the canonical core-body budget. */
104
+ function normalizeCoreBody(text) {
105
+ return text.replace(/\r\n?/g, '\n').trim();
106
+ }
107
+
101
108
  /** Validate one core body's text. Returns error strings (empty when valid). */
102
109
  export function validateCoreBody(text, label = 'core body') {
103
110
  const errors = [];
104
- const bytes = Buffer.byteLength(text, 'utf8');
105
- if (!text.trim()) errors.push(`${label}: core body is empty`);
111
+ const body = normalizeCoreBody(text);
112
+ const bytes = Buffer.byteLength(body, 'utf8');
113
+ if (!body) errors.push(`${label}: core body is empty`);
106
114
  if (bytes > CORE_BODY_MAX_BYTES) errors.push(`${label}: core body is ${bytes} bytes; the per-body cap is ${CORE_BODY_MAX_BYTES} bytes`);
107
- if (/^---\r?\n/.test(text)) errors.push(`${label}: core body must not carry frontmatter`);
108
- if (AT_IMPORT.test(text)) errors.push(`${label}: core body must not contain an @ file reference/import; use a plain path or \`aiwg show rule <name>\``);
115
+ if (/^---\r?\n/.test(body)) errors.push(`${label}: core body must not carry frontmatter`);
116
+ if (AT_IMPORT.test(body)) errors.push(`${label}: core body must not contain an @ file reference/import; use a plain path or \`aiwg show rule <name>\``);
109
117
  return errors;
110
118
  }
111
119
 
112
120
  /** Validate the whole core set against the reserved budget. */
113
121
  export function validateCoreSet(bodies) {
114
- const total = bodies.reduce((sum, item) => sum + Buffer.byteLength(item.text, 'utf8'), 0);
122
+ const measured = bodies.map(item => ({ name: item.name, bytes: Buffer.byteLength(normalizeCoreBody(item.text), 'utf8') }));
123
+ const total = measured.reduce((sum, item) => sum + item.bytes, 0);
115
124
  return total > CORE_TOTAL_MAX_BYTES
116
- ? [`Core rules total ${total} bytes; the reserved core budget is ${CORE_TOTAL_MAX_BYTES} bytes (${bodies.map(item => `${item.name}: ${Buffer.byteLength(item.text, 'utf8')}`).join(', ')})`]
125
+ ? [`Core rules total ${total} bytes; the reserved core budget is ${CORE_TOTAL_MAX_BYTES} bytes (${measured.map(item => `${item.name}: ${item.bytes}`).join(', ')})`]
117
126
  : [];
118
127
  }
119
128
 
@@ -121,7 +130,7 @@ export function validateCoreSet(bodies) {
121
130
  export function readCoreBody(ruleFile) {
122
131
  const file = coreBodyPath(ruleFile);
123
132
  if (!existsSync(file)) throw new Error(`${ruleFile}: activation core requires a compact body file ${path.basename(file)}`);
124
- const text = readFileSync(file, 'utf8').trim();
133
+ const text = normalizeCoreBody(readFileSync(file, 'utf8'));
125
134
  const errors = validateCoreBody(text, file);
126
135
  if (errors.length) throw new Error(errors.join('; '));
127
136
  return text;
@@ -1,6 +1,7 @@
1
1
  import type { RuleDiagnostic } from './activation.mjs';
2
2
  export interface RulePinSelector { rules?: string[]; enforcement?: Array<'critical' | 'high' | 'medium' | 'low'>; capabilities?: string[]; group?: string; all?: true }
3
- export interface RulesConfig { inline_budget_tokens?: number; always_load?: RulePinSelector[]; pin_groups?: Record<string, string[]> }
3
+ export interface RulePrecedenceOverride { tier?: 'critical' | 'high' | 'medium' | 'low'; project_context?: boolean }
4
+ export interface RulesConfig { precedence?: Record<string, RulePrecedenceOverride>; inline_budget_tokens?: number; always_load?: RulePinSelector[]; pin_groups?: Record<string, string[]> }
4
5
  export interface InlineBudgetConfig { rules?: RulesConfig }
5
6
  export interface StartupContributor { path: string; bytes?: number; content?: string }
6
7
  export interface InlineBudgetReport {