wrxn-reversa 1.13.1 → 1.14.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 +11 -0
- package/agents/reversa-coding/SKILL.md +3 -0
- package/bin/reversa.js +3 -0
- package/lib/commands/hooks.js +38 -0
- package/lib/commands/install.js +21 -0
- package/lib/commands/uninstall.js +7 -1
- package/lib/installer/prompts.js +10 -0
- package/lib/installer/recovery-hooks.js +186 -0
- package/locales/en/agents/reversa-coding/SKILL.md +3 -0
- package/locales/en/templates/hooks/README.md +19 -51
- package/package.json +1 -1
- package/templates/hooks/README.md +19 -51
- package/templates/hooks/reanchor-omp.mjs +26 -1
- package/templates/hooks/reanchor.mjs +84 -25
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.14.0
|
|
4
|
+
|
|
5
|
+
### Changes
|
|
6
|
+
|
|
7
|
+
- Fresh standalone installations offer optional recovery hooks for Claude Code, Codex, and OMP.
|
|
8
|
+
The hooks are off by default, and updates preserve existing registrations.
|
|
9
|
+
- From a standalone project root, use `wrxn-reversa hooks enable`, `hooks disable`, or `hooks status`.
|
|
10
|
+
Add `--engine=claude-code`, `--engine=codex`, or `--engine=omp` to target one engine.
|
|
11
|
+
- Recovery warns when `actions.md` already marks the owner session's current action complete.
|
|
12
|
+
The warning does not block the turn, start another turn, or rewrite the saved checkpoint.
|
|
13
|
+
|
|
3
14
|
## 1.13.1
|
|
4
15
|
|
|
5
16
|
### Packaging
|
|
@@ -116,6 +116,9 @@ Para cada fase, na ordem Preparação, Testes, Núcleo, Integração, Polimento:
|
|
|
116
116
|
3. Para o conjunto independente, identifique sub-conjunto marcado `[//]`
|
|
117
117
|
3.1. Execute esse sub-conjunto pensando em cada ação como bloco coerente, mas relate à parte
|
|
118
118
|
4. Execute as demais ações do conjunto sequencialmente
|
|
119
|
+
Marque a posição inicial do bloco com `checkpoint` e use `T042 [<feature-dir>]` no começo de `step` para identificar a ação em andamento.
|
|
120
|
+
Não faça checkpoint com delegação de lista de arquivos em andamento, nem mude `step` antes de importar os artefatos dessa delegação.
|
|
121
|
+
Antes de pausar, salve o progresso verificado e atualize a posição para a próxima ação real ou para o gate que aguarda resposta.
|
|
119
122
|
4.1. Numa ação de teste (fase Testes, ou ação de teste que precede sua implementação), rode o teste novo: cada caso de comportamento novo ou alterado deve falhar pelo motivo esperado, e módulo ausente conta como esse motivo; um caso que protege comportamento preservado pode passar. Registre `status: red` no progress e marque `[X]`, porque isso não é falha da ação. Um caso de comportamento novo ou alterado que passa antes da implementação não para a fase: registre `status: unexpected-green` no progress, marque `[X]`, continue e cite o caso no relatório final. Um caso que falha por outro motivo é falha. Numa ação de implementação, rode os testes ligados a ela; um caso vermelho ali é falha da ação só quando falha por motivo que esta ação deveria resolver (um módulo que uma ação posterior cria não conta). Uma ação de teste com um caso `red` e outro `unexpected-green` escreve uma linha de progress para cada status.
|
|
120
123
|
5. Após cada ação:
|
|
121
124
|
5.1. Atualize `feature-dir/actions.md`, mudando `[ ]` para `[X]`, por edição direta da sessão dona depois de reler o arquivo, ou pelo helper `write`.
|
package/bin/reversa.js
CHANGED
|
@@ -18,6 +18,7 @@ const commands = {
|
|
|
18
18
|
'export-diagrams': () => import('../lib/commands/export-diagrams.js'),
|
|
19
19
|
role: () => import('../lib/commands/role.js'),
|
|
20
20
|
repo: () => import('../lib/commands/repo.js'),
|
|
21
|
+
hooks: () => import('../lib/commands/hooks.js'),
|
|
21
22
|
};
|
|
22
23
|
|
|
23
24
|
if (!command || command === '--help' || command === '-h') {
|
|
@@ -39,6 +40,8 @@ if (!command || command === '--help' || command === '-h') {
|
|
|
39
40
|
--impeccable=skip|<version>|bundled
|
|
40
41
|
mantém, fixa na versão já instalada ou usa a versão do pacote
|
|
41
42
|
status Mostra o estado atual da análise
|
|
43
|
+
hooks Ativa, desativa ou consulta os hooks de retomada do projeto
|
|
44
|
+
hooks <enable|disable|status> [--engine=claude-code|codex|omp]
|
|
42
45
|
uninstall Remove o Reversa do projeto
|
|
43
46
|
add-engine Adiciona suporte a uma engine
|
|
44
47
|
Opções: --keep-edits mantém arquivos de skill alterados localmente
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import chalk from 'chalk';
|
|
2
|
+
import { resolve } from 'path';
|
|
3
|
+
import { readCheckoutState } from '../../agents/reversa/scripts/session-state.mjs';
|
|
4
|
+
import { applyWhenIdle, idlePreview } from '../installer/checkout-guard.js';
|
|
5
|
+
import { applyRecoveryHooks, planRecoveryHooks, recoveryEngines, recoveryLocalNotice, recoveryStatus } from '../installer/recovery-hooks.js';
|
|
6
|
+
import { pathState } from '../installer/reconcile.js';
|
|
7
|
+
import { roleOf, SATELLITE } from '../installer/role.js';
|
|
8
|
+
|
|
9
|
+
export default async function hooks([verb, ...args]) {
|
|
10
|
+
const engine = args[0]?.startsWith('--engine=') ? args[0].slice(9) : undefined;
|
|
11
|
+
if (!['enable', 'disable', 'status'].includes(verb) || (args.length && (args.length !== 1 || !recoveryEngines.includes(engine)))) {
|
|
12
|
+
throw new Error('Usage: hooks <enable|disable|status> [--engine=claude-code|codex|omp]');
|
|
13
|
+
}
|
|
14
|
+
const root = resolve(process.cwd());
|
|
15
|
+
if (pathState(root, '.reversa/state.json') !== 'file') throw new Error('Reversa is not installed here.');
|
|
16
|
+
const snapshot = verb === 'status' ? readCheckoutState(root) : idlePreview(root, chalk);
|
|
17
|
+
if (!snapshot) { process.exitCode = 1; return; }
|
|
18
|
+
const { state } = snapshot;
|
|
19
|
+
const installed = recoveryEngines.filter(id => state.engines?.includes(id));
|
|
20
|
+
const selected = engine ? [engine] : installed;
|
|
21
|
+
if (verb === 'enable' && (roleOf(state) === SATELLITE || selected.some(id => !installed.includes(id)))) {
|
|
22
|
+
throw new Error('Recovery hooks require a standalone installation and an installed engine.');
|
|
23
|
+
}
|
|
24
|
+
if (!selected.length) throw new Error('No supported recovery hook engine is installed.');
|
|
25
|
+
const show = data => selected.forEach(id => console.log(`${id}: ${recoveryStatus(root, data, id)}`));
|
|
26
|
+
if (verb === 'status') { show(state); return; }
|
|
27
|
+
if (verb === 'enable') {
|
|
28
|
+
for (const file of ['reanchor.mjs', 'reanchor-omp.mjs']) {
|
|
29
|
+
if (pathState(root, `.reversa/hooks/${file}`) !== 'file') throw new Error(`Missing recovery handler ${file}. Run update first.`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const plan = planRecoveryHooks(root, state, selected, verb === 'enable');
|
|
33
|
+
const applied = await applyWhenIdle(root, snapshot, chalk, () => applyRecoveryHooks(root, plan, state));
|
|
34
|
+
if (!applied) { process.exitCode = 1; return; }
|
|
35
|
+
for (const warning of plan.warnings) console.log(chalk.yellow(warning));
|
|
36
|
+
if (verb === 'enable') console.log(recoveryLocalNotice);
|
|
37
|
+
show({ ...state, recovery_hooks: plan.records });
|
|
38
|
+
}
|
package/lib/commands/install.js
CHANGED
|
@@ -13,6 +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
17
|
import { applyMirrors, describeSkillLayout, planMirrors, previewMirrors, recordChanges, resolveSkillLayout, resolveSkillsMode, verifySkillLayout } from '../installer/skill-layout.js';
|
|
17
18
|
|
|
18
19
|
export default async function install(args = []) {
|
|
@@ -71,6 +72,8 @@ export default async function install(args = []) {
|
|
|
71
72
|
}
|
|
72
73
|
|
|
73
74
|
const selectedEngines = ENGINES.filter(e => answers.engines.includes(e.id));
|
|
75
|
+
const recovery = answers.role === SATELLITE ? [] : (answers.recovery_hooks ?? []);
|
|
76
|
+
if (recovery.length) planRecoveryHooks(projectRoot, preview.state, recovery, true);
|
|
74
77
|
const manifest = {};
|
|
75
78
|
const index = indexManifest(manifest);
|
|
76
79
|
const layout = resolveSkillLayout(projectRoot, selectedEngines);
|
|
@@ -164,6 +167,24 @@ export default async function install(args = []) {
|
|
|
164
167
|
}
|
|
165
168
|
}
|
|
166
169
|
|
|
170
|
+
// Activate only after an optional restore, with a fresh idle checkout snapshot.
|
|
171
|
+
if (recovery.length) {
|
|
172
|
+
const hookPreview = idlePreview(projectRoot, chalk);
|
|
173
|
+
if (!hookPreview || !await applyWhenIdle(projectRoot, hookPreview, chalk, () => {
|
|
174
|
+
const plan = planRecoveryHooks(projectRoot, hookPreview.state, recovery, true);
|
|
175
|
+
applyRecoveryHooks(projectRoot, plan, hookPreview.state);
|
|
176
|
+
})) {
|
|
177
|
+
process.exitCode = 1;
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
console.log(' Recovery hooks configured. Restart the selected engines.');
|
|
181
|
+
console.log(` ${recoveryLocalNotice}`);
|
|
182
|
+
console.log(' Keep these project-local files out of Git, or stage unrelated edits separately.');
|
|
183
|
+
if (recovery.includes('codex')) console.log(' Review and trust the exact hook definitions in Codex /hooks.');
|
|
184
|
+
} else if (answers.role !== SATELLITE) {
|
|
185
|
+
console.log(` Recovery hooks are off. To enable them later, run npx ${getPackageInfo().name} hooks enable.`);
|
|
186
|
+
}
|
|
187
|
+
|
|
167
188
|
// Resumo
|
|
168
189
|
const engineNames = selectedEngines.map(e => e.name).join(', ');
|
|
169
190
|
const migrationInstalled = answers.agents.filter(a => MIGRATION_AGENT_IDS.includes(a));
|
|
@@ -9,6 +9,7 @@ import { applyWhenIdle, idlePreview } from '../installer/checkout-guard.js';
|
|
|
9
9
|
import { listAllAgents } from '../installer/prompts.js';
|
|
10
10
|
import { CANONICAL_SKILLS_DIR, ownedMirror, skillRoots } from '../installer/skill-layout.js';
|
|
11
11
|
import { UNINSTALL_BACKUPS, backupStamp, compressBackup } from '../installer/backup.js';
|
|
12
|
+
import { applyRecoveryHooks, planRecoveryHooks, recoveryEngines } from '../installer/recovery-hooks.js';
|
|
12
13
|
|
|
13
14
|
const STATE = '.reversa/state.json';
|
|
14
15
|
const MANIFEST = '.reversa/_config/files-manifest.json';
|
|
@@ -32,6 +33,9 @@ export default async function uninstall() {
|
|
|
32
33
|
const preview = idlePreview(projectRoot, chalk);
|
|
33
34
|
if (!preview) return;
|
|
34
35
|
const { state } = existing;
|
|
36
|
+
const recovery = planRecoveryHooks(projectRoot, state, recoveryEngines, false);
|
|
37
|
+
for (const warning of recovery.warnings) console.log(chalk.yellow(` ${warning}`));
|
|
38
|
+
for (const { rel } of recovery.operations) console.log(` Remove Reversa recovery registration from ${rel}`);
|
|
35
39
|
// The hub keeps its registry entry until the owner removes it there.
|
|
36
40
|
const coordinator = state.coordinator;
|
|
37
41
|
if (state.role === 'satellite' && coordinator?.path) {
|
|
@@ -201,7 +205,9 @@ export default async function uninstall() {
|
|
|
201
205
|
};
|
|
202
206
|
|
|
203
207
|
await applyWhenIdle(projectRoot, preview, chalk, async () => {
|
|
204
|
-
|
|
208
|
+
// Remove exact registrations first; ambiguous files were reported in the preview.
|
|
209
|
+
applyRecoveryHooks(projectRoot, recovery);
|
|
210
|
+
let removed = recovery.operations.length;
|
|
205
211
|
let errors = 0;
|
|
206
212
|
for (const { rel, hash, next } of blocks) {
|
|
207
213
|
try {
|
package/lib/installer/prompts.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import inquirer from 'inquirer';
|
|
2
|
+
import { recoveryEngines } from './recovery-hooks.js';
|
|
2
3
|
import { readdirSync } from 'fs';
|
|
3
4
|
import { join, resolve, dirname } from 'path';
|
|
4
5
|
import { fileURLToPath } from 'url';
|
|
@@ -261,6 +262,15 @@ export async function runInstallPrompts(detectedEngines, { skillsLanguage, role
|
|
|
261
262
|
{ name: 'In the questions.md file (more organized)', value: 'file' },
|
|
262
263
|
],
|
|
263
264
|
},
|
|
265
|
+
{
|
|
266
|
+
...P,
|
|
267
|
+
type: 'checkbox',
|
|
268
|
+
name: 'recovery_hooks',
|
|
269
|
+
message: promptTitle(11, 'Enable project recovery hooks? Leave all unchecked to keep them off.', 'checkbox'),
|
|
270
|
+
when: answers => isStandalone(answers) && recoveryEngines.some(id => answers.engines.includes(id)),
|
|
271
|
+
choices: answers => detectedEngines.filter(engine => recoveryEngines.includes(engine.id) && answers.engines.includes(engine.id))
|
|
272
|
+
.map(({ id, name }) => ({ name, value: id })),
|
|
273
|
+
},
|
|
264
274
|
]);
|
|
265
275
|
|
|
266
276
|
// Todos os agentes são sempre instalados, sem seleção
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { readFileSync, unlinkSync } from 'fs';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import { isDeepStrictEqual } from 'util';
|
|
4
|
+
import { hashContent } from './manifest.js';
|
|
5
|
+
import { matchesBaseline, pathState } from './reconcile.js';
|
|
6
|
+
import { json, object, replace, safePath } from '../../agents/reversa/scripts/lib/safe-fs.mjs';
|
|
7
|
+
|
|
8
|
+
const targets = { 'claude-code': '.claude/settings.local.json', codex: '.codex/hooks.json', omp: '.omp/extensions/reversa-recovery.js' };
|
|
9
|
+
const alternate = { 'claude-code': '.claude/settings.json', codex: '.codex/config.toml' };
|
|
10
|
+
export const recoveryEngines = Object.keys(targets);
|
|
11
|
+
const hooksDir = '.reversa/hooks';
|
|
12
|
+
const ompSource = `export { default } from '../../${hooksDir}/reanchor-omp.mjs';\n`;
|
|
13
|
+
const statePath = '.reversa/state.json';
|
|
14
|
+
const fingerprint = value => hashContent(json(value));
|
|
15
|
+
const mentionsRecovery = text => /\.reversa[\\/]+hooks[\\/]+reanchor(?:-omp)?\.mjs/.test(text);
|
|
16
|
+
|
|
17
|
+
function registration(root, engine) {
|
|
18
|
+
const script = join(root, hooksDir, 'reanchor.mjs');
|
|
19
|
+
if (process.platform === 'win32' && /["%!$`\r\n]/.test(script)) throw new Error('Cannot quote the recovery handler in this Windows path.');
|
|
20
|
+
const quoted = process.platform === 'win32' ? `"${script}"` : `'${script.replaceAll("'", "'\\''")}'`;
|
|
21
|
+
const handler = { type: 'command', command: `node ${quoted} ${engine}`, timeout: 2, statusMessage: 'Reversa recovery' };
|
|
22
|
+
return { SessionStart: { matcher: 'compact|resume', hooks: [handler] },
|
|
23
|
+
UserPromptSubmit: { hooks: [handler] }, Stop: { hooks: [handler] } };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function snapshot(root, rel) {
|
|
27
|
+
const kind = pathState(root, rel);
|
|
28
|
+
if (kind === 'missing') return {};
|
|
29
|
+
if (kind !== 'file') throw new Error(`${rel} is not a regular file.`);
|
|
30
|
+
const text = readFileSync(join(root, rel), 'utf8');
|
|
31
|
+
return { text, baseline: hashContent(text) };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function config(text, rel) {
|
|
35
|
+
const data = text === undefined ? {} : JSON.parse(text.replace(/^\uFEFF/, ''));
|
|
36
|
+
if (!object(data) || ('hooks' in data && !object(data.hooks))) throw new Error(`${rel} has an invalid hooks object.`);
|
|
37
|
+
return data;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function cleanup(warnings, rel, event) {
|
|
41
|
+
warnings.push(`Keep ${rel}${event ? ` (${event})` : ''}. Review and remove any Reversa recovery entries manually.`);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function matchesRecovery(group) {
|
|
45
|
+
return Array.isArray(group?.hooks) && group.hooks.some(item => item?.statusMessage === 'Reversa recovery'
|
|
46
|
+
|| (typeof item?.command === 'string' && mentionsRecovery(item.command)));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function planTarget(root, engine, enable, prior, warnings) {
|
|
50
|
+
const rel = targets[engine];
|
|
51
|
+
const { text, baseline } = snapshot(root, rel);
|
|
52
|
+
const op = { rel, baseline, next: text, changed: false, record: prior };
|
|
53
|
+
if (engine === 'omp') {
|
|
54
|
+
if (text !== undefined && text !== ompSource) {
|
|
55
|
+
if (enable) throw new Error(`${rel} is not an unmodified Reversa extension.`);
|
|
56
|
+
if (prior || mentionsRecovery(text)) cleanup(warnings, rel);
|
|
57
|
+
return op;
|
|
58
|
+
}
|
|
59
|
+
return { ...op, changed: enable !== (text !== undefined), next: enable ? ompSource : undefined, record: enable ? { created: true } : undefined };
|
|
60
|
+
}
|
|
61
|
+
if (!enable && text === undefined) return { ...op, record: undefined };
|
|
62
|
+
const data = config(text, rel);
|
|
63
|
+
const hadHooks = Object.hasOwn(data, 'hooks');
|
|
64
|
+
const hooks = data.hooks ??= {};
|
|
65
|
+
const owned = { ...prior?.pending, ...prior?.groups };
|
|
66
|
+
const desired = enable ? registration(root, engine) : {};
|
|
67
|
+
for (const event of new Set([...Object.keys(hooks), ...Object.keys(owned), ...Object.keys(desired)])) {
|
|
68
|
+
const list = hooks[event] ?? [];
|
|
69
|
+
const group = desired[event];
|
|
70
|
+
const previous = owned[event];
|
|
71
|
+
if (!Array.isArray(list)) {
|
|
72
|
+
if (group) throw new Error(`${rel} has an invalid ${event} list.`);
|
|
73
|
+
if (previous || mentionsRecovery(json(list))) cleanup(warnings, rel, event);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const digest = group && fingerprint(group);
|
|
77
|
+
const index = list.findIndex(item => {
|
|
78
|
+
const candidate = fingerprint(item);
|
|
79
|
+
return candidate === (previous ?? digest) || candidate === prior?.pending?.[event] || (enable && candidate === digest);
|
|
80
|
+
});
|
|
81
|
+
const other = list.some((item, i) => i !== index && matchesRecovery(item));
|
|
82
|
+
if (other) {
|
|
83
|
+
if (enable) throw new Error(`${rel} already has another Reversa recovery hook for ${event}. Remove the duplicate manually first.`);
|
|
84
|
+
cleanup(warnings, rel, event);
|
|
85
|
+
}
|
|
86
|
+
if (enable) {
|
|
87
|
+
if (!group) continue;
|
|
88
|
+
if (index < 0) { hooks[event] = [...list, group]; op.changed = true; }
|
|
89
|
+
else if (!isDeepStrictEqual(list[index], group)) {
|
|
90
|
+
hooks[event] = list.map((item, i) => i === index ? group : item);
|
|
91
|
+
op.changed = true;
|
|
92
|
+
}
|
|
93
|
+
owned[event] = digest;
|
|
94
|
+
} else {
|
|
95
|
+
if (index >= 0) {
|
|
96
|
+
hooks[event] = list.filter((_, i) => index !== i);
|
|
97
|
+
if (!hooks[event].length) delete hooks[event];
|
|
98
|
+
op.changed = true;
|
|
99
|
+
}
|
|
100
|
+
if (!other) delete owned[event];
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
if (!Object.keys(hooks).length && !prior?.hadHooks) delete data.hooks;
|
|
104
|
+
op.record = enable || Object.keys(owned).length ? { created: prior?.created ?? text === undefined, hadHooks: prior?.hadHooks ?? hadHooks, groups: owned } : undefined;
|
|
105
|
+
if (op.changed) op.next = !enable && prior?.created && Object.keys(data).length === 0 ? undefined : json(data);
|
|
106
|
+
return op;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function planRecoveryHooks(root, state, engines, enable) {
|
|
110
|
+
const records = { ...state.recovery_hooks };
|
|
111
|
+
const intent = { ...records };
|
|
112
|
+
const operations = [];
|
|
113
|
+
const warnings = [];
|
|
114
|
+
for (const engine of engines) {
|
|
115
|
+
if (!Object.hasOwn(targets, engine)) throw new Error(`Unsupported recovery hook engine: ${engine}`);
|
|
116
|
+
const extra = alternate[engine];
|
|
117
|
+
if (extra) {
|
|
118
|
+
try {
|
|
119
|
+
if (mentionsRecovery(snapshot(root, extra).text ?? '')) throw new Error('Existing Reversa recovery hook.');
|
|
120
|
+
} catch (err) {
|
|
121
|
+
if (enable) throw new Error(`Cannot verify ${extra}: ${err.message} Check for a duplicate Reversa recovery registration.`);
|
|
122
|
+
cleanup(warnings, extra);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
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
|
+
}
|
|
140
|
+
return { operations, records, intent, warnings, enable };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function save(root, state, records) {
|
|
144
|
+
const updated = { ...state };
|
|
145
|
+
if (Object.keys(records).length) updated.recovery_hooks = records;
|
|
146
|
+
else delete updated.recovery_hooks;
|
|
147
|
+
replace(safePath(root, statePath), json(updated));
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function applyRecoveryHooks(root, plan, state) {
|
|
151
|
+
for (const { rel, baseline } of plan.operations) {
|
|
152
|
+
if (!matchesBaseline(root, rel, baseline)) throw new Error(`Cannot manage ${rel}: changed since preview.`);
|
|
153
|
+
}
|
|
154
|
+
const recordChanged = state && !isDeepStrictEqual(state.recovery_hooks ?? {}, plan.records);
|
|
155
|
+
// Publish the enable receipt first; disable keeps the receipt until removal completes.
|
|
156
|
+
// If part of enable fails, an exact generated group can be re-adopted on retry.
|
|
157
|
+
if (recordChanged && plan.enable) save(root, state, plan.intent);
|
|
158
|
+
for (const { rel, next, baseline } of plan.operations) {
|
|
159
|
+
if (!matchesBaseline(root, rel, baseline)) throw new Error(`Cannot manage ${rel}: changed since preview.`);
|
|
160
|
+
const path = safePath(root, rel, { createParents: next !== undefined });
|
|
161
|
+
if (next === undefined) unlinkSync(path);
|
|
162
|
+
else replace(path, next);
|
|
163
|
+
}
|
|
164
|
+
if (recordChanged) save(root, state, plan.records);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function recoveryStatus(root, state, engine) {
|
|
168
|
+
const record = state.recovery_hooks?.[engine];
|
|
169
|
+
if (!record) return 'off';
|
|
170
|
+
try {
|
|
171
|
+
const { text } = snapshot(root, targets[engine]);
|
|
172
|
+
if (text === undefined) return 'registration missing';
|
|
173
|
+
const names = engine === 'omp' ? ['reanchor.mjs', 'reanchor-omp.mjs'] : ['reanchor.mjs'];
|
|
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';
|
|
176
|
+
const data = config(text, targets[engine]);
|
|
177
|
+
const desired = registration(root, engine);
|
|
178
|
+
return Object.entries(desired).every(([event, group]) => record.groups?.[event] === fingerprint(group)
|
|
179
|
+
&& Array.isArray(data.hooks?.[event]) && data.hooks[event].some(item => isDeepStrictEqual(item, group)))
|
|
180
|
+
? (engine === 'codex' ? 'configured (review trust in Codex /hooks)' : 'configured') : 'registration changed (run hooks enable)';
|
|
181
|
+
} catch (err) {
|
|
182
|
+
return `registration unreadable (${err.message})`;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export const recoveryLocalNotice = 'Recovery registrations are local. Do not commit generated hook entries or the OMP recovery extension.';
|
|
@@ -116,6 +116,9 @@ For each phase, in the order Setup, Tests, Core, Integration, Polish (`Preparaç
|
|
|
116
116
|
3. For the independent set, identify the subset marked `[//]`
|
|
117
117
|
3.1. Execute that subset treating each action as a coherent block, but report each one separately
|
|
118
118
|
4. Execute the remaining actions of the set sequentially
|
|
119
|
+
Record the initial work-block position with `checkpoint` and start `step` with `T042 [<feature-dir>]` to identify the current action.
|
|
120
|
+
Do not checkpoint during an in-flight file-list delegation, or change `step` before you import artifacts from that delegation.
|
|
121
|
+
Before a pause, save verified progress and update the position to the actual next action or the gate awaiting a reply.
|
|
119
122
|
4.1. In a test action (the Tests phase, or a test action that comes before its implementation), run the new test: each test case of new or changed behavior must fail for the expected reason, and a missing module counts as that reason; a test case that protects preserved behavior may pass. Record `status: red` in progress and mark `[X]`, because this is not a failure of the action. A test case of new or changed behavior that passes before the implementation does not stop the phase: record `status: unexpected-green` in progress, mark `[X]`, continue, and name the case in the final report. A test case that fails for another reason is a failure. In an implementation action, run the tests linked to it; a red case there is a failure of the action only when it fails for a reason that this action should resolve (a module that a later action creates does not count). A test action with one `red` case and one `unexpected-green` case writes one progress line for each status.
|
|
120
123
|
5. After each action:
|
|
121
124
|
5.1. Update `feature-dir/actions.md`, changing `[ ]` to `[X]`, with a direct edit by the owner session after it rereads the file, or through the `write` helper.
|
|
@@ -43,54 +43,22 @@ Requirement: Node.js 18+ available on the PATH (the same one the Reversa install
|
|
|
43
43
|
|
|
44
44
|
Remove the block above from `.claude/settings.json`. The file `.reversa/hooks/check-legacy-policy.mjs` can stay; it only acts when the settings file references it.
|
|
45
45
|
|
|
46
|
-
##
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
Use
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
"hooks": [{"type": "command", "command": "node \"/absolute/project/.reversa/hooks/reanchor.mjs\" claude-code", "timeout": 1}]
|
|
66
|
-
}],
|
|
67
|
-
"UserPromptSubmit": [{
|
|
68
|
-
"hooks": [{"type": "command", "command": "node \"/absolute/project/.reversa/hooks/reanchor.mjs\" claude-code", "timeout": 1}]
|
|
69
|
-
}]
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
### Codex
|
|
75
|
-
|
|
76
|
-
Add the same `hooks` entries to the trusted project's `.codex/hooks.json`.
|
|
77
|
-
Replace `claude-code` at the end of each command with `codex`.
|
|
78
|
-
Review the exact entries in Codex `/hooks` before granting trust.
|
|
79
|
-
Do not bypass the trust check.
|
|
80
|
-
|
|
81
|
-
### OMP
|
|
82
|
-
|
|
83
|
-
Opt in at launch:
|
|
84
|
-
|
|
85
|
-
```sh
|
|
86
|
-
omp --extension "/absolute/project/.reversa/hooks/reanchor-omp.mjs"
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
The extension supplies the native main-session identity and adds a position hint on the next applicable model request.
|
|
90
|
-
After compaction it queues context without requesting another turn.
|
|
91
|
-
|
|
92
|
-
### Disable recovery hooks
|
|
93
|
-
|
|
94
|
-
Remove only the added Claude Code or Codex hook entries and restart the session.
|
|
95
|
-
In OMP, omit the extension flag on the next launch.
|
|
96
|
-
Leave the saved checkpoints and installed handler files intact.
|
|
46
|
+
## Recovery and verification (optional)
|
|
47
|
+
|
|
48
|
+
Installation offers recovery hooks by engine and leaves them off by default.
|
|
49
|
+
To enable hooks later, run `npx wrxn-reversa hooks enable --engine=claude-code` from the project root.
|
|
50
|
+
Use `codex` or `omp` for the other supported engines.
|
|
51
|
+
Use `hooks status` to see the configuration and `hooks disable --engine=<id>` to remove only the entries that Reversa created.
|
|
52
|
+
Restart the engine after enabling or disabling hooks.
|
|
53
|
+
|
|
54
|
+
Generated registrations are local; do not add them to Git.
|
|
55
|
+
The installer uses `.claude/settings.local.json`, `.codex/hooks.json`, or `.omp/extensions/reversa-recovery.js`.
|
|
56
|
+
In Codex, review and trust the exact hooks in `/hooks` before use.
|
|
57
|
+
In OMP, open the project from its root to discover the local extension.
|
|
58
|
+
Do not use both the local extension and the manual `--extension` option for the same hook.
|
|
59
|
+
If a global runner already manages Reversa recovery, leave the project hooks off.
|
|
60
|
+
|
|
61
|
+
Recovery shows the owner session's position and warns if `actions.md` already marks its current action complete.
|
|
62
|
+
At the end of the turn, the hook warns without blocking or starting a new turn.
|
|
63
|
+
Hooks do not repair state, grant ownership, or replace human approval.
|
|
64
|
+
When hooks are off, follow manual recovery in `reversa/references/modo-de-execucao.md`.
|
package/package.json
CHANGED
|
@@ -43,54 +43,22 @@ Requisito: Node.js 18+ disponível no PATH (o mesmo exigido pelo instalador do R
|
|
|
43
43
|
|
|
44
44
|
Remova o bloco acima do `.claude/settings.json`. O arquivo `.reversa/hooks/check-legacy-policy.mjs` pode ficar, ele só age quando referenciado pelo settings.
|
|
45
45
|
|
|
46
|
-
##
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
Use
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
"hooks": [{"type": "command", "command": "node \"/absolute/project/.reversa/hooks/reanchor.mjs\" claude-code", "timeout": 1}]
|
|
66
|
-
}],
|
|
67
|
-
"UserPromptSubmit": [{
|
|
68
|
-
"hooks": [{"type": "command", "command": "node \"/absolute/project/.reversa/hooks/reanchor.mjs\" claude-code", "timeout": 1}]
|
|
69
|
-
}]
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
### Codex
|
|
75
|
-
|
|
76
|
-
Add the same `hooks` entries to the trusted project's `.codex/hooks.json`.
|
|
77
|
-
Replace `claude-code` at the end of each command with `codex`.
|
|
78
|
-
Review the exact entries in Codex `/hooks` before granting trust.
|
|
79
|
-
Do not bypass the trust check.
|
|
80
|
-
|
|
81
|
-
### OMP
|
|
82
|
-
|
|
83
|
-
Opt in at launch:
|
|
84
|
-
|
|
85
|
-
```sh
|
|
86
|
-
omp --extension "/absolute/project/.reversa/hooks/reanchor-omp.mjs"
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
The extension supplies the native main-session identity and adds a position hint on the next applicable model request.
|
|
90
|
-
After compaction it queues context without requesting another turn.
|
|
91
|
-
|
|
92
|
-
### Disable recovery hooks
|
|
93
|
-
|
|
94
|
-
Remove only the added Claude Code or Codex hook entries and restart the session.
|
|
95
|
-
In OMP, omit the extension flag on the next launch.
|
|
96
|
-
Leave the saved checkpoints and installed handler files intact.
|
|
46
|
+
## Retomada e verificação (opcional)
|
|
47
|
+
|
|
48
|
+
A instalação oferece hooks por motor e os deixa desligados por padrão.
|
|
49
|
+
Para ativar depois, rode `npx wrxn-reversa hooks enable --engine=claude-code` na raiz do projeto.
|
|
50
|
+
Use `codex` ou `omp` para os outros motores compatíveis.
|
|
51
|
+
Use `hooks status` para ver a configuração e `hooks disable --engine=<id>` para remover só os registros que o Reversa criou.
|
|
52
|
+
Reinicie o motor depois de ativar ou desativar.
|
|
53
|
+
|
|
54
|
+
As configurações geradas são locais; não as adicione ao Git.
|
|
55
|
+
O instalador usa `.claude/settings.local.json`, `.codex/hooks.json` ou `.omp/extensions/reversa-recovery.js`.
|
|
56
|
+
No Codex, revise e aprove os hooks exatos em `/hooks` antes de usar.
|
|
57
|
+
No OMP, abra o projeto pela raiz para descobrir a extensão local.
|
|
58
|
+
Não use ao mesmo tempo a extensão local e o parâmetro manual `--extension` para o mesmo hook.
|
|
59
|
+
Se um runner global já gerencia a retomada do Reversa, deixe os hooks do projeto desligados.
|
|
60
|
+
|
|
61
|
+
A retomada mostra a posição da sessão dona e avisa se sua ação em andamento já aparece concluída em `actions.md`.
|
|
62
|
+
No fim do turno, o hook avisa sem bloquear nem iniciar outro turno.
|
|
63
|
+
Os hooks não corrigem o estado, não concedem posse nem substituem uma aprovação humana.
|
|
64
|
+
Se estiverem desligados, siga a retomada manual em `reversa/references/modo-de-execucao.md`.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { anchorFor } from './reanchor.mjs';
|
|
1
|
+
import { anchorFor, recoveryWarning } from './reanchor.mjs';
|
|
2
2
|
|
|
3
3
|
const identity = ctx => ctx.agent.kind === 'main'
|
|
4
4
|
? { harness: 'omp', session: ctx.sessionManager.getSessionId() }
|
|
@@ -10,6 +10,11 @@ function anchor(ctx) {
|
|
|
10
10
|
}
|
|
11
11
|
|
|
12
12
|
export default function reanchor(pi) {
|
|
13
|
+
registerRecovery(pi, async () => (await import('@oh-my-pi/pi-coding-agent')).VERSION);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function registerRecovery(pi, readVersion) {
|
|
17
|
+
let legacy;
|
|
13
18
|
pi.on('before_agent_start', (event, ctx) => {
|
|
14
19
|
if (event.reason !== 'prompt') return;
|
|
15
20
|
const value = anchor(ctx);
|
|
@@ -22,6 +27,26 @@ export default function reanchor(pi) {
|
|
|
22
27
|
if (value) pi.sendMessage({ customType: 'reversa-position', content: value, display: false }, { deliverAs: 'nextTurn' });
|
|
23
28
|
});
|
|
24
29
|
|
|
30
|
+
function observe(event, ctx) {
|
|
31
|
+
const current = identity(ctx);
|
|
32
|
+
if (!current || event.stop_hook_active === true || (event.session_id && event.session_id !== current.session)) return;
|
|
33
|
+
const warning = recoveryWarning(ctx.cwd, current);
|
|
34
|
+
if (warning) ctx.ui?.notify(warning, 'warning');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
pi.on('session_stop', observe);
|
|
38
|
+
// Older engines expose only agent_end. Do not request a continuation there.
|
|
39
|
+
pi.on('agent_end', async (event, ctx) => {
|
|
40
|
+
if (!identity(ctx)) return;
|
|
41
|
+
legacy ??= Promise.resolve().then(readVersion).then(version => {
|
|
42
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version ?? '');
|
|
43
|
+
if (!match) return false;
|
|
44
|
+
const [, major, minor, patch] = match.map(Number);
|
|
45
|
+
return major < 19 || (major === 19 && (minor < 4 || (minor === 4 && patch < 1)));
|
|
46
|
+
}).catch(() => false);
|
|
47
|
+
if (await legacy) observe(event, ctx);
|
|
48
|
+
});
|
|
49
|
+
|
|
25
50
|
pi.registerTool({
|
|
26
51
|
name: 'reversa_session_identity',
|
|
27
52
|
label: 'Reversa session identity',
|
|
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
|
|
|
4
4
|
|
|
5
5
|
const LIMIT = 256 * 1024;
|
|
6
6
|
const HARNESS = new Set(['claude-code', 'codex', 'omp']);
|
|
7
|
-
const COMMAND_EVENTS = new Set(['SessionStart', 'UserPromptSubmit']);
|
|
7
|
+
const COMMAND_EVENTS = new Set(['SessionStart', 'UserPromptSubmit', 'Stop']);
|
|
8
8
|
const clean = value => typeof value === 'string' ? value.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, ' ').trim() : '';
|
|
9
9
|
|
|
10
10
|
function stat(path) {
|
|
@@ -12,30 +12,36 @@ function stat(path) {
|
|
|
12
12
|
catch (err) { if (err.code === 'ENOENT') return null; throw err; }
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
-
function
|
|
15
|
+
function readBounded(path) {
|
|
16
|
+
const file = stat(path);
|
|
17
|
+
if (!file?.isFile() || file.size > LIMIT) return null;
|
|
18
|
+
const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
19
|
+
try {
|
|
20
|
+
const opened = fstatSync(fd);
|
|
21
|
+
if (!opened.isFile() || opened.size > LIMIT) return null;
|
|
22
|
+
const buffer = Buffer.allocUnsafe(opened.size + 1);
|
|
23
|
+
let offset = 0;
|
|
24
|
+
while (offset < buffer.length) {
|
|
25
|
+
const count = readSync(fd, buffer, offset, buffer.length - offset, null);
|
|
26
|
+
if (!count) break;
|
|
27
|
+
offset += count;
|
|
28
|
+
}
|
|
29
|
+
return offset === opened.size ? buffer.toString('utf8', 0, offset).replace(/^\uFEFF/, '') : null;
|
|
30
|
+
} finally { closeSync(fd); }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function ownedSnapshot(cwd, { harness, session } = {}) {
|
|
34
|
+
if (typeof cwd !== 'string' || !isAbsolute(cwd) || !HARNESS.has(harness) || typeof session !== 'string' || !session) return null;
|
|
16
35
|
let root = realpathSync(cwd);
|
|
17
36
|
for (;;) {
|
|
18
37
|
const directory = join(root, '.reversa');
|
|
19
38
|
const dir = stat(directory);
|
|
20
39
|
if (dir && !dir.isDirectory()) return null;
|
|
21
40
|
const path = join(directory, 'state.json');
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
try {
|
|
27
|
-
const opened = fstatSync(fd);
|
|
28
|
-
if (!opened.isFile() || opened.size > LIMIT) return null;
|
|
29
|
-
const buffer = Buffer.allocUnsafe(opened.size + 1);
|
|
30
|
-
let offset = 0;
|
|
31
|
-
while (offset < buffer.length) {
|
|
32
|
-
const count = readSync(fd, buffer, offset, buffer.length - offset, null);
|
|
33
|
-
if (!count) break;
|
|
34
|
-
offset += count;
|
|
35
|
-
}
|
|
36
|
-
if (offset !== opened.size) return null;
|
|
37
|
-
return JSON.parse(buffer.toString('utf8', 0, offset).replace(/^\uFEFF/, '')).active;
|
|
38
|
-
} finally { closeSync(fd); }
|
|
41
|
+
if (dir && stat(path)) {
|
|
42
|
+
const bytes = readBounded(path);
|
|
43
|
+
const active = bytes === null ? null : JSON.parse(bytes)?.active;
|
|
44
|
+
return active?.owner?.harness === harness && active.owner.session === session ? { root, directory, path, bytes, active } : null;
|
|
39
45
|
}
|
|
40
46
|
const parent = dirname(root);
|
|
41
47
|
if (parent === root) return null;
|
|
@@ -43,11 +49,57 @@ function readActive(cwd) {
|
|
|
43
49
|
}
|
|
44
50
|
}
|
|
45
51
|
|
|
46
|
-
|
|
47
|
-
if (typeof cwd !== 'string' || !isAbsolute(cwd) || !HARNESS.has(harness) || typeof session !== 'string' || !session) return null;
|
|
52
|
+
function contradiction({ root, directory, path, bytes, active }) {
|
|
48
53
|
try {
|
|
49
|
-
|
|
50
|
-
|
|
54
|
+
if (active.flow !== 'forward' || active.agent !== 'reversa-coding' || active.status !== 'working') return null;
|
|
55
|
+
const match = /^(T\d{3,12})\b(?: \[([^\]]+)\])?/.exec(clean(active.step));
|
|
56
|
+
if (!match) return null;
|
|
57
|
+
const [, action, feature] = match;
|
|
58
|
+
const requirements = join(directory, 'active-requirements.json');
|
|
59
|
+
const source = readBounded(requirements);
|
|
60
|
+
if (source === null) return null;
|
|
61
|
+
const folder = JSON.parse(source)?.['feature-dir'];
|
|
62
|
+
if (typeof folder !== 'string' || /[\\:\p{Cc}]/u.test(folder) || (feature && feature !== folder)) return null;
|
|
63
|
+
let parent = root;
|
|
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');
|
|
70
|
+
const table = readBounded(actions);
|
|
71
|
+
if (table === null) return null;
|
|
72
|
+
const row = new RegExp(`^\\s*\\|\\s*${action}\\s*\\|`);
|
|
73
|
+
let status;
|
|
74
|
+
for (const line of table.split('\n')) {
|
|
75
|
+
if (!row.test(line)) continue;
|
|
76
|
+
if (status !== undefined) return null;
|
|
77
|
+
status = /\|\s*(?:`\[([Xx ])\]`|\[([Xx ])\])\s*\|\s*$/.exec(line)?.slice(1).find(value => value !== undefined) ?? null;
|
|
78
|
+
}
|
|
79
|
+
if (!status || status.toUpperCase() !== 'X') return null;
|
|
80
|
+
if (readBounded(requirements) !== source || readBounded(actions) !== table || readBounded(path) !== bytes) return null;
|
|
81
|
+
return `Checkpoint atrasado: ${action} consta como concluída em actions.md. Confira os artefatos e salve a posição pelo helper.`;
|
|
82
|
+
} catch (err) {
|
|
83
|
+
if (err instanceof SyntaxError || err instanceof TypeError || err.code) return null;
|
|
84
|
+
throw err;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function recoveryWarning(cwd, identity) {
|
|
89
|
+
try {
|
|
90
|
+
const snapshot = ownedSnapshot(cwd, identity);
|
|
91
|
+
return snapshot ? contradiction(snapshot) : null;
|
|
92
|
+
} catch (err) {
|
|
93
|
+
if (err instanceof SyntaxError || err instanceof TypeError || err.code) return null;
|
|
94
|
+
throw err;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function anchorFor(cwd, identity) {
|
|
99
|
+
try {
|
|
100
|
+
const snapshot = ownedSnapshot(cwd, identity);
|
|
101
|
+
if (!snapshot) return null;
|
|
102
|
+
const { active } = snapshot;
|
|
51
103
|
const flow = clean(active.flow);
|
|
52
104
|
const agent = clean(active.agent);
|
|
53
105
|
const step = clean(active.step);
|
|
@@ -55,7 +107,8 @@ export function anchorFor(cwd, { harness, session } = {}) {
|
|
|
55
107
|
const { step_index: index, step_total: total } = active;
|
|
56
108
|
const count = Number.isSafeInteger(index) && Number.isSafeInteger(total) && index > 0 && index <= total ? ` (${index}/${total})` : '';
|
|
57
109
|
const status = active.status === 'waiting_user' ? ' · aguardando sua resposta' : '';
|
|
58
|
-
const
|
|
110
|
+
const warning = contradiction(snapshot);
|
|
111
|
+
const hint = ' — Releia o estado, o gate e o SKILL.md instalado antes de agir.' + (warning ? ` ${warning}` : '');
|
|
59
112
|
const prefix = Array.from(`🧭 Reversa › ${flow} › ${agent} › ${step}`);
|
|
60
113
|
return prefix.slice(0, 600 - Array.from(count + status + hint).length).join('') + count + status + hint;
|
|
61
114
|
} catch (err) {
|
|
@@ -66,7 +119,13 @@ export function anchorFor(cwd, { harness, session } = {}) {
|
|
|
66
119
|
|
|
67
120
|
function handle(harness, event) {
|
|
68
121
|
if (!COMMAND_EVENTS.has(event?.hook_event_name) || event.agent_id || event.agent_type) return null;
|
|
69
|
-
const
|
|
122
|
+
const identity = { harness, session: event.session_id };
|
|
123
|
+
if (event.hook_event_name === 'Stop') {
|
|
124
|
+
if (event.stop_hook_active === true) return null;
|
|
125
|
+
const warning = recoveryWarning(event.cwd, identity);
|
|
126
|
+
return warning ? { systemMessage: warning.slice(0, 240) } : null;
|
|
127
|
+
}
|
|
128
|
+
const anchor = anchorFor(event.cwd, identity);
|
|
70
129
|
return anchor && { hookSpecificOutput: { hookEventName: event.hook_event_name, additionalContext: anchor } };
|
|
71
130
|
}
|
|
72
131
|
|