@evomap/evolver-cli 2.0.48 → 2.0.50

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 (41) hide show
  1. package/dist/autoDistillTranscript.d.ts +1 -1
  2. package/dist/autoDistillTranscript.js +9 -2
  3. package/dist/autoexec.js +3 -0
  4. package/dist/cliContracts.js +5 -28
  5. package/dist/cycleConsumer.js +3 -0
  6. package/dist/distillAdmission.d.ts +8 -1
  7. package/dist/distillAdmission.js +30 -0
  8. package/dist/distillObserver.d.ts +0 -6
  9. package/dist/distillObserver.js +17 -5
  10. package/dist/distillPrimitives.d.ts +4 -3
  11. package/dist/distillPrimitives.js +27 -18
  12. package/dist/doctor.d.ts +3 -0
  13. package/dist/doctor.js +17 -0
  14. package/dist/index.d.ts +3 -0
  15. package/dist/index.js +7 -0
  16. package/dist/lifecycle.d.ts +9 -0
  17. package/dist/lifecycle.js +159 -102
  18. package/dist/lifecycleAutoexecCompanion.d.ts +40 -0
  19. package/dist/lifecycleAutoexecCompanion.js +102 -0
  20. package/dist/lifecycleBootstrapTransaction.js +38 -17
  21. package/dist/llmCycle.js +15 -5
  22. package/dist/localMemoryGraph.js +29 -19
  23. package/dist/promptRecallRuntime.d.ts +3 -0
  24. package/dist/promptRecallRuntime.js +8 -0
  25. package/dist/promptRecallShared.d.ts +2 -0
  26. package/dist/promptRecallShared.js +13 -3
  27. package/dist/protectedAuditStatus.d.ts +22 -0
  28. package/dist/protectedAuditStatus.js +234 -0
  29. package/dist/recall.js +2 -3
  30. package/dist/runtimeCapabilities.d.ts +1 -1
  31. package/dist/runtimeCapabilities.js +24 -0
  32. package/dist/runtimeSessionSource.js +4 -4
  33. package/dist/sessionIngest.js +3 -0
  34. package/dist/setupHooks.d.ts +3 -0
  35. package/dist/setupHooks.js +98 -17
  36. package/dist/setupHooksLifecycle.d.ts +19 -3
  37. package/dist/setupHooksLifecycle.js +17 -246
  38. package/dist/setupHooksTransaction.d.ts +12 -0
  39. package/dist/setupHooksTransaction.js +220 -0
  40. package/dist/trajectoryExport.js +2 -2
  41. package/package.json +7 -7
@@ -0,0 +1,234 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { closeSync, constants, fstatSync, mkdirSync, openSync, readFileSync, readSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { acquireLock, releaseLock } from '@evomap/evolver-core/prompt-recall';
5
+ import { hookStdoutNotSubmitted, writeHookStdout } from './promptRecallShared.js';
6
+ export const PROTECTED_AUDIT_INSTALL_GUIDE = 'an administrator must install the protected audit service with install-protected-audit-service.sh '
7
+ + 'from the same sealed release as this evolver binary (docs/release-smoke.md, section "POSIX 用户实际安装边界")';
8
+ const NOT_PROVISIONED_REASONS = new Set(['service_not_provisioned', 'client_config_missing']);
9
+ const MAX_NOTIFIED_SESSIONS = 256;
10
+ const NOTICE_OWNER = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
11
+ function protectedAuditInstallState(readiness) {
12
+ if (readiness.state !== 'unavailable')
13
+ return readiness.state;
14
+ return NOT_PROVISIONED_REASONS.has(readiness.reason) ? 'not_provisioned' : 'unavailable';
15
+ }
16
+ export function protectedAuditInstallReport(readiness) {
17
+ const state = protectedAuditInstallState(readiness);
18
+ if (state === 'ready' || state === 'not_required')
19
+ return { protected_audit: state };
20
+ const reason = readiness.state === 'unavailable' ? readiness.reason : state;
21
+ return {
22
+ protected_audit: state,
23
+ protected_audit_next_step: `Evolver cannot record audit events until the protected audit service is available (${reason}); ${PROTECTED_AUDIT_INSTALL_GUIDE}.`,
24
+ };
25
+ }
26
+ export function protectedAuditNoticeStatePath(evomapHome) {
27
+ return join(evomapHome, 'evolution', 'protected-audit-session-notice.json');
28
+ }
29
+ function decodeNoticeState(text) {
30
+ const data = JSON.parse(text);
31
+ const sessions = data.sessions;
32
+ if (!Array.isArray(sessions) || sessions.length > MAX_NOTIFIED_SESSIONS
33
+ || sessions.some((key) => typeof key !== 'string' || !/^[a-f0-9]{64}$/.test(key)))
34
+ throw new Error('invalid_audit_notice_state');
35
+ if (data.version === 1)
36
+ return { sessions, pending: {} };
37
+ const pending = data.pending;
38
+ if (data.version !== 2 || !pending || typeof pending !== 'object' || Array.isArray(pending)
39
+ || Object.entries(pending).some(([key, owner]) => !sessions.includes(key) || typeof owner !== 'string' || !NOTICE_OWNER.test(owner))) {
40
+ throw new Error('invalid_audit_notice_state');
41
+ }
42
+ return { sessions, pending };
43
+ }
44
+ function readNoticeState(path) {
45
+ try {
46
+ return decodeNoticeState(readFileSync(path, 'utf8'));
47
+ }
48
+ catch (error) {
49
+ if (error.code === 'ENOENT')
50
+ return { sessions: [], pending: {} };
51
+ throw error;
52
+ }
53
+ }
54
+ function writeOwnedNoticeFile(path, text) {
55
+ const fd = openSync(path, 'wx', 0o600);
56
+ try {
57
+ try {
58
+ writeFileSync(fd, text, 'utf8');
59
+ }
60
+ finally {
61
+ closeSync(fd);
62
+ }
63
+ }
64
+ catch (error) {
65
+ removeNoticeFile(path);
66
+ throw error;
67
+ }
68
+ }
69
+ function removeNoticeFile(path) {
70
+ try {
71
+ unlinkSync(path);
72
+ }
73
+ catch { /* The state file remains authoritative. */ }
74
+ }
75
+ function writeNoticeState(path, state) {
76
+ const temporary = `${path}.${randomUUID()}.tmp`;
77
+ writeOwnedNoticeFile(temporary, `${JSON.stringify({ version: 2, ...state })}\n`);
78
+ try {
79
+ renameSync(temporary, path);
80
+ }
81
+ catch (error) {
82
+ removeNoticeFile(temporary);
83
+ throw error;
84
+ }
85
+ }
86
+ function applyNoticeSettlement(state, key, owner, outcome) {
87
+ if (state.pending[key] !== owner)
88
+ return false;
89
+ delete state.pending[key];
90
+ if (outcome === 'not_submitted')
91
+ state.sessions.splice(state.sessions.indexOf(key), 1);
92
+ return true;
93
+ }
94
+ function noticeSettlementPath(path, owner) {
95
+ return `${path}.${owner}.settled`;
96
+ }
97
+ function readNoticeSettlement(path, key) {
98
+ try {
99
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
100
+ try {
101
+ const info = fstatSync(fd);
102
+ if (!info.isFile() || info.size > 80)
103
+ return undefined;
104
+ const bytes = Buffer.alloc(80);
105
+ const length = readSync(fd, bytes, 0, bytes.length, 0);
106
+ if (length !== info.size)
107
+ return undefined;
108
+ const receipt = bytes.toString('utf8', 0, length);
109
+ if (receipt === `${key}:written\n`)
110
+ return 'written';
111
+ if (receipt === `${key}:not_submitted\n`)
112
+ return 'not_submitted';
113
+ }
114
+ finally {
115
+ closeSync(fd);
116
+ }
117
+ }
118
+ catch { /* An unavailable receipt cannot authorize replay. */ }
119
+ return undefined;
120
+ }
121
+ function recoverNoticeSettlements(path, state, key) {
122
+ const candidates = state.sessions.length === MAX_NOTIFIED_SESSIONS ? Object.keys(state.pending) : [key];
123
+ const consumed = [];
124
+ for (const session of candidates) {
125
+ const owner = state.pending[session];
126
+ if (!owner)
127
+ continue;
128
+ const receipt = noticeSettlementPath(path, owner);
129
+ const outcome = readNoticeSettlement(receipt, session);
130
+ if (outcome && applyNoticeSettlement(state, session, owner, outcome))
131
+ consumed.push(receipt);
132
+ }
133
+ return consumed;
134
+ }
135
+ function updateNoticeState(path, update, recoveryKey) {
136
+ try {
137
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
138
+ const lockPath = `${path}.lock`;
139
+ const owner = acquireLock(lockPath, { maxTries: 1, waitMs: 0 });
140
+ let changed = false, released = false;
141
+ try {
142
+ const state = readNoticeState(path);
143
+ const consumed = recoveryKey ? recoverNoticeSettlements(path, state, recoveryKey) : [];
144
+ changed = update(state);
145
+ if (changed || consumed.length > 0)
146
+ writeNoticeState(path, state);
147
+ for (const receipt of consumed)
148
+ removeNoticeFile(receipt);
149
+ }
150
+ finally {
151
+ released = releaseLock(lockPath, owner).released;
152
+ }
153
+ return changed && released;
154
+ }
155
+ catch {
156
+ return false;
157
+ }
158
+ }
159
+ function settleNotice(path, key, owner, outcome) {
160
+ // The callback can outlive the caller or lose the state lock to another hook.
161
+ // An exclusive receipt preserves the exact outcome without waiting on that lock.
162
+ try {
163
+ writeOwnedNoticeFile(noticeSettlementPath(path, owner), `${key}:${outcome}\n`);
164
+ }
165
+ catch (error) {
166
+ if (error.code !== 'EEXIST') {
167
+ updateNoticeState(path, (state) => applyNoticeSettlement(state, key, owner, outcome));
168
+ return;
169
+ }
170
+ }
171
+ updateNoticeState(path, () => false, key);
172
+ }
173
+ function claimProtectedAuditSessionNotice(sessionId, readiness, path) {
174
+ if (readiness.state !== 'unavailable' || !sessionId)
175
+ return undefined;
176
+ const key = createHash('sha256').update(sessionId).digest('hex');
177
+ const owner = randomUUID();
178
+ const claimed = updateNoticeState(path, (state) => {
179
+ if (state.sessions.includes(key))
180
+ return false;
181
+ if (state.sessions.length === MAX_NOTIFIED_SESSIONS) {
182
+ // An interrupted write may have delivered bytes. Never evict an unconfirmed reservation.
183
+ const oldestConfirmed = state.sessions.findIndex((session) => !Object.hasOwn(state.pending, session));
184
+ if (oldestConfirmed < 0)
185
+ return false;
186
+ state.sessions.splice(oldestConfirmed, 1);
187
+ }
188
+ state.sessions.push(key);
189
+ state.pending[key] = owner;
190
+ return true;
191
+ }, key);
192
+ if (!claimed)
193
+ return undefined;
194
+ return {
195
+ message: `[evolver] Memory recall and recording are paused: the protected audit service is unavailable (${readiness.reason}); ${PROTECTED_AUDIT_INSTALL_GUIDE}.`,
196
+ settle: (outcome) => settleNotice(path, key, owner, outcome),
197
+ };
198
+ }
199
+ /** Reserve before attempting one write; only the actual transport acknowledgement confirms it. */
200
+ export async function writeProtectedAuditSessionNotice(sessionId, readiness, path, writer, emptyOutput = '') {
201
+ const notice = claimProtectedAuditSessionNotice(sessionId, readiness, path);
202
+ const text = notice ? `${JSON.stringify({ systemMessage: notice.message })}\n` : emptyOutput;
203
+ if (!text)
204
+ return;
205
+ let settled = false, outputWritten = false;
206
+ const actual = (written) => {
207
+ if (settled)
208
+ return;
209
+ settled = true;
210
+ if (!written)
211
+ return;
212
+ outputWritten = true;
213
+ notice?.settle('written');
214
+ try {
215
+ writer.onOutputWritten?.();
216
+ }
217
+ catch { /* An observer cannot invalidate confirmed stdout. */ }
218
+ };
219
+ try {
220
+ if (writer.stdoutWithSettlement)
221
+ await writer.stdoutWithSettlement(text, actual);
222
+ else if (writer.stdout) {
223
+ await writer.stdout(text);
224
+ actual(true);
225
+ }
226
+ else
227
+ await writeHookStdout(text, { onSettled: actual });
228
+ }
229
+ catch (error) {
230
+ // EPIPE, timeout and other post-dispatch errors can follow a partial delivery.
231
+ if (!outputWritten && hookStdoutNotSubmitted(error))
232
+ notice?.settle('not_submitted');
233
+ }
234
+ }
package/dist/recall.js CHANGED
@@ -5,10 +5,9 @@
5
5
  // `<session_id>.jsonl`, so recall matches them by session id (falling back to the most-recent inject for un-stamped
6
6
  // events / runtimes with no id). Pure logic lives in evolver-core/ops/recall; this module is the IO glue (read
7
7
  // transcript -> turns, resolve genes from the store, pull geneIds off the matching inject event).
8
- import { readFileSync } from 'node:fs';
9
8
  import { basename } from 'node:path';
10
9
  import { assetstore, events, ops } from '@evomap/evolver-core';
11
- import { adapterForPath } from '@evomap/evolver-runtime-adapters';
10
+ import { adapterForPath, readSessionLog } from '@evomap/evolver-runtime-adapters';
12
11
  /** Claude Code names a transcript `<session_id>.jsonl`, so the basename (minus extension) is the session id used to
13
12
  * match the inject event that produced THIS session (#205). Other runtimes' names simply won't match any stamped
14
13
  * sessionId, and the caller falls back to the most-recent inject — safe, never wrong, just less precise. */
@@ -146,7 +145,7 @@ export async function runRecall(argv, deps = {}) {
146
145
  }
147
146
  let content;
148
147
  try {
149
- content = (deps.readFile ?? ((p) => readFileSync(p, 'utf8')))(transcript);
148
+ content = (deps.readFile ?? readSessionLog)(transcript);
150
149
  }
151
150
  catch (e) {
152
151
  err(`recall: cannot read ${transcript}: ${e instanceof Error ? e.message : String(e)}`);
@@ -1,5 +1,5 @@
1
1
  type RuntimeCapabilityStatus = 'supported' | 'experimental' | 'unsupported';
2
- type RuntimeCapabilityId = 'claude-code' | 'codex' | 'cursor' | 'gemini' | 'antigravity' | 'kimi' | 'kiro' | 'opencode' | 'generic-chat' | 'llm';
2
+ type RuntimeCapabilityId = 'claude-code' | 'codex' | 'cursor' | 'gemini' | 'antigravity' | 'kimi' | 'workbuddy' | 'dsh' | 'grok' | 'kiro' | 'opencode' | 'generic-chat' | 'llm';
3
3
  interface RuntimeCapability {
4
4
  status: RuntimeCapabilityStatus;
5
5
  evidence: string;
@@ -59,6 +59,30 @@ export const RUNTIME_CAPABILITY_MATRIX = {
59
59
  verify: unsupported('no Kimi execution runner exists'),
60
60
  resume: unsupported('no verified Kimi resume contract'),
61
61
  },
62
+ workbuddy: {
63
+ runtime: 'workbuddy',
64
+ ingest: supported('WorkBuddy ~/.workbuddy/projects JSONL adapter verified against a sanitized real-log golden'),
65
+ inject: unsupported('no Evolver CLI injection installer; live hooks come from evolver-agent-plugin'),
66
+ execute: unsupported('no verified WorkBuddy runner contract'),
67
+ verify: unsupported('no WorkBuddy execution runner exists'),
68
+ resume: unsupported('no verified WorkBuddy resume contract'),
69
+ },
70
+ dsh: {
71
+ runtime: 'dsh',
72
+ ingest: supported('DeepSeek Harness session.v4.jsonl.zstd adapter verified against a sanitized real-log golden; needs Node zstd support'),
73
+ inject: unsupported('no Evolver CLI injection installer; live hooks come from evolver-agent-plugin'),
74
+ execute: unsupported('no verified DeepSeek Harness runner contract'),
75
+ verify: unsupported('no DeepSeek Harness execution runner exists'),
76
+ resume: unsupported('no verified DeepSeek Harness resume contract'),
77
+ },
78
+ grok: {
79
+ runtime: 'grok',
80
+ ingest: supported('Grok CLI chat_history.jsonl adapter verified against a sanitized real-log golden'),
81
+ inject: unsupported('no Evolver CLI injection installer; live hooks come from evolver-agent-plugin'),
82
+ execute: unsupported('no verified Grok runner contract'),
83
+ verify: unsupported('no Grok execution runner exists'),
84
+ resume: unsupported('no verified Grok resume contract'),
85
+ },
62
86
  kiro: {
63
87
  runtime: 'kiro',
64
88
  ingest: unsupported('transcript adapter is not registered; no real-log golden fixture'),
@@ -1,7 +1,7 @@
1
- import { readFileSync, realpathSync } from 'node:fs';
1
+ import { realpathSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { isAbsolute, join, relative, resolve } from 'node:path';
4
- import { adapterForPath, isCursorStateVscdbPath, parseJsonlLinesWithStats, parseCursorStateVscdb, stripUtf8Bom, } from '@evomap/evolver-runtime-adapters';
4
+ import { adapterForPath, isCursorStateVscdbPath, parseJsonlLinesWithStats, parseCursorStateVscdb, readSessionLog, stripUtf8Bom, } from '@evomap/evolver-runtime-adapters';
5
5
  const EMPTY_DIAGNOSTICS = { rowsScanned: 0, rowsRead: 0, invalidJson: 0 };
6
6
  function canonicalNativeSessionSource(path, agent, nativeSessionHome) {
7
7
  const runtimeRoot = agent === 'claude-code'
@@ -46,7 +46,7 @@ function diagnosticsForRuntimeSource(raw) {
46
46
  return parseJsonlLinesWithStats(raw).stats;
47
47
  }
48
48
  }
49
- export function parseRuntimeSessionSourcesWithDiagnostics(path, readSource = (p) => readFileSync(p, 'utf8'), nativeSessionHome = homedir()) {
49
+ export function parseRuntimeSessionSourcesWithDiagnostics(path, readSource = readSessionLog, nativeSessionHome = homedir()) {
50
50
  const absPath = resolve(path);
51
51
  if (isCursorStateVscdbPath(absPath)) {
52
52
  const sources = parseCursorStateVscdb(absPath)
@@ -103,6 +103,6 @@ export function parseRuntimeSessionSourcesWithDiagnostics(path, readSource = (p)
103
103
  diagnostics: diagnosticsForRuntimeSource(raw),
104
104
  };
105
105
  }
106
- export function parseRuntimeSessionSources(path, readSource = (p) => readFileSync(p, 'utf8'), nativeSessionHome = homedir()) {
106
+ export function parseRuntimeSessionSources(path, readSource = readSessionLog, nativeSessionHome = homedir()) {
107
107
  return parseRuntimeSessionSourcesWithDiagnostics(path, readSource, nativeSessionHome).sources;
108
108
  }
@@ -92,6 +92,9 @@ const MATERIAL_SOURCE_AGENTS = new Set([
92
92
  'gemini',
93
93
  'antigravity',
94
94
  'kimi',
95
+ 'workbuddy',
96
+ 'dsh',
97
+ 'grok',
95
98
  'kiro',
96
99
  'opencode',
97
100
  'generic-chat',
@@ -1,11 +1,14 @@
1
1
  import { type InstallScope } from '@evomap/evolver-mcp';
2
2
  import { assetstore } from '@evomap/evolver-core';
3
3
  import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
4
+ import { type ProtectedAuditReadiness } from './protectedAuditStatus.js';
4
5
  interface SetupHooksDeps {
5
6
  emitNonGitWorkspaceNotice?: typeof maybeEmitNonGitWorkspaceNotice;
6
7
  runtimeAvailable?: (runtime: 'opencode' | 'kiro', configRoot: string, scope: InstallScope) => boolean;
7
8
  /** Test seam proving service-only/manual paths do not resolve an unrelated MCP Node executable. */
8
9
  resolveMcpNodePath?: () => string;
10
+ /** Test seam for the read-only protected audit service probe. */
11
+ protectedAudit?: () => ProtectedAuditReadiness;
9
12
  }
10
13
  export declare function commandNamesForPath(command: string, platform: NodeJS.Platform, pathExt: string | undefined): string[];
11
14
  /** Paths under package-manager stores are volatile: the linked Node disappears on the next install/upgrade,
@@ -6,17 +6,19 @@
6
6
  // cleanly removes only evolver's entries.
7
7
  import { planInjection, installInjection, uninstallInjection, runtimeSupport, renderManualWiring, renderServiceGuidance, SETUP_RUNTIMES, SERVICE_TARGETS, kiroConfigRoot, resolveOpenCodeConfig, McpConfigConflictError, McpConfigOwnershipError, McpConfigVerificationError, McpServerValidationError } from '@evomap/evolver-mcp';
8
8
  import { assetstore, events } from '@evomap/evolver-core';
9
- import { resolveInstallComponents } from '@evomap/evolver-mcp';
10
- import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
9
+ import { resolveInstallComponents, InstallerTransactionError, installerTransactionFromError } from '@evomap/evolver-mcp';
10
+ import { accessSync, constants, existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs';
11
11
  import { createRequire } from 'node:module';
12
12
  import { homedir } from 'node:os';
13
- import { basename, delimiter, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
13
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
15
  import { currentTopCursorGenes } from './cursorRewrite.js';
16
16
  import { resolveProxyBinPath, resolveStableNodePath } from './lifecycle.js';
17
17
  import { reviewLedgerForStore } from './reviewFilter.js';
18
18
  import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
19
- import { createSetupLifecyclePlan, decodeSetupLifecyclePlan, executeSetupLifecyclePlan, SETUP_LIFECYCLE_SCHEMA, setupLifecycleCapabilities, SetupLifecycleError, verifySetupLifecycle, } from './setupHooksLifecycle.js';
19
+ import { AGENT_PLUGIN_NAME, pluginHostNamed } from './pluginHosts.js';
20
+ import { protectedAuditInstallReport } from './protectedAuditStatus.js';
21
+ import { createSetupLifecyclePlan, decodeSetupLifecyclePlan, executeSetupLifecyclePlan, inspectSetupTransactions, recoverSetupLifecycle, SETUP_LIFECYCLE_SCHEMA, setupLifecycleCapabilities, SetupLifecycleError, verifySetupLifecycle, } from './setupHooksLifecycle.js';
20
22
  const requireFromHere = createRequire(import.meta.url);
21
23
  function configuredHomeDir() {
22
24
  const configured = process.platform === 'win32'
@@ -24,6 +26,14 @@ function configuredHomeDir() {
24
26
  : process.env['HOME'];
25
27
  return configured && configured.trim() ? configured : homedir();
26
28
  }
29
+ function projectRootIsDirectoryOrMissing(path) {
30
+ try {
31
+ return lstatSync(path).isDirectory();
32
+ }
33
+ catch (error) {
34
+ return error.code === 'ENOENT';
35
+ }
36
+ }
27
37
  function parseFlags(argv) {
28
38
  const out = {};
29
39
  for (let i = 0; i < argv.length; i++) {
@@ -44,7 +54,8 @@ function parseFlags(argv) {
44
54
  }
45
55
  return out;
46
56
  }
47
- const USAGE = `usage: evolver setup-hooks [--runtime=${SETUP_RUNTIMES.join('|')}] [--scope=user|project|global] [--components=product-only|evolution-only|both] [--root=<dir>] [--lifecycle=capabilities|plan|verify|execute] [--action=install|uninstall] [--confirmed-plan=<base64url>] [--target-id=<id>] [--completed-targets=<id,id>] [--env-file=<path>] [--profile-descriptor=<json>] [--service=${SERVICE_TARGETS.join('|')}] [--verify] [--uninstall] [--dry-run] [--force] [--json] [--hook-command="evolver inject session-start"] [--prompt-recall-hook-command="evolver inject prompt-recall"] [--server-node=<absolute-node>] [--server-command=<cmd>] [--server-args=a,b] [--service-command=<cmd>] [--service-args=a,b]\n --verify is read-only for claude-code, codex, opencode and kiro\n lifecycle operations are versioned JSON and require --json\n`;
57
+ const USAGE = `usage: evolver setup-hooks [--runtime=${SETUP_RUNTIMES.join('|')}] [--scope=user|project|global] [--components=product-only|evolution-only|both] [--root=<dir>] [--lifecycle=capabilities|plan|verify|execute|status|recover] [--action=install|uninstall] [--confirmed-plan=<base64url>] [--target-id=<id>] [--completed-targets=<id,id>] [--env-file=<path>] [--profile-descriptor=<json>] [--service=${SERVICE_TARGETS.join('|')}] [--verify] [--uninstall] [--dry-run] [--force] [--json] [--hook-command="evolver inject session-start"] [--prompt-recall-hook-command="evolver inject prompt-recall"] [--server-node=<absolute-node>] [--server-command=<cmd>] [--server-args=a,b] [--service-command=<cmd>] [--service-args=a,b]\n --verify is read-only for claude-code, codex, opencode and kiro\n lifecycle operations are versioned JSON and require --json\n`;
58
+ const TRANSACTION_USAGE = '\nRecovery (configuration files and ownership backups; sequential, not instant cross-file visibility):\n --lifecycle=status --json [--transaction-id=<id>]\n --lifecycle=recover --json --transaction-id=<id> --recovery=rollback\n --lifecycle=recover --json --transaction-id=<id> --recovery=resume --action=install|uninstall\n After manually reconciling a blocked config, inspect status again, then explicitly preserve that reviewed state:\n --lifecycle=recover --json --transaction-id=<id> --recovery=accept-current --confirmed-state=<resolution_digest>\nUse the same runtime, scope, root and original install options. Concurrent edits block rollback rather than being overwritten.\n';
48
59
  export function commandNamesForPath(command, platform, pathExt) {
49
60
  if (platform !== 'win32' || /\.[^\\/]+$/.test(command))
50
61
  return [command];
@@ -202,6 +213,8 @@ function displayResultPaths(paths, configRoot, scope) {
202
213
  export function safeSetupOperationError(error) {
203
214
  if (error instanceof Error && error.message === '[setup-hooks] product bridge is user-owned; explicit --force is required')
204
215
  return error.message;
216
+ if (error instanceof InstallerTransactionError)
217
+ return error.message;
205
218
  if (error instanceof McpConfigConflictError)
206
219
  return error.message;
207
220
  if (error instanceof McpConfigOwnershipError)
@@ -525,7 +538,7 @@ function appendAdapterNotes(text, hints) {
525
538
  : text;
526
539
  }
527
540
  const SETUP_VALUE_FLAGS = new Set([
528
- 'runtime', 'platform', 'scope', 'root', 'components', 'lifecycle', 'action', 'confirmed-plan', 'target-id', 'completed-targets', 'env-file', 'profile-descriptor', 'service',
541
+ 'runtime', 'platform', 'scope', 'root', 'components', 'lifecycle', 'action', 'confirmed-plan', 'transaction-id', 'recovery', 'confirmed-state', 'target-id', 'completed-targets', 'env-file', 'profile-descriptor', 'service',
529
542
  'hook-command', 'server-node', 'server-command', 'server-args', 'service-command', 'service-args',
530
543
  ]);
531
544
  function setupHelpRequested(argv) {
@@ -562,7 +575,7 @@ function runSetupLifecycle(f, runtime, scope, configRoot, emit, deps) {
562
575
  };
563
576
  if (f['json'] !== true)
564
577
  return fail('PLAN_INVALID', 'lifecycle operations require --json');
565
- if (typeof operation !== 'string' || !['capabilities', 'plan', 'verify', 'execute'].includes(operation)) {
578
+ if (typeof operation !== 'string' || !['capabilities', 'plan', 'verify', 'execute', 'status', 'recover'].includes(operation)) {
566
579
  return fail('PLAN_INVALID', 'invalid --lifecycle operation');
567
580
  }
568
581
  if (f['verify'] !== undefined || f['uninstall'] !== undefined || f['dry-run'] !== undefined || f['force'] !== undefined) {
@@ -587,8 +600,20 @@ function runSetupLifecycle(f, runtime, scope, configRoot, emit, deps) {
587
600
  }
588
601
  if (!capabilities.supported)
589
602
  return fail('CAPABILITY_UNAVAILABLE', `lifecycle protocol is unavailable for ${runtime}/${scope}`);
603
+ if ((f['transaction-id'] !== undefined && operation !== 'status' && operation !== 'recover')
604
+ || (f['recovery'] !== undefined && operation !== 'recover')
605
+ || (f['confirmed-state'] !== undefined && (operation !== 'recover' || f['recovery'] !== 'accept-current'))) {
606
+ return fail('PLAN_INVALID', 'transaction recovery flags require --lifecycle=status|recover');
607
+ }
608
+ const transactionID = f['transaction-id'];
609
+ const recovery = f['recovery'];
610
+ if ((transactionID !== undefined && (typeof transactionID !== 'string' || !/^[a-f0-9]{64}$/.test(transactionID)))
611
+ || operation === 'recover' && (typeof transactionID !== 'string' || recovery !== 'resume' && recovery !== 'rollback' && recovery !== 'accept-current')
612
+ || recovery === 'accept-current' && (typeof f['confirmed-state'] !== 'string' || !/^[a-f0-9]{64}$/.test(f['confirmed-state']))) {
613
+ return fail('PLAN_INVALID', 'recovery requires --transaction-id=<id> and --recovery=resume|rollback|accept-current; accept-current also requires --confirmed-state=<resolution_digest>');
614
+ }
590
615
  const action = lifecycleAction(f['action']);
591
- if ((operation === 'plan' || operation === 'execute') && action === undefined) {
616
+ if ((operation === 'plan' || operation === 'execute' || operation === 'recover' && recovery === 'resume') && action === undefined) {
592
617
  return fail('PLAN_INVALID', '--action=install|uninstall is required');
593
618
  }
594
619
  const descriptor = f['components'] === 'product-only'
@@ -598,7 +623,7 @@ function runSetupLifecycle(f, runtime, scope, configRoot, emit, deps) {
598
623
  return fail('PLAN_INVALID', descriptor.error, 1);
599
624
  let server = { command: 'evolver-mcp' };
600
625
  let productBridgeNodePath;
601
- if (operation === 'verify' || action === 'install') {
626
+ if (operation === 'verify' || action === 'install' && operation !== 'status' && !(operation === 'recover' && recovery !== 'resume')) {
602
627
  try {
603
628
  const built = buildServer(f, descriptor.descriptor, deps.resolveMcpNodePath);
604
629
  server = built.server;
@@ -633,6 +658,22 @@ function runSetupLifecycle(f, runtime, scope, configRoot, emit, deps) {
633
658
  },
634
659
  };
635
660
  try {
661
+ if (operation === 'status') {
662
+ emit({ schema: SETUP_LIFECYCLE_SCHEMA, operation, ok: true,
663
+ transactions: inspectSetupTransactions(context, typeof transactionID === 'string' ? transactionID : undefined)
664
+ .filter(transaction => transaction.runtime === runtime && transaction.scope === scope) });
665
+ return 0;
666
+ }
667
+ if (operation === 'recover') {
668
+ if (recovery === 'resume') {
669
+ const recorded = inspectSetupTransactions(context, transactionID)[0];
670
+ if (recorded && recorded.action !== action)
671
+ return fail('PLAN_INVALID', 'resume action does not match the durable transaction', 1);
672
+ }
673
+ const result = recoverSetupLifecycle(context, transactionID, recovery, typeof f['confirmed-state'] === 'string' ? f['confirmed-state'] : undefined);
674
+ emit({ schema: SETUP_LIFECYCLE_SCHEMA, operation, ok: true, result });
675
+ return result.complete ? 0 : 1;
676
+ }
636
677
  if (operation === 'plan') {
637
678
  const plan = createSetupLifecyclePlan(context, action);
638
679
  emit({ schema: SETUP_LIFECYCLE_SCHEMA, operation, ok: true, plan });
@@ -670,12 +711,17 @@ function runSetupLifecycle(f, runtime, scope, configRoot, emit, deps) {
670
711
  catch (error) {
671
712
  if (error instanceof SetupLifecycleError)
672
713
  return fail(error.code, error.message, 1);
714
+ if (error instanceof InstallerTransactionError) {
715
+ emit({ schema: SETUP_LIFECYCLE_SCHEMA, operation, ok: false, code: error.code, error: error.message,
716
+ ...(error.transaction ? { transaction: error.transaction } : {}) });
717
+ return 1;
718
+ }
673
719
  return fail('VERIFY_FAILED', safeSetupOperationError(error), 1);
674
720
  }
675
721
  }
676
722
  export async function runSetupHooks(argv, store, review, deps = {}) {
677
723
  if (setupHelpRequested(argv)) {
678
- process.stdout.write(USAGE);
724
+ process.stdout.write(USAGE + TRANSACTION_USAGE);
679
725
  return 0;
680
726
  }
681
727
  const f = parseFlags(argv);
@@ -729,6 +775,17 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
729
775
  process.stderr.write(`${message}\n`);
730
776
  return 2;
731
777
  }
778
+ // Reject invalid project roots before Node resolution or recovery-state creation. Lifecycle recovery
779
+ // and user-only targets keep their existing handling of missing or unrelated project paths.
780
+ if (support.outcome === 'installed' && scope === 'project' && runtime !== 'antigravity'
781
+ && !projectRootIsDirectoryOrMissing(configRoot)) {
782
+ const error = '[setup-hooks] config root must be a real directory';
783
+ if (json)
784
+ emit({ runtime, outcome: 'error', files: [], error });
785
+ else
786
+ process.stderr.write(`${error}\n`);
787
+ return 1;
788
+ }
732
789
  // V1 exposed setup-hooks --verify as a read-only operation. Silently ignoring it is unsafe: the command then
733
790
  // falls through to installInjection and can rewrite runtime configuration while the operator asked only to
734
791
  // inspect it. V2's JSON MCP installers already have a transaction-free dry-run preflight, so use that as the
@@ -837,7 +894,8 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
837
894
  catch (error) {
838
895
  const message = safeSetupOperationError(error);
839
896
  if (json)
840
- emit({ runtime, action: 'uninstall', files: [], error: message });
897
+ emit({ runtime, action: 'uninstall', files: [], error: message,
898
+ transaction: installerTransactionFromError(error) });
841
899
  else
842
900
  process.stderr.write(`${message}\n`);
843
901
  return 1;
@@ -860,7 +918,7 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
860
918
  return 0;
861
919
  }
862
920
  if (json)
863
- emit({ runtime, action: 'uninstall', files, backups });
921
+ emit({ runtime, action: 'uninstall', files, backups, transaction: r.transaction });
864
922
  else
865
923
  process.stdout.write(files.length ? `removed evolver from: ${files.join(', ')}\n` : 'nothing to remove\n');
866
924
  return 0;
@@ -1006,7 +1064,8 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
1006
1064
  // distinct from the support-matrix `unsupported` (an unrecognized runtime id) (Bugbot #264).
1007
1065
  const msg = safeSetupOperationError(e);
1008
1066
  if (json)
1009
- emit({ runtime, outcome: 'error', files: [], error: msg });
1067
+ emit({ runtime, outcome: 'error', files: [], error: msg,
1068
+ transaction: installerTransactionFromError(e) });
1010
1069
  else
1011
1070
  process.stderr.write(`${msg}\n`);
1012
1071
  return 1;
@@ -1022,6 +1081,13 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
1022
1081
  }
1023
1082
  const files = displayResultPaths(r.files, configRoot, scope) ?? [];
1024
1083
  const backups = displayResultPaths(r.backups, configRoot, scope);
1084
+ const audit = protectedAuditInstallReport((deps.protectedAudit ?? events.protectedAuditReadiness)());
1085
+ const warnings = [
1086
+ ...(r.warnings ?? []),
1087
+ ...(audit.protected_audit_next_step ? [audit.protected_audit_next_step] : []),
1088
+ ...(runtime === 'claude-code' && f['components'] !== 'product-only' && claudeAgentPluginEnabled() ? [CLAUDE_PLUGIN_OVERLAP_WARNING] : []),
1089
+ ];
1090
+ const warningFields = warnings.length > 0 ? { warnings } : {};
1025
1091
  if (r.dryRun) {
1026
1092
  if (json) {
1027
1093
  emit({
@@ -1031,6 +1097,8 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
1031
1097
  backups,
1032
1098
  dryRun: true,
1033
1099
  ...(r.alreadyInstalled ? { alreadyInstalled: true } : {}),
1100
+ ...audit,
1101
+ ...warningFields,
1034
1102
  });
1035
1103
  }
1036
1104
  else if (r.alreadyInstalled) {
@@ -1039,20 +1107,33 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
1039
1107
  else {
1040
1108
  process.stdout.write(`dry-run: would install evolver (${r.mode}) → ${files.join(', ')}\n`);
1041
1109
  }
1110
+ emitWarnings(warnings);
1042
1111
  return 0;
1043
1112
  }
1044
1113
  if (r.alreadyInstalled) {
1045
1114
  if (json)
1046
- emit({ runtime, outcome: 'installed', files, alreadyInstalled: true, ...(r.warnings ? { warnings: r.warnings } : {}) });
1115
+ emit({ runtime, outcome: 'installed', files, alreadyInstalled: true, ...audit, ...warningFields });
1047
1116
  else
1048
1117
  process.stdout.write('evolver already installed (use --force to reinstall)\n');
1049
- emitWarnings(r.warnings);
1118
+ emitWarnings(warnings);
1050
1119
  return 0;
1051
1120
  }
1052
1121
  if (json)
1053
- emit({ runtime, outcome: 'installed', files, backups, mode: r.mode, verified: r.verified, ...(r.warnings ? { warnings: r.warnings } : {}) });
1122
+ emit({ runtime, outcome: 'installed', files, backups, mode: r.mode, verified: r.verified, transaction: r.transaction, ...audit, ...warningFields });
1054
1123
  else
1055
1124
  process.stdout.write(`installed evolver (${r.mode}) → ${files.join(', ')}\n`);
1056
- emitWarnings(r.warnings);
1125
+ emitWarnings(warnings);
1057
1126
  return 0;
1127
+ }
1128
+ const CLAUDE_PLUGIN_OVERLAP_WARNING = `Claude Code already enables ${AGENT_PLUGIN_NAME}, which covers recall; the SessionStart/UserPromptSubmit hooks written by setup-hooks duplicate it. Consider removing only those two evolver hook entries from your Claude Code settings; setup-hooks did not change the plugin or its settings.`;
1129
+ function claudeAgentPluginEnabled() {
1130
+ const marketplace = pluginHostNamed('claude-code')?.marketplace;
1131
+ const settingsPath = join(process.env['CLAUDE_CONFIG_DIR'] || join(configuredHomeDir(), '.claude'), 'settings.json');
1132
+ try {
1133
+ const settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
1134
+ return settings.enabledPlugins?.[`${AGENT_PLUGIN_NAME}@${marketplace}`] === true;
1135
+ }
1136
+ catch {
1137
+ return false;
1138
+ }
1058
1139
  }
@@ -1,4 +1,5 @@
1
- import { type InjectionPlan, type InstallOptions, type InstallScope, type RuntimeId } from '@evomap/evolver-mcp';
1
+ import { INSTALLER_TRANSACTION_SCHEMA, type InstallerTransactionSummary, type InjectionPlan, type InstallOptions, type InstallScope, type RuntimeId } from '@evomap/evolver-mcp';
2
+ export { inspectSetupTransactions } from './setupHooksTransaction.js';
2
3
  export declare const SETUP_LIFECYCLE_SCHEMA = "evolver.setup_hooks.lifecycle.v1";
3
4
  export declare const SETUP_LIFECYCLE_PLAN_TTL_MS = 120000;
4
5
  export type SetupLifecycleAction = 'install' | 'uninstall';
@@ -11,6 +12,12 @@ export interface SetupLifecycleCapabilities {
11
12
  hookCommandsBound: boolean;
12
13
  standaloneMcp: boolean;
13
14
  operations: Record<SetupLifecycleOperation, boolean>;
15
+ transactions: {
16
+ schema: typeof INSTALLER_TRANSACTION_SCHEMA;
17
+ durable: boolean;
18
+ atomicVisibility: false;
19
+ recovery: boolean;
20
+ };
14
21
  }
15
22
  export interface SetupLifecycleTarget {
16
23
  target_id: string;
@@ -37,7 +44,8 @@ export interface SetupLifecycleTargetResult {
37
44
  outcome: 'installed' | 'removed' | 'already_satisfied' | 'already_absent' | 'failed';
38
45
  committed: boolean;
39
46
  verified: boolean;
40
- recovery?: 'REFRESH_PLAN' | 'OPEN_CONFIG' | 'RETRY_VERIFICATION';
47
+ recovery?: 'REFRESH_PLAN' | 'OPEN_CONFIG' | 'RETRY_VERIFICATION' | 'ROLLBACK_TRANSACTION';
48
+ rolled_back?: boolean;
41
49
  }
42
50
  export interface SetupLifecycleExecutionResult {
43
51
  schema: typeof SETUP_LIFECYCLE_SCHEMA;
@@ -50,6 +58,13 @@ export interface SetupLifecycleExecutionResult {
50
58
  complete: boolean;
51
59
  verified: boolean;
52
60
  targets: SetupLifecycleTargetResult[];
61
+ transaction?: InstallerTransactionSummary;
62
+ failure?: {
63
+ code: string;
64
+ target_id?: string;
65
+ message: string;
66
+ recovery: 'REFRESH_PLAN' | 'ROLLBACK_TRANSACTION';
67
+ };
53
68
  }
54
69
  export interface SetupLifecycleExecutionOptions {
55
70
  targetId?: string;
@@ -72,4 +87,5 @@ export declare function createSetupLifecyclePlan(context: SetupLifecycleContext,
72
87
  export declare function encodeSetupLifecyclePlan(plan: SetupLifecyclePlan): string;
73
88
  export declare function decodeSetupLifecyclePlan(raw: string): SetupLifecyclePlan;
74
89
  export declare function verifySetupLifecycle(context: SetupLifecycleContext): boolean;
75
- export declare function executeSetupLifecyclePlan(context: SetupLifecycleContext, confirmed: SetupLifecyclePlan, options?: SetupLifecycleExecutionOptions): SetupLifecycleExecutionResult;
90
+ export declare function executeSetupLifecyclePlan(context: SetupLifecycleContext, confirmed: SetupLifecyclePlan, options?: SetupLifecycleExecutionOptions): SetupLifecycleExecutionResult;
91
+ export declare function recoverSetupLifecycle(context: SetupLifecycleContext, id: string, recovery: 'resume' | 'rollback' | 'accept-current', confirmedState?: string): InstallerTransactionSummary | SetupLifecycleExecutionResult;