@fatelabs/pi-estelle 0.0.0-stage → 0.0.18
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/LICENSE +201 -0
- package/NOTICE +6 -0
- package/README.md +44 -2
- package/adapters/claude.mjs +17 -0
- package/adapters/codex.mjs +85 -0
- package/adapters/cursor.mjs +66 -0
- package/adapters/dsh-host.mjs +181 -0
- package/adapters/dsh-plugin.mjs +11 -0
- package/adapters/dsh.mjs +54 -0
- package/adapters/grok.mjs +63 -0
- package/adapters/host-bridge.mjs +85 -0
- package/adapters/kimi.mjs +135 -0
- package/adapters/opencode-mirror.mjs +103 -0
- package/adapters/opencode-plugin.mjs +143 -0
- package/adapters/opencode.mjs +15 -0
- package/adapters/pi-extension.mjs +107 -0
- package/adapters/pi.mjs +13 -0
- package/adapters/plugin-envelope.mjs +56 -0
- package/commands/cloud.md +28 -0
- package/commands/code.md +6 -0
- package/commands/handoff.md +25 -0
- package/commands/monitor.md +6 -0
- package/commands/resume.md +6 -0
- package/commands/review.md +6 -0
- package/commands/rooms.md +7 -0
- package/instructions.md +19 -0
- package/package.json +38 -4
- package/runtime/auth.mjs +27 -0
- package/runtime/checkpoint.mjs +208 -0
- package/runtime/claude-setup.mjs +130 -0
- package/runtime/cli.mjs +112 -0
- package/runtime/codex-trust.mjs +68 -0
- package/runtime/credential.mjs +341 -0
- package/runtime/dsh-session.mjs +91 -0
- package/runtime/dsh-telemetry.mjs +31 -0
- package/runtime/hooks.mjs +234 -0
- package/runtime/identity.mjs +20 -0
- package/runtime/io.mjs +155 -0
- package/runtime/key-check.mjs +51 -0
- package/runtime/kimi-history.mjs +163 -0
- package/runtime/mailbox.mjs +46 -0
- package/runtime/migration.mjs +118 -0
- package/runtime/move.mjs +443 -0
- package/runtime/native-export.mjs +204 -0
- package/runtime/native-index.mjs +77 -0
- package/runtime/native-tree.mjs +117 -0
- package/runtime/queued-context.mjs +152 -0
- package/runtime/redact.mjs +74 -0
- package/runtime/reindex.mjs +259 -0
- package/runtime/setup.mjs +174 -0
- package/runtime/stream.mjs +755 -0
- package/runtime/version.mjs +2 -0
- package/runtime/write-warning.mjs +67 -0
- package/skills/abstain-right/SKILL.md +19 -0
- package/skills/api-call-ground/SKILL.md +19 -0
- package/skills/bug-hunt/SKILL.md +20 -0
- package/skills/chain-of-verification/SKILL.md +19 -0
- package/skills/change-impact/SKILL.md +19 -0
- package/skills/coding-workflow/SKILL.md +20 -0
- package/skills/commit-guard/SKILL.md +20 -0
- package/skills/context-checkpoint/SKILL.md +19 -0
- package/skills/continuity-brief/SKILL.md +19 -0
- package/skills/dead-code-sweep/SKILL.md +19 -0
- package/skills/deep-search/SKILL.md +19 -0
- package/skills/diff-review/SKILL.md +19 -0
- package/skills/estelle/SKILL.md +119 -0
- package/skills/estelle-loop/SKILL.md +19 -0
- package/skills/estelle-monitor-install/SKILL.md +20 -0
- package/skills/evidence-traceability-audit/SKILL.md +19 -0
- package/skills/grounded-generate/SKILL.md +19 -0
- package/skills/incident-rca/SKILL.md +20 -0
- package/skills/mutation-test/SKILL.md +19 -0
- package/skills/program-repair/SKILL.md +20 -0
- package/skills/prompt-injection-defense/SKILL.md +19 -0
- package/skills/property-based-test/SKILL.md +19 -0
- package/skills/refactor-rfc/SKILL.md +19 -0
- package/skills/root-cause-loop/SKILL.md +19 -0
- package/skills/test-first/SKILL.md +19 -0
- package/skills/threat-model-stride/SKILL.md +19 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Current Kimi wire 1.5 reader. The source contracts are pinned in docs/research/kimi-current-capture.md.
|
|
2
|
+
import { open } from 'node:fs/promises';
|
|
3
|
+
import { getTranscriptPath } from '../adapters/kimi.mjs';
|
|
4
|
+
import { cap, sanitize } from './redact.mjs';
|
|
5
|
+
|
|
6
|
+
export const KIMI_HISTORY_LIMITS = Object.freeze({ bytes: 32 * 1024 * 1024,
|
|
7
|
+
records: 100_000, branches: 256, parts: 1_000, calls: 1_000 });
|
|
8
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
9
|
+
const typeOf = value => typeof value?.type === 'string' ? value.type.replace(/^human\./, '') : '';
|
|
10
|
+
const timeOf = value => Number.isSafeInteger(value) && value >= 0 && Number.isFinite(new Date(value).getTime());
|
|
11
|
+
const string = value => typeof value === 'string' ? value : '';
|
|
12
|
+
|
|
13
|
+
function visibleMessage(value) {
|
|
14
|
+
if (!object(value) || !['user', 'assistant', 'tool'].includes(value.role)) return null;
|
|
15
|
+
const content = typeof value.content === 'string' ? [{ type: 'text', text: value.content }] : value.content;
|
|
16
|
+
if (!Array.isArray(content) || content.length > KIMI_HISTORY_LIMITS.parts) return null;
|
|
17
|
+
const parts = [];
|
|
18
|
+
let incomplete = false;
|
|
19
|
+
for (const part of content) {
|
|
20
|
+
if (part?.type === 'text' && typeof part.text === 'string') {
|
|
21
|
+
parts.push({ type: 'text', text: cap(part.text) });
|
|
22
|
+
if (Array.from(part.text).length > 20_000) incomplete = true;
|
|
23
|
+
}
|
|
24
|
+
if (['image_url', 'image', 'audio_url', 'video_url'].includes(part?.type)) {
|
|
25
|
+
parts.push({ type: 'text', text: '[media attachment; bytes and URL omitted]' });
|
|
26
|
+
}
|
|
27
|
+
// Do not recover or persist encrypted, hidden, or recorded reasoning through this reader.
|
|
28
|
+
if (!['text', 'think', 'image_url', 'image', 'audio_url', 'video_url'].includes(part?.type)) incomplete = true;
|
|
29
|
+
}
|
|
30
|
+
const calls = value.toolCalls ?? [];
|
|
31
|
+
if (!Array.isArray(calls) || calls.length > KIMI_HISTORY_LIMITS.calls) return null;
|
|
32
|
+
return { message: { role: value.role, content: parts,
|
|
33
|
+
...(typeof value.toolCallId === 'string' ? { toolCallId: value.toolCallId } : {}),
|
|
34
|
+
...(typeof value.isError === 'boolean' ? { isError: value.isError } : {}),
|
|
35
|
+
...(value.role === 'assistant' ? { toolCalls: sanitize(calls) } : {}),
|
|
36
|
+
}, incomplete };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Normalize a single actual journal record without inventing its timestamp, session, or identity. */
|
|
40
|
+
export function normalizeKimiRecord(record) {
|
|
41
|
+
if (!object(record) || !timeOf(record.time)) return null;
|
|
42
|
+
const type = typeOf(record);
|
|
43
|
+
if (['agent.turn.ended', 'turn.ended'].includes(type)) return { type: 'turn.ended', time: record.time };
|
|
44
|
+
if (!['agent.message.appended', 'context.append_message'].includes(type)) return null;
|
|
45
|
+
const wrapper = record.message;
|
|
46
|
+
const raw = object(wrapper?.message) ? wrapper.message : wrapper;
|
|
47
|
+
const visible = visibleMessage(raw);
|
|
48
|
+
if (!visible) return null;
|
|
49
|
+
const { message } = visible;
|
|
50
|
+
// System injections and generated summaries are not things the person typed.
|
|
51
|
+
const source = wrapper?.meta?.source;
|
|
52
|
+
const origin = raw?.origin?.kind ?? wrapper?.meta?.origin?.kind;
|
|
53
|
+
if (message.role === 'user' && ((source && source !== 'input') || (origin && origin !== 'user'))) return null;
|
|
54
|
+
return { type: 'context.append_message', time: record.time, message,
|
|
55
|
+
...(visible.incomplete ? { capture_incomplete: true } : {}) };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function switchEdge(record, line) {
|
|
59
|
+
if (typeOf(record) !== 'agent.switched') return null;
|
|
60
|
+
if (typeof record.branch !== 'string' || !/^[A-Za-z0-9_-]{1,200}$/.test(record.branch)) throw new Error('invalid_branch');
|
|
61
|
+
if (!object(record.base) || typeof record.base.branch !== 'string' ||
|
|
62
|
+
!/^[A-Za-z0-9_-]{1,200}$/.test(record.base.branch) || !Number.isSafeInteger(record.base.line) ||
|
|
63
|
+
record.base.line < 0 || record.base.line >= line) throw new Error('invalid_branch_base');
|
|
64
|
+
return { branch: record.branch, line, base: record.base };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Select the same branch ancestry as Kimi's wire activeChain, iteratively and with a fixed bound. */
|
|
68
|
+
export function activeKimiRecords(records) {
|
|
69
|
+
if (!Array.isArray(records) || records.length > KIMI_HISTORY_LIMITS.records) throw new Error('record_bound');
|
|
70
|
+
const segments = new Map();
|
|
71
|
+
let branch = 'main';
|
|
72
|
+
let from = 1;
|
|
73
|
+
let base;
|
|
74
|
+
for (const [index, record] of records.entries()) {
|
|
75
|
+
const line = index + 1;
|
|
76
|
+
const edge = switchEdge(record, line);
|
|
77
|
+
if (!edge) continue;
|
|
78
|
+
segments.set(branch, { from, to: line, base });
|
|
79
|
+
if (segments.has(edge.branch) || segments.size >= KIMI_HISTORY_LIMITS.branches) throw new Error('branch_bound_or_duplicate');
|
|
80
|
+
branch = edge.branch; from = line + 1; base = edge.base;
|
|
81
|
+
}
|
|
82
|
+
segments.set(branch, { from, to: records.length, base });
|
|
83
|
+
const chain = [];
|
|
84
|
+
const visited = new Set();
|
|
85
|
+
let ceiling = records.length;
|
|
86
|
+
for (let depth = 0; depth < KIMI_HISTORY_LIMITS.branches; depth++) {
|
|
87
|
+
if (visited.has(branch)) throw new Error('branch_cycle');
|
|
88
|
+
const segment = segments.get(branch);
|
|
89
|
+
if (!segment || ceiling > segment.to || ceiling < segment.from - 1) throw new Error('unknown_branch_base');
|
|
90
|
+
visited.add(branch); chain.push({ from: segment.from, to: ceiling });
|
|
91
|
+
if (!segment.base) break;
|
|
92
|
+
ceiling = segment.base.line; branch = segment.base.branch;
|
|
93
|
+
}
|
|
94
|
+
if (chain.length >= KIMI_HISTORY_LIMITS.branches) throw new Error('branch_bound');
|
|
95
|
+
return chain.reverse().flatMap(segment => records.slice(segment.from - 1, segment.to)
|
|
96
|
+
.filter(record => typeOf(record) !== 'agent.switched'));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function readBounded(path) {
|
|
100
|
+
const file = await open(path, 'r');
|
|
101
|
+
try {
|
|
102
|
+
const info = await file.stat();
|
|
103
|
+
if (!info.isFile() || info.size > KIMI_HISTORY_LIMITS.bytes) return { incomplete: true, reason: 'byte_bound', fileBytes: info.size };
|
|
104
|
+
const buffer = Buffer.alloc(info.size + 1);
|
|
105
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
|
|
106
|
+
if (bytesRead > info.size) return { incomplete: true, reason: 'concurrent_growth', fileBytes: info.size };
|
|
107
|
+
const text = buffer.subarray(0, bytesRead).toString('utf8');
|
|
108
|
+
const end = text.lastIndexOf('\n');
|
|
109
|
+
const lines = text.slice(0, end + 1).split('\n').slice(0, -1);
|
|
110
|
+
if (lines.length > KIMI_HISTORY_LIMITS.records) return { incomplete: true, reason: 'record_bound', fileBytes: info.size };
|
|
111
|
+
return { lines, fileBytes: info.size, incomplete: end + 1 < text.length || bytesRead < info.size };
|
|
112
|
+
} finally { await file.close(); }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const OBSERVATION = new Set(['metadata', 'agent.turn.started', 'agent.turn.ended', 'turn.prompt', 'turn.ended',
|
|
116
|
+
'turn.cancel', 'context.undo', 'context.undone', 'agent.switched', 'llm.request', 'llm.response',
|
|
117
|
+
'tools.update_store', 'state.updated', 'agent.state.updated']);
|
|
118
|
+
|
|
119
|
+
/** Read this registered main agent only. It never scans other sessions, reads blobs, or writes Kimi state. */
|
|
120
|
+
export async function readKimiHistory({ sessionId, cwd, home }) {
|
|
121
|
+
if (typeof sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,200}$/.test(sessionId)) throw new Error('invalid_session');
|
|
122
|
+
const sourcePath = await getTranscriptPath({ host: 'kimi', sessionId, cwd }, { home });
|
|
123
|
+
if (!sourcePath) return { available: false, coverage: { complete: false, reason: 'registered_wire_unavailable' } };
|
|
124
|
+
const bounded = await readBounded(sourcePath);
|
|
125
|
+
if (!bounded.lines) return { available: false, sourcePath, coverage: { complete: false, ...bounded } };
|
|
126
|
+
const records = [];
|
|
127
|
+
let invalid = 0;
|
|
128
|
+
for (const line of bounded.lines) {
|
|
129
|
+
try { const value = JSON.parse(line); if (!object(value) || typeof value.type !== 'string') invalid++; else records.push(value); }
|
|
130
|
+
catch { invalid++; }
|
|
131
|
+
}
|
|
132
|
+
const metadata = records[0]?.type === 'metadata' ? records[0] : null;
|
|
133
|
+
const version = metadata?.protocol_version ?? '1.4';
|
|
134
|
+
if (typeof version !== 'string' || !/^1\.[0-5]$/.test(version)) {
|
|
135
|
+
return { available: false, sourcePath, coverage: { complete: false, reason: 'unsupported_wire_version' } };
|
|
136
|
+
}
|
|
137
|
+
// Line numbers are part of branch identity; do not project through missing or malformed records.
|
|
138
|
+
if (invalid) return { available: false, sourcePath, coverage: { complete: false, reason: 'invalid_records', invalid } };
|
|
139
|
+
let active;
|
|
140
|
+
try { active = activeKimiRecords(records); }
|
|
141
|
+
catch { return { available: false, sourcePath, coverage: { complete: false, reason: 'invalid_branch_history' } }; }
|
|
142
|
+
const lineOf = new Map(records.map((record, index) => [record, index + 1]));
|
|
143
|
+
const pairedUndo = new Set(records.filter(record => typeOf(record) === 'agent.switched')
|
|
144
|
+
.map(record => record.legacyUndoLine).filter(Number.isSafeInteger));
|
|
145
|
+
if (active.some(record => ['context.apply_compaction', 'context.clear'].includes(typeOf(record)) ||
|
|
146
|
+
(typeOf(record) === 'context.undo' && !pairedUndo.has(lineOf.get(record))))) {
|
|
147
|
+
return { available: false, sourcePath, coverage: { complete: false, reason: 'unsupported_context_mutation' } };
|
|
148
|
+
}
|
|
149
|
+
const normalized = [];
|
|
150
|
+
let unsupported = 0;
|
|
151
|
+
for (const record of active) {
|
|
152
|
+
const item = normalizeKimiRecord(record);
|
|
153
|
+
if (item) { normalized.push(item); if (item.capture_incomplete) unsupported++; }
|
|
154
|
+
else if (!OBSERVATION.has(typeOf(record))) unsupported++;
|
|
155
|
+
}
|
|
156
|
+
const messages = normalized.filter(record => record.type === 'context.append_message' && ['user', 'assistant'].includes(record.message.role))
|
|
157
|
+
.map(record => ({ role: record.message.role, content: record.message.content.filter(part => part.type === 'text').map(part => part.text).join('\n') }))
|
|
158
|
+
.filter(message => message.content);
|
|
159
|
+
return { available: true, sourcePath, format: `kimi-wire-${version}`, records: normalized, messages,
|
|
160
|
+
coverage: { complete: !bounded.incomplete && unsupported === 0, partialLastLine: bounded.incomplete,
|
|
161
|
+
fileBytes: bounded.fileBytes, recordsRead: records.length, recordsSelected: active.length, unsupported,
|
|
162
|
+
scope: 'registered main-agent visible conversation and tool records; media bytes and reasoning omitted' } };
|
|
163
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// A session's own identity at SessionStart, and its mail at its next tool call.
|
|
2
|
+
//
|
|
3
|
+
// Identity: Estelle's server hands this session its id and session_token (POST /session/mail {action: identity})
|
|
4
|
+
// and the hook prints that line into the model's context. Before this, the token arrived only once, inside the
|
|
5
|
+
// first prompt's recall, so a compaction erased it and the session could not prove itself in a room or as a
|
|
6
|
+
// mail sender. SessionStart fires again on resume, clear and compact, so the line is restated each time.
|
|
7
|
+
//
|
|
8
|
+
// Tool boundary: at PostToolUse the hook pulls this session's pending mail and room entries
|
|
9
|
+
// (POST /session/mail {action: deliver, boundary: tool}), so a running session sees a message at its next
|
|
10
|
+
// tool call instead of waiting for its person's next prompt. Bounded: at most one pull per
|
|
11
|
+
// TOOL_PULL_INTERVAL_MS per session, and never from a subagent's tool call (the mail is the main
|
|
12
|
+
// conversation's; a subagent shares its session id).
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { hash, readJson, writeJson } from './io.mjs';
|
|
15
|
+
import { timelineIdentity } from './identity.mjs';
|
|
16
|
+
|
|
17
|
+
// Hosts whose sessions the server can mail (its live list) and whose hook output carries additionalContext.
|
|
18
|
+
// OpenCode and Pi carry the text through their in-process plugin (adapters/opencode-plugin.mjs, adapters/pi-extension.mjs);
|
|
19
|
+
// the server must list them as local hosts too, or identity is refused and only the start text is printed.
|
|
20
|
+
export const MAILBOX_HOSTS = new Set(['claude-code', 'codex', 'opencode', 'pi']);
|
|
21
|
+
export const TOOL_PULL_INTERVAL_MS = 10_000;
|
|
22
|
+
// Characters of delivered text one hook output carries; the server already bounds a delivery well below this.
|
|
23
|
+
const MAX_CONTEXT_CHARS = 12_000;
|
|
24
|
+
|
|
25
|
+
const textOf = result => (typeof result?.context === 'string' ? result.context.slice(0, MAX_CONTEXT_CHARS) : '');
|
|
26
|
+
|
|
27
|
+
/** This session's id and token, as the line to print. '' when the server issued none. */
|
|
28
|
+
export async function sessionIdentity(n, request) {
|
|
29
|
+
const result = await request('/session/mail', { action: 'identity', session_id: timelineIdentity(n.host, n.sessionId) });
|
|
30
|
+
return { text: textOf(result) };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Pending mail and room entries at a boundary ('start' or 'tool'). A tool pull is throttled per session. */
|
|
34
|
+
export async function pullAtBoundary(n, stateDir, request, boundary, now = Date.now()) {
|
|
35
|
+
if (boundary === 'tool') {
|
|
36
|
+
const path = join(stateDir, 'mailbox', `${hash(`${n.host}:${n.sessionId}`)}.json`);
|
|
37
|
+
const last = await readJson(path).catch(() => null);
|
|
38
|
+
if (last && typeof last.at === 'number' && now - last.at >= 0 && now - last.at < TOOL_PULL_INTERVAL_MS) {
|
|
39
|
+
return { text: '', skipped: true };
|
|
40
|
+
}
|
|
41
|
+
await writeJson(path, { at: now });
|
|
42
|
+
}
|
|
43
|
+
const result = await request('/session/mail', { action: 'deliver', session_id: timelineIdentity(n.host, n.sessionId),
|
|
44
|
+
boundary });
|
|
45
|
+
return { text: textOf(result) };
|
|
46
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/** Explicit setup only: exact legacy registrations, never hook-time configuration mutation. */
|
|
2
|
+
import * as nativeFs from 'node:fs/promises';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
5
|
+
import { dirname, basename, join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
export const MIGRATION_LIMITS = Object.freeze({ bytes:262144, rows:1024, depth:32 });
|
|
8
|
+
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
9
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
10
|
+
const EVENTS = Object.freeze({ ground:['PreToolUse'],guard:['PreToolUse'],pull:['PreToolUse'],
|
|
11
|
+
shift:['PostToolUse'],sync:['PostToolUse'],distil:['PostToolUse'],welcome:['SessionStart'],
|
|
12
|
+
context:['UserPromptSubmit','SubagentStart'],checkpoint:['Stop','SubagentStop','PreCompact','SessionEnd'],
|
|
13
|
+
stream:['UserPromptSubmit','PostToolUse','Stop','SessionEnd'] });
|
|
14
|
+
|
|
15
|
+
export function legacyCommand(command,event) {
|
|
16
|
+
if(typeof command !== 'string' || command.length>512)return false;
|
|
17
|
+
const match=/^(?:estelle|npx -y @fatelabs\/estelle(?:@(?:[0-9]+(?:\.[0-9]+){0,2}|latest|v0-latest))?|npx -y --package=@fatelabs\/estelle(?:@(?:[0-9]+(?:\.[0-9]+){0,2}|latest|v0-latest))? -- estelle) hook ([a-z-]+)(?: --event ([A-Za-z]+))?$/.exec(command);
|
|
18
|
+
return Boolean(match && Object.hasOwn(EVENTS,match[1]) && EVENTS[match[1]].includes(event) && (!match[2] || match[2]===event));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** JSON.parse alone silently discards duplicate keys; never rewrite such an ambiguous document. */
|
|
22
|
+
function checkedJson(bytes) {
|
|
23
|
+
if(!Buffer.isBuffer(bytes) || bytes.length>MIGRATION_LIMITS.bytes)throw Error('hooks_bound');
|
|
24
|
+
const text=new TextDecoder('utf-8',{fatal:true}).decode(bytes), value=JSON.parse(text),stack=[];
|
|
25
|
+
for(const token of text.matchAll(/"(?:\\[\s\S]|[^"\\])*"|[{}\[\]]/g)) {
|
|
26
|
+
const word=token[0];
|
|
27
|
+
if(word==='{' || word==='[')stack.push(word==='{'?new Set():null);
|
|
28
|
+
else if(word==='}' || word===']')stack.pop();
|
|
29
|
+
else if(/^\s*:/.test(text.slice(token.index+word.length))) {
|
|
30
|
+
const keys=stack.at(-1),key=JSON.parse(word);
|
|
31
|
+
if(!keys || keys.has(key))throw Error('hooks_schema');keys.add(key);
|
|
32
|
+
}
|
|
33
|
+
if(stack.length>MIGRATION_LIMITS.depth)throw Error('hooks_bound');
|
|
34
|
+
}
|
|
35
|
+
if(!object(value))throw Error('hooks_schema');return value;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function planHooks(bytes) {
|
|
39
|
+
const value=checkedJson(bytes);let removed=0,rows=0;
|
|
40
|
+
if(!Object.hasOwn(value,'hooks'))return {bytes,removed,hash:digest(bytes)};
|
|
41
|
+
if(!object(value.hooks))throw Error('hooks_schema');
|
|
42
|
+
for(const [event,groups] of Object.entries(value.hooks)) {
|
|
43
|
+
if(!Array.isArray(groups))throw Error('hooks_schema');
|
|
44
|
+
for(const group of groups) {
|
|
45
|
+
if(!object(group) || !Array.isArray(group.hooks))throw Error('hooks_schema');
|
|
46
|
+
group.hooks=group.hooks.filter(hook=>{
|
|
47
|
+
if(++rows>MIGRATION_LIMITS.rows || !object(hook))throw Error('hooks_bound');
|
|
48
|
+
const own=hook.type==='command' && legacyCommand(hook.command,event);
|
|
49
|
+
if(own)removed++;return !own;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const output=removed?Buffer.from(JSON.stringify(value,null,2)+'\n'):bytes;
|
|
54
|
+
if(output.length>MIGRATION_LIMITS.bytes)throw Error('hooks_bound');
|
|
55
|
+
return {bytes:output,removed,hash:digest(bytes)};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const identity = info => [info.dev,info.ino,info.size,info.mtimeNs,info.ctimeNs].map(String).join(':');
|
|
59
|
+
export async function inspectHooks(path,{fs=nativeFs}={}) {
|
|
60
|
+
let file;
|
|
61
|
+
try{file=await fs.open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);}
|
|
62
|
+
catch(error){if(error.code==='ENOENT')return null;throw Error('hooks_unavailable');}
|
|
63
|
+
try{
|
|
64
|
+
const info=await file.stat({bigint:true});
|
|
65
|
+
if(!info.isFile() || info.size>BigInt(MIGRATION_LIMITS.bytes))throw Error('hooks_bound');
|
|
66
|
+
const bytes=Buffer.alloc(MIGRATION_LIMITS.bytes+1),result=await file.read(bytes,0,bytes.length,0);
|
|
67
|
+
if(result.bytesRead>MIGRATION_LIMITS.bytes)throw Error('hooks_bound');
|
|
68
|
+
if(result.bytesRead!==Number(info.size))throw Error('hooks_incomplete');
|
|
69
|
+
if(identity(await file.stat({bigint:true}))!==identity(info))throw Error('hooks_conflict');
|
|
70
|
+
const data=bytes.subarray(0,result.bytesRead);planHooks(data);
|
|
71
|
+
return {bytes:data,hash:digest(data),identity:identity(info)};
|
|
72
|
+
}finally{await file.close();}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function sameSnapshot(path,expected,fs) {
|
|
76
|
+
const current=await inspectHooks(path,{fs});
|
|
77
|
+
if(!current || current.hash!==expected?.hash || current.identity!==expected?.identity)throw Error('hooks_conflict');
|
|
78
|
+
return current;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function releaseLock(path,file,fs) {
|
|
82
|
+
try{
|
|
83
|
+
const held=await file.stat({bigint:true}),current=await fs.lstat(path,{bigint:true});
|
|
84
|
+
if(held.dev!==current.dev || held.ino!==current.ino)return false;
|
|
85
|
+
await fs.unlink(path);return true;
|
|
86
|
+
}catch{return false;}
|
|
87
|
+
finally{await file.close();}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Optimistic conflict checks + atomic replacement; foreign writers must serialize setup changes. */
|
|
91
|
+
export async function commitHooks(path,expected,{fs=nativeFs}={}) {
|
|
92
|
+
let lock;
|
|
93
|
+
try{lock=await fs.open(path+'.estelle-setup.lock','wx',0o600);}
|
|
94
|
+
catch{throw Error('hooks_busy');}
|
|
95
|
+
const temporary=join(dirname(path),`.${basename(path)}.estelle-${randomUUID()}.tmp`);
|
|
96
|
+
let replacement=null,renameStarted=false,result;
|
|
97
|
+
try{
|
|
98
|
+
const current=await sameSnapshot(path,expected,fs),plan=planHooks(current.bytes);
|
|
99
|
+
if(!plan.removed){result={status:'unchanged',removed:0};return result;}
|
|
100
|
+
replacement=await fs.open(temporary,'wx',0o600);await replacement.writeFile(plan.bytes);await replacement.sync();
|
|
101
|
+
await replacement.close();replacement=null;
|
|
102
|
+
await sameSnapshot(path,expected,fs);
|
|
103
|
+
renameStarted=true;await fs.rename(temporary,path);
|
|
104
|
+
const directory=await fs.open(dirname(path),constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK|constants.O_DIRECTORY);
|
|
105
|
+
try{await directory.sync();}finally{await directory.close();}
|
|
106
|
+
const saved=await inspectHooks(path,{fs});if(saved?.hash!==digest(plan.bytes))throw Error('hooks_ack');
|
|
107
|
+
result={status:'applied',removed:plan.removed};
|
|
108
|
+
}catch(error){
|
|
109
|
+
if(!renameStarted)throw error;
|
|
110
|
+
result={status:'unknown',removed:null};
|
|
111
|
+
}finally{
|
|
112
|
+
if(replacement)await replacement.close().catch(()=>{});
|
|
113
|
+
await fs.unlink(temporary).catch(()=>{});
|
|
114
|
+
const unlocked=await releaseLock(path+'.estelle-setup.lock',lock,fs);
|
|
115
|
+
if(result && !unlocked)result.cleanup='unknown';
|
|
116
|
+
}
|
|
117
|
+
return result;
|
|
118
|
+
}
|