wrxn-reversa 1.15.0 → 1.16.0
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.
- package/CHANGELOG.md +15 -0
- package/lib/commands/hooks.js +11 -4
- package/lib/commands/install.js +20 -7
- package/lib/commands/update.js +40 -9
- package/lib/installer/prompts.js +4 -3
- package/lib/installer/recovery-hooks.js +93 -16
- package/lib/installer/writer.js +6 -2
- package/package.json +1 -1
- package/templates/hooks/reanchor-omp.mjs +2 -2
- package/templates/hooks/reanchor.mjs +161 -57
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.16.0
|
|
4
|
+
|
|
5
|
+
- Reversa recovery hooks honor the owner-level selector at `$XDG_CONFIG_HOME/agents/work-state.json`.
|
|
6
|
+
If `XDG_CONFIG_HOME` is empty or unset, they use `~/.config/agents/work-state.json`.
|
|
7
|
+
A missing selector preserves project opt-in.
|
|
8
|
+
An unreadable or invalid selector leaves recovery silent.
|
|
9
|
+
Use a real directory path: a symlink in the config path makes it invalid even if the file is absent.
|
|
10
|
+
A relative `XDG_CONFIG_HOME`, or no `XDG_CONFIG_HOME` and no `HOME`, also makes it invalid.
|
|
11
|
+
Make the selector file yours with mode `0600` or stricter, in a directory that you own and only you can write.
|
|
12
|
+
Any other owner or permission makes it invalid.
|
|
13
|
+
Run `wrxn-reversa hooks status` to check the selected mode and local registration.
|
|
14
|
+
- When the selector names `global` or `off` for an engine, `install` and `update` do not offer or create its project recovery hooks.
|
|
15
|
+
Existing registrations stay in place and their handlers stay silent.
|
|
16
|
+
`hooks enable` refuses an engine with `global` or an invalid selector and writes nothing.
|
|
17
|
+
|
|
3
18
|
## 1.15.0
|
|
4
19
|
|
|
5
20
|
- Update now offers recovery-hook choices for each installed engine that supports them.
|
package/lib/commands/hooks.js
CHANGED
|
@@ -2,7 +2,7 @@ import chalk from 'chalk';
|
|
|
2
2
|
import { resolve } from 'path';
|
|
3
3
|
import { readCheckoutState } from '../../agents/reversa/scripts/session-state.mjs';
|
|
4
4
|
import { applyWhenIdle, idlePreview } from '../installer/checkout-guard.js';
|
|
5
|
-
import { applyRecoveryHooks, planRecoveryHooks, recoveryEngines, recoveryLocalNotice, recoveryStatus, verifyRecoveryHookFiles } from '../installer/recovery-hooks.js';
|
|
5
|
+
import { applyRecoveryHooks, planRecoveryHooks, recoveryEngines, recoveryLocalNotice, recoverySelection, recoveryStatus, verifyRecoveryEnable, verifyRecoveryHookFiles, verifyRecoverySelection } from '../installer/recovery-hooks.js';
|
|
6
6
|
import { pathState } from '../installer/reconcile.js';
|
|
7
7
|
import { roleOf, SATELLITE } from '../installer/role.js';
|
|
8
8
|
|
|
@@ -24,11 +24,18 @@ export default async function hooks([verb, ...args]) {
|
|
|
24
24
|
if (!selected.length) throw new Error('No supported recovery hook engine is installed.');
|
|
25
25
|
const show = data => selected.forEach(id => console.log(`${id}: ${recoveryStatus(root, data, id)}`));
|
|
26
26
|
if (verb === 'status') { show(state); return; }
|
|
27
|
-
|
|
27
|
+
const selection = verb === 'enable' ? recoverySelection(selected) : null;
|
|
28
|
+
if (selection) {
|
|
29
|
+
verifyRecoveryEnable(selection);
|
|
30
|
+
verifyRecoveryHookFiles(root, selected);
|
|
31
|
+
}
|
|
28
32
|
const plan = planRecoveryHooks(root, state, { [verb]: selected });
|
|
29
|
-
const applied = await applyWhenIdle(root, snapshot, chalk, () => applyRecoveryHooks(root, plan, state));
|
|
30
|
-
if (!applied) { process.exitCode = 1; return; }
|
|
31
33
|
for (const warning of plan.warnings) console.log(chalk.yellow(warning));
|
|
34
|
+
const applied = await applyWhenIdle(root, snapshot, chalk, () => {
|
|
35
|
+
if (selection) verifyRecoverySelection(selection);
|
|
36
|
+
applyRecoveryHooks(root, plan, state);
|
|
37
|
+
});
|
|
38
|
+
if (!applied) { process.exitCode = 1; return; }
|
|
32
39
|
if (verb === 'enable') console.log(recoveryLocalNotice);
|
|
33
40
|
show({ ...state, recovery_hooks: plan.records });
|
|
34
41
|
}
|
package/lib/commands/install.js
CHANGED
|
@@ -13,7 +13,7 @@ import { applyWhenIdle, idlePreview } from '../installer/checkout-guard.js';
|
|
|
13
13
|
import { UNINSTALL_BACKUPS, listBackups, readBackup, restoreBackup } from '../installer/backup.js';
|
|
14
14
|
import { languageName, requestedSkillsLanguage } from '../installer/locale.js';
|
|
15
15
|
import { SATELLITE, requestedRole, roleOf } from '../installer/role.js';
|
|
16
|
-
import { applyRecoveryHooks, planRecoveryHooks, recoveryLocalNotice } from '../installer/recovery-hooks.js';
|
|
16
|
+
import { applyRecoveryHooks, planRecoveryHooks, recoveryEngines, recoveryLocalNotice, recoverySelection, verifyRecoveryHookPlan, verifyRecoverySelection } from '../installer/recovery-hooks.js';
|
|
17
17
|
import { applyMirrors, describeSkillLayout, planMirrors, previewMirrors, recordChanges, resolveSkillLayout, resolveSkillsMode, verifySkillLayout } from '../installer/skill-layout.js';
|
|
18
18
|
|
|
19
19
|
export default async function install(args = []) {
|
|
@@ -60,9 +60,11 @@ export default async function install(args = []) {
|
|
|
60
60
|
}
|
|
61
61
|
|
|
62
62
|
// Collect answers
|
|
63
|
+
const selection = recoverySelection(recoveryEngines);
|
|
64
|
+
const eligible = recoveryEngines.filter(engine => selection[engine].mode === 'standalone');
|
|
63
65
|
let answers;
|
|
64
66
|
try {
|
|
65
|
-
answers = await runInstallPrompts(detectedEngines, { skillsLanguage: requestedLanguage, role });
|
|
67
|
+
answers = await runInstallPrompts(detectedEngines, { skillsLanguage: requestedLanguage, role, recoveryEligible: eligible });
|
|
66
68
|
} catch (err) {
|
|
67
69
|
if (err.isTtyError || err.message?.includes('cancel')) {
|
|
68
70
|
console.log(chalk.gray('\n Installation cancelled.\n'));
|
|
@@ -72,8 +74,15 @@ export default async function install(args = []) {
|
|
|
72
74
|
}
|
|
73
75
|
|
|
74
76
|
const selectedEngines = ENGINES.filter(e => answers.engines.includes(e.id));
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
+
const selectedRecovery = Object.fromEntries(selectedEngines.filter(e => selection[e.id]).map(e => [e.id, selection[e.id]]));
|
|
78
|
+
const recovery = answers.role === SATELLITE ? [] : (answers.recovery_hooks ?? []).filter(engine => eligible.includes(engine));
|
|
79
|
+
const hookPlan = recovery.length ? planRecoveryHooks(projectRoot, preview.state, { enable: recovery }) : null;
|
|
80
|
+
if (answers.role !== SATELLITE) {
|
|
81
|
+
for (const [engine, { mode }] of Object.entries(selectedRecovery)) {
|
|
82
|
+
if (mode !== 'standalone') console.log(` ${engine}: ${mode} selector; no project recovery activation.`);
|
|
83
|
+
if (mode === 'invalid') console.log(' Check the selector path and permissions, including symlinked parent directories.');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
77
86
|
const manifest = {};
|
|
78
87
|
const index = indexManifest(manifest);
|
|
79
88
|
const layout = resolveSkillLayout(projectRoot, selectedEngines);
|
|
@@ -82,6 +91,8 @@ export default async function install(args = []) {
|
|
|
82
91
|
previewMirrors(mirrors);
|
|
83
92
|
let failed = false;
|
|
84
93
|
if (!await applyWhenIdle(projectRoot, preview, chalk, async () => {
|
|
94
|
+
if (hookPlan) verifyRecoverySelection(Object.fromEntries(recovery.map(id => [id, selection[id]])));
|
|
95
|
+
if (hookPlan) verifyRecoveryHookPlan(projectRoot, hookPlan);
|
|
85
96
|
verifySkillLayout(projectRoot, selectedEngines, layout);
|
|
86
97
|
const writer = new Writer(projectRoot, { lang: answers.skills_language, keepEdits });
|
|
87
98
|
|
|
@@ -171,8 +182,9 @@ export default async function install(args = []) {
|
|
|
171
182
|
if (recovery.length) {
|
|
172
183
|
const hookPreview = idlePreview(projectRoot, chalk);
|
|
173
184
|
if (!hookPreview || !await applyWhenIdle(projectRoot, hookPreview, chalk, () => {
|
|
174
|
-
|
|
175
|
-
|
|
185
|
+
verifyRecoverySelection(Object.fromEntries(recovery.map(id => [id, selection[id]])));
|
|
186
|
+
const restoredPlan = planRecoveryHooks(projectRoot, hookPreview.state, { enable: recovery });
|
|
187
|
+
applyRecoveryHooks(projectRoot, restoredPlan, hookPreview.state);
|
|
176
188
|
})) {
|
|
177
189
|
process.exitCode = 1;
|
|
178
190
|
return;
|
|
@@ -181,7 +193,8 @@ export default async function install(args = []) {
|
|
|
181
193
|
console.log(` ${recoveryLocalNotice}`);
|
|
182
194
|
console.log(' Keep these project-local files out of Git, or stage unrelated edits separately.');
|
|
183
195
|
if (recovery.includes('codex')) console.log(' Review and trust the exact hook definitions in Codex /hooks.');
|
|
184
|
-
} else if (answers.role !== SATELLITE)
|
|
196
|
+
} else if (answers.role !== SATELLITE && (!Object.keys(selectedRecovery).length
|
|
197
|
+
|| Object.values(selectedRecovery).some(({ mode }) => mode === 'standalone'))) {
|
|
185
198
|
console.log(` Recovery hooks are off. To enable them later, run npx ${getPackageInfo().name} hooks enable.`);
|
|
186
199
|
}
|
|
187
200
|
|
package/lib/commands/update.js
CHANGED
|
@@ -17,7 +17,7 @@ import { findBlock } from '../installer/entry-block.js';
|
|
|
17
17
|
import { languageName, resolveSkillsLanguage } from '../installer/locale.js';
|
|
18
18
|
import { SATELLITE, planHubAssets, requestedRole, roleOf } from '../installer/role.js';
|
|
19
19
|
import { applyMirrors, describeSkillLayout, planMirrors, previewMirrors, recordChanges, resolveSkillLayout, resolveSkillsMode, verifySkillLayout } from '../installer/skill-layout.js';
|
|
20
|
-
import { applyRecoveryHooks, planRecoveryHooks, recoveryLocalNotice, recoveryRegistrationIssue, verifyRecoveryHookFiles, verifyRecoveryHookPlan } from '../installer/recovery-hooks.js';
|
|
20
|
+
import { applyRecoveryHooks, hasRecoveryRegistration, planRecoveryHooks, recoveryEngines, recoveryLocalNotice, recoveryRegistrationIssue, recoverySelection, verifyRecoveryHookFiles, verifyRecoveryHookPlan, verifyRecoverySelection } from '../installer/recovery-hooks.js';
|
|
21
21
|
|
|
22
22
|
async function fetchLatestVersion(packageName) {
|
|
23
23
|
try {
|
|
@@ -33,10 +33,27 @@ async function fetchLatestVersion(packageName) {
|
|
|
33
33
|
const STATE = '.reversa/state.json';
|
|
34
34
|
const MANIFEST = '.reversa/_config/files-manifest.json';
|
|
35
35
|
|
|
36
|
-
async function chooseRecoveryHooks(root, state, engines, inquirer, writes) {
|
|
37
|
-
const choices = recoveryHookChoices(engines, state.recovery_hooks);
|
|
38
|
-
if (!choices.length) return null;
|
|
36
|
+
async function chooseRecoveryHooks(root, state, engines, inquirer, writes, selection) {
|
|
37
|
+
const choices = recoveryHookChoices(engines.filter(({ id }) => selection[id]?.mode === 'standalone'), state.recovery_hooks);
|
|
39
38
|
const current = choices.filter(choice => choice.checked).map(choice => choice.value);
|
|
39
|
+
const retained = Object.keys(selection).filter(id => {
|
|
40
|
+
const record = state.recovery_hooks?.[id];
|
|
41
|
+
if (!record || selection[id].mode === 'invalid' || recoveryRegistrationIssue(root, id, record)) return false;
|
|
42
|
+
try {
|
|
43
|
+
verifyRecoveryHookFiles(root, [id], writes);
|
|
44
|
+
return true;
|
|
45
|
+
} catch {
|
|
46
|
+
console.log(` ${id}: keeping local handler; migration pending.`);
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
const build = (enable, disable) => {
|
|
51
|
+
const retain = retained.filter(id => !enable.includes(id) && !disable.includes(id));
|
|
52
|
+
const plan = planRecoveryHooks(root, state, { enable, disable, retain });
|
|
53
|
+
verifyRecoveryHookFiles(root, plan.verify, writes);
|
|
54
|
+
return { enable, plan };
|
|
55
|
+
};
|
|
56
|
+
if (!choices.length) return build([], []);
|
|
40
57
|
const repairs = new Map();
|
|
41
58
|
for (const choice of choices.slice()) {
|
|
42
59
|
if (!choice.checked) continue;
|
|
@@ -63,8 +80,7 @@ async function chooseRecoveryHooks(root, state, engines, inquirer, writes) {
|
|
|
63
80
|
enable.push(id);
|
|
64
81
|
}
|
|
65
82
|
try {
|
|
66
|
-
|
|
67
|
-
recovery = enable.length || disable.length ? { enable, plan: planRecoveryHooks(root, state, { enable, disable }) } : null;
|
|
83
|
+
recovery = build(enable, disable);
|
|
68
84
|
return true;
|
|
69
85
|
} catch (err) {
|
|
70
86
|
return `${err.message} Adjust the selection to continue the update.`;
|
|
@@ -214,8 +230,17 @@ async function runUpdate(args, beginApply) {
|
|
|
214
230
|
|
|
215
231
|
const inquirer = interactive ? (await import('inquirer')).default : null;
|
|
216
232
|
if (interactive) applyOrangeTheme();
|
|
233
|
+
const selection = role === SATELLITE ? {} : recoverySelection(recoveryEngines.filter(id => state.engines?.includes(id)));
|
|
234
|
+
for (const [id, { mode }] of Object.entries(selection)) {
|
|
235
|
+
if (mode === 'invalid') console.log(` ${id}: invalid selector; migration pending.`);
|
|
236
|
+
if (mode === 'global' && id === 'omp') console.log(' omp: global selected, no global OMP runner proven.');
|
|
237
|
+
if ((mode === 'global' || mode === 'off') && (state.recovery_hooks?.[id] || hasRecoveryRegistration(projectRoot, id))) {
|
|
238
|
+
try { verifyRecoveryHookFiles(projectRoot, [id], plan.writes); }
|
|
239
|
+
catch (err) { return { reason: `${err.message} The existing recovery route may still be active.` }; }
|
|
240
|
+
}
|
|
241
|
+
}
|
|
217
242
|
const recovery = interactive && role !== SATELLITE
|
|
218
|
-
? await chooseRecoveryHooks(projectRoot, state, installedEngines, inquirer, plan.writes)
|
|
243
|
+
? await chooseRecoveryHooks(projectRoot, state, installedEngines, inquirer, plan.writes, selection)
|
|
219
244
|
: null;
|
|
220
245
|
|
|
221
246
|
const LABELS = { restore: 'Restore', new: 'Add', migrate: 'Migrate', refresh: 'Refresh', replace: 'Replace' };
|
|
@@ -233,6 +258,11 @@ async function runUpdate(args, beginApply) {
|
|
|
233
258
|
previewMirrors(mirrors);
|
|
234
259
|
if (recovery) {
|
|
235
260
|
for (const warning of recovery.plan.warnings) console.log(chalk.yellow(` ${warning}`));
|
|
261
|
+
for (const id of recovery.plan.verify) {
|
|
262
|
+
if (state.recovery_hooks?.[id]?.selector_version !== 1 || recovery.enable.includes(id)) {
|
|
263
|
+
console.log(` Verify ${id} recovery registration and record selector compatibility.`);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
236
266
|
for (const { rel, enabling } of recovery.plan.operations) {
|
|
237
267
|
console.log(` ${enabling ? 'Enable' : 'Disable'} Reversa recovery hooks in ${rel}`);
|
|
238
268
|
}
|
|
@@ -271,8 +301,9 @@ async function runUpdate(args, beginApply) {
|
|
|
271
301
|
outcome = { reason: 'Impeccable changed since preview; run the update again.' };
|
|
272
302
|
return;
|
|
273
303
|
}
|
|
304
|
+
verifyRecoverySelection(selection);
|
|
274
305
|
if (recovery) {
|
|
275
|
-
verifyRecoveryHookFiles(projectRoot, recovery.
|
|
306
|
+
verifyRecoveryHookFiles(projectRoot, recovery.plan.verify, plan.writes);
|
|
276
307
|
verifyRecoveryHookPlan(projectRoot, recovery.plan);
|
|
277
308
|
}
|
|
278
309
|
|
|
@@ -327,7 +358,7 @@ async function runUpdate(args, beginApply) {
|
|
|
327
358
|
else if (writer.replaced > 0) console.log(` ${writer.replaced} file(s) replaced without a backup.`);
|
|
328
359
|
let hookChanged = false;
|
|
329
360
|
if (!failed && recovery) {
|
|
330
|
-
|
|
361
|
+
verifyRecoverySelection(selection);
|
|
331
362
|
hookChanged = applyRecoveryHooks(projectRoot, recovery.plan, state);
|
|
332
363
|
if (hookChanged) console.log(' Recovery hook settings updated. Restart the affected engines.');
|
|
333
364
|
if (recovery.enable.length) console.log(` ${recoveryLocalNotice}`);
|
package/lib/installer/prompts.js
CHANGED
|
@@ -162,7 +162,7 @@ export function recoveryHookChoices(engines, current = {}) {
|
|
|
162
162
|
|
|
163
163
|
// skillsLanguage: language already decided (--lang or an existing installation); skips the question.
|
|
164
164
|
// role: repository role already decided (--role); skips the question.
|
|
165
|
-
export async function runInstallPrompts(detectedEngines, { skillsLanguage, role } = {}) {
|
|
165
|
+
export async function runInstallPrompts(detectedEngines, { skillsLanguage, role, recoveryEligible = recoveryEngines } = {}) {
|
|
166
166
|
const engineChoices = detectedEngines.map(e => ({
|
|
167
167
|
name: `${e.name}${e.star ? ' (recommended)' : ''}`,
|
|
168
168
|
value: e.id,
|
|
@@ -272,8 +272,9 @@ export async function runInstallPrompts(detectedEngines, { skillsLanguage, role
|
|
|
272
272
|
type: 'checkbox',
|
|
273
273
|
name: 'recovery_hooks',
|
|
274
274
|
message: promptTitle(11, 'Enable project recovery hooks? Leave all unchecked to keep them off.', 'checkbox'),
|
|
275
|
-
when: answers => isStandalone(answers) &&
|
|
276
|
-
choices: answers => recoveryHookChoices(detectedEngines.filter(engine =>
|
|
275
|
+
when: answers => isStandalone(answers) && recoveryEligible.some(id => answers.engines.includes(id)),
|
|
276
|
+
choices: answers => recoveryHookChoices(detectedEngines.filter(engine =>
|
|
277
|
+
recoveryEligible.includes(engine.id) && answers.engines.includes(engine.id))),
|
|
277
278
|
},
|
|
278
279
|
]);
|
|
279
280
|
|
|
@@ -4,6 +4,8 @@ import { isDeepStrictEqual } from 'util';
|
|
|
4
4
|
import { hashContent } from './manifest.js';
|
|
5
5
|
import { matchesBaseline, pathState } from './reconcile.js';
|
|
6
6
|
import { json, object, replace, safePath } from '../../agents/reversa/scripts/lib/safe-fs.mjs';
|
|
7
|
+
import { readRecoverySelector } from '../../templates/hooks/reanchor.mjs';
|
|
8
|
+
import { getPackageInfo } from '../utils/package-info.js';
|
|
7
9
|
|
|
8
10
|
const targets = { 'claude-code': '.claude/settings.local.json', codex: '.codex/hooks.json', omp: '.omp/extensions/reversa-recovery.js' };
|
|
9
11
|
const alternate = { 'claude-code': '.claude/settings.json', codex: '.codex/config.toml' };
|
|
@@ -14,6 +16,25 @@ const statePath = '.reversa/state.json';
|
|
|
14
16
|
const fingerprint = value => hashContent(json(value));
|
|
15
17
|
const mentionsRecovery = text => /\.reversa[\\/]+hooks[\\/]+reanchor(?:-omp)?\.mjs/.test(text);
|
|
16
18
|
|
|
19
|
+
export function recoverySelection(engines) {
|
|
20
|
+
return Object.fromEntries(engines.map(engine => [engine, readRecoverySelector(engine)]));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function verifyRecoverySelection(selection) {
|
|
24
|
+
if (!isDeepStrictEqual(selection, recoverySelection(Object.keys(selection)))) {
|
|
25
|
+
throw new Error('Recovery selector changed since preview. Run the command again.');
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function verifyRecoveryEnable(selection) {
|
|
30
|
+
for (const [engine, { mode }] of Object.entries(selection)) {
|
|
31
|
+
if (mode === 'global' || mode === 'invalid') {
|
|
32
|
+
const runner = engine === 'omp' && mode === 'global' ? '; no global OMP runner proven' : '';
|
|
33
|
+
throw new Error(`Cannot enable ${engine} recovery: ${mode} selected${runner}.`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
17
38
|
function registration(root, engine) {
|
|
18
39
|
const script = join(root, hooksDir, 'reanchor.mjs');
|
|
19
40
|
if (process.platform === 'win32' && /["%!$`\r\n]/.test(script)) throw new Error('Cannot quote the recovery handler in this Windows path.');
|
|
@@ -31,6 +52,18 @@ function snapshot(root, rel) {
|
|
|
31
52
|
return { text, baseline: hashContent(text) };
|
|
32
53
|
}
|
|
33
54
|
|
|
55
|
+
export function hasRecoveryRegistration(root, engine) {
|
|
56
|
+
for (const rel of [targets[engine], alternate[engine]].filter(Boolean)) {
|
|
57
|
+
try {
|
|
58
|
+
const { text } = snapshot(root, rel);
|
|
59
|
+
if (mentionsRecovery(text ?? '') || text?.includes('Reversa recovery')) return true;
|
|
60
|
+
} catch {
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
|
|
34
67
|
function config(text, rel) {
|
|
35
68
|
const data = text === undefined ? {} : JSON.parse(text.replace(/^\uFEFF/, ''));
|
|
36
69
|
if (!object(data) || ('hooks' in data && !object(data.hooks))) throw new Error(`${rel} has an invalid hooks object.`);
|
|
@@ -111,12 +144,18 @@ function planTarget(root, engine, enable, prior, warnings) {
|
|
|
111
144
|
return op;
|
|
112
145
|
}
|
|
113
146
|
|
|
114
|
-
export function planRecoveryHooks(root, state, { enable = [], disable = [] }) {
|
|
147
|
+
export function planRecoveryHooks(root, state, { enable = [], disable = [], retain = [] }) {
|
|
115
148
|
const records = { ...state.recovery_hooks };
|
|
116
149
|
const intent = { ...records };
|
|
117
150
|
const operations = [];
|
|
118
151
|
const baselines = [];
|
|
119
152
|
const warnings = [];
|
|
153
|
+
const verify = [...new Set([...enable, ...retain])];
|
|
154
|
+
for (const engine of retain) {
|
|
155
|
+
for (const rel of [targets[engine], alternate[engine]].filter(Boolean)) {
|
|
156
|
+
baselines.push({ rel, baseline: snapshot(root, rel).baseline });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
120
159
|
for (const [engines, enabling] of [[enable, true], [disable, false]]) {
|
|
121
160
|
for (const engine of engines) {
|
|
122
161
|
if (!Object.hasOwn(targets, engine)) throw new Error(`Unsupported recovery hook engine: ${engine}`);
|
|
@@ -135,11 +174,15 @@ export function planRecoveryHooks(root, state, { enable = [], disable = [] }) {
|
|
|
135
174
|
const previous = records[engine];
|
|
136
175
|
const op = planTarget(root, engine, enabling, previous, warnings);
|
|
137
176
|
baselines.push(op);
|
|
138
|
-
if (op.changed)
|
|
177
|
+
if (op.changed) {
|
|
178
|
+
operations.push({ ...op, enabling });
|
|
179
|
+
if (!enabling && engine === 'omp') warnings.push('Removing the OMP extension removes reversa_session_identity.');
|
|
180
|
+
}
|
|
139
181
|
if (op.record) {
|
|
140
|
-
if (enabling &&
|
|
141
|
-
|
|
142
|
-
: op.record;
|
|
182
|
+
if (enabling && op.changed) {
|
|
183
|
+
const { selector_version: _old, ...record } = previous ?? op.record;
|
|
184
|
+
intent[engine] = { ...record, pending: op.record.groups ?? {} };
|
|
185
|
+
}
|
|
143
186
|
records[engine] = op.record;
|
|
144
187
|
} else delete records[engine];
|
|
145
188
|
} catch (err) {
|
|
@@ -148,7 +191,7 @@ export function planRecoveryHooks(root, state, { enable = [], disable = [] }) {
|
|
|
148
191
|
}
|
|
149
192
|
}
|
|
150
193
|
}
|
|
151
|
-
return { operations, baselines, records, intent, warnings };
|
|
194
|
+
return { operations, baselines, records, intent, warnings, verify };
|
|
152
195
|
}
|
|
153
196
|
|
|
154
197
|
function save(root, state, records) {
|
|
@@ -166,8 +209,9 @@ export function verifyRecoveryHookPlan(root, plan) {
|
|
|
166
209
|
|
|
167
210
|
export function applyRecoveryHooks(root, plan, state) {
|
|
168
211
|
verifyRecoveryHookPlan(root, plan);
|
|
212
|
+
verifyRecoveryHookFiles(root, plan.verify);
|
|
169
213
|
const intentChanged = state && !isDeepStrictEqual(state.recovery_hooks ?? {}, plan.intent);
|
|
170
|
-
const
|
|
214
|
+
const previous = state?.recovery_hooks ?? {};
|
|
171
215
|
// Save new receipts before enabling. Keep the old receipts until removal completes.
|
|
172
216
|
if (intentChanged) save(root, state, plan.intent);
|
|
173
217
|
for (const { rel, next, baseline } of plan.operations) {
|
|
@@ -176,18 +220,32 @@ export function applyRecoveryHooks(root, plan, state) {
|
|
|
176
220
|
if (next === undefined) unlinkSync(path);
|
|
177
221
|
else replace(path, next);
|
|
178
222
|
}
|
|
223
|
+
for (const engine of plan.verify) {
|
|
224
|
+
const issue = recoveryRegistrationIssue(root, engine, plan.records[engine]);
|
|
225
|
+
if (issue) throw new Error(`Cannot certify ${engine} recovery: ${issue}.`);
|
|
226
|
+
const { pending: _pending, ...record } = plan.records[engine];
|
|
227
|
+
plan.records[engine] = { ...record, selector_version: 1 };
|
|
228
|
+
}
|
|
229
|
+
const recordsChanged = state && !isDeepStrictEqual(plan.intent, plan.records);
|
|
179
230
|
if (recordsChanged) save(root, state, plan.records);
|
|
180
|
-
return Boolean(plan.operations.length || intentChanged || recordsChanged);
|
|
231
|
+
return Boolean(plan.operations.length || intentChanged || recordsChanged || !isDeepStrictEqual(previous, plan.records));
|
|
181
232
|
}
|
|
182
233
|
|
|
183
234
|
const handlerFiles = engines => engines.includes('omp') ? ['reanchor.mjs', 'reanchor-omp.mjs'] : ['reanchor.mjs'];
|
|
184
235
|
|
|
236
|
+
function expectedHandler(file) {
|
|
237
|
+
const content = readFileSync(new URL(`../../templates/hooks/${file}`, import.meta.url), 'utf8');
|
|
238
|
+
return file === 'reanchor.mjs' ? content.replace('{{REVERSA_VERSION}}', getPackageInfo().version) : content;
|
|
239
|
+
}
|
|
240
|
+
|
|
185
241
|
export function verifyRecoveryHookFiles(root, engines, writes = []) {
|
|
186
242
|
if (!engines.length) return;
|
|
187
243
|
for (const file of handlerFiles(engines)) {
|
|
188
244
|
const rel = `${hooksDir}/${file}`;
|
|
189
|
-
|
|
190
|
-
|
|
245
|
+
const expected = expectedHandler(file);
|
|
246
|
+
const kind = pathState(root, rel);
|
|
247
|
+
if (kind === 'file' && readFileSync(join(root, rel), 'utf8') === expected) continue;
|
|
248
|
+
if (!writes.some(write => write.rel === rel && write.content === expected && matchesBaseline(root, rel, write.baseline))) {
|
|
191
249
|
throw new Error(`Required recovery handler is unavailable: ${rel}.`);
|
|
192
250
|
}
|
|
193
251
|
}
|
|
@@ -195,13 +253,18 @@ export function verifyRecoveryHookFiles(root, engines, writes = []) {
|
|
|
195
253
|
|
|
196
254
|
export function recoveryRegistrationIssue(root, engine, record) {
|
|
197
255
|
try {
|
|
256
|
+
const extra = alternate[engine];
|
|
257
|
+
if (extra && mentionsRecovery(snapshot(root, extra).text ?? '')) return 'alternate recovery registration';
|
|
198
258
|
const { text } = snapshot(root, targets[engine]);
|
|
199
259
|
if (text === undefined) return 'registration missing';
|
|
200
260
|
if (engine === 'omp') return text === ompSource ? null : 'registration changed';
|
|
201
261
|
const data = config(text, targets[engine]);
|
|
202
262
|
const desired = registration(root, engine);
|
|
203
|
-
const configured = Object.entries(desired).every(([event, group]) => record
|
|
204
|
-
&& Array.isArray(data.hooks?.[event]) && data.hooks[event].
|
|
263
|
+
const configured = Object.entries(desired).every(([event, group]) => record?.groups?.[event] === fingerprint(group)
|
|
264
|
+
&& Array.isArray(data.hooks?.[event]) && data.hooks[event].filter(matchesRecovery).length === 1
|
|
265
|
+
&& data.hooks[event].some(item => isDeepStrictEqual(item, group)))
|
|
266
|
+
&& !Object.entries(data.hooks ?? {}).some(([event, list]) =>
|
|
267
|
+
!Object.hasOwn(desired, event) && (Array.isArray(list) ? list.some(matchesRecovery) : mentionsRecovery(json(list))));
|
|
205
268
|
return configured ? null : 'registration changed';
|
|
206
269
|
} catch (err) {
|
|
207
270
|
return `registration unreadable (${err.message})`;
|
|
@@ -209,12 +272,26 @@ export function recoveryRegistrationIssue(root, engine, record) {
|
|
|
209
272
|
}
|
|
210
273
|
|
|
211
274
|
export function recoveryStatus(root, state, engine) {
|
|
275
|
+
const { mode } = readRecoverySelector(engine);
|
|
276
|
+
const suffix = engine === 'omp' && mode === 'global' ? 'global selected, no global OMP runner proven'
|
|
277
|
+
: mode === 'invalid' ? 'invalid selector; migration pending' : `mode ${mode}`;
|
|
212
278
|
const record = state.recovery_hooks?.[engine];
|
|
213
|
-
if (!record)
|
|
279
|
+
if (!record) {
|
|
280
|
+
const known = [targets[engine], alternate[engine]].filter(Boolean);
|
|
281
|
+
try {
|
|
282
|
+
if (known.some(rel => mentionsRecovery(snapshot(root, rel).text ?? ''))) return `manual registration; ${suffix}`;
|
|
283
|
+
} catch {
|
|
284
|
+
return `unreadable registration; ${suffix}`;
|
|
285
|
+
}
|
|
286
|
+
return `off; ${suffix}`;
|
|
287
|
+
}
|
|
214
288
|
const issue = recoveryRegistrationIssue(root, engine, record);
|
|
215
|
-
if (issue) return issue;
|
|
216
|
-
|
|
217
|
-
return
|
|
289
|
+
if (issue) return `${issue}; ${suffix}`;
|
|
290
|
+
try { verifyRecoveryHookFiles(root, [engine]); }
|
|
291
|
+
catch { return `handler missing or changed (run update); migration pending; ${suffix}`; }
|
|
292
|
+
const trust = engine === 'codex' ? ' (review trust in Codex /hooks)' : '';
|
|
293
|
+
const proof = record.pending ? 'repair pending' : record.selector_version === 1 ? 'selector compatible' : 'migration pending';
|
|
294
|
+
return `configured${trust}; ${proof}; ${suffix}`;
|
|
218
295
|
}
|
|
219
296
|
|
|
220
297
|
export const recoveryLocalNotice = 'Recovery registrations are local. Do not commit generated hook entries or the OMP recovery extension.';
|
package/lib/installer/writer.js
CHANGED
|
@@ -72,7 +72,8 @@ export class Writer {
|
|
|
72
72
|
|
|
73
73
|
// Reads a bundled template in the installation language.
|
|
74
74
|
_template(rel) {
|
|
75
|
-
|
|
75
|
+
const content = readFileSync(localizedPath('templates', rel, this.lang), 'utf8');
|
|
76
|
+
return rel === 'hooks/reanchor.mjs' ? content.replace('{{REVERSA_VERSION}}', getPackageInfo().version) : content;
|
|
76
77
|
}
|
|
77
78
|
|
|
78
79
|
// Normalises an absolute path to project-relative
|
|
@@ -403,7 +404,10 @@ export class Writer {
|
|
|
403
404
|
// userConfig: a file the user is meant to edit (hooks.yml); an edited copy always stays.
|
|
404
405
|
_planContent(plan, rel, content, index, { userConfig = false } = {}) {
|
|
405
406
|
const decision = classifyTarget(this.projectRoot, rel, index, hashContent(content));
|
|
406
|
-
if (decision.action === 'write')
|
|
407
|
+
if (decision.action === 'write') {
|
|
408
|
+
const baseline = decision.reason === 'refresh' ? index.get(rel).hash : undefined;
|
|
409
|
+
plan.writes.push({ rel, reason: decision.reason, content, baseline });
|
|
410
|
+
}
|
|
407
411
|
else if (decision.action !== 'keep') return;
|
|
408
412
|
else if (userConfig || this.keepEdits || !['untracked', 'modified'].includes(decision.reason)) plan.kept.push({ rel, reason: decision.reason });
|
|
409
413
|
else {
|
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { anchorFor, recoveryWarning } from './reanchor.mjs';
|
|
1
|
+
import { anchorFor, readRecoverySelector, recoveryWarning } from './reanchor.mjs';
|
|
2
2
|
|
|
3
3
|
const identity = ctx => ctx.agent.kind === 'main'
|
|
4
4
|
? { harness: 'omp', session: ctx.sessionManager.getSessionId() }
|
|
@@ -37,7 +37,7 @@ export function registerRecovery(pi, readVersion) {
|
|
|
37
37
|
pi.on('session_stop', observe);
|
|
38
38
|
// Older engines expose only agent_end. Do not request a continuation there.
|
|
39
39
|
pi.on('agent_end', async (event, ctx) => {
|
|
40
|
-
if (!identity(ctx)) return;
|
|
40
|
+
if (!identity(ctx) || readRecoverySelector('omp').mode !== 'standalone') return;
|
|
41
41
|
legacy ??= Promise.resolve().then(readVersion).then(version => {
|
|
42
42
|
const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version ?? '');
|
|
43
43
|
if (!match) return false;
|
|
@@ -1,8 +1,36 @@
|
|
|
1
1
|
import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readSync, realpathSync } from 'node:fs';
|
|
2
|
-
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
2
|
+
import { basename, dirname, isAbsolute, join, parse, sep } from 'node:path';
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
|
|
5
5
|
const LIMIT = 256 * 1024;
|
|
6
|
+
const bundledVersion = '{{REVERSA_VERSION}}';
|
|
7
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
8
|
+
const decode = bytes => decoder.decode(bytes).replace(/^\uFEFF+/, '');
|
|
9
|
+
|
|
10
|
+
function parseDocument(bytes, integers = []) {
|
|
11
|
+
const text = decode(bytes);
|
|
12
|
+
const value = JSON.parse(text);
|
|
13
|
+
const keys = [];
|
|
14
|
+
const numericTokens = {};
|
|
15
|
+
let rootKey;
|
|
16
|
+
// JSON.parse validates syntax; retain key identity and top-level number spelling.
|
|
17
|
+
for (const [token, key, colon] of text.matchAll(/("(?:\\[\s\S]|[^"\\])*")(\s*:)?|[{}\[\]]|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g)) {
|
|
18
|
+
if (colon) {
|
|
19
|
+
const name = JSON.parse(key);
|
|
20
|
+
const scope = keys.at(-1);
|
|
21
|
+
if (scope.has(name)) throw new SyntaxError('Duplicate JSON key');
|
|
22
|
+
scope.add(name);
|
|
23
|
+
rootKey = keys.length === 1 && integers.includes(name) ? name : undefined;
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
if (rootKey && typeof value[rootKey] === 'number') numericTokens[rootKey] = token;
|
|
27
|
+
rootKey = undefined;
|
|
28
|
+
if (token === '{') keys.push(new Set());
|
|
29
|
+
else if (token === '}') keys.pop();
|
|
30
|
+
}
|
|
31
|
+
return { value, numericTokens };
|
|
32
|
+
}
|
|
33
|
+
const unknown = reason => ({ kind: 'unknown', reason });
|
|
6
34
|
const HARNESS = new Set(['claude-code', 'codex', 'omp']);
|
|
7
35
|
const COMMAND_EVENTS = new Set(['SessionStart', 'UserPromptSubmit', 'Stop']);
|
|
8
36
|
const clean = value => typeof value === 'string' ? value.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, ' ').trim() : '';
|
|
@@ -12,13 +40,49 @@ function stat(path) {
|
|
|
12
40
|
catch (err) { if (err.code === 'ENOENT') return null; throw err; }
|
|
13
41
|
}
|
|
14
42
|
|
|
15
|
-
function
|
|
16
|
-
|
|
17
|
-
if (!
|
|
18
|
-
const
|
|
43
|
+
function parentChain(path) {
|
|
44
|
+
let current = parse(path).root;
|
|
45
|
+
if (!current) throw new Error('Path is not absolute');
|
|
46
|
+
const parts = dirname(path).slice(current.length).split(sep).filter(Boolean);
|
|
47
|
+
return parts.map(part => {
|
|
48
|
+
if (part === '.' || part === '..') throw new Error('Unsafe path');
|
|
49
|
+
current = join(current, part);
|
|
50
|
+
if (process.platform === 'win32') {
|
|
51
|
+
const entry = lstatSync(current);
|
|
52
|
+
if (!entry.isDirectory()) throw new Error('Unsafe directory');
|
|
53
|
+
return entry;
|
|
54
|
+
}
|
|
55
|
+
const descriptor = openSync(current, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
56
|
+
try {
|
|
57
|
+
const entry = fstatSync(descriptor);
|
|
58
|
+
if (!entry.isDirectory() || !sameFile(entry, lstatSync(current))) throw new Error('Unsafe directory');
|
|
59
|
+
return entry;
|
|
60
|
+
} finally { closeSync(descriptor); }
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
|
|
65
|
+
const unchanged = (a, b) => sameFile(a, b) && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs && a.size === b.size;
|
|
66
|
+
|
|
67
|
+
function readBounded(path, limit = LIMIT, ownerConfig = false) {
|
|
68
|
+
const chain = parentChain(path);
|
|
69
|
+
const file = lstatSync(path);
|
|
70
|
+
if (!file.isFile() || file.size > limit) throw new Error('Unsafe file');
|
|
71
|
+
let fd;
|
|
72
|
+
try { fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)); }
|
|
73
|
+
catch (err) { throw new Error('File changed before open', { cause: err }); }
|
|
19
74
|
try {
|
|
20
75
|
const opened = fstatSync(fd);
|
|
21
|
-
if (!opened.isFile() || opened
|
|
76
|
+
if (!opened.isFile() || !unchanged(file, opened)) throw new Error('File changed');
|
|
77
|
+
const before = parentChain(path);
|
|
78
|
+
if (chain.length !== before.length || chain.some((entry, i) => !sameFile(entry, before[i]))) throw new Error('Directory changed');
|
|
79
|
+
if (ownerConfig) {
|
|
80
|
+
const parent = chain.at(-1);
|
|
81
|
+
const uid = process.geteuid?.();
|
|
82
|
+
if (uid === undefined || opened.uid !== uid || opened.mode & 0o077 || parent?.uid !== uid || parent.mode & 0o022) {
|
|
83
|
+
throw new Error('Unsafe selector permissions');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
22
86
|
const buffer = Buffer.allocUnsafe(opened.size + 1);
|
|
23
87
|
let offset = 0;
|
|
24
88
|
while (offset < buffer.length) {
|
|
@@ -26,78 +90,117 @@ function readBounded(path) {
|
|
|
26
90
|
if (!count) break;
|
|
27
91
|
offset += count;
|
|
28
92
|
}
|
|
29
|
-
|
|
93
|
+
const after = parentChain(path);
|
|
94
|
+
if (offset !== opened.size || !unchanged(opened, fstatSync(fd)) || !unchanged(file, lstatSync(path))
|
|
95
|
+
|| chain.length !== after.length || chain.some((entry, i) => !sameFile(entry, after[i]))) throw new Error('File changed');
|
|
96
|
+
return buffer.subarray(0, offset);
|
|
97
|
+
} catch (err) {
|
|
98
|
+
throw new Error('Could not establish stable file bytes', { cause: err });
|
|
30
99
|
} finally { closeSync(fd); }
|
|
31
100
|
}
|
|
32
101
|
|
|
33
|
-
function
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
102
|
+
export function readRecoverySelector(harness, env = process.env) {
|
|
103
|
+
const key = harness === 'claude-code' ? 'claude' : harness;
|
|
104
|
+
const config = env.XDG_CONFIG_HOME || (env.HOME && `${env.HOME}/.config`);
|
|
105
|
+
if (!config || !isAbsolute(config) || config.split(sep).includes('..')) {
|
|
106
|
+
return { mode: 'invalid', reason: 'selector-home' };
|
|
107
|
+
}
|
|
108
|
+
const path = join(config, 'agents', 'work-state.json');
|
|
109
|
+
try {
|
|
110
|
+
const bytes = readBounded(path, 4096, true);
|
|
111
|
+
const { value: doc, numericTokens: numbers } = parseDocument(bytes, ['schema_version', 'revision']);
|
|
112
|
+
if (numbers.schema_version !== '1' || doc.family !== 'work-state-recovery'
|
|
113
|
+
|| !/^[1-9]\d{0,19}$/.test(numbers.revision)
|
|
114
|
+
|| BigInt(numbers.revision) > 18446744073709551615n || !['observe', 'corrective'].includes(doc.stop_mode)
|
|
115
|
+
|| !['claude', 'codex', 'omp'].every(id => ['standalone', 'global', 'off'].includes(doc.owners?.[id]))) {
|
|
116
|
+
return { mode: 'invalid', reason: 'selector-invalid', path, bytes };
|
|
117
|
+
}
|
|
118
|
+
return { mode: doc.owners[key], path, bytes };
|
|
119
|
+
} catch (err) {
|
|
120
|
+
if (err.code === 'ENOENT') return { mode: 'standalone', path };
|
|
121
|
+
return { mode: 'invalid', reason: 'selector-unreadable', path };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function probeRecovery(cwd, { harness, session } = {}) {
|
|
126
|
+
if (typeof cwd !== 'string' || !isAbsolute(cwd) || !HARNESS.has(harness) || typeof session !== 'string' || !session) return unknown('identity-unavailable');
|
|
127
|
+
try {
|
|
128
|
+
let root = realpathSync(cwd);
|
|
129
|
+
for (;;) {
|
|
130
|
+
const directory = join(root, '.reversa');
|
|
131
|
+
const dir = stat(directory);
|
|
132
|
+
if (dir && !dir.isDirectory()) return unknown('checkpoint-unavailable');
|
|
133
|
+
const path = join(directory, 'state.json');
|
|
134
|
+
if (dir && stat(path)) {
|
|
135
|
+
const bytes = readBounded(path);
|
|
136
|
+
const { value: state, numericTokens } = parseDocument(bytes, ['schema_version', 'delegation-format']);
|
|
137
|
+
const active = state?.active;
|
|
138
|
+
if (active == null) return { kind: 'absent' };
|
|
139
|
+
if (typeof state.version !== 'string' || (state.version !== bundledVersion && !/^1\.13\.\d+$/.test(state.version)
|
|
140
|
+
&& !['1.14.0', '1.15.0'].includes(state.version))) return unknown('unsupported-reversa-version');
|
|
141
|
+
if ((Object.hasOwn(state, 'schema_version') && numericTokens.schema_version !== '1')
|
|
142
|
+
|| (Object.hasOwn(state, 'delegation-format') && numericTokens['delegation-format'] !== '2')
|
|
143
|
+
|| !Array.isArray(active.delegations) || typeof active.owner?.generation !== 'string') return unknown('unsupported-reversa-schema');
|
|
144
|
+
if (active.owner.harness !== harness || active.owner.session !== session) return { kind: 'foreign' };
|
|
145
|
+
return { kind: 'owned', snapshot: { root, directory, path, bytes, active } };
|
|
146
|
+
}
|
|
147
|
+
const parent = dirname(root);
|
|
148
|
+
if (parent === root) return { kind: 'absent' };
|
|
149
|
+
root = parent;
|
|
45
150
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
root = parent;
|
|
151
|
+
} catch {
|
|
152
|
+
return unknown('checkpoint-unavailable');
|
|
49
153
|
}
|
|
50
154
|
}
|
|
51
155
|
|
|
52
|
-
function
|
|
156
|
+
export function verifyRecovery({ root, directory, path, bytes, active }, expired = () => false) {
|
|
53
157
|
try {
|
|
54
|
-
if (
|
|
55
|
-
|
|
56
|
-
|
|
158
|
+
if (expired() || !readBounded(path).equals(bytes)) return unknown('checkpoint-unavailable');
|
|
159
|
+
if (active.delegations.length || active.flow !== 'forward' || active.agent !== 'reversa-coding'
|
|
160
|
+
|| active.status !== 'working') return { kind: 'pass' };
|
|
161
|
+
const match = /^(T\d{3,12})(?![a-zA-Z0-9_])(?: \[([^\]]+)\])?/.exec(clean(active.step));
|
|
162
|
+
if (!match) return unknown('action-unavailable');
|
|
57
163
|
const [, action, feature] = match;
|
|
58
164
|
const requirements = join(directory, 'active-requirements.json');
|
|
59
165
|
const source = readBounded(requirements);
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
for (const part of folder.split('/')) {
|
|
65
|
-
if (!part || part === '.' || part === '..') return null;
|
|
66
|
-
parent = join(parent, part);
|
|
67
|
-
if (!stat(parent)?.isDirectory()) return null;
|
|
68
|
-
}
|
|
69
|
-
const actions = join(parent, 'actions.md');
|
|
166
|
+
const folder = parseDocument(source).value?.['feature-dir'];
|
|
167
|
+
if (typeof folder !== 'string' || /[\\:\p{Cc}]/u.test(folder) || (feature && feature !== folder)
|
|
168
|
+
|| folder.split('/').some(part => !part || part === '.' || part === '..')) return unknown('feature-unavailable');
|
|
169
|
+
const actions = join(root, folder, 'actions.md');
|
|
70
170
|
const table = readBounded(actions);
|
|
71
|
-
if (table === null) return null;
|
|
72
171
|
const row = new RegExp(`^\\s*\\|\\s*${action}\\s*\\|`);
|
|
73
172
|
let status;
|
|
74
|
-
for (const line of table.split('\n')) {
|
|
173
|
+
for (const line of decode(table).split('\n')) {
|
|
75
174
|
if (!row.test(line)) continue;
|
|
76
|
-
if (status !== undefined) return
|
|
175
|
+
if (status !== undefined) return unknown('action-ambiguous');
|
|
77
176
|
status = /\|\s*(?:`\[([Xx ])\]`|\[([Xx ])\])\s*\|\s*$/.exec(line)?.slice(1).find(value => value !== undefined) ?? null;
|
|
78
177
|
}
|
|
79
|
-
if (!status
|
|
80
|
-
if (
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
178
|
+
if (!status) return unknown('action-ambiguous');
|
|
179
|
+
if (expired() || !readBounded(requirements).equals(source) || !readBounded(actions).equals(table)
|
|
180
|
+
|| !readBounded(path).equals(bytes) || expired()) return unknown('checkpoint-raced');
|
|
181
|
+
return status === ' ' ? { kind: 'pass' }
|
|
182
|
+
: { kind: 'contradiction', reason: 'stale-reversa-action', evidence: `${folder}/actions.md#${action}`, action };
|
|
183
|
+
} catch {
|
|
184
|
+
return unknown('checkpoint-unavailable');
|
|
85
185
|
}
|
|
86
186
|
}
|
|
87
187
|
|
|
188
|
+
function renderWarning(verdict) {
|
|
189
|
+
return verdict.kind === 'contradiction'
|
|
190
|
+
? `Checkpoint atrasado: ${verdict.action} consta como concluída em actions.md. Confira os artefatos e salve a posição pelo helper.`
|
|
191
|
+
: null;
|
|
192
|
+
}
|
|
193
|
+
|
|
88
194
|
export function recoveryWarning(cwd, identity) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
} catch (err) {
|
|
93
|
-
if (err instanceof SyntaxError || err instanceof TypeError || err.code) return null;
|
|
94
|
-
throw err;
|
|
95
|
-
}
|
|
195
|
+
if (readRecoverySelector(identity?.harness).mode !== 'standalone') return null;
|
|
196
|
+
const probe = probeRecovery(cwd, identity);
|
|
197
|
+
return probe.kind === 'owned' ? renderWarning(verifyRecovery(probe.snapshot)) : null;
|
|
96
198
|
}
|
|
97
199
|
|
|
98
200
|
export function anchorFor(cwd, identity) {
|
|
99
201
|
try {
|
|
100
|
-
|
|
202
|
+
if (readRecoverySelector(identity?.harness).mode !== 'standalone') return null;
|
|
203
|
+
const { snapshot } = probeRecovery(cwd, identity);
|
|
101
204
|
if (!snapshot) return null;
|
|
102
205
|
const { active } = snapshot;
|
|
103
206
|
const flow = clean(active.flow);
|
|
@@ -107,13 +210,14 @@ export function anchorFor(cwd, identity) {
|
|
|
107
210
|
const { step_index: index, step_total: total } = active;
|
|
108
211
|
const count = Number.isSafeInteger(index) && Number.isSafeInteger(total) && index > 0 && index <= total ? ` (${index}/${total})` : '';
|
|
109
212
|
const status = active.status === 'waiting_user' ? ' · aguardando sua resposta' : '';
|
|
110
|
-
const
|
|
213
|
+
const verdict = verifyRecovery(snapshot);
|
|
214
|
+
if (verdict.reason === 'checkpoint-raced' || !readBounded(snapshot.path).equals(snapshot.bytes)) return null;
|
|
215
|
+
const warning = renderWarning(verdict);
|
|
111
216
|
const hint = ' — Releia o estado, o gate e o SKILL.md instalado antes de agir.' + (warning ? ` ${warning}` : '');
|
|
112
217
|
const prefix = Array.from(`🧭 Reversa › ${flow} › ${agent} › ${step}`);
|
|
113
218
|
return prefix.slice(0, 600 - Array.from(count + status + hint).length).join('') + count + status + hint;
|
|
114
|
-
} catch
|
|
115
|
-
|
|
116
|
-
throw err;
|
|
219
|
+
} catch {
|
|
220
|
+
return null;
|
|
117
221
|
}
|
|
118
222
|
}
|
|
119
223
|
|