@sentropic/h2a 0.98.6 → 0.98.7-rc.2

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 (170) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/dist/cli-command-map.d.ts.map +1 -1
  4. package/dist/cli-command-map.js +1 -0
  5. package/dist/cli-command-map.js.map +1 -1
  6. package/dist/cli-contract.js +2 -2
  7. package/dist/cli-contract.js.map +1 -1
  8. package/dist/cli.d.ts.map +1 -1
  9. package/dist/cli.js +226 -16
  10. package/dist/cli.js.map +1 -1
  11. package/dist/hosts/agy.js +1 -1
  12. package/dist/hosts/agy.js.map +1 -1
  13. package/dist/hosts/installation-doctor.d.ts +1 -0
  14. package/dist/hosts/installation-doctor.d.ts.map +1 -1
  15. package/dist/hosts/installation-doctor.js +1 -1
  16. package/dist/hosts/installation-doctor.js.map +1 -1
  17. package/dist/hosts/muse.d.ts.map +1 -1
  18. package/dist/hosts/muse.js +2 -4
  19. package/dist/hosts/muse.js.map +1 -1
  20. package/dist/hosts/native-artifacts.d.ts +33 -0
  21. package/dist/hosts/native-artifacts.d.ts.map +1 -0
  22. package/dist/hosts/native-artifacts.js +104 -0
  23. package/dist/hosts/native-artifacts.js.map +1 -0
  24. package/dist/hosts/native-catalog.d.ts +19 -0
  25. package/dist/hosts/native-catalog.d.ts.map +1 -0
  26. package/dist/hosts/native-catalog.js +14 -0
  27. package/dist/hosts/native-catalog.js.map +1 -0
  28. package/dist/hosts/native-convergence.d.ts +132 -0
  29. package/dist/hosts/native-convergence.d.ts.map +1 -0
  30. package/dist/hosts/native-convergence.js +86 -0
  31. package/dist/hosts/native-convergence.js.map +1 -0
  32. package/dist/hosts/native-files.d.ts +40 -0
  33. package/dist/hosts/native-files.d.ts.map +1 -0
  34. package/dist/hosts/native-files.js +131 -0
  35. package/dist/hosts/native-files.js.map +1 -0
  36. package/dist/hosts/native-inspection.d.ts +31 -0
  37. package/dist/hosts/native-inspection.d.ts.map +1 -0
  38. package/dist/hosts/native-inspection.js +79 -0
  39. package/dist/hosts/native-inspection.js.map +1 -0
  40. package/dist/hosts/native-paths.d.ts +11 -0
  41. package/dist/hosts/native-paths.d.ts.map +1 -0
  42. package/dist/hosts/native-paths.js +21 -0
  43. package/dist/hosts/native-paths.js.map +1 -0
  44. package/dist/hosts/native-proof.d.ts +32 -0
  45. package/dist/hosts/native-proof.d.ts.map +1 -0
  46. package/dist/hosts/native-proof.js +31 -0
  47. package/dist/hosts/native-proof.js.map +1 -0
  48. package/dist/hosts/native-runtime-record.d.ts +3 -0
  49. package/dist/hosts/native-runtime-record.d.ts.map +1 -0
  50. package/dist/hosts/native-runtime-record.js +60 -0
  51. package/dist/hosts/native-runtime-record.js.map +1 -0
  52. package/dist/hosts/native-skills.d.ts +24 -0
  53. package/dist/hosts/native-skills.d.ts.map +1 -0
  54. package/dist/hosts/native-skills.js +56 -0
  55. package/dist/hosts/native-skills.js.map +1 -0
  56. package/dist/hosts/native-toml.d.ts +18 -0
  57. package/dist/hosts/native-toml.d.ts.map +1 -0
  58. package/dist/hosts/native-toml.js +91 -0
  59. package/dist/hosts/native-toml.js.map +1 -0
  60. package/dist/hosts/operator-notices.d.ts +3 -0
  61. package/dist/hosts/operator-notices.d.ts.map +1 -0
  62. package/dist/hosts/operator-notices.js +31 -0
  63. package/dist/hosts/operator-notices.js.map +1 -0
  64. package/dist/hosts/plugin.d.ts.map +1 -1
  65. package/dist/hosts/plugin.js +3 -2
  66. package/dist/hosts/plugin.js.map +1 -1
  67. package/dist/hosts/upgrade-equipment.d.ts +42 -0
  68. package/dist/hosts/upgrade-equipment.d.ts.map +1 -0
  69. package/dist/hosts/upgrade-equipment.js +26 -0
  70. package/dist/hosts/upgrade-equipment.js.map +1 -0
  71. package/dist/hosts/vibe-discovery.d.ts +12 -0
  72. package/dist/hosts/vibe-discovery.d.ts.map +1 -0
  73. package/dist/hosts/vibe-discovery.js +33 -0
  74. package/dist/hosts/vibe-discovery.js.map +1 -0
  75. package/dist/hosts/vibe-equipment.d.ts +71 -0
  76. package/dist/hosts/vibe-equipment.d.ts.map +1 -0
  77. package/dist/hosts/vibe-equipment.js +162 -0
  78. package/dist/hosts/vibe-equipment.js.map +1 -0
  79. package/dist/hosts/vibe-mcp.d.ts +32 -0
  80. package/dist/hosts/vibe-mcp.d.ts.map +1 -0
  81. package/dist/hosts/vibe-mcp.js +210 -0
  82. package/dist/hosts/vibe-mcp.js.map +1 -0
  83. package/dist/hosts/vibe.d.ts +12 -3
  84. package/dist/hosts/vibe.d.ts.map +1 -1
  85. package/dist/hosts/vibe.js +15 -7
  86. package/dist/hosts/vibe.js.map +1 -1
  87. package/dist/index.d.ts +1 -1
  88. package/dist/index.d.ts.map +1 -1
  89. package/dist/index.js +1 -1
  90. package/dist/index.js.map +1 -1
  91. package/dist/runtime/agy-claude.d.ts +42 -0
  92. package/dist/runtime/agy-claude.d.ts.map +1 -0
  93. package/dist/runtime/agy-claude.js +140 -0
  94. package/dist/runtime/agy-claude.js.map +1 -0
  95. package/dist/runtime/live/contracts.d.ts +55 -0
  96. package/dist/runtime/live/contracts.d.ts.map +1 -0
  97. package/dist/runtime/live/contracts.js +59 -0
  98. package/dist/runtime/live/contracts.js.map +1 -0
  99. package/dist/runtime/local-files/identity-fence.d.ts.map +1 -1
  100. package/dist/runtime/local-files/identity-fence.js +2 -0
  101. package/dist/runtime/local-files/identity-fence.js.map +1 -1
  102. package/dist/runtime/local-files/orphan-gc.d.ts +3 -0
  103. package/dist/runtime/local-files/orphan-gc.d.ts.map +1 -0
  104. package/dist/runtime/local-files/orphan-gc.js +69 -0
  105. package/dist/runtime/local-files/orphan-gc.js.map +1 -0
  106. package/dist/runtime/local-files/presence.d.ts +5 -2
  107. package/dist/runtime/local-files/presence.d.ts.map +1 -1
  108. package/dist/runtime/local-files/presence.js +32 -29
  109. package/dist/runtime/local-files/presence.js.map +1 -1
  110. package/dist/runtime/local-files/recipient-hints.d.ts +10 -0
  111. package/dist/runtime/local-files/recipient-hints.d.ts.map +1 -0
  112. package/dist/runtime/local-files/recipient-hints.js +156 -0
  113. package/dist/runtime/local-files/recipient-hints.js.map +1 -0
  114. package/dist/runtime/local-files/store.d.ts.map +1 -1
  115. package/dist/runtime/local-files/store.js +22 -2
  116. package/dist/runtime/local-files/store.js.map +1 -1
  117. package/dist/runtime/mcp/agent-launch.d.ts +3 -0
  118. package/dist/runtime/mcp/agent-launch.d.ts.map +1 -1
  119. package/dist/runtime/mcp/agent-launch.js +93 -8
  120. package/dist/runtime/mcp/agent-launch.js.map +1 -1
  121. package/dist/runtime/mcp/handlers.d.ts +1 -0
  122. package/dist/runtime/mcp/handlers.d.ts.map +1 -1
  123. package/dist/runtime/mcp/handlers.js +7 -4
  124. package/dist/runtime/mcp/handlers.js.map +1 -1
  125. package/dist/runtime/mcp/notifications.d.ts +2 -1
  126. package/dist/runtime/mcp/notifications.d.ts.map +1 -1
  127. package/dist/runtime/mcp/notifications.js +16 -2
  128. package/dist/runtime/mcp/notifications.js.map +1 -1
  129. package/dist/runtime/mcp/server.d.ts +3 -0
  130. package/dist/runtime/mcp/server.d.ts.map +1 -1
  131. package/dist/runtime/mcp/server.js +19 -6
  132. package/dist/runtime/mcp/server.js.map +1 -1
  133. package/dist/runtime/mcp/sessions.d.ts +6 -6
  134. package/dist/runtime/mcp/sessions.d.ts.map +1 -1
  135. package/dist/runtime/mcp/sessions.js +18 -6
  136. package/dist/runtime/mcp/sessions.js.map +1 -1
  137. package/dist/runtime/mcp/stdio.d.ts.map +1 -1
  138. package/dist/runtime/mcp/stdio.js +11 -0
  139. package/dist/runtime/mcp/stdio.js.map +1 -1
  140. package/dist/runtime/mcp/tools.d.ts.map +1 -1
  141. package/dist/runtime/mcp/tools.js +7 -4
  142. package/dist/runtime/mcp/tools.js.map +1 -1
  143. package/dist/runtime/send.d.ts +10 -0
  144. package/dist/runtime/send.d.ts.map +1 -1
  145. package/dist/runtime/send.js +80 -5
  146. package/dist/runtime/send.js.map +1 -1
  147. package/dist/runtime/upgrade/index.d.ts +1 -0
  148. package/dist/runtime/upgrade/index.d.ts.map +1 -1
  149. package/dist/runtime/upgrade/index.js +1 -0
  150. package/dist/runtime/upgrade/index.js.map +1 -1
  151. package/dist/vendor/engram-live/contracts.d.ts +825 -0
  152. package/dist/vendor/engram-live/contracts.js +1734 -0
  153. package/fixtures/native-host-catalog.json +1 -0
  154. package/fixtures/native-host-history.json +1261 -0
  155. package/fixtures/native-host-renderers.json +1 -0
  156. package/hooks/deny-manual-h2a-cli.mjs +38 -0
  157. package/hooks/hooks.json +17 -0
  158. package/hooks/vibe-post-agent.mjs +29 -0
  159. package/hooks/vibe-pre-tool.mjs +40 -0
  160. package/package.json +13 -6
  161. package/scripts/qualification-budget.mjs +56 -0
  162. package/scripts/qualification-cleanup.mjs +15 -0
  163. package/scripts/qualification-oracles.mjs +44 -0
  164. package/scripts/qualification-patch.mjs +21 -0
  165. package/scripts/qualification-poll-hosts.mjs +19 -0
  166. package/scripts/qualification-probe.mjs +63 -0
  167. package/scripts/qualification-rpc.mjs +59 -0
  168. package/scripts/qualification-vibe.mjs +159 -0
  169. package/scripts/qualify-host.mjs +143 -0
  170. package/skills/h2a/SKILL.md +6 -2
@@ -0,0 +1,159 @@
1
+ import fs from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { openQualificationRpc } from './qualification-rpc.mjs';
5
+ import { PHASE2_RECIPE } from './qualification-budget.mjs';
6
+ import { inspectGuardEntries, inspectLifecycleEntries, inspectMcpEntries, inspectSkillEntries } from './qualification-oracles.mjs';
7
+ import { patchNativeHistory } from './qualification-patch.mjs';
8
+ const sha = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
9
+ export function nativeStats(stats) {
10
+ if (!Number.isInteger(stats?.steps)) throw new Error('native iteration accounting unavailable');
11
+ const { sessionPromptTokens: prompt, sessionCompletionTokens: completion, sessionCachedTokens: cached,
12
+ inputPricePerMillion: input, outputPricePerMillion: output, cachedInputPricePerMillion: cachePrice } = stats;
13
+ if (![prompt, completion, cached, input, output].every(n => Number.isFinite(n) && n >= 0) || cached > prompt || cachePrice != null && (!Number.isFinite(cachePrice) || cachePrice < 0)) throw new Error('native price accounting unavailable');
14
+ return { modelCalls: stats.steps, price: ((prompt - cached) * input + cached * (cachePrice ?? input) + completion * output) / 1_000_000 };
15
+ }
16
+ export async function qualifyVibe({ command = 'vibe-app-server', args = [], env, workspaces, busRoot, phase, budget, signal, evidence, cleanup, components, requiredResources = [], clearRecords = () => {}, recordSnapshot = () => undefined }) {
17
+ const sessions = new Map(), history = new Map(), turns = new Map(), completedTurns = new Map(), calls = [];
18
+ let rpc;
19
+ let lifecycleOrigin, recordBaseline, parentHookStarted, childRecordUntouched = false, parentRecordTransitions = 0, parentAfter;
20
+ const accounted = new Map();
21
+ const account = (sessionId, stats) => {
22
+ const execution = sessions.get(sessionId); if (!execution) throw new Error('unmapped native statistics');
23
+ const current = nativeStats(stats), previous = accounted.get(sessionId) ?? { modelCalls: 0, price: 0 };
24
+ budget.account(execution.id, { modelCalls: current.modelCalls - previous.modelCalls, price: current.price - previous.price }); accounted.set(sessionId, current);
25
+ };
26
+ const onEvent = message => {
27
+ const p = message.params ?? {};
28
+ if (p.entry) { const entries = history.get(p.sessionId) ?? new Map(); entries.set(p.entry.id, p.entry); history.set(p.sessionId, entries); }
29
+ if (p.entryId && p.patch) {
30
+ const entries = history.get(p.sessionId), entry = entries?.get(p.entryId);
31
+ if (entry) try { entries.set(p.entryId, patchNativeHistory(entry, p.patch)); } catch { entries.delete(p.entryId); }
32
+ }
33
+ if (p.childSession && sessions.has(p.sessionId)) {
34
+ sessions.set(p.childSession.id, sessions.get(p.sessionId)); cleanup.sessions.push(p.childSession.id);
35
+ if (p.sessionId === lifecycleOrigin && p.childSession.status?.type === 'idle') childRecordUntouched = JSON.stringify(recordSnapshot()) === JSON.stringify(recordBaseline);
36
+ }
37
+ if (message.method === 'stats/updated' && sessions.has(p.sessionId)) try { account(p.sessionId, p.stats); } catch { rpc.child.kill('SIGTERM'); }
38
+ const detail = p.entry?.detail;
39
+ if (p.sessionId === lifecycleOrigin && detail?.scope === 'post_agent') {
40
+ if (detail.kind === 'hook_run_started') {
41
+ parentHookStarted = Date.now();
42
+ if (JSON.stringify(recordSnapshot()) !== JSON.stringify(recordBaseline)) childRecordUntouched = false;
43
+ }
44
+ if (detail.kind === 'hook_run_completed') {
45
+ const current = recordSnapshot();
46
+ if (JSON.stringify(current?.own) !== JSON.stringify(parentAfter?.own)) parentRecordTransitions++;
47
+ parentAfter = current;
48
+ }
49
+ }
50
+ if (message.method === 'turn/completed') { completedTurns.set(p.turn?.id, p.turn); turns.get(p.turn?.id)?.(p.turn); }
51
+ evidence.push({ method: message.method, sessionId: p.sessionId, eventId: p.eventId, sha256: sha(message) });
52
+ };
53
+ rpc = openQualificationRpc(command, args, { cwd: workspaces[0], env, signal, observe: onEvent,
54
+ serverRequest: async message => {
55
+ if (message.method !== 'callback/call') throw new Error('unexpected server request');
56
+ const cb = message.params.callback, effect = cb.detail?.effect, command = effect?.input?.command;
57
+ const resourceRead = effect?.kind === 'file_read' && ['read_file', 'file_system.read_file', 'file_read'].includes(effect.toolName) &&
58
+ requiredResources.some(r => [effect.input?.path, effect.input?.filePath].includes(r.path));
59
+ const expectedCommand = ['shell', 'process'].includes(effect?.kind) && ['bash', 'file_system.bash', 'process_start', 'process.start'].includes(effect.toolName) &&
60
+ ['printf vibe-guard-ok', 'h2a --version'].includes(command);
61
+ const allowed = cb.detail?.kind === 'approval' && (expectedCommand || resourceRead) && sessions.has(cb.sessionId);
62
+ queueMicrotask(() => rpc.request('callback/respond', { sessionId: cb.sessionId, callbackId: cb.callbackId,
63
+ output: { type: 'approval', decision: { type: allowed ? 'approve' : 'deny' } } }).catch(() => {}));
64
+ evidence.push({ method: 'qualification/approval', sessionId: cb.sessionId, allowed, sha256: sha(cb.detail) });
65
+ return { callbackId: cb.callbackId, accepted: true };
66
+ } });
67
+ const start = async (id, cwd) => {
68
+ const allocation = budget.begin(id), started = Date.now();
69
+ const agentConfig = { cwd, headless: true, maxTurns: allocation.maxIterations, maxPrice: allocation.maxPrice };
70
+ const result = await rpc.request('session/start', { agentConfig });
71
+ const session = result.state?.session;
72
+ if (!session?.id || session.cwd !== cwd || session.parentSessionId !== null) throw new Error('native session context mismatch');
73
+ sessions.set(session.id, { id, allocation, started, cwd }); cleanup.sessions.push(session.id);
74
+ return session.id;
75
+ };
76
+ const turn = async (sessionId, text) => {
77
+ const execution = sessions.get(sessionId);
78
+ const watchdog = setTimeout(() => rpc.child.kill('SIGTERM'), Math.max(1, Math.min(budget.remaining(), execution.allocation.maxSeconds * 1000 - (Date.now() - budget.executions.get(execution.id).started))));
79
+ try {
80
+ const result = await rpc.request('turn/start', { sessionId, message: [{ type: 'text', text }] });
81
+ const completed = completedTurns.has(result.turn.id) ? Promise.resolve(completedTurns.get(result.turn.id)) : new Promise(resolve => turns.set(result.turn.id, resolve));
82
+ let onExit;
83
+ const died = new Promise((_, reject) => { onExit = () => reject(new Error('native turn ended without completion')); rpc.child.once('exit', onExit); });
84
+ const done = await Promise.race([completed, died]).finally(() => rpc.child.removeListener('exit', onExit)); turns.delete(result.turn.id);
85
+ if (done.status !== 'completed') throw new Error('native turn incomplete');
86
+ const stats = await rpc.request('stats/read', { sessionId });
87
+ account(sessionId, stats.stats);
88
+ const state = await rpc.request('session/read', { sessionId });
89
+ // Delegated calls are included; unavailable child accounting is partial.
90
+ for (const child of state.state?.childSessions ?? []) {
91
+ cleanup.sessions.push(child.id);
92
+ const childStats = await rpc.request('stats/read', { sessionId: child.id });
93
+ sessions.set(child.id, execution); account(child.id, childStats.stats);
94
+ }
95
+ return [...(history.get(sessionId)?.values() ?? [])];
96
+ } finally { clearTimeout(watchdog); }
97
+ };
98
+ const result = { skills: 'partial', MCP: 'partial', context: 'partial', guard: 'partial', lifecycle: 'partial', sessions: [], runtimeVersion: undefined };
99
+ const mcpContexts = [], skillContexts = [];
100
+ try {
101
+ const initialized = await rpc.request('initialize', { clientInfo: { name: 'h2a-qualification', version: '1' }, capabilities: { callbackKinds: ['approval'] } });
102
+ result.runtimeVersion = initialized.serverInfo?.version; rpc.notify('initialized');
103
+ if (phase === 1) {
104
+ for (const [i, id] of ['phase1-a', 'phase1-b'].entries()) {
105
+ const sessionId = await start(id, workspaces[i]); result.sessions.push(sessionId);
106
+ const skills = await rpc.request('skills/list', { sessionId });
107
+ const runtime = await rpc.request('runtime/read', { sessionId });
108
+ result.probeTools = (runtime.runtime?.tools ?? []).map(t => t.name).filter(name => ['read_file', 'file_system.read_file', 'file_read'].includes(name) || /(?:h2a_identity_status|h2a_session_open|track_status)$/.test(name));
109
+ const names = (skills.skills ?? []).filter(s => s.enabled && s.source === 'local').map(s => s.name);
110
+ evidence.push({ method: 'qualification/skills', sessionId, names, runtimeHash: sha(runtime.runtime) });
111
+ if (components.some(c => ['skills', 'MCP', 'context'].includes(c))) {
112
+ const prompt = 'Use the installed H2A skill. Read the required skill resources at ' + requiredResources.map(r => r.path).join(', ') +
113
+ (components.some(c => ['MCP', 'context'].includes(c)) ? '. Use MCP tools h2a_identity_status and h2a_session_open to report this session identity, bus root and workspace, then track_status with level=task and baselineCommit=qualification for this workspace.' : '') + ' Do not run shell commands.';
114
+ const entries = await turn(sessionId, prompt);
115
+ calls.push(...entries); mcpContexts.push(inspectMcpEntries(entries, sessionId, { busRoot, workspace: workspaces[i] }));
116
+ skillContexts.push(names.includes('h2a') && names.includes('track-operation') && inspectSkillEntries(entries, requiredResources));
117
+ }
118
+ }
119
+ if (skillContexts.length === 2 && skillContexts.every(Boolean)) result.skills = 'observed';
120
+ if (mcpContexts.length === 2 && mcpContexts.every(c => c.MCP)) result.MCP = 'observed';
121
+ if (mcpContexts.length === 2 && mcpContexts.every(c => c.context) && mcpContexts[0].h2aSessionId !== mcpContexts[1].h2aSessionId) result.context = 'observed';
122
+ } else {
123
+ const origin = await start('phase2-origin', workspaces[0]); result.sessions.push(origin);
124
+ lifecycleOrigin = origin; recordBaseline = recordSnapshot();
125
+ const allocation = budget.begin('phase2-copy');
126
+ const fork = await rpc.request('session/fork', { sourceSessionId: origin, attach: PHASE2_RECIPE.fork.attach });
127
+ const copy = fork.state?.session;
128
+ if (!copy?.id || copy.parentSessionId !== origin) throw new Error('native fork context mismatch');
129
+ cleanup.sessions.push(copy.id); result.sessions.push(copy.id);
130
+ const originEntries = await turn(origin, 'Delegate exactly one brief read-only task to one subagent, then answer once. Do not use shell or mutate files.');
131
+ const parentRecord = recordSnapshot();
132
+ await rpc.request('session/resume', { sessionId: copy.id, agentConfig: { cwd: workspaces[0], headless: true, maxTurns: allocation.maxIterations, maxPrice: allocation.maxPrice } });
133
+ sessions.set(copy.id, { id: allocation.id, allocation, started: Date.now(), cwd: workspaces[0] });
134
+ const copyEntries = await turn(copy.id, 'Run exactly printf vibe-guard-ok, then request h2a --version to exercise the installed guard, then answer once. Do not run other commands.');
135
+ result.lifecycleRecordUnchangedInFork = JSON.stringify(parentRecord) === JSON.stringify(recordSnapshot());
136
+ result.parentRecordPresent = !!parentRecord?.own;
137
+ result.recordedAfterParent = !!parentHookStarted && !!parentRecord?.own?.stoppedAt && Date.parse(parentRecord.own.stoppedAt) >= parentHookStarted;
138
+ result.childRecordUntouched = childRecordUntouched; result.parentRecordTransitions = parentRecordTransitions;
139
+ result.otherInstancesUntouched = JSON.stringify(parentRecord?.others) === JSON.stringify(recordBaseline?.others);
140
+ calls.push(...originEntries, ...copyEntries);
141
+ if (inspectGuardEntries(copyEntries, copy.id)) result.guard = 'observed';
142
+ if (inspectLifecycleEntries(calls, origin, copy.id, result)) result.lifecycle = 'observed';
143
+ }
144
+ result.observedEntries = calls.map(e => ({ type: e.type, sessionId: e.sessionId, sha256: sha(e), detail: e.type === 'notice' ? { kind: e.detail?.kind, scope: e.detail?.scope, hookName: e.detail?.hookName, status: e.detail?.status, toolCallId: e.detail?.toolCallId } : undefined }));
145
+ return result;
146
+ } finally {
147
+ // Stop producers before deleting only recorded qualification sessions.
148
+ for (const id of [...new Set(cleanup.sessions)].reverse()) {
149
+ try { await rpc.request('session/stop', { sessionId: id }); }
150
+ catch { cleanup.incomplete = true; }
151
+ }
152
+ try { await clearRecords(); } catch { cleanup.incomplete = true; }
153
+ for (const id of [...new Set(cleanup.sessions)].reverse()) {
154
+ try { await rpc.request('session/delete', { sessionId: id }); cleanup.deleted.push(id); }
155
+ catch { cleanup.incomplete = true; }
156
+ }
157
+ await rpc.close();
158
+ }
159
+ }
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env node
2
+ // Opt-in native recipe. No native process is launched by doctor or upgrade.
3
+ import fs from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { isAbsolute, join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { randomUUID } from 'node:crypto';
8
+ import { runCli as runTrackCli } from '@sentropic/track';
9
+ import { QualificationBudget, VIBE_QUALIFICATION_PLAN, PHASE2_RECIPE } from './qualification-budget.mjs';
10
+ import { qualifyVibe } from './qualification-vibe.mjs';
11
+ import { qualifyVibeProbe } from './qualification-probe.mjs';
12
+ import { qualifyPollHost } from './qualification-poll-hosts.mjs';
13
+ import { clearQualificationRecords, ownedRecordSnapshot } from './qualification-cleanup.mjs';
14
+ import { atomicNativeWrite, digest, jsonBytes, snapshot } from '../dist/hosts/native-files.js';
15
+ import { planVibeEquipment } from '../dist/hosts/vibe-equipment.js';
16
+ import { captureRuntimeGeneratedFiles, verifyRuntimeRecord } from '../dist/hosts/native-runtime-record.js';
17
+ import { parseNativeToml } from '../dist/hosts/native-toml.js';
18
+ const flags = {};
19
+ for (let i = 2; i < process.argv.length; i++) {
20
+ const key = process.argv[i]; if (!key.startsWith('--')) throw new Error('named flags required');
21
+ flags[key.slice(2)] = process.argv[i + 1]?.startsWith('--') || i + 1 === process.argv.length ? true : process.argv[++i];
22
+ }
23
+ if (!['vibe', 'muse', 'agy'].includes(flags.host)) throw new Error('--host vibe|muse|agy required');
24
+ const components = String(flags.components ?? 'skills,MCP,context,guard,lifecycle').split(',');
25
+ if (components.some(c => !['skills', 'MCP', 'context', 'guard', 'lifecycle'].includes(c))) throw new Error('unknown component');
26
+ const plan = { host: flags.host, components, status: 'not executed', execution: 'one app-server session (fork included), or the CLI probe',
27
+ iteration: 'one model call, including every delegated child call', budget: VIBE_QUALIFICATION_PLAN, phase2: PHASE2_RECIPE,
28
+ migration: 'bootstrap B and R5/R7 receipts remain external', notice: 'After every update run h2a doctor --repair; immediate visible relay is not guaranteed.' };
29
+ if (!flags.execute) { process.stdout.write(JSON.stringify(plan, null, 2) + '\n'); process.exit(0); }
30
+ if (!flags.home || !flags.output || !isAbsolute(flags.home) || !isAbsolute(flags.output)) throw new Error('--execute requires explicit absolute --home and --output paths');
31
+ const phase = Number(flags.phase ?? 1); if (![1, 2].includes(phase)) throw new Error('--phase 1|2 required');
32
+ const lane = fs.mkdtempSync(join(tmpdir(), 'h2a-qualification-'));
33
+ const output = resolve(flags.output); fs.mkdirSync(output, { recursive: true, mode: 0o700 });
34
+ for (const name of ['workspace-a', 'workspace-b', 'runtime', 'config', 'state']) fs.mkdirSync(join(lane, name), { mode: 0o700 });
35
+ const env = { ...process.env, HOME: flags.home, VIBE_HOME: join(flags.home, '.vibe'), XDG_RUNTIME_DIR: join(lane, 'runtime'), XDG_CONFIG_HOME: join(flags.home, '.config'), XDG_STATE_HOME: join(flags.home, '.local/state') };
36
+ const busRoot = flags.root ? resolve(flags.root) : join(lane, 'bus');
37
+ const instance = `h2a-qualification-${randomUUID()}`;
38
+ const entrypoint = fileURLToPath(new URL('../dist/bin.js', import.meta.url));
39
+ const evidence = [], cleanup = { sessions: [], deleted: [], incomplete: false, instances: [] };
40
+ const budget = new QualificationBudget();
41
+ let previousAttempt;
42
+ if (phase === 2) {
43
+ if (!flags.previous) throw new Error('phase 2 requires --previous <phase-1 attempt.json>');
44
+ const previous = JSON.parse(fs.readFileSync(flags.previous, 'utf8'));
45
+ if (previous.host !== flags.host || previous.busRoot !== busRoot || previous.profileHome !== flags.home || previous.phase !== 1) throw new Error('phase-1 profile/bus mismatch');
46
+ budget.restorePhase1(previous.accounting, previous.elapsedMilliseconds);
47
+ previousAttempt = previous;
48
+ }
49
+ const controller = new AbortController(), interrupt = () => controller.abort();
50
+ process.once('SIGINT', interrupt); process.once('SIGTERM', interrupt);
51
+ const watchdog = setTimeout(interrupt, budget.remaining());
52
+ let receiptPublication;
53
+ const evidencePath = join(output, 'qualification-' + instance + '.json');
54
+ const report = { ...plan, status: 'partial', fixture: flags.fixture === true, phase, instance, busRoot, profileHome: flags.home, cleanup, evidence, results: {} };
55
+ try {
56
+ if (flags.host !== 'vibe') {
57
+ report.results = qualifyPollHost({ host: flags.host, env, cwd: join(lane, 'workspace-a'), evidence });
58
+ if (flags.host === 'agy') {
59
+ const root = join(flags.home, '.gemini'), state = join(root, '.h2a-install-agy');
60
+ const shared = snapshot(join(root, '.h2a-install-agy/shared-owner.json'));
61
+ if (shared) {
62
+ const path = join(state, 'import-observation.json');
63
+ atomicNativeWrite(path, jsonBytes({ schema: 1, root, status: report.results.import, sharedManifestHash: digest(shared.bytes) }), { state, expected: snapshot(path) });
64
+ }
65
+ }
66
+ report.limit = 'The native Muse/agy model accounting and session trace contracts are unverified. No unbounded model invocation is launched; M-B remains required.';
67
+ } else {
68
+ // Track must resolve a real, private store in each disposable workspace;
69
+ // an empty-view hint from an unadopted directory is not context evidence.
70
+ for (const name of ['workspace-a', 'workspace-b']) {
71
+ const workspace = join(lane, name);
72
+ const code = await runTrackCli(['--track-dir', join(workspace, '.track'), 'init'], { cwd: workspace, out: () => {}, err: () => {} });
73
+ if (code !== 0) throw new Error('private qualification Track initialization failed');
74
+ }
75
+ if (phase === 2) {
76
+ const root = env.VIBE_HOME || join(flags.home, '.vibe');
77
+ const manifest = JSON.parse(fs.readFileSync(join(root, '.h2a-install/manifest.json'), 'utf8'));
78
+ // Never exercise a lifecycle that can mutate somebody else's instance.
79
+ if (!manifest.lifecycle?.enabled || manifest.lifecycle.root !== busRoot || !flags['owned-instance'] || manifest.lifecycle.instance !== flags['owned-instance'])
80
+ throw new Error('Phase 2 requires a dedicated lifecycle instance and exact private bus root explicitly declared with --owned-instance.');
81
+ if (ownedRecordSnapshot(busRoot, flags['owned-instance']).own) throw new Error('qualification instance already has a record');
82
+ cleanup.instances.push(flags['owned-instance']);
83
+ }
84
+ const profileRoot = env.VIBE_HOME || join(flags.home, '.vibe');
85
+ const manifest = JSON.parse(fs.readFileSync(join(profileRoot, '.h2a-install/manifest.json'), 'utf8'));
86
+ const requiredResources = Object.entries(manifest.files).filter(([path, entry]) => path.includes('/assets/') && entry.selected).map(([path]) => ({ path: resolve(profileRoot, path), bytes: fs.readFileSync(resolve(profileRoot, path), 'utf8') }));
87
+ report.results = await qualifyVibe({ command: flags['app-server'] ?? 'vibe-app-server', args: [], env,
88
+ workspaces: [join(lane, 'workspace-a'), join(lane, 'workspace-b')], busRoot, phase, budget, signal: controller.signal, evidence, cleanup, components, requiredResources,
89
+ clearRecords: () => clearQualificationRecords({ root: busRoot, instances: cleanup.instances, entrypoint, env }),
90
+ recordSnapshot: () => ownedRecordSnapshot(busRoot, flags['owned-instance']) });
91
+ if (phase === 1) report.probe = await qualifyVibeProbe({ command: flags.vibe ?? 'vibe', appServer: flags['app-server'] ?? 'vibe-app-server', cwd: join(lane, 'workspace-a'), env,
92
+ tools: report.results.probeTools ?? [], requiredResources, busRoot, components, budget, signal: controller.signal, evidence, cleanup, directory: lane });
93
+ if (flags.record && flags.metadata && !cleanup.incomplete) {
94
+ const metadata = fs.readFileSync(flags.metadata, 'utf8'), version = /^Version: (.+)$/m.exec(metadata)?.[1];
95
+ if (!/Name: mistral[-_]vibe/i.test(metadata) || version !== report.results.runtimeVersion) throw new Error('mistral-vibe wheel metadata does not match the native runtime');
96
+ const state = join(profileRoot, '.h2a-install'), config = parseNativeToml(fs.readFileSync(join(profileRoot, 'config.toml'), 'utf8'));
97
+ const installed = planVibeEquipment({ root: profileRoot, state, version: manifest.version, config, mcpAvailable: (config.mcp_servers ?? []).length > 0, repair: false });
98
+ const previous = snapshot(join(state, 'qualification.json'));
99
+ const receipt = previous ? JSON.parse(previous.bytes.toString()) : { schema: 1, host: 'vibe', root: profileRoot, components: {} };
100
+ if (previous && receipt.fixture !== report.fixture) receipt.components = {};
101
+ receipt.fixture = report.fixture; receipt.recordedAt = new Date().toISOString();
102
+ const generatedFiles = captureRuntimeGeneratedFiles(resolve(flags.record));
103
+ if (!verifyRuntimeRecord(resolve(flags.record), generatedFiles)) throw new Error('native runtime RECORD verification failed');
104
+ receipt.runtime = { generatedFiles, distribution: 'mistral-vibe', version, recordPath: resolve(flags.record), metadataPath: resolve(flags.metadata), recordSha256: digest(fs.readFileSync(flags.record)) };
105
+ const dependencies = { MCP: ['MCP', 'profile', 'node', 'entrypoint'], context: ['MCP', 'profile', 'node', 'entrypoint'],
106
+ skills: ['skills', 'filters', 'profile'], guard: ['guard', 'node', 'entrypoint', 'masking', 'guardBlock', 'MCP'], lifecycle: ['lifecycle', 'node', 'entrypoint', 'lifecycleSelection', 'lifecycleBlock'] };
107
+ const exercised = phase === 1 ? ['skills', 'MCP', 'context'] : ['guard', 'lifecycle'];
108
+ for (const component of components.filter(c => exercised.includes(c))) receipt.components[component] = { status: report.results[component] === 'observed' && (phase !== 1 || report.probe?.status === 'observed') ? 'qualified' : 'partial', dependencies: Object.fromEntries(dependencies[component].map(key => [key, installed.observed[key]])),
109
+ evidence: [evidencePath], evidenceHashes: {}, scope: phase === 2 ? 'explicit lifecycle; parent non-forked only' : 'two isolated native sessions; observed direct MCP is non migrated' };
110
+ receiptPublication = { state, previous, receipt, exercised };
111
+ }
112
+ report.limit = 'Native observations are partial until resource resolution, CLI probe, context and per-component oracles all agree; no fixture qualifies the target host.';
113
+ }
114
+ } catch (error) { report.error = String(error.message).replace(/[\r\n]/g, ' ').slice(0, 500); }
115
+ finally {
116
+ clearTimeout(watchdog); process.removeListener('SIGINT', interrupt); process.removeListener('SIGTERM', interrupt);
117
+ report.accounting = [...budget.executions.values()];
118
+ report.elapsedMilliseconds = Date.now() - budget.start;
119
+ const currentPhase = phase === 1 ? ['skills', 'MCP', 'context'] : ['guard', 'lifecycle'];
120
+ report.componentStatus = Object.fromEntries(components.map(component => {
121
+ const current = currentPhase.includes(component);
122
+ const attempt = current ? report : previousAttempt;
123
+ const observed = attempt?.results?.[component] === 'observed' &&
124
+ (!['skills', 'MCP', 'context'].includes(component) || attempt?.probe?.status === 'observed') &&
125
+ !attempt?.error && !attempt?.cleanup?.incomplete && attempt?.fixture === report.fixture;
126
+ return [component, observed ? 'qualified' : 'partial'];
127
+ }));
128
+ if (!report.error && !cleanup.incomplete && Object.values(report.componentStatus).every(status => status === 'qualified'))
129
+ report.status = report.fixture ? 'fixture-only' : 'qualified';
130
+ // Persist only bounded metadata/hashes, never prompts, model output, stderr or credentials.
131
+ const path = evidencePath;
132
+ if (!cleanup.incomplete) fs.rmSync(lane, { recursive: true, force: true });
133
+ else { report.cleanupResume = { sessions: cleanup.sessions.filter(id => !cleanup.deleted.includes(id)), lane, busRoot, instances: cleanup.instances }; }
134
+ const bytes = JSON.stringify(report, null, 2) + '\n';
135
+ fs.writeFileSync(path, bytes, { mode: 0o600, flag: 'wx' });
136
+ if (receiptPublication && !report.error && !cleanup.incomplete) {
137
+ const { state, previous, receipt, exercised } = receiptPublication;
138
+ for (const c of components.filter(c => exercised.includes(c))) receipt.components[c].evidenceHashes[path] = digest(bytes);
139
+ atomicNativeWrite(join(state, 'qualification.json'), jsonBytes(receipt), { state, expected: previous });
140
+ }
141
+ }
142
+ process.stdout.write(JSON.stringify({ status: report.status, evidence: evidencePath, cleanupComplete: !cleanup.incomplete }) + '\n');
143
+ process.exitCode = report.status === 'qualified' ? 0 : 2;
@@ -356,7 +356,7 @@ These can be invoked directly from the shell at any time, outside the slash-comm
356
356
  - `h2a sessions [--root <path>]` — same listing as `/h2a discover` but from the shell.
357
357
  - `h2a status [--root <path>] [--scope <s>] [--instance <i>]` — inventory of connected sessions split **direct** (local mcp-serve heartbeat) vs **indirect** (mirrored in from a remote/sidecar), with counts.
358
358
  - `h2a keys generate --instance <id>` — produce an ed25519 PEM keypair.
359
- - `h2a install-skills --host <claude|codex|gemini|agy|hermes|opencode|muse>` — re-install or update this skill on another host. *(For **agy**/Antigravity the skill is written to the shared `~/.gemini/commands/h2a.toml`; the command then prints an `importHint` — run `agy plugin import gemini` (then `agy plugin enable h2a`) to pull it into agy. DEC-096/101. For **muse** the skill lands in `~/.config/muse/skills` (user scope, verified) or `<workspace>/.muse/skills` (project scope); verify pickup with `muse skills list`.)*
359
+ - `h2a install-skills --host <claude|codex|gemini|agy|hermes|opencode|muse|vibe>` — install skills and their referenced resources. Vibe uses nonempty `VIBE_HOME` (default `~/.vibe`); Muse uses `~/.config/muse/skills`. agy shares Gemini commands and their ownership; run `agy plugin import gemini`, then `agy plugin enable h2a`. Native discovery/import is distinct from qualification; Gemini never qualifies agy. Unknown/custom native files survive `--force`.
360
360
 
361
361
  **Operational surfaces** (also shell-invocable; matching `h2a_*` MCP tools where noted):
362
362
 
@@ -364,4 +364,8 @@ These can be invoked directly from the shell at any time, outside the slash-comm
364
364
  - `h2a blockage raise|list|resolve` — the peer blockage feedback loop, distinct from the drumbeat and from escalation (`h2a_blockage_*`, DEC-092). Subscribed sessions get `peer.blocked`/`peer.unblocked` pushes.
365
365
  - `h2a drumbeat record|scan|clear|escalations|watch` — anti-stall relance daemon + escalation-to-PRINCIPAL (DEC-086/091/095). Gov D2/D4 (0.64.0): a claimed conductor owns its workspace's relances — peers defer on fresh stalls (relanceCount=0); a failsafe lets a peer step in if the conductor leaves an agent stuck (relanceCount>=1, preventing workspace freeze). Cross-workspace relances emit a CoI advisory (warn, not blocked). Both behaviors are opt-in and default-allow: pass `--instance <self>` to `h2a drumbeat watch` to activate them.
366
366
  - `h2a sysml verify --json <env> --public-key <pem>` — verify a SysML-v2 ref embedded in a signed envelope (commit-trust + content-integrity, DEC-099).
367
- - `h2a host setup|status|plugin --host <codex|claude|gemini|agy|hermes|opencode|muse>` — render the per-host singleton MCP config / stop-hook glue. `host setup --endpoint local|remote` selects one h2a endpoint and removes standalone Track MCP configuration. *(For **muse**: stdio pickup under `mcpServers` in `~/.config/muse/settings.json` is unconfirmed — only streamable-HTTP is documented — so verify with your muse build, else re-run with `--endpoint remote`. Muse is poll-only for the plugin surface.)*
367
+ - `h2a host setup|status|plugin --host <codex|claude|gemini|agy|hermes|opencode|muse|vibe>` — inspect installation/qualification/migration separately. Muse/agy setup and connect render only a nonrecommended historical endpoint: **non migré — bootstrap registre attendu**. Do not ask the operator to paste, translate or merge those snippets. Vibe ships the interim direct entry (owner 16/10, derogation O7.2): `h2a host setup --host vibe --write` installs `[[mcp_servers]] h2a` into `<VIBE_HOME>/config.toml`; `h2a host setup --host vibe --remove` clears it for the R5/R7 registry migration. The registry integrator owns bootstrap/activation and R5/R7 receipts. Existing explicit Muse/agy JSON writers remain available until their migration. Vibe JSON targets stay refused. Muse stdio remains unconfirmed; polling does not qualify hooks.
368
+ - `h2a doctor --repair --host vibe|muse|agy` converges managed native components; `--dry-run` is nonmutating and launches no runtime. Vibe repair installs the interim direct MCP entry when absent (additive; `setup --write` owns argument changes). A Vibe with no MCP entry at inspect time still means **Skills installées, outils MCP absents — bootstrap registre attendu**; repair success never closes native equipment or registry migration. `--skip-hosts` skips this extension.
369
+ - Vibe lifecycle is explicit: `host plugin --host vibe --instance <id> --write <VIBE_HOME>/hooks.toml`. One dedicated non-forked parent session only; no automatic instance isolation is demonstrated. `--instance auto` is unavailable until B. Child/fork payloads produce no record. `/branch` and ACP copies are inactive on resume; `session/fork` attaches its copy by default immediately, while the origin stays active. `vibe -c` can resume the latest copy: use `vibe --resume <original-id>` or a fresh non-forked session. After repair use a new session or clean idle resume with an empty journal; an interrupted-turn resume retains old bindings. `drive receive` is N-A for Vibe.
370
+ - First Vibe guard activation needs a current native MCP component receipt; configuration, fixture and manual observation are insufficient. Native recipes are opt-in and never automatic. Preserve ordinary stale hooks; observable MCP loss suspends an intact managed guard. Muse/agy M-B stays required until the owner accepts M-A.
371
+ - Relay any `operator_notices` returned by `h2a_session_open` or `h2a_identity_status` visibly to the operator. If these tools are not called or the host hides their results, immediate notification is not guaranteed. **After every update run `h2a doctor --repair`** using the verified new entrypoint. Starting from 0.98.6: `h2a upgrade`, `h2a --version`, then `h2a doctor --repair`; the old upgrade alone does not equip hosts.