@aiwg/cli 2026.11.3 → 2026.11.4

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 (135) 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 +15 -18
  7. package/dist/src/a2a/hitl-authorization.js +46 -0
  8. package/dist/src/a2a/hitl-driver.js +5 -5
  9. package/dist/src/artifacts/browser-export.js +2 -0
  10. package/dist/src/artifacts/framework-source-digest.js +1 -1
  11. package/dist/src/artifacts/index-builder.js +5 -25
  12. package/dist/src/artifacts/index-capability.js +24 -0
  13. package/dist/src/artifacts/query-engine-discover-output.js +8 -3
  14. package/dist/src/artifacts/query-engine-rules.js +27 -9
  15. package/dist/src/artifacts/query-engine-scoring.js +5 -5
  16. package/dist/src/artifacts/query-engine-show-card.js +5 -1
  17. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  18. package/dist/src/artifacts/query-engine-show.js +3 -3
  19. package/dist/src/artifacts/query-engine-templates.js +10 -4
  20. package/dist/src/artifacts/query-engine-verbose.js +18 -4
  21. package/dist/src/artifacts/relations-builder.js +1 -0
  22. package/dist/src/artifacts/types.js +1 -1
  23. package/dist/src/cli/handlers/checkpoint-handoff.js +2 -1
  24. package/dist/src/cli/handlers/guided-setup.js +3 -1
  25. package/dist/src/cli/handlers/refresh-managed-deployment.js +17 -5
  26. package/dist/src/cli/handlers/rules.js +1 -1
  27. package/dist/src/cli/handlers/sessions.js +1 -1
  28. package/dist/src/cli/handlers/steward.js +1 -1
  29. package/dist/src/cli/handlers/use.js +1 -2
  30. package/dist/src/cli/handlers/utility-doctor.js +5 -2
  31. package/dist/src/cli/handlers/workspace.js +1 -1
  32. package/dist/src/cli/services/deployment-probe-scope.js +40 -0
  33. package/dist/src/cli/services/deployment-verification.js +4 -5
  34. package/dist/src/config/aiwg-config.js +6 -0
  35. package/dist/src/config/authorization-cli.js +61 -3
  36. package/dist/src/config/cli-help.js +1 -1
  37. package/dist/src/config/cli.js +4 -2
  38. package/dist/src/config/host-resource-runtime.mjs +1 -1
  39. package/dist/src/config/user-registry.js +9 -1
  40. package/dist/src/config/worker-owner-lock.js +90 -10
  41. package/dist/src/decision/graph-flow-adapter.js +1 -1
  42. package/dist/src/effects/authorization-grant.js +50 -0
  43. package/dist/src/effects/authorization-store.js +130 -0
  44. package/dist/src/effects/index.js +2 -0
  45. package/dist/src/effects/ledger.js +1 -0
  46. package/dist/src/effects/lifecycle.js +1 -1
  47. package/dist/src/effects/reader.js +4 -0
  48. package/dist/src/effects/records.js +4 -0
  49. package/dist/src/effects/schema.js +2 -0
  50. package/dist/src/extensions/claude-hooks-installer.js +7 -7
  51. package/dist/src/extensions/muse-managed-hooks.js +11 -0
  52. package/dist/src/extensions/user-hook-diagnostics.js +32 -0
  53. package/dist/src/extensions/verified-hook-command.js +32 -0
  54. package/dist/src/lint/rule-conflicts.js +52 -0
  55. package/dist/src/lint/runner.js +3 -0
  56. package/dist/src/mcp/cli.mjs +3 -1
  57. package/dist/src/mcp/elicitation.mjs +30 -0
  58. package/dist/src/mcp/grok-build-config.mjs +1 -1
  59. package/dist/src/mcp/muse-native-config.mjs +1 -0
  60. package/dist/src/mcp/server.mjs +2 -0
  61. package/dist/src/mcp/tools/authorization.mjs +78 -0
  62. package/dist/src/policy/authorization-capture.js +64 -0
  63. package/dist/src/policy/authorization-operations.js +108 -0
  64. package/dist/src/policy/hitl-check.js +3 -2
  65. package/dist/src/policy/hitl-consume.js +14 -0
  66. package/dist/src/policy/hitl-durable-store.js +60 -0
  67. package/dist/src/policy/hitl-durable.js +60 -0
  68. package/dist/src/policy/hitl-receipt.js +5 -0
  69. package/dist/src/policy/hitl.js +44 -6
  70. package/dist/src/process/bounded-child-process.mjs +49 -39
  71. package/dist/src/providers/capability-matrix.yaml +15 -18
  72. package/dist/src/providers/deployment-ownership.d.mts +1 -0
  73. package/dist/src/providers/deployment-ownership.mjs +21 -2
  74. package/dist/src/providers/grok-build-headless.js +170 -77
  75. package/dist/src/providers/grok-build-inspect.js +1 -0
  76. package/dist/src/providers/grok-build-paths.js +2 -0
  77. package/dist/src/providers/muse-paths.js +4 -2
  78. package/dist/src/providers/provider-context-contracts.js +12 -4
  79. package/dist/src/providers/provider-definition-schema.js +6 -0
  80. package/dist/src/providers/provider-seeds-1.js +3 -3
  81. package/dist/src/providers/provider-seeds-2.js +6 -4
  82. package/dist/src/providers/provider-seeds-3.js +6 -6
  83. package/dist/src/rules/activation.d.mts +2 -0
  84. package/dist/src/rules/activation.mjs +16 -7
  85. package/dist/src/rules/inline-budget.d.mts +2 -1
  86. package/dist/src/rules/inline-budget.mjs +4 -2
  87. package/dist/src/rules/inventory.js +3 -0
  88. package/dist/src/rules/precedence.d.mts +6 -0
  89. package/dist/src/rules/precedence.mjs +49 -0
  90. package/dist/src/rules/project-precedence.js +73 -0
  91. package/dist/src/rules/rule-frontmatter.schema.json +15 -0
  92. package/dist/src/serve/a2a-terminal-observer.js +12 -3
  93. package/dist/src/serve/mission-hitl.js +20 -1
  94. package/dist/src/sessions/adapters/grok-build-fallback.js +33 -0
  95. package/dist/src/sessions/adapters/grok-build-native-records.js +64 -0
  96. package/dist/src/sessions/adapters/grok-build-native.js +92 -100
  97. package/dist/src/sessions/adapters/grok-build.js +65 -24
  98. package/dist/src/sessions/grok-build-cli-output.js +113 -0
  99. package/dist/src/sessions/grok-build-cli.js +4 -28
  100. package/dist/src/smiths/context-pipeline/bridge-ownership.js +4 -3
  101. package/dist/src/smiths/context-pipeline/finalization.js +5 -0
  102. package/dist/src/smiths/context-pipeline/generator.js +1 -1
  103. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +20 -17
  104. package/dist/src/smiths/context-pipeline/workspace-doctor.js +2 -1
  105. package/dist/src/smiths/context-pipeline/workspace-document.js +6 -0
  106. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -12
  107. package/dist/src/smiths/hook-bridge/codex-translator.js +11 -14
  108. package/dist/src/smiths/hook-bridge/codex-trust.js +7 -2
  109. package/dist/src/smiths/hook-bridge/copilot-translator.js +2 -1
  110. package/dist/src/smiths/hook-bridge/grok-build-translator.js +3 -1
  111. package/dist/src/smiths/hook-bridge/hermes-prompt-discovery.js +78 -0
  112. package/dist/src/smiths/hook-bridge/hermes-translator.js +5 -3
  113. package/dist/src/smiths/hook-bridge/index.js +3 -1
  114. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +3 -2
  115. package/package.json +7 -1
  116. package/tools/agents/deploy-agents.mjs +5 -6
  117. package/tools/agents/deploy-options.mjs +1 -0
  118. package/tools/agents/providers/base-frontmatter.mjs +3 -2
  119. package/tools/agents/providers/claude-post-deploy.mjs +1 -1
  120. package/tools/agents/providers/codex-post-deploy.mjs +1 -1
  121. package/tools/agents/providers/generic.mjs +66 -0
  122. package/tools/agents/providers/grok-build.mjs +3 -1
  123. package/tools/agents/providers/muse-hooks.mjs +13 -11
  124. package/tools/agents/providers/muse-prompt-discovery.mjs +5 -1
  125. package/tools/agents/providers/muse.mjs +2 -1
  126. package/tools/agents/providers/openclaw.mjs +2 -1
  127. package/tools/agents/providers/rule-deployment-prepare.mjs +5 -3
  128. package/tools/agents/providers/rule-deployment-state.mjs +14 -6
  129. package/tools/agents/providers/rule-startup.mjs +11 -10
  130. package/tools/agents/providers/staged-directory-reference.mjs +14 -0
  131. package/tools/agents/providers/user-hooks.mjs +26 -0
  132. package/tools/cli/authorization-health.mjs +20 -0
  133. package/tools/cli/workspace-status.mjs +7 -0
  134. package/tools/commands/deploy-prompts-codex.mjs +15 -1
  135. package/vscode-extension/schemas/aiwg.config.v1.json +20 -0
@@ -0,0 +1,64 @@
1
+ // Project only the observed 1.0.77 chat records; never acquire snapshots or attachments.
2
+ import { z } from 'zod';
3
+ import { SessionContractError } from '../contracts.js';
4
+ const text = z.strictObject({ type: z.literal('text'), text: z.string() });
5
+ const tool = z.strictObject({ id: z.string().min(1), name: z.string().min(1), arguments: z.string() });
6
+ const recordSchema = z.discriminatedUnion('type', [
7
+ z.strictObject({ type: z.literal('user'), content: z.array(text), prompt_index: z.number().int().nonnegative().optional(), synthetic_reason: z.literal('system_reminder').optional() }),
8
+ z.strictObject({ type: z.literal('assistant'), content: z.string(), tool_calls: z.array(tool).max(999).optional(), model_id: z.string().optional(), model_fingerprint: z.string().optional(), reasoning_effort: z.string().optional() }),
9
+ z.strictObject({ type: z.literal('tool_result'), tool_call_id: z.string(), content: z.string() }),
10
+ z.strictObject({ type: z.literal('system'), content: z.string() }),
11
+ z.strictObject({ type: z.literal('reasoning'), id: z.string(), summary: z.array(z.unknown()), encrypted_content: z.string(), status: z.literal('completed') }),
12
+ ]);
13
+ const summarySchema = z.looseObject({
14
+ chat_format_version: z.literal(1),
15
+ info: z.strictObject({ id: z.string().uuid(), cwd: z.string().min(1) }),
16
+ created_at: z.string(), updated_at: z.string(), current_model_id: z.string(),
17
+ });
18
+ export function nativeDrift() {
19
+ throw new SessionContractError('SCHEMA_DRIFT', 'Unrecognized Grok Build 1.0.77 native schema; fall back to `grok export <session-id> <session-id>.md`.');
20
+ }
21
+ export function parseNativeSummary(value, sessionId, cwd) {
22
+ const parsed = summarySchema.safeParse(value);
23
+ if (!parsed.success || parsed.data.info.id.toLowerCase() !== sessionId || parsed.data.info.cwd !== cwd)
24
+ nativeDrift();
25
+ for (const time of [parsed.data.created_at, parsed.data.updated_at])
26
+ if (!Number.isFinite(Date.parse(time)))
27
+ nativeDrift();
28
+ return { sessionCreatedAt: parsed.data.created_at, sessionUpdatedAt: parsed.data.updated_at, currentModelId: parsed.data.current_model_id };
29
+ }
30
+ export function projectNativeLine(line, cwd, metadata) {
31
+ const parsed = recordSchema.safeParse(line.value);
32
+ if (!parsed.success)
33
+ nativeDrift();
34
+ const value = parsed.data;
35
+ const records = [];
36
+ const base = { cwd, ...metadata, sequence: line.sequence * 1_000 };
37
+ if (value.type === 'user' && !value.synthetic_reason)
38
+ records.push({ ...base, kind: 'message', role: 'user', content: value.content.map(c => c.text).join('\n') });
39
+ if (value.type === 'assistant') {
40
+ if (value.content)
41
+ records.push({ ...base, kind: 'message', role: 'assistant', content: value.content, model: value.model_id });
42
+ for (const [index, call] of (value.tool_calls ?? []).entries())
43
+ records.push({ ...base, sequence: base.sequence + index + 1, kind: 'tool-call', role: 'tool', content: call.arguments, toolName: call.name, toolCallId: call.id, model: value.model_id });
44
+ }
45
+ if (value.type === 'tool_result')
46
+ records.push({ ...base, kind: 'tool-result', role: 'tool', content: value.content, toolCallId: value.tool_call_id });
47
+ return records.map(record => ({ record, line }));
48
+ }
49
+ export function nativeProjectionRecord(sessionId, entry) {
50
+ const { record, line } = entry;
51
+ return {
52
+ nativeSessionId: sessionId, nativeEventId: `${sessionId}:${record.sequence}`, sequence: record.sequence,
53
+ kind: record.kind, role: record.role, occurredAt: undefined, text: record.content, model: record.model,
54
+ toolName: record.toolName, toolCallId: record.toolCallId,
55
+ rawReference: { locatorClass: 'grok-build-native-chat-history', sequence: line.sequence },
56
+ extensions: {
57
+ lifecycle: 'unknown-at-import',
58
+ provenance: { product: 'grok-build', acquisition: 'grok-build-native-chat-history', sourceSchema: '1.0.0', nativeStoreInspected: true, toolOutputAvailable: true, grokVersion: '1.0.77', workingDirectory: record.cwd, sessionCreatedAt: record.sessionCreatedAt, sessionUpdatedAt: record.sessionUpdatedAt, sessionCreatedAtMs: Date.parse(record.sessionCreatedAt), sessionUpdatedAtMs: Date.parse(record.sessionUpdatedAt), currentModelId: record.currentModelId },
59
+ identity: { nativeSessionIdKnown: true, nativeEventIdKnown: false, eventIdentityBasis: 'source-position' },
60
+ lossReport: { lossless: false, excludedRecordTypes: ['system', 'system_reminder', 'reasoning'], unavailable: ['eventTimestamps', 'attachments', 'fileSnapshots', 'compaction', 'lineage', 'subagents'] },
61
+ },
62
+ };
63
+ }
64
+ //# sourceMappingURL=grok-build-native-records.js.map
@@ -1,12 +1,13 @@
1
- // Native Grok Build session-store reader (synthetic schema v1; real stores never inspected).
2
- import { opendir, readFile } from 'node:fs/promises';
3
- import { dirname, resolve } from 'node:path';
1
+ // Bounded native projection pinned to the captured Grok Build 1.0.77 store.
2
+ import { lstat, opendir, readFile } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, parse, resolve } from 'node:path';
4
4
  import { z } from 'zod';
5
- import { integer, number } from '../../schema/zod-validation.mjs';
5
+ import { number } from '../../schema/zod-validation.mjs';
6
6
  import { schemaIssueDetail, schemaRejectionDetail, SessionContractError, assertSupportedSchemaMajor, } from '../contracts.js';
7
7
  import { matchSessionWorkspace } from '../workspace-matching.js';
8
8
  import { authorizeSourceFile } from '../policy.js';
9
- import { streamBoundedJsonLines, } from '../readers.js';
9
+ import { streamBoundedJsonLines, readBoundedText, } from '../readers.js';
10
+ import { nativeDrift, parseNativeSummary, projectNativeLine, nativeProjectionRecord } from './grok-build-native-records.js';
10
11
  export const GROK_BUILD_NATIVE_SCHEMA_VERSION = '1.0.0';
11
12
  export const GROK_BUILD_NATIVE_SCHEMA_MAJOR = 1;
12
13
  export const GROK_BUILD_NATIVE_LOCATOR_CLASS = 'grok-build-native-chat-history';
@@ -16,18 +17,19 @@ export const GROK_BUILD_ACTIVE_FRESHNESS_MS = 120_000;
16
17
  export const GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES = 10_000;
17
18
  const ACTIVE_SESSIONS_MAX_BYTES = 1024 * 1024;
18
19
  export function grokBuildNativeEnabled() {
19
- return process.env.AIWG_GROK_BUILD_NATIVE_EXPERIMENTAL === '1';
20
+ return process.env.AIWG_GROK_BUILD_NATIVE_EXPERIMENTAL === '1'
21
+ && process.env.AIWG_GROK_BUILD_NATIVE_VERSION === '1.0.77';
20
22
  }
21
23
  /** One availability message for native readers, discovery and CLI capability reports. */
22
24
  export function grokBuildNativeAvailability() {
23
25
  const enabled = grokBuildNativeEnabled();
24
26
  return {
25
27
  reasonCode: enabled ? 'GROK_BUILD_NATIVE_EXPERIMENTAL_ENABLED' : 'GROK_BUILD_NATIVE_EXPERIMENTAL_DISABLED',
26
- remediation: `Grok Build native ingestion is experimental and ${enabled ? 'enabled but' : 'disabled by default because it is'} `
27
- + 'unqualified: no released-binary schema or version range is qualified. '
28
- + 'AIWG_GROK_BUILD_NATIVE_EXPERIMENTAL=1 opts in to synthetic v1 chat_history.jsonl and active_sessions.json only; '
29
- + 'authorize the sessions root separately with --grok-root and the optional registry file with --grok-active-sessions. '
30
- + 'Use `grok export <session-id> <session-id>.md` and import the authorized Markdown file for the documented CLI path.',
28
+ remediation: `Grok Build native ingestion is experimental and ${enabled ? 'enabled for the captured subset; other scenarios remain' : 'disabled and'} unqualified. `
29
+ + 'AIWG_GROK_BUILD_NATIVE_EXPERIMENTAL=1 and AIWG_GROK_BUILD_NATIVE_VERSION=1.0.77 are both required; '
30
+ + 'only exact 1.0.77 text/tool records with chat_format_version 1 are supported. '
31
+ + 'Authorize the sessions root separately with --grok-root. '
32
+ + 'Unknown versions or schemas must fall back to `grok export <session-id> <session-id>.md` and import the authorized Markdown file.',
31
33
  };
32
34
  }
33
35
  export function assertGrokBuildNativeEnabled() {
@@ -36,20 +38,6 @@ export function assertGrokBuildNativeEnabled() {
36
38
  }
37
39
  }
38
40
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
39
- // Synthetic native record shape (v1): one JSON object per line. Real
40
- // chat_history.jsonl schemas are unqualified (real stores are never read),
41
- // so any record outside this shape fails closed with SCHEMA_DRIFT.
42
- const NativeRecordSchema = z.looseObject({
43
- schemaVersion: z.union([z.string(), z.number()]),
44
- sessionId: z.string().regex(UUID),
45
- seq: integer().nonnegative(),
46
- role: z.enum(['user', 'assistant', 'tool']),
47
- content: z.string(),
48
- timestamp: number().optional(),
49
- toolName: z.string().min(1).optional(),
50
- toolCallId: z.string().optional(),
51
- id: z.string().min(1).optional(),
52
- });
53
41
  const ActiveSessionsSchema = z.looseObject({
54
42
  schemaVersion: z.union([z.string(), z.number()]),
55
43
  sessions: z.array(z.looseObject({
@@ -80,6 +68,7 @@ export function grokBuildNativeSessionId(locator) {
80
68
  /** Enumerate documented `<root>/<url-encoded cwd>/<id>/chat_history.jsonl` paths. */
81
69
  export async function* discoverGrokBuildNativeChatHistories(root, maxFiles = GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES) {
82
70
  assertGrokBuildNativeEnabled();
71
+ await assertSafeNativeRoot(root);
83
72
  const resolved = resolve(root);
84
73
  let workspaces;
85
74
  try {
@@ -147,83 +136,89 @@ export async function grokBuildSourceWorkspaceMatch(locator, workspacePath) {
147
136
  }
148
137
  export async function readGrokBuildNativeChatHistory(source, limits) {
149
138
  assertGrokBuildNativeEnabled();
150
- const sessionId = grokBuildNativeSessionId(source.locator);
151
- if (source.locatorClass !== GROK_BUILD_NATIVE_LOCATOR_CLASS || !sessionId) {
152
- throw new SessionContractError('SOURCE_NOT_AUTHORIZED', 'Grok Build native source must be an explicitly authorized chat_history.jsonl path');
139
+ const { sessionId, cwd } = await authorizeGrokBuildNativeSource(source);
140
+ try {
141
+ await rejectNativeSymlinks(resolve(dirname(source.locator), 'summary.json'));
153
142
  }
154
- await authorizeSourceFile({
155
- selectedPath: source.locator,
156
- allowedRoots: source.authorizedScope.allowedRoots,
157
- });
158
- const input = await streamBoundedJsonLines({
159
- selectedPath: source.locator,
160
- allowedRoots: source.authorizedScope.allowedRoots,
161
- }, { consistency: 'provisional', limits });
143
+ catch (error) {
144
+ if (error.code === 'ENOENT')
145
+ nativeDrift();
146
+ throw error;
147
+ }
148
+ const summary = await readBoundedText({
149
+ selectedPath: resolve(dirname(source.locator), 'summary.json'), allowedRoots: source.authorizedScope.allowedRoots,
150
+ }, limits);
151
+ let metadata;
152
+ try {
153
+ metadata = JSON.parse(summary.value);
154
+ }
155
+ catch {
156
+ nativeDrift();
157
+ }
158
+ const sessionMetadata = parseNativeSummary(metadata, sessionId, cwd);
159
+ const input = await streamBoundedJsonLines({ selectedPath: source.locator, allowedRoots: source.authorizedScope.allowedRoots }, { consistency: 'complete', limits });
162
160
  const records = [];
163
- let lastSeq = -1;
161
+ const calls = new Set();
162
+ const results = new Set();
163
+ let promptIndex = -1;
164
164
  for await (const line of input) {
165
- const parsed = NativeRecordSchema.safeParse(line.value);
166
- if (!parsed.success) {
167
- throw new SessionContractError('SCHEMA_DRIFT', 'unrecognized Grok Build native chat_history.jsonl record', schemaRejectionDetail(parsed.error));
168
- }
169
- assertSupportedSchemaMajor(declaredSchema(parsed.data.schemaVersion), GROK_BUILD_NATIVE_SCHEMA_MAJOR);
170
- if (parsed.data.sessionId.toLowerCase() !== sessionId) {
171
- throw new SessionContractError('SCHEMA_DRIFT', 'Grok Build native record session does not match its session directory', schemaIssueDetail('sessionId'));
172
- }
173
- if (parsed.data.seq <= lastSeq) {
174
- throw new SessionContractError('SCHEMA_DRIFT', 'Grok Build native chat history sequence is not strictly increasing', schemaIssueDetail('seq'));
165
+ const projected = projectNativeLine(line, cwd, sessionMetadata);
166
+ const raw = line.value;
167
+ if (raw.prompt_index !== undefined) {
168
+ if (raw.prompt_index <= promptIndex)
169
+ nativeDrift();
170
+ promptIndex = raw.prompt_index;
175
171
  }
176
- lastSeq = parsed.data.seq;
177
- if (parsed.data.role === 'tool' && !parsed.data.toolName) {
178
- throw new SessionContractError('SCHEMA_DRIFT', 'Grok Build native tool record is missing its tool name', schemaIssueDetail('toolName'));
172
+ for (const entry of projected) {
173
+ const { kind, toolCallId } = entry.record;
174
+ if (kind === 'tool-call' && toolCallId) {
175
+ if (calls.has(toolCallId))
176
+ nativeDrift();
177
+ calls.add(toolCallId);
178
+ }
179
+ if (kind === 'tool-result' && toolCallId) {
180
+ if (!calls.has(toolCallId) || results.has(toolCallId))
181
+ nativeDrift();
182
+ results.add(toolCallId);
183
+ }
184
+ records.push(entry);
179
185
  }
180
- records.push({ record: parsed.data, line });
181
- }
182
- if (records.length === 0) {
183
- throw new SessionContractError('MALFORMED_SOURCE', 'Grok Build native chat history is empty', schemaIssueDetail('<root>'));
184
186
  }
187
+ if (records.length === 0)
188
+ throw new SessionContractError('MALFORMED_SOURCE', 'Grok Build native chat history is empty; use `grok export <session-id> <session-id>.md`.');
185
189
  return { records, incompleteTail: input.incompleteTail };
186
190
  }
187
- export function toGrokBuildNativeRecord(sessionId, entry) {
188
- const { record, line } = entry;
189
- const occurredAt = timestamp(record.timestamp);
190
- const nativeEventId = record.id ?? `${sessionId}:${record.seq}`;
191
- const common = {
192
- lifecycle: 'unknown-at-import',
193
- provenance: {
194
- product: 'grok-build',
195
- acquisition: GROK_BUILD_NATIVE_LOCATOR_CLASS,
196
- sourceSchema: GROK_BUILD_NATIVE_SCHEMA_VERSION,
197
- nativeStoreInspected: true,
198
- },
199
- identity: { nativeSessionIdKnown: true, nativeEventIdKnown: true },
200
- };
201
- if (record.role === 'tool') {
202
- return {
203
- nativeSessionId: sessionId,
204
- nativeEventId,
205
- sequence: line.sequence * 1_000,
206
- kind: 'tool-call',
207
- role: 'tool',
208
- toolName: record.toolName,
209
- toolCallId: record.toolCallId,
210
- occurredAt,
211
- text: record.content,
212
- rawReference: { locatorClass: GROK_BUILD_NATIVE_LOCATOR_CLASS, sequence: line.sequence },
213
- extensions: common,
214
- };
191
+ /** Authorize native identity/path before a caller may use the CLI fallback. */
192
+ export async function authorizeGrokBuildNativeSource(source) {
193
+ const sessionId = grokBuildNativeSessionId(source.locator);
194
+ if (source.locatorClass !== GROK_BUILD_NATIVE_LOCATOR_CLASS || !sessionId
195
+ || basename(source.locator) !== GROK_BUILD_NATIVE_SESSION_FILENAME) {
196
+ throw new SessionContractError('SOURCE_NOT_AUTHORIZED', 'Grok Build native source must be an explicitly authorized chat_history.jsonl path');
197
+ }
198
+ await authorizeSourceFile({ selectedPath: source.locator, allowedRoots: source.authorizedScope.allowedRoots });
199
+ for (const root of source.authorizedScope.allowedRoots)
200
+ await assertSafeNativeRoot(root);
201
+ await rejectNativeSymlinks(source.locator);
202
+ const cwd = decodeGrokBuildWorkspaceDir(dirname(dirname(source.locator)).split('/').pop() ?? '');
203
+ if (!cwd)
204
+ nativeDrift();
205
+ return { sessionId, cwd };
206
+ }
207
+ export const toGrokBuildNativeRecord = nativeProjectionRecord;
208
+ async function rejectNativeSymlinks(input) {
209
+ let current = resolve(input);
210
+ while (current !== parse(current).root) {
211
+ if ((await lstat(current)).isSymbolicLink())
212
+ throw new SessionContractError('SOURCE_SYMLINK', 'Grok Build native paths cannot contain symlinks');
213
+ current = dirname(current);
215
214
  }
216
- return {
217
- nativeSessionId: sessionId,
218
- nativeEventId,
219
- sequence: line.sequence * 1_000,
220
- kind: 'message',
221
- role: record.role,
222
- occurredAt,
223
- text: record.content,
224
- rawReference: { locatorClass: GROK_BUILD_NATIVE_LOCATOR_CLASS, sequence: line.sequence },
225
- extensions: common,
226
- };
215
+ }
216
+ async function assertSafeNativeRoot(root) {
217
+ if (!isAbsolute(root) || resolve(root) === parse(resolve(root)).root)
218
+ throw new SessionContractError('SOURCE_NOT_AUTHORIZED', 'Grok Build sessions root must be an absolute non-root directory');
219
+ await rejectNativeSymlinks(root);
220
+ if (!(await lstat(root)).isDirectory())
221
+ throw new SessionContractError('SOURCE_NOT_AUTHORIZED', 'Grok Build sessions root must be a directory');
227
222
  }
228
223
  /** Read and validate active_sessions.json (read-only, bounded); throws on misuse. */
229
224
  export async function readGrokBuildActiveRegistry(selectedPath, allowedRoots) {
@@ -276,17 +271,14 @@ export function parseGrokBuildNativeCursor(value) {
276
271
  if (!/^\d+$/.test(value)) {
277
272
  throw new SessionContractError('SCHEMA_DRIFT', 'invalid Grok Build native cursor', schemaIssueDetail('cursor'));
278
273
  }
279
- return Number(value);
274
+ const cursor = Number(value);
275
+ if (!Number.isSafeInteger(cursor))
276
+ throw new SessionContractError('SCHEMA_DRIFT', 'invalid Grok Build native cursor', schemaIssueDetail('cursor'));
277
+ return cursor;
280
278
  }
281
279
  function declaredSchema(value) {
282
280
  if (typeof value === 'number')
283
281
  return `${value}.0.0`;
284
282
  return /^\d+$/.test(String(value)) ? `${value}.0.0` : String(value);
285
283
  }
286
- function timestamp(value) {
287
- if (value === undefined || value === null)
288
- return undefined;
289
- const date = new Date(value < 10_000_000_000 ? value * 1_000 : value);
290
- return Number.isNaN(date.getTime()) ? undefined : date.toISOString();
291
- }
292
284
  //# sourceMappingURL=grok-build-native.js.map
@@ -1,8 +1,9 @@
1
1
  import { basename, extname } from 'node:path';
2
+ import { canFallbackGrokNative, withGrokCliFallback } from './grok-build-fallback.js';
2
3
  import { SessionContractError, schemaIssueDetail, } from '../contracts.js';
3
4
  import { readBoundedText } from '../readers.js';
4
5
  import { assertGrokBuildNativeEnabled, discoverGrokBuildNativeChatHistories, GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES, GROK_BUILD_NATIVE_LOCATOR_CLASS, GROK_BUILD_NATIVE_SCHEMA_VERSION, grokBuildNativeSessionId, grokBuildNativeEnabled, parseGrokBuildNativeCursor, readGrokBuildNativeChatHistory, toGrokBuildNativeRecord, } from './grok-build-native.js';
5
- export const GROK_BUILD_ADAPTER_VERSION = '1.0.0';
6
+ export const GROK_BUILD_ADAPTER_VERSION = '1.1.0';
6
7
  export const GROK_BUILD_CLI_EXPORT_SCHEMA_VERSION = '1.0.0';
7
8
  export const GROK_BUILD_CLI_EXPORT_LOCATOR_CLASS = 'grok-build-cli-markdown-export';
8
9
  /**
@@ -11,13 +12,14 @@ export const GROK_BUILD_CLI_EXPORT_LOCATOR_CLASS = 'grok-build-cli-markdown-expo
11
12
  * opt-in and an explicitly authorized sessions root (`--grok-root`).
12
13
  *
13
14
  * The public export contract is intentionally lossy. Native reads use the
14
- * synthetic v1 schema in grok-build-native.ts (real stores were never
15
- * inspected); anything outside it fails closed. This adapter never invokes
16
- * `grok export` automatically: CLI export remains operator-selected.
15
+ * captured 1.0.77 projection in grok-build-native.ts; anything outside
16
+ * the observed schema fails closed. Explicit CLI imports supply bounded CLI
17
+ * options to fall back to export; direct API callers may supply the same options.
17
18
  */
18
19
  export class GrokBuildSessionAdapter {
19
20
  limits;
20
21
  maxFiles;
22
+ cliFallback;
21
23
  provider = 'grok-build';
22
24
  adapterVersion = GROK_BUILD_ADAPTER_VERSION;
23
25
  disposition = 'implemented';
@@ -27,9 +29,10 @@ export class GrokBuildSessionAdapter {
27
29
  get acquisitionModes() {
28
30
  return grokBuildNativeEnabled() ? ['manual-export', 'jsonl'] : ['manual-export'];
29
31
  }
30
- constructor(limits, maxFiles = GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES) {
32
+ constructor(limits, maxFiles = GROK_BUILD_NATIVE_DISCOVERY_MAX_FILES, cliFallback) {
31
33
  this.limits = limits;
32
34
  this.maxFiles = maxFiles;
35
+ this.cliFallback = cliFallback;
33
36
  }
34
37
  async *discover(scope) {
35
38
  assertGrokBuildNativeEnabled();
@@ -42,7 +45,15 @@ export class GrokBuildSessionAdapter {
42
45
  }
43
46
  async inspect(source) {
44
47
  if (source.locatorClass === GROK_BUILD_NATIVE_LOCATOR_CLASS) {
45
- const native = await readGrokBuildNativeChatHistory(source, this.limits);
48
+ let native;
49
+ try {
50
+ native = await readGrokBuildNativeChatHistory(source, this.limits);
51
+ }
52
+ catch (error) {
53
+ if (!canFallbackGrokNative(error, this.cliFallback))
54
+ throw error;
55
+ return withGrokCliFallback(source, this.cliFallback, selected => this.inspect(selected));
56
+ }
46
57
  return {
47
58
  sourceSchemaVersion: GROK_BUILD_NATIVE_SCHEMA_VERSION,
48
59
  consistency: native.incompleteTail ? 'provisional' : 'complete',
@@ -58,13 +69,23 @@ export class GrokBuildSessionAdapter {
58
69
  }
59
70
  async *stream(source, cursor) {
60
71
  if (source.locatorClass === GROK_BUILD_NATIVE_LOCATOR_CLASS) {
61
- // The experimental gate answers first, so a disabled gate never reports a locator error.
62
- assertGrokBuildNativeEnabled();
63
- const sessionId = grokBuildNativeSessionId(source.locator);
64
- if (!sessionId) {
65
- throw new SessionContractError('SOURCE_NOT_AUTHORIZED', 'Grok Build native source must be an explicitly authorized chat_history.jsonl path');
72
+ if (cursor?.value.startsWith('grok-cli:')) {
73
+ yield* await this.fallbackRecords(source, cursor.value.slice('grok-cli:'.length));
74
+ return;
75
+ }
76
+ let native;
77
+ try {
78
+ native = await readGrokBuildNativeChatHistory(source, this.limits);
66
79
  }
67
- const native = await readGrokBuildNativeChatHistory(source, this.limits);
80
+ catch (error) {
81
+ if (!canFallbackGrokNative(error, this.cliFallback))
82
+ throw error;
83
+ if (cursor?.value && cursor.value !== '0')
84
+ throw new SessionContractError('SCHEMA_DRIFT', 'Grok Build acquisition changed after a native checkpoint; restart with a separate CLI export source.');
85
+ yield* await this.fallbackRecords(source);
86
+ return;
87
+ }
88
+ const sessionId = grokBuildNativeSessionId(source.locator);
68
89
  const start = parseGrokBuildNativeCursor(cursor?.value);
69
90
  let outputIndex = 0;
70
91
  for (const entry of native.records) {
@@ -116,6 +137,22 @@ export class GrokBuildSessionAdapter {
116
137
  };
117
138
  }
118
139
  }
140
+ async fallbackRecords(source, cursor) {
141
+ const start = parseCursor(cursor);
142
+ if (!this.cliFallback)
143
+ throw new SessionContractError('UNSUPPORTED_OPERATION', 'Grok Build CLI fallback is unavailable; use an explicit `grok export`.');
144
+ return withGrokCliFallback(source, this.cliFallback, async (selected) => {
145
+ const records = [];
146
+ let index = start;
147
+ for await (const record of this.stream(selected, { value: String(start) })) {
148
+ const extensions = record.extensions ?? {};
149
+ records.push({ ...record, sourceCursor: `grok-cli:${++index}`, extensions: { ...extensions,
150
+ provenance: { ...extensions.provenance, nativeFallback: true },
151
+ } });
152
+ }
153
+ return records;
154
+ });
155
+ }
119
156
  async readSource(source) {
120
157
  if (source.locatorClass !== GROK_BUILD_CLI_EXPORT_LOCATOR_CLASS) {
121
158
  throw new SessionContractError('UNSUPPORTED_OPERATION', 'Grok Build accepts only a documented `grok export` Markdown transcript or an '
@@ -166,7 +203,7 @@ function parseBlocks(value) {
166
203
  current = { heading: match[1], lines: [] };
167
204
  }
168
205
  else if (/^##\s+/.test(line)) {
169
- throw new SessionContractError('SCHEMA_DRIFT', `unknown Grok Build CLI export heading: ${line}`, schemaIssueDetail('headings'));
206
+ throw new SessionContractError('SCHEMA_DRIFT', 'unknown Grok Build CLI export heading; check the source CLI version', schemaIssueDetail('headings'));
170
207
  }
171
208
  else if (current) {
172
209
  current.lines.push(line);
@@ -179,21 +216,24 @@ function parseBlocks(value) {
179
216
  return blocks;
180
217
  }
181
218
  function parseTools(text, blockSequence) {
182
- const lines = text.split('\n').filter((line) => line.trim());
183
- if (lines.length === 0 || lines.length > 1_000) {
219
+ const summaries = [];
220
+ for (const line of text.split('\n')) {
221
+ if (/^- .+/.test(line))
222
+ summaries.push(line.slice(2));
223
+ else if (summaries.length)
224
+ summaries[summaries.length - 1] += `\n${line}`;
225
+ else if (line.trim()) {
226
+ throw new SessionContractError('SCHEMA_DRIFT', 'unrecognized Grok Build tool summary', schemaIssueDetail('tools'));
227
+ }
228
+ }
229
+ if (!summaries.length || summaries.length > 1_000) {
184
230
  throw new SessionContractError('SCHEMA_DRIFT', 'Grok Build tools block has no summaries or exceeds 1,000 summaries', schemaIssueDetail('tools'));
185
231
  }
186
- return lines.map((line, index) => {
187
- const match = /^- (.+)$/.exec(line);
188
- if (!match) {
189
- throw new SessionContractError('SCHEMA_DRIFT', `unrecognized Grok Build tool summary: ${line}`, schemaIssueDetail('tools'));
190
- }
191
- const summary = match[1];
232
+ return summaries.map((summary, index) => {
192
233
  const name = summary.split(/:| \(/, 1)[0]?.trim();
193
- if (!name) {
234
+ if (!name)
194
235
  throw new SessionContractError('SCHEMA_DRIFT', 'empty Grok Build tool summary', schemaIssueDetail('tools'));
195
- }
196
- return { sequence: blockSequence * 1_000 + index, name, text: summary };
236
+ return { sequence: blockSequence * 1_000 + index, name, text: summary.trimEnd() };
197
237
  });
198
238
  }
199
239
  function provenance(source, sessionId, heading) {
@@ -206,6 +246,7 @@ function provenance(source, sessionId, heading) {
206
246
  sourceSchema: GROK_BUILD_CLI_EXPORT_SCHEMA_VERSION,
207
247
  heading,
208
248
  nativeStoreInspected: false,
249
+ toolOutputAvailable: false,
209
250
  originalFilename: basename(source.locator),
210
251
  },
211
252
  identity: {
@@ -0,0 +1,113 @@
1
+ // Fail-closed parsers for the captured Grok Build 1.0.77 public CLI output.
2
+ import { SessionContractError } from './contracts.js';
3
+ const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}';
4
+ const listRow = new RegExp(`^(${UUID}) \\d{4}-\\d{2}-\\d{2} \\d{4}-\\d{2}-\\d{2} local .+$`, 'i');
5
+ const searchRow = new RegExp(`^(${UUID}) \\(score: \\d+\\.\\d+\\) [A-Z][a-z]{2} \\d{2}, +\\d{1,2}:\\d{2}[ap]m$`, 'i');
6
+ const drift = (message) => { throw new SessionContractError('SCHEMA_DRIFT', `unrecognized Grok Build ${message}; check CLI version and use a supported export`); };
7
+ export function parseGrokSessionIds(stdout, mode) {
8
+ const lines = stdout.split(/\r?\n/).filter(line => line.trim());
9
+ if (lines.length === 1 && lines[0] === 'No sessions found.')
10
+ return [];
11
+ const ids = [];
12
+ let header = false;
13
+ let total;
14
+ let label = false;
15
+ for (const line of lines) {
16
+ if (mode === 'list') {
17
+ if (line === '(no label)' || /^Label: .+$/.test(line)) {
18
+ if (label)
19
+ drift('list label');
20
+ label = true;
21
+ header = false;
22
+ continue;
23
+ }
24
+ if (/^SESSION ID +CREATED +UPDATED +STATUS +SUMMARY$/.test(line)) {
25
+ if (header)
26
+ drift('list header');
27
+ header = true;
28
+ label = false;
29
+ continue;
30
+ }
31
+ const row = listRow.exec(line);
32
+ if (!header || !row)
33
+ drift('list row');
34
+ ids.push(row[1].toLowerCase());
35
+ }
36
+ else {
37
+ if (total !== undefined)
38
+ drift('search trailer');
39
+ const row = searchRow.exec(line);
40
+ if (row) {
41
+ ids.push(row[1].toLowerCase());
42
+ continue;
43
+ }
44
+ if (/^Total: \d+$/.test(line)) {
45
+ total = Number(line.slice(7));
46
+ continue;
47
+ }
48
+ if (/^ \S/.test(line) && ids.length)
49
+ continue;
50
+ drift('search row');
51
+ }
52
+ }
53
+ if (mode === 'list' ? !header || label : total !== ids.length)
54
+ drift(`${mode} output`);
55
+ if (new Set(ids).size !== ids.length)
56
+ drift(`${mode} duplicate session IDs`);
57
+ return ids;
58
+ }
59
+ const resultKeys = ['text', 'stopReason', 'sessionId', 'requestId', 'cwd', 'thought', 'usage', 'num_turns', 'total_cost_usd', 'total_cost_usd_ticks', 'modelUsage'];
60
+ const eventKeys = {
61
+ text: ['type', 'data'], thought: ['type', 'data'],
62
+ available_commands: ['type', 'tools', 'commands'],
63
+ usage: ['type', 'usage', 'signature'],
64
+ tool_call: ['type', 'toolCallId', 'title', 'kind', 'status', 'toolName', 'rawInput', 'content', 'locations'],
65
+ tool_call_update: ['type', 'toolCallId', 'status', 'content', 'rawOutput', 'locations'],
66
+ end: ['type', ...resultKeys.filter(k => k !== 'text' && k !== 'thought')],
67
+ };
68
+ const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
69
+ export function validateGrokHeadlessEnvelope(value, format) {
70
+ const type = format === 'json' ? 'result' : String(value.type);
71
+ const keys = type === 'result' ? resultKeys : eventKeys[type];
72
+ if (!keys || Object.keys(value).some(key => !keys.includes(key)))
73
+ drift('headless event');
74
+ if (type === 'result' || type === 'end') {
75
+ for (const key of ['sessionId', 'requestId', 'cwd', 'stopReason'])
76
+ if (typeof value[key] !== 'string')
77
+ drift('headless result');
78
+ for (const key of ['usage', 'modelUsage'])
79
+ if (!object(value[key]))
80
+ drift('headless usage');
81
+ for (const key of ['num_turns', 'total_cost_usd', 'total_cost_usd_ticks'])
82
+ if (typeof value[key] !== 'number' || !Number.isFinite(value[key]))
83
+ drift('headless usage');
84
+ if (type === 'result' && (typeof value.text !== 'string' || typeof value.thought !== 'string'))
85
+ drift('headless result');
86
+ }
87
+ else if (type === 'text' || type === 'thought') {
88
+ if (typeof value.data !== 'string')
89
+ drift('headless text');
90
+ }
91
+ else if (type === 'available_commands') {
92
+ if (!Array.isArray(value.tools) || !Array.isArray(value.commands))
93
+ drift('headless commands');
94
+ }
95
+ else if (type === 'usage') {
96
+ if (!object(value.usage) || typeof value.signature !== 'string')
97
+ drift('headless usage');
98
+ }
99
+ else {
100
+ if (typeof value.toolCallId !== 'string' || !value.toolCallId || !Array.isArray(value.content) || !Array.isArray(value.locations))
101
+ drift('headless tool call');
102
+ if (type === 'tool_call') {
103
+ for (const key of ['title', 'kind', 'status', 'toolName'])
104
+ if (typeof value[key] !== 'string')
105
+ drift('headless tool call');
106
+ if (!object(value.rawInput))
107
+ drift('headless tool call');
108
+ }
109
+ else if (!(value.status === null || typeof value.status === 'string') || !(value.rawOutput === null || object(value.rawOutput)))
110
+ drift('headless tool update');
111
+ }
112
+ }
113
+ //# sourceMappingURL=grok-build-cli-output.js.map