wrxn-reversa 1.14.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 +22 -0
- package/lib/commands/hooks.js +11 -8
- package/lib/commands/install.js +20 -7
- package/lib/commands/uninstall.js +1 -1
- package/lib/commands/update.js +100 -5
- package/lib/installer/prompts.js +9 -4
- package/lib/installer/recovery-hooks.js +151 -40
- package/lib/installer/writer.js +6 -2
- package/locales/en/templates/hooks/README.md +3 -0
- package/package.json +1 -1
- package/templates/hooks/README.md +3 -0
- package/templates/hooks/reanchor-omp.mjs +2 -2
- package/templates/hooks/reanchor.mjs +161 -57
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
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
|
+
|
|
18
|
+
## 1.15.0
|
|
19
|
+
|
|
20
|
+
- Update now offers recovery-hook choices for each installed engine that supports them.
|
|
21
|
+
The default keeps the current selection.
|
|
22
|
+
- Enable, disable, or repair Reversa-managed recovery hooks during update without a separate command.
|
|
23
|
+
Existing manual registrations stay under user control.
|
|
24
|
+
|
|
3
25
|
## 1.14.0
|
|
4
26
|
|
|
5
27
|
### Changes
|
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 } 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,15 +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
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
const selection = verb === 'enable' ? recoverySelection(selected) : null;
|
|
28
|
+
if (selection) {
|
|
29
|
+
verifyRecoveryEnable(selection);
|
|
30
|
+
verifyRecoveryHookFiles(root, selected);
|
|
31
31
|
}
|
|
32
|
-
const plan = planRecoveryHooks(root, state,
|
|
33
|
-
const applied = await applyWhenIdle(root, snapshot, chalk, () => applyRecoveryHooks(root, plan, state));
|
|
34
|
-
if (!applied) { process.exitCode = 1; return; }
|
|
32
|
+
const plan = planRecoveryHooks(root, state, { [verb]: selected });
|
|
35
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; }
|
|
36
39
|
if (verb === 'enable') console.log(recoveryLocalNotice);
|
|
37
40
|
show({ ...state, recovery_hooks: plan.records });
|
|
38
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
|
|
|
@@ -33,7 +33,7 @@ export default async function uninstall() {
|
|
|
33
33
|
const preview = idlePreview(projectRoot, chalk);
|
|
34
34
|
if (!preview) return;
|
|
35
35
|
const { state } = existing;
|
|
36
|
-
const recovery = planRecoveryHooks(projectRoot, state, recoveryEngines
|
|
36
|
+
const recovery = planRecoveryHooks(projectRoot, state, { disable: recoveryEngines });
|
|
37
37
|
for (const warning of recovery.warnings) console.log(chalk.yellow(` ${warning}`));
|
|
38
38
|
for (const { rel } of recovery.operations) console.log(` Remove Reversa recovery registration from ${rel}`);
|
|
39
39
|
// The hub keeps its registry entry until the owner removes it there.
|
package/lib/commands/update.js
CHANGED
|
@@ -6,7 +6,7 @@ import { hashFile, loadManifest, saveManifest, indexManifest, isUnder } from '..
|
|
|
6
6
|
import { isSafeRel, matchesBaseline, pathState } from '../installer/reconcile.js';
|
|
7
7
|
import { Writer } from '../installer/writer.js';
|
|
8
8
|
import { ENGINES, entryTargets } from '../installer/detector.js';
|
|
9
|
-
import { listAllAgents } from '../installer/prompts.js';
|
|
9
|
+
import { listAllAgents, recoveryHookChoices } from '../installer/prompts.js';
|
|
10
10
|
import { renderImpeccableNotice, IMPECCABLE_AGENT_ID, installedImpeccableVersion, resolveImpeccablePolicy } from '../installer/bundled.js';
|
|
11
11
|
import { planImpeccableAgents } from '../installer/impeccable-agents.js';
|
|
12
12
|
import { applyOrangeTheme, ORANGE_PREFIX } from '../installer/orange-prompts.js';
|
|
@@ -17,6 +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, hasRecoveryRegistration, planRecoveryHooks, recoveryEngines, recoveryLocalNotice, recoveryRegistrationIssue, recoverySelection, verifyRecoveryHookFiles, verifyRecoveryHookPlan, verifyRecoverySelection } from '../installer/recovery-hooks.js';
|
|
20
21
|
|
|
21
22
|
async function fetchLatestVersion(packageName) {
|
|
22
23
|
try {
|
|
@@ -32,6 +33,63 @@ async function fetchLatestVersion(packageName) {
|
|
|
32
33
|
const STATE = '.reversa/state.json';
|
|
33
34
|
const MANIFEST = '.reversa/_config/files-manifest.json';
|
|
34
35
|
|
|
36
|
+
async function chooseRecoveryHooks(root, state, engines, inquirer, writes, selection) {
|
|
37
|
+
const choices = recoveryHookChoices(engines.filter(({ id }) => selection[id]?.mode === 'standalone'), state.recovery_hooks);
|
|
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([], []);
|
|
57
|
+
const repairs = new Map();
|
|
58
|
+
for (const choice of choices.slice()) {
|
|
59
|
+
if (!choice.checked) continue;
|
|
60
|
+
const issue = recoveryRegistrationIssue(root, choice.value, state.recovery_hooks[choice.value]);
|
|
61
|
+
if (!issue) continue;
|
|
62
|
+
const repair = `repair:${choice.value}`;
|
|
63
|
+
repairs.set(repair, choice.value);
|
|
64
|
+
choices.push({ name: `Repair ${choice.name} (${issue})`, value: repair });
|
|
65
|
+
}
|
|
66
|
+
let recovery;
|
|
67
|
+
await inquirer.prompt([{
|
|
68
|
+
prefix: ORANGE_PREFIX,
|
|
69
|
+
type: 'checkbox',
|
|
70
|
+
name: 'recovery_hooks',
|
|
71
|
+
message: '\nWhich engines should use Reversa-managed recovery hooks? Keep the current selection to leave hooks unchanged.',
|
|
72
|
+
choices,
|
|
73
|
+
loop: false,
|
|
74
|
+
validate(selected) {
|
|
75
|
+
const enable = selected.filter(id => !current.includes(id) && !repairs.has(id));
|
|
76
|
+
const disable = current.filter(id => !selected.includes(id));
|
|
77
|
+
for (const [repair, id] of repairs) {
|
|
78
|
+
if (!selected.includes(repair)) continue;
|
|
79
|
+
if (disable.includes(id)) return 'Keep the engine selected to repair its hooks, or clear both choices to disable them.';
|
|
80
|
+
enable.push(id);
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
recovery = build(enable, disable);
|
|
84
|
+
return true;
|
|
85
|
+
} catch (err) {
|
|
86
|
+
return `${err.message} Adjust the selection to continue the update.`;
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
}]);
|
|
90
|
+
return recovery;
|
|
91
|
+
}
|
|
92
|
+
|
|
35
93
|
function validateUpdateOptions(args) {
|
|
36
94
|
const seen = new Set();
|
|
37
95
|
for (let i = 0; i < args.length; i++) {
|
|
@@ -170,6 +228,21 @@ async function runUpdate(args, beginApply) {
|
|
|
170
228
|
const label = choice === 'skip' ? 'skipped' : keepImpeccable ? 'pinned' : 'bundled';
|
|
171
229
|
if (keepImpeccable) console.log(` Impeccable: ${label} (${impeccableBefore ? `v${impeccableBefore} retained` : 'no recorded version'})`);
|
|
172
230
|
|
|
231
|
+
const inquirer = interactive ? (await import('inquirer')).default : null;
|
|
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
|
+
}
|
|
242
|
+
const recovery = interactive && role !== SATELLITE
|
|
243
|
+
? await chooseRecoveryHooks(projectRoot, state, installedEngines, inquirer, plan.writes, selection)
|
|
244
|
+
: null;
|
|
245
|
+
|
|
173
246
|
const LABELS = { restore: 'Restore', new: 'Add', migrate: 'Migrate', refresh: 'Refresh', replace: 'Replace' };
|
|
174
247
|
for (const { rel, reason } of plan.kept) {
|
|
175
248
|
if (targetPaths.has(rel) && reason === 'already current') continue;
|
|
@@ -183,10 +256,19 @@ async function runUpdate(args, beginApply) {
|
|
|
183
256
|
if (policyChanges) console.log(` Change Impeccable policy from ${previousPolicy} to ${choice} in ${STATE}.`);
|
|
184
257
|
console.log(` ${plan.writes.length + records.writes.length + Number(policyChanges)} file(s) to write; ${plan.removals.length} to remove.`);
|
|
185
258
|
previewMirrors(mirrors);
|
|
259
|
+
if (recovery) {
|
|
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
|
+
}
|
|
266
|
+
for (const { rel, enabling } of recovery.plan.operations) {
|
|
267
|
+
console.log(` ${enabling ? 'Enable' : 'Disable'} Reversa recovery hooks in ${rel}`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
186
270
|
if (!interactive) return { reason: 'confirmation requires an interactive terminal. Run the update again and answer the prompts.' };
|
|
187
271
|
|
|
188
|
-
const { default: inquirer } = await import('inquirer');
|
|
189
|
-
applyOrangeTheme();
|
|
190
272
|
const { confirm } = await inquirer.prompt([{
|
|
191
273
|
prefix: ORANGE_PREFIX,
|
|
192
274
|
type: 'confirm',
|
|
@@ -219,6 +301,11 @@ async function runUpdate(args, beginApply) {
|
|
|
219
301
|
outcome = { reason: 'Impeccable changed since preview; run the update again.' };
|
|
220
302
|
return;
|
|
221
303
|
}
|
|
304
|
+
verifyRecoverySelection(selection);
|
|
305
|
+
if (recovery) {
|
|
306
|
+
verifyRecoveryHookFiles(projectRoot, recovery.plan.verify, plan.writes);
|
|
307
|
+
verifyRecoveryHookPlan(projectRoot, recovery.plan);
|
|
308
|
+
}
|
|
222
309
|
|
|
223
310
|
beginApply(writer);
|
|
224
311
|
const applied = writer.applyPlan(plan, index);
|
|
@@ -269,13 +356,21 @@ async function runUpdate(args, beginApply) {
|
|
|
269
356
|
if (archive) console.log(` ${writer.replaced} replaced file(s) were saved in ${archive}. Use --keep-edits to keep local versions.`);
|
|
270
357
|
else if (writer.backupDir) console.log(` Backup copies remain in ${writer.backupDir}; no archive was written.`);
|
|
271
358
|
else if (writer.replaced > 0) console.log(` ${writer.replaced} file(s) replaced without a backup.`);
|
|
359
|
+
let hookChanged = false;
|
|
360
|
+
if (!failed && recovery) {
|
|
361
|
+
verifyRecoverySelection(selection);
|
|
362
|
+
hookChanged = applyRecoveryHooks(projectRoot, recovery.plan, state);
|
|
363
|
+
if (hookChanged) console.log(' Recovery hook settings updated. Restart the affected engines.');
|
|
364
|
+
if (recovery.enable.length) console.log(` ${recoveryLocalNotice}`);
|
|
365
|
+
if (recovery.enable.includes('codex')) console.log(' Review and trust the exact hook definitions in Codex /hooks.');
|
|
366
|
+
}
|
|
272
367
|
const fileChanges = applied.written.length + applied.removed.length + counts.linked + counts.copied + refreshed
|
|
273
368
|
+ recordsWritten + Number(manifestChanged);
|
|
274
369
|
if (failed) outcome = { reason: 'resolve the files that could not be applied above.',
|
|
275
370
|
incomplete: fileChanges > 0 || stateChanged, backupPath: archive ?? writer.backupDir };
|
|
276
|
-
else if (!fileChanges && !stateChanged) outcome = { reason: 'no changes were needed under the selected update policy.' };
|
|
371
|
+
else if (!fileChanges && !stateChanged && !hookChanged) outcome = { reason: 'no changes were needed under the selected update policy.' };
|
|
277
372
|
else {
|
|
278
|
-
const policyOnly = !fileChanges && previousPolicy !== choice
|
|
373
|
+
const policyOnly = !fileChanges && !hookChanged && previousPolicy !== choice
|
|
279
374
|
&& JSON.stringify({ ...previousState, impeccable_policy: undefined }) === JSON.stringify({ ...state, impeccable_policy: undefined });
|
|
280
375
|
outcome = { from: installedVersion, to: version, policyOnly, previousPolicy, policy: choice };
|
|
281
376
|
}
|
package/lib/installer/prompts.js
CHANGED
|
@@ -155,9 +155,14 @@ const promptTitle = (number, message, suffix = 'none') => {
|
|
|
155
155
|
return `\n${number}. ${message}${tail}`;
|
|
156
156
|
};
|
|
157
157
|
|
|
158
|
+
export function recoveryHookChoices(engines, current = {}) {
|
|
159
|
+
return engines.filter(({ id }) => recoveryEngines.includes(id))
|
|
160
|
+
.map(({ id, name }) => ({ name, value: id, checked: Object.hasOwn(current, id) }));
|
|
161
|
+
}
|
|
162
|
+
|
|
158
163
|
// skillsLanguage: language already decided (--lang or an existing installation); skips the question.
|
|
159
164
|
// role: repository role already decided (--role); skips the question.
|
|
160
|
-
export async function runInstallPrompts(detectedEngines, { skillsLanguage, role } = {}) {
|
|
165
|
+
export async function runInstallPrompts(detectedEngines, { skillsLanguage, role, recoveryEligible = recoveryEngines } = {}) {
|
|
161
166
|
const engineChoices = detectedEngines.map(e => ({
|
|
162
167
|
name: `${e.name}${e.star ? ' (recommended)' : ''}`,
|
|
163
168
|
value: e.id,
|
|
@@ -267,9 +272,9 @@ export async function runInstallPrompts(detectedEngines, { skillsLanguage, role
|
|
|
267
272
|
type: 'checkbox',
|
|
268
273
|
name: 'recovery_hooks',
|
|
269
274
|
message: promptTitle(11, 'Enable project recovery hooks? Leave all unchecked to keep them off.', 'checkbox'),
|
|
270
|
-
when: answers => isStandalone(answers) &&
|
|
271
|
-
choices: answers => detectedEngines.filter(engine =>
|
|
272
|
-
.
|
|
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))),
|
|
273
278
|
},
|
|
274
279
|
]);
|
|
275
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.`);
|
|
@@ -56,6 +89,11 @@ function planTarget(root, engine, enable, prior, warnings) {
|
|
|
56
89
|
if (prior || mentionsRecovery(text)) cleanup(warnings, rel);
|
|
57
90
|
return op;
|
|
58
91
|
}
|
|
92
|
+
if (text !== undefined && !prior) {
|
|
93
|
+
if (enable) throw new Error(`${rel} is already registered outside Reversa management.`);
|
|
94
|
+
cleanup(warnings, rel);
|
|
95
|
+
return op;
|
|
96
|
+
}
|
|
59
97
|
return { ...op, changed: enable !== (text !== undefined), next: enable ? ompSource : undefined, record: enable ? { created: true } : undefined };
|
|
60
98
|
}
|
|
61
99
|
if (!enable && text === undefined) return { ...op, record: undefined };
|
|
@@ -76,7 +114,7 @@ function planTarget(root, engine, enable, prior, warnings) {
|
|
|
76
114
|
const digest = group && fingerprint(group);
|
|
77
115
|
const index = list.findIndex(item => {
|
|
78
116
|
const candidate = fingerprint(item);
|
|
79
|
-
return candidate ===
|
|
117
|
+
return candidate === previous || candidate === prior?.pending?.[event];
|
|
80
118
|
});
|
|
81
119
|
const other = list.some((item, i) => i !== index && matchesRecovery(item));
|
|
82
120
|
if (other) {
|
|
@@ -106,38 +144,54 @@ function planTarget(root, engine, enable, prior, warnings) {
|
|
|
106
144
|
return op;
|
|
107
145
|
}
|
|
108
146
|
|
|
109
|
-
export function planRecoveryHooks(root, state,
|
|
147
|
+
export function planRecoveryHooks(root, state, { enable = [], disable = [], retain = [] }) {
|
|
110
148
|
const records = { ...state.recovery_hooks };
|
|
111
149
|
const intent = { ...records };
|
|
112
150
|
const operations = [];
|
|
151
|
+
const baselines = [];
|
|
113
152
|
const warnings = [];
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const
|
|
117
|
-
|
|
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
|
+
}
|
|
159
|
+
for (const [engines, enabling] of [[enable, true], [disable, false]]) {
|
|
160
|
+
for (const engine of engines) {
|
|
161
|
+
if (!Object.hasOwn(targets, engine)) throw new Error(`Unsupported recovery hook engine: ${engine}`);
|
|
162
|
+
const extra = alternate[engine];
|
|
163
|
+
if (extra) {
|
|
164
|
+
try {
|
|
165
|
+
const info = snapshot(root, extra);
|
|
166
|
+
if (mentionsRecovery(info.text ?? '')) throw new Error('Existing Reversa recovery hook.');
|
|
167
|
+
if (enabling) baselines.push({ rel: extra, baseline: info.baseline });
|
|
168
|
+
} catch (err) {
|
|
169
|
+
if (enabling) throw new Error(`Cannot verify ${extra}: ${err.message} Check for a duplicate Reversa recovery registration.`);
|
|
170
|
+
cleanup(warnings, extra);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
118
173
|
try {
|
|
119
|
-
|
|
174
|
+
const previous = records[engine];
|
|
175
|
+
const op = planTarget(root, engine, enabling, previous, warnings);
|
|
176
|
+
baselines.push(op);
|
|
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
|
+
}
|
|
181
|
+
if (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
|
+
}
|
|
186
|
+
records[engine] = op.record;
|
|
187
|
+
} else delete records[engine];
|
|
120
188
|
} catch (err) {
|
|
121
|
-
if (
|
|
122
|
-
cleanup(warnings,
|
|
189
|
+
if (enabling) throw err;
|
|
190
|
+
cleanup(warnings, targets[engine]);
|
|
123
191
|
}
|
|
124
192
|
}
|
|
125
|
-
try {
|
|
126
|
-
const op = planTarget(root, engine, enable, records[engine], warnings);
|
|
127
|
-
if (op.changed) operations.push(op);
|
|
128
|
-
if (op.record) {
|
|
129
|
-
const previous = records[engine];
|
|
130
|
-
if (enable) intent[engine] = previous
|
|
131
|
-
? { ...op.record, groups: previous.groups, pending: op.record.groups }
|
|
132
|
-
: op.record;
|
|
133
|
-
records[engine] = op.record;
|
|
134
|
-
} else delete records[engine];
|
|
135
|
-
} catch (err) {
|
|
136
|
-
if (enable) throw err;
|
|
137
|
-
cleanup(warnings, targets[engine]);
|
|
138
|
-
}
|
|
139
193
|
}
|
|
140
|
-
return { operations, records, intent, warnings,
|
|
194
|
+
return { operations, baselines, records, intent, warnings, verify };
|
|
141
195
|
}
|
|
142
196
|
|
|
143
197
|
function save(root, state, records) {
|
|
@@ -147,40 +201,97 @@ function save(root, state, records) {
|
|
|
147
201
|
replace(safePath(root, statePath), json(updated));
|
|
148
202
|
}
|
|
149
203
|
|
|
150
|
-
export function
|
|
151
|
-
for (const { rel, baseline } of plan.
|
|
204
|
+
export function verifyRecoveryHookPlan(root, plan) {
|
|
205
|
+
for (const { rel, baseline } of plan.baselines) {
|
|
152
206
|
if (!matchesBaseline(root, rel, baseline)) throw new Error(`Cannot manage ${rel}: changed since preview.`);
|
|
153
207
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function applyRecoveryHooks(root, plan, state) {
|
|
211
|
+
verifyRecoveryHookPlan(root, plan);
|
|
212
|
+
verifyRecoveryHookFiles(root, plan.verify);
|
|
213
|
+
const intentChanged = state && !isDeepStrictEqual(state.recovery_hooks ?? {}, plan.intent);
|
|
214
|
+
const previous = state?.recovery_hooks ?? {};
|
|
215
|
+
// Save new receipts before enabling. Keep the old receipts until removal completes.
|
|
216
|
+
if (intentChanged) save(root, state, plan.intent);
|
|
158
217
|
for (const { rel, next, baseline } of plan.operations) {
|
|
159
218
|
if (!matchesBaseline(root, rel, baseline)) throw new Error(`Cannot manage ${rel}: changed since preview.`);
|
|
160
219
|
const path = safePath(root, rel, { createParents: next !== undefined });
|
|
161
220
|
if (next === undefined) unlinkSync(path);
|
|
162
221
|
else replace(path, next);
|
|
163
222
|
}
|
|
164
|
-
|
|
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);
|
|
230
|
+
if (recordsChanged) save(root, state, plan.records);
|
|
231
|
+
return Boolean(plan.operations.length || intentChanged || recordsChanged || !isDeepStrictEqual(previous, plan.records));
|
|
165
232
|
}
|
|
166
233
|
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
234
|
+
const handlerFiles = engines => engines.includes('omp') ? ['reanchor.mjs', 'reanchor-omp.mjs'] : ['reanchor.mjs'];
|
|
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
|
+
|
|
241
|
+
export function verifyRecoveryHookFiles(root, engines, writes = []) {
|
|
242
|
+
if (!engines.length) return;
|
|
243
|
+
for (const file of handlerFiles(engines)) {
|
|
244
|
+
const rel = `${hooksDir}/${file}`;
|
|
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))) {
|
|
249
|
+
throw new Error(`Required recovery handler is unavailable: ${rel}.`);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function recoveryRegistrationIssue(root, engine, record) {
|
|
170
255
|
try {
|
|
256
|
+
const extra = alternate[engine];
|
|
257
|
+
if (extra && mentionsRecovery(snapshot(root, extra).text ?? '')) return 'alternate recovery registration';
|
|
171
258
|
const { text } = snapshot(root, targets[engine]);
|
|
172
259
|
if (text === undefined) return 'registration missing';
|
|
173
|
-
|
|
174
|
-
if (names.some(name => pathState(root, `${hooksDir}/${name}`) !== 'file')) return 'handler missing (run update)';
|
|
175
|
-
if (engine === 'omp') return text === ompSource ? 'configured' : 'registration changed';
|
|
260
|
+
if (engine === 'omp') return text === ompSource ? null : 'registration changed';
|
|
176
261
|
const data = config(text, targets[engine]);
|
|
177
262
|
const desired = registration(root, engine);
|
|
178
|
-
|
|
179
|
-
&& Array.isArray(data.hooks?.[event]) && data.hooks[event].
|
|
180
|
-
|
|
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))));
|
|
268
|
+
return configured ? null : 'registration changed';
|
|
181
269
|
} catch (err) {
|
|
182
270
|
return `registration unreadable (${err.message})`;
|
|
183
271
|
}
|
|
184
272
|
}
|
|
185
273
|
|
|
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}`;
|
|
278
|
+
const record = state.recovery_hooks?.[engine];
|
|
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
|
+
}
|
|
288
|
+
const issue = recoveryRegistrationIssue(root, engine, record);
|
|
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}`;
|
|
295
|
+
}
|
|
296
|
+
|
|
186
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 {
|
|
@@ -46,6 +46,9 @@ Remove the block above from `.claude/settings.json`. The file `.reversa/hooks/ch
|
|
|
46
46
|
## Recovery and verification (optional)
|
|
47
47
|
|
|
48
48
|
Installation offers recovery hooks by engine and leaves them off by default.
|
|
49
|
+
Update offers the same choice and keeps the current selection by default.
|
|
50
|
+
Clear an engine to remove only the recovery registrations that Reversa created.
|
|
51
|
+
If the menu shows an incomplete registration, keep the engine selected and also select its repair option.
|
|
49
52
|
To enable hooks later, run `npx wrxn-reversa hooks enable --engine=claude-code` from the project root.
|
|
50
53
|
Use `codex` or `omp` for the other supported engines.
|
|
51
54
|
Use `hooks status` to see the configuration and `hooks disable --engine=<id>` to remove only the entries that Reversa created.
|
package/package.json
CHANGED
|
@@ -46,6 +46,9 @@ Remova o bloco acima do `.claude/settings.json`. O arquivo `.reversa/hooks/check
|
|
|
46
46
|
## Retomada e verificação (opcional)
|
|
47
47
|
|
|
48
48
|
A instalação oferece hooks por motor e os deixa desligados por padrão.
|
|
49
|
+
A atualização oferece a mesma escolha e mantém a seleção atual por padrão.
|
|
50
|
+
Desmarque um motor para remover apenas os registros de retomada que o Reversa criou.
|
|
51
|
+
Se o menu mostrar um registro incompleto, mantenha o motor marcado e selecione também a opção de reparo.
|
|
49
52
|
Para ativar depois, rode `npx wrxn-reversa hooks enable --engine=claude-code` na raiz do projeto.
|
|
50
53
|
Use `codex` ou `omp` para os outros motores compatíveis.
|
|
51
54
|
Use `hooks status` para ver a configuração e `hooks disable --engine=<id>` para remover só os registros que o Reversa criou.
|
|
@@ -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
|
|