@ngockhoale/ukit 3.5.15 → 3.5.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/CHANGELOG.md +25 -0
- package/manifests/platform.full.yaml +48 -0
- package/package.json +2 -1
- package/scripts/release/heavy-first.mjs +12 -0
- package/scripts/release/release-steps.mjs +7 -4
- package/scripts/release/run-core-batch.mjs +50 -0
- package/src/cli/commands/mission.js +102 -0
- package/src/cli/commands/rescue.js +83 -0
- package/src/cli/index.js +14 -0
- package/src/core/compact/contextBudget.js +62 -41
- package/src/core/compact/threshold.js +14 -32
- package/src/core/observability/schema/registry.js +91 -0
- package/src/core/runtimeConfig.js +53 -2
- package/src/diagnostics/routeOutcomes.js +5 -1
- package/src/diagnostics/skillAccuracy.js +5 -2
- package/src/render/buildVariables.js +2 -5
- package/template_project/.claude/commands/ukit/handoff-implement.md +3 -3
- package/template_project/.claude/commands/ukit/handoff-review.md +3 -3
- package/template_project/.claude/hooks/context-hardcap-gate.sh +47 -20
- package/template_project/.claude/hooks/context-window-guard.sh +82 -27
- package/template_project/.claude/hooks/delegation-gate.mjs +1 -1
- package/template_project/.claude/hooks/handoff-resume.sh +11 -2
- package/template_project/.claude/hooks/mission-capture.mjs +37 -0
- package/template_project/.claude/hooks/post-compact-observe.mjs +34 -0
- package/template_project/.claude/hooks/shell-watch.mjs +34 -0
- package/template_project/.claude/hooks/skill-router.sh +13 -0
- package/template_project/.claude/hooks/stop-failure-rescue.mjs +109 -0
- package/template_project/.claude/settings.json +36 -4
- package/template_project/.claude/skills/backend-api/SKILL.md +1 -1
- package/template_project/.claude/skills/delivery/SKILL.md +1 -1
- package/template_project/.claude/skills/docs-manager/SKILL.md +1 -1
- package/template_project/.claude/skills/duraone/SKILL.md +2 -1
- package/template_project/.claude/skills/file-organizer/SKILL.md +1 -1
- package/template_project/.claude/skills/frontend/SKILL.md +1 -1
- package/template_project/.claude/skills/frontend-vue/SKILL.md +1 -1
- package/template_project/.claude/skills/pdf-processing/SKILL.md +1 -1
- package/template_project/.claude/skills/postgres/SKILL.md +1 -1
- package/template_project/.claude/skills/testing-quality/SKILL.md +2 -0
- package/template_project/.claude/skills/webapp-testing/SKILL.md +1 -1
- package/template_project/.claude/ukit/index/route-task.mjs +3 -1
- package/template_project/.claude/ukit/index/tier-lane.mjs +1 -1
- package/template_project/.claude/ukit/runtime/compact-threshold.mjs +15 -29
- package/template_project/.claude/ukit/runtime/context-capacity.mjs +64 -1
- package/template_project/.claude/ukit/runtime/execution-ledger.mjs +107 -4
- package/template_project/.claude/ukit/runtime/hook-chain-runner.mjs +20 -1
- package/template_project/.claude/ukit/runtime/mission/checkpoint.mjs +85 -0
- package/template_project/.claude/ukit/runtime/mission/classify.mjs +182 -0
- package/template_project/.claude/ukit/runtime/mission/drift.mjs +58 -0
- package/template_project/.claude/ukit/runtime/mission/graph.mjs +381 -0
- package/template_project/.claude/ukit/runtime/mission/hooks.mjs +199 -0
- package/template_project/.claude/ukit/runtime/mission/journal.mjs +68 -0
- package/template_project/.claude/ukit/runtime/mission/metrics.mjs +64 -0
- package/template_project/.claude/ukit/runtime/mission/recall.mjs +132 -0
- package/template_project/.claude/ukit/runtime/mission/redact.mjs +25 -0
- package/template_project/.claude/ukit/runtime/mission/restore.mjs +107 -0
- package/template_project/.claude/ukit/runtime/mission/store.mjs +231 -0
- package/template_project/.claude/ukit/runtime/mission/working.mjs +88 -0
- package/template_project/.claude/ukit/runtime/prompt-injection-cap.mjs +33 -0
- package/template_project/.claude/ukit/runtime/reinject-context.mjs +87 -6
- package/template_project/.claude/ukit/runtime/rescue/bundle.mjs +122 -0
- package/template_project/.claude/ukit/runtime/rescue/classify-failure.mjs +136 -0
- package/template_project/.claude/ukit/runtime/rescue/lease.mjs +65 -0
- package/template_project/.claude/ukit/runtime/rescue/reconstruct.mjs +273 -0
- package/template_project/.claude/ukit/runtime/rescue/recovery-state.mjs +120 -0
- package/template_project/.claude/ukit/runtime/rescue/rollover.mjs +151 -0
- package/template_project/.claude/ukit/runtime/sensitive-value-scanner.mjs +1 -1
- package/template_project/.claude/ukit/runtime/shell-watch.mjs +278 -0
- package/template_project/.claude/ukit/runtime/stop-coordinator.mjs +154 -0
- package/template_project/.omp/RULES.md +1 -1
- package/template_project/.omp/config.yml +2 -2
- package/template_project/.omp/hooks/pre/ukit-bridge.js +69 -2
- package/template_project/AGENTS.md +5 -1
- package/template_project/CLAUDE.md +5 -1
- package/template_project/docs/AI_HANDOFF/RULES.md +4 -4
- package/template_project/instructions/core.md +5 -1
- package/template_project/instructions/overlays/omp-rules.md +1 -1
- package/template_project/ukit/storage/config.json +32 -10
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// classify-failure.mjs - pure StopFailure / compaction-failure classifier (WP-R1).
|
|
2
|
+
// No I/O. Input text is redacted + truncated before it can reach a fingerprint or log;
|
|
3
|
+
// a fingerprint never contains prompt text.
|
|
4
|
+
import crypto from 'node:crypto';
|
|
5
|
+
import { TOKEN_PATTERNS } from '../sensitive-value-scanner.mjs';
|
|
6
|
+
|
|
7
|
+
// The 15 advisor failure classes (docs/plans/2026-11-21-context-rescue-advisor.md Phase 1).
|
|
8
|
+
export const CLASS_TABLE = Object.freeze({
|
|
9
|
+
1: { name: 'prompt-over-window', retryable: false, action: 'rollover' },
|
|
10
|
+
2: { name: 'native-compaction-late', retryable: false, action: 'rollover' },
|
|
11
|
+
3: { name: 'compaction-overflow', retryable: false, action: 'rollover' },
|
|
12
|
+
4: { name: 'request-byte-limit', retryable: false, action: 'reconstruct' },
|
|
13
|
+
5: { name: 'oversized-tool-output', retryable: false, action: 'reconstruct' },
|
|
14
|
+
6: { name: 'subagent-output-refill', retryable: false, action: 'reconstruct' },
|
|
15
|
+
7: { name: 'gateway-wrong-context-limit', retryable: false, action: 'rollover' },
|
|
16
|
+
8: { name: 'malformed-error-bytes', retryable: false, action: 'reconstruct' },
|
|
17
|
+
9: { name: 'thinking-corruption', retryable: false, action: 'rollover' },
|
|
18
|
+
10: { name: 'tool-pairing-corruption', retryable: false, action: 'rollover' },
|
|
19
|
+
11: { name: 'empty-compaction-summary', retryable: false, action: 'reconstruct' },
|
|
20
|
+
12: { name: 'compaction-refill', retryable: false, action: 'rollover' },
|
|
21
|
+
13: { name: 'transient-network-provider', retryable: true, action: 'wait' },
|
|
22
|
+
14: { name: 'session-unresumable', retryable: false, action: 'rollover' },
|
|
23
|
+
15: { name: 'hook-blocks-compaction', retryable: false, action: 'reconstruct' },
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
// Non-advisor terminal classes (cls 0): never retryable.
|
|
27
|
+
const BLOCK_NAMES = {
|
|
28
|
+
authentication_failed: 'auth-blocked',
|
|
29
|
+
billing_error: 'billing-blocked',
|
|
30
|
+
model_not_found: 'model-not-found-blocked',
|
|
31
|
+
account: 'account-blocked',
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const MAX_TEXT = 600;
|
|
35
|
+
|
|
36
|
+
export function nonPrintableRatio(value) {
|
|
37
|
+
const s = typeof value === 'string' ? value : '';
|
|
38
|
+
if (!s) return 0;
|
|
39
|
+
let bad = 0;
|
|
40
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
41
|
+
const c = s.charCodeAt(i);
|
|
42
|
+
if (c === 0xfffd || (c < 32 && c !== 9 && c !== 10 && c !== 13) || (c >= 0x7f && c < 0xa0)) bad += 1;
|
|
43
|
+
}
|
|
44
|
+
return bad / s.length;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function redact(value) {
|
|
48
|
+
let s = String(value ?? '').slice(0, 4000);
|
|
49
|
+
for (const { re } of TOKEN_PATTERNS) { re.lastIndex = 0; s = s.replace(re, '[REDACTED]'); }
|
|
50
|
+
// eslint-disable-next-line no-control-regex
|
|
51
|
+
s = s.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f�]+/g, '?');
|
|
52
|
+
return s.slice(0, MAX_TEXT);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function textOf(v) {
|
|
56
|
+
if (v == null) return '';
|
|
57
|
+
if (typeof v === 'string') return v;
|
|
58
|
+
try { return JSON.stringify(v); } catch { return ''; }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function bucket(ratio) {
|
|
62
|
+
if (ratio <= 0) return 'b0';
|
|
63
|
+
if (ratio < 0.05) return 'b1';
|
|
64
|
+
if (ratio < 0.2) return 'b2';
|
|
65
|
+
return 'b3';
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function upstreamTag(text) {
|
|
69
|
+
const m = /\[upstream model:\s*([A-Za-z0-9._\-/:]{1,64})/i.exec(text);
|
|
70
|
+
return m ? m[1].toLowerCase() : '';
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function messageClass(t) {
|
|
74
|
+
if (/prompt is too long|context.{0,20}(length|window)|too many tokens|exceeds the (model|context)/.test(t)) return 'ctx-overflow';
|
|
75
|
+
if (/request too large|request_too_large|payload too large|\b413\b|request body/.test(t)) return 'bytes';
|
|
76
|
+
if (/thinking/.test(t)) return 'thinking';
|
|
77
|
+
if (/tool_use|tool_result/.test(t)) return 'tool-pairing';
|
|
78
|
+
if (/empty (compaction )?summary|unusable summary/.test(t)) return 'empty-summary';
|
|
79
|
+
if (/rate.?limit|\b429\b|overloaded|\b5\d\d\b|timeout|timed out|econn|enotfound|network|socket|unavailable/.test(t)) return 'transient';
|
|
80
|
+
if (/no conversation found|cannot resume|unable to resume/.test(t)) return 'unresumable';
|
|
81
|
+
return 'other';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function classifyFailure({ error, error_details, message, usage } = {}) {
|
|
85
|
+
const errKind = String(error || '').toLowerCase();
|
|
86
|
+
const raw = [textOf(error_details), textOf(message)].filter(Boolean).join(' ');
|
|
87
|
+
const byteRatio = nonPrintableRatio(raw);
|
|
88
|
+
const t = redact(raw).toLowerCase();
|
|
89
|
+
const tag = upstreamTag(raw);
|
|
90
|
+
const flags = [];
|
|
91
|
+
if (tag) flags.push('gateway-rewrite');
|
|
92
|
+
if (byteRatio >= 0.05) flags.push('malformed-bytes');
|
|
93
|
+
const mc = messageClass(t);
|
|
94
|
+
const compaction = /compaction|compacting|compact failed/.test(t);
|
|
95
|
+
|
|
96
|
+
const out = (cls, extra = {}) => {
|
|
97
|
+
const row = CLASS_TABLE[cls];
|
|
98
|
+
return { cls, name: row.name, retryable: row.retryable, action: row.action, confidence: 0.8, flags, byteRatio, ...extra };
|
|
99
|
+
};
|
|
100
|
+
const block = (name) => ({ cls: 0, name, retryable: false, action: 'block', confidence: 0.95, flags, byteRatio });
|
|
101
|
+
|
|
102
|
+
if (BLOCK_NAMES[errKind]) return block(BLOCK_NAMES[errKind]);
|
|
103
|
+
if (/model[_ ]not[_ ]found|invalid api key|authentication|unauthori[sz]ed|billing|credit balance|account (disabled|suspended)|organization.{0,20}disabled/.test(t)) {
|
|
104
|
+
return block(/billing|credit/.test(t) ? 'billing-blocked' : /model/.test(t) ? 'model-not-found-blocked' : /account|organization/.test(t) ? 'account-blocked' : 'auth-blocked');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (mc === 'thinking' && /invalid|signature|redacted|cannot be modified|block/.test(t)) return out(9, { confidence: 0.9 });
|
|
108
|
+
if (mc === 'tool-pairing' && /without|must have|unexpected|no corresponding|immediately|ids?/.test(t)) return out(10, { confidence: 0.9 });
|
|
109
|
+
if (mc === 'empty-summary') return out(11, { confidence: 0.9 });
|
|
110
|
+
if (mc === 'bytes') return out(4, { confidence: 0.9 });
|
|
111
|
+
if (/tool (output|result) (too large|exceed)/.test(t)) return out(5);
|
|
112
|
+
if (mc === 'unresumable') return out(14, { confidence: 0.85 });
|
|
113
|
+
if (/hook.{0,40}(block|prevent|denied)/.test(t) && /compact/.test(t)) return out(15);
|
|
114
|
+
if (usage && Number(usage.compactionRefills) >= 3) return out(12);
|
|
115
|
+
|
|
116
|
+
if (mc === 'ctx-overflow') {
|
|
117
|
+
const tokens = Number(usage?.tokens), win = Number(usage?.window);
|
|
118
|
+
if (compaction) return out(3, { confidence: tag ? 0.95 : 0.9 });
|
|
119
|
+
// Gateway rewrote the 400 while measured usage is below the assumed window: wrong limit.
|
|
120
|
+
if (tag && Number.isFinite(tokens) && Number.isFinite(win) && win > 0 && tokens < win * 0.95) return out(7, { confidence: 0.75 });
|
|
121
|
+
if (usage && usage.autoCompactFired === false) return out(2, { confidence: 0.7 });
|
|
122
|
+
return out(1, { confidence: 0.85 });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (byteRatio >= 0.05) return out(8, { confidence: 0.6 });
|
|
126
|
+
if (errKind === 'rate_limit' || errKind === 'server_error' || mc === 'transient') return out(13, { confidence: 0.9 });
|
|
127
|
+
if (errKind === 'max_output_tokens') return { cls: 0, name: 'max-output-tokens', retryable: false, action: 'none', confidence: 0.7, flags, byteRatio };
|
|
128
|
+
return { cls: 0, name: 'unknown', retryable: false, action: 'none', confidence: 0.2, flags, byteRatio };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// sha1(error | message class | upstream tag | byte-ratio bucket). Never includes message text.
|
|
132
|
+
export function fingerprint({ error, error_details, message } = {}) {
|
|
133
|
+
const raw = [textOf(error_details), textOf(message)].filter(Boolean).join(' ');
|
|
134
|
+
const parts = [String(error || '').toLowerCase().slice(0, 40), messageClass(redact(raw).toLowerCase()), upstreamTag(raw), bucket(nonPrintableRatio(raw))];
|
|
135
|
+
return crypto.createHash('sha1').update(parts.join('|')).digest('hex');
|
|
136
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// lease.mjs - rollover lease with epoch fencing (WP-R2). A writer holding an older epoch is rejected.
|
|
2
|
+
import fsp from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { withAsyncLock } from '../async-lock.mjs';
|
|
5
|
+
|
|
6
|
+
export const LEASE_TTL_MS = 10 * 60 * 1000;
|
|
7
|
+
const LOCK_MS = 5000;
|
|
8
|
+
|
|
9
|
+
export function leasePath(root) { return path.join(root, '.ukit', 'storage', 'rescue', 'lease.json'); }
|
|
10
|
+
|
|
11
|
+
export async function readLease(root) {
|
|
12
|
+
try { return JSON.parse(await fsp.readFile(leasePath(root), 'utf8')); } catch { return null; }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
async function writeAtomic(file, data) {
|
|
16
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
17
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
18
|
+
await fsp.writeFile(tmp, JSON.stringify(data));
|
|
19
|
+
await fsp.rename(tmp, file);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function locked(root, fn) {
|
|
23
|
+
const file = leasePath(root);
|
|
24
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
25
|
+
const r = await withAsyncLock(file, { deadlineMs: LOCK_MS }, fn);
|
|
26
|
+
return r.ok ? r.value : { ok: false, code: 'BUSY' };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function acquire({ root, holderSessionId, now = Date.now(), ttlMs = LEASE_TTL_MS }) {
|
|
30
|
+
return locked(root, async () => {
|
|
31
|
+
const cur = await readLease(root);
|
|
32
|
+
const live = cur && cur.expiresAt > now;
|
|
33
|
+
if (live && cur.holderSessionId !== holderSessionId) return { ok: false, code: 'HELD', epoch: cur.epoch, holderSessionId: cur.holderSessionId };
|
|
34
|
+
const epoch = live ? cur.epoch : (cur?.epoch || 0) + 1;
|
|
35
|
+
const lease = { holderSessionId, epoch, expiresAt: now + ttlMs, acquiredAt: live ? cur.acquiredAt : now };
|
|
36
|
+
await writeAtomic(leasePath(root), lease);
|
|
37
|
+
return { ok: true, epoch, expiresAt: lease.expiresAt };
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function renew({ root, holderSessionId, epoch, now = Date.now(), ttlMs = LEASE_TTL_MS }) {
|
|
42
|
+
return locked(root, async () => {
|
|
43
|
+
const cur = await readLease(root);
|
|
44
|
+
if (!cur || cur.epoch !== epoch || cur.holderSessionId !== holderSessionId) return { ok: false, code: 'STALE_EPOCH', epoch: cur?.epoch ?? 0 };
|
|
45
|
+
if (cur.expiresAt <= now) return { ok: false, code: 'EXPIRED', epoch: cur.epoch };
|
|
46
|
+
await writeAtomic(leasePath(root), { ...cur, expiresAt: now + ttlMs });
|
|
47
|
+
return { ok: true, epoch, expiresAt: now + ttlMs };
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function release({ root, holderSessionId, epoch, now = Date.now() }) {
|
|
52
|
+
return locked(root, async () => {
|
|
53
|
+
const cur = await readLease(root);
|
|
54
|
+
if (!cur || cur.epoch !== epoch || cur.holderSessionId !== holderSessionId) return { ok: false, code: 'STALE_EPOCH', epoch: cur?.epoch ?? 0 };
|
|
55
|
+
// Keep the epoch (monotonic) but expire the lease.
|
|
56
|
+
await writeAtomic(leasePath(root), { ...cur, expiresAt: now, releasedAt: now });
|
|
57
|
+
return { ok: true };
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Fencing check for writers: true only when epoch is the current one.
|
|
62
|
+
export async function isCurrentEpoch(root, epoch) {
|
|
63
|
+
const cur = await readLease(root);
|
|
64
|
+
return !!cur && cur.epoch === epoch;
|
|
65
|
+
}
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
// reconstruct.mjs - deterministic offline mission reconstruction (WP-R3). No model calls, read-only.
|
|
2
|
+
// reconstructMission({projectRoot, transcriptPath?, sessionId?, expected?, now}) -> recon object.
|
|
3
|
+
// Sources: transcript (streamed with readline, bounded memory), mission journal, TodoWrite/TaskCreate/
|
|
4
|
+
// TaskUpdate inputs, execution-ledger receipts, git, owner STOP + denied operations.
|
|
5
|
+
// Item classes: VERIFIED (receipt/commit/passing-test evidence), RECOVERED_FROM_SOURCE (verbatim prompt or
|
|
6
|
+
// git), INFERRED_UNVERIFIED (assistant text, summaries, todo "completed" without receipt), UNKNOWN, BLOCKED.
|
|
7
|
+
// Assistant claims and todo statuses NEVER become VERIFIED. Transcripts are never written.
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import fsp from 'node:fs/promises';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import readline from 'node:readline';
|
|
12
|
+
import { execFile } from 'node:child_process';
|
|
13
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
14
|
+
import { TOKEN_PATTERNS } from '../sensitive-value-scanner.mjs';
|
|
15
|
+
|
|
16
|
+
export const CLASSES = Object.freeze(['VERIFIED', 'RECOVERED_FROM_SOURCE', 'INFERRED_UNVERIFIED', 'UNKNOWN', 'BLOCKED']);
|
|
17
|
+
export const PROMPT_KEEP_TAIL = 60;
|
|
18
|
+
export const PROMPT_TEXT_MAX = 2000;
|
|
19
|
+
export const MAX_LINE_CHARS = 4 * 1024 * 1024;
|
|
20
|
+
const GIT_TIMEOUT_MS = 1500;
|
|
21
|
+
const LEDGER_MAX_BYTES = 8 * 1024 * 1024;
|
|
22
|
+
const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
23
|
+
|
|
24
|
+
const ASSIGN_RE = /\b((?:pass(?:word|wd)?|secret|api[_-]?key|access[_-]?token|auth[_-]?token|token)\s*[:=]\s*)(["']?)([^\s"']{6,})\2/gi;
|
|
25
|
+
|
|
26
|
+
export function redact(text) {
|
|
27
|
+
try {
|
|
28
|
+
if (typeof text !== 'string' || !text) return '';
|
|
29
|
+
let out = text;
|
|
30
|
+
for (const { label, re } of TOKEN_PATTERNS) {
|
|
31
|
+
const rx = new RegExp(re.source, re.flags.includes('g') ? re.flags : `${re.flags}g`);
|
|
32
|
+
out = out.replace(rx, `[REDACTED:${label}]`);
|
|
33
|
+
}
|
|
34
|
+
return out.replace(ASSIGN_RE, (_m, pre) => `${pre}[REDACTED:credential assignment]`);
|
|
35
|
+
} catch { return '[REDACTION-FAILED]'; }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const SUPERSEDE_RE = /\b(instead|no longer|actually|ignore (?:the )?(?:previous|earlier|above)|supersede[sd]?|scrap that|forget (?:that|it)|do not|don't|thay vì|bỏ qua|không cần nữa)\b/i;
|
|
39
|
+
const SYSTEM_PREFIX_RE = /^(<|Caveat:|\[Request interrupted|\[ukit|This session is being continued|Stop hook feedback|UserPromptSubmit hook|\[Image)/;
|
|
40
|
+
|
|
41
|
+
function userText(content) {
|
|
42
|
+
let t = '';
|
|
43
|
+
if (typeof content === 'string') t = content;
|
|
44
|
+
else if (Array.isArray(content)) t = content.filter((b) => b && b.type === 'text' && typeof b.text === 'string').map((b) => b.text).join('\n');
|
|
45
|
+
t = t.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').trim();
|
|
46
|
+
if (!t || SYSTEM_PREFIX_RE.test(t)) return '';
|
|
47
|
+
return t;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Stream the transcript once. Bounded: first prompt + last PROMPT_KEEP_TAIL prompts, capped text. */
|
|
51
|
+
export async function scanTranscript(transcriptPath) {
|
|
52
|
+
const out = {
|
|
53
|
+
ok: false, lines: 0, skippedLines: 0, promptCount: 0, prompts: [], todos: [], tasks: new Map(),
|
|
54
|
+
pendingTools: [], lastAssistantText: '', gitBranch: '', cwd: '', sessionId: '',
|
|
55
|
+
};
|
|
56
|
+
if (!transcriptPath) return out;
|
|
57
|
+
let stream;
|
|
58
|
+
try { await fsp.access(transcriptPath, fs.constants.R_OK); } catch { return out; }
|
|
59
|
+
const pending = new Map();
|
|
60
|
+
let lastAssistantLine = '';
|
|
61
|
+
let first = null;
|
|
62
|
+
const tail = [];
|
|
63
|
+
try {
|
|
64
|
+
stream = fs.createReadStream(transcriptPath, { encoding: 'utf8' });
|
|
65
|
+
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
66
|
+
for await (const line of rl) {
|
|
67
|
+
out.lines += 1;
|
|
68
|
+
if (!line || line.length > MAX_LINE_CHARS) { if (line) out.skippedLines += 1; continue; }
|
|
69
|
+
// Cheap regex pass: tool pairing without parsing (tool_result lines can be huge).
|
|
70
|
+
if (line.includes('"tool_use_id"')) for (const m of line.matchAll(/"tool_use_id":"([^"]+)"/g)) pending.delete(m[1]);
|
|
71
|
+
if (line.includes('"tool_use"')) {
|
|
72
|
+
for (const m of line.matchAll(/"type":"tool_use","id":"([^"]+)","name":"([^"]+)"/g)) {
|
|
73
|
+
pending.set(m[1], m[2]);
|
|
74
|
+
if (pending.size > 64) pending.delete(pending.keys().next().value);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const isUser = line.includes('"type":"user"');
|
|
78
|
+
const isAssistant = !isUser && line.includes('"type":"assistant"');
|
|
79
|
+
if (isUser && !line.includes('"type":"tool_result"')) {
|
|
80
|
+
let o; try { o = JSON.parse(line); } catch { out.skippedLines += 1; continue; }
|
|
81
|
+
if (o.gitBranch) out.gitBranch = String(o.gitBranch);
|
|
82
|
+
if (o.cwd) out.cwd = String(o.cwd);
|
|
83
|
+
if (o.sessionId) out.sessionId = String(o.sessionId);
|
|
84
|
+
if (o.isMeta || o.isSidechain || o.isCompactSummary) continue;
|
|
85
|
+
const text = userText(o.message?.content);
|
|
86
|
+
if (!text) continue;
|
|
87
|
+
out.promptCount += 1;
|
|
88
|
+
const rec = {
|
|
89
|
+
id: `T${out.promptCount}`, ts: o.timestamp || null,
|
|
90
|
+
text: redact(text.slice(0, PROMPT_TEXT_MAX)), supersedes: SUPERSEDE_RE.test(text.slice(0, PROMPT_TEXT_MAX)),
|
|
91
|
+
};
|
|
92
|
+
if (out.promptCount === 1) first = rec; else { tail.push(rec); if (tail.length > PROMPT_KEEP_TAIL) tail.shift(); }
|
|
93
|
+
} else if (isAssistant) {
|
|
94
|
+
if (/"name":"(?:TodoWrite|TaskCreate|TaskUpdate)"/.test(line)) {
|
|
95
|
+
let o; try { o = JSON.parse(line); } catch { out.skippedLines += 1; continue; }
|
|
96
|
+
for (const b of Array.isArray(o.message?.content) ? o.message.content : []) {
|
|
97
|
+
if (b?.type !== 'tool_use') continue;
|
|
98
|
+
const inp = b.input || {};
|
|
99
|
+
if (b.name === 'TodoWrite' && Array.isArray(inp.todos)) {
|
|
100
|
+
out.todos = inp.todos.slice(0, 100).map((t) => ({ content: redact(String(t?.content ?? t?.subject ?? '').slice(0, 200)), status: String(t?.status || 'pending') }));
|
|
101
|
+
} else if (b.name === 'TaskCreate') {
|
|
102
|
+
const id = String(out.tasks.size + 1);
|
|
103
|
+
if (out.tasks.size < 200) out.tasks.set(id, { content: redact(String(inp.subject || inp.description || '').slice(0, 200)), status: 'pending' });
|
|
104
|
+
} else if (b.name === 'TaskUpdate' && inp.taskId != null) {
|
|
105
|
+
const t = out.tasks.get(String(inp.taskId));
|
|
106
|
+
if (t && inp.status) t.status = String(inp.status);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
} else if (line.includes('"type":"text"') && line.length <= 256 * 1024) {
|
|
110
|
+
lastAssistantLine = line;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
out.ok = true;
|
|
115
|
+
} catch { /* partial scan is still useful */ } finally { try { stream?.destroy(); } catch { /* ignore */ } }
|
|
116
|
+
out.prompts = [first, ...tail].filter(Boolean);
|
|
117
|
+
out.pendingTools = [...pending].map(([id, name]) => ({ id, name }));
|
|
118
|
+
if (lastAssistantLine) {
|
|
119
|
+
try {
|
|
120
|
+
const o = JSON.parse(lastAssistantLine);
|
|
121
|
+
const t = (Array.isArray(o.message?.content) ? o.message.content : []).filter((b) => b?.type === 'text').map((b) => b.text).join(' ');
|
|
122
|
+
out.lastAssistantText = redact(t.replace(/\s+/g, ' ').slice(0, 300));
|
|
123
|
+
} catch { /* ignore */ }
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function git(root, args) {
|
|
129
|
+
return new Promise((resolve) => {
|
|
130
|
+
try {
|
|
131
|
+
execFile('git', args, { cwd: root, timeout: GIT_TIMEOUT_MS, maxBuffer: 1024 * 1024, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' } },
|
|
132
|
+
(err, stdout) => resolve(err ? null : String(stdout)));
|
|
133
|
+
} catch { resolve(null); }
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export async function readGit(root) {
|
|
138
|
+
const [head, branch, status] = await Promise.all([
|
|
139
|
+
git(root, ['rev-parse', 'HEAD']), git(root, ['rev-parse', '--abbrev-ref', 'HEAD']), git(root, ['status', '--porcelain']),
|
|
140
|
+
]);
|
|
141
|
+
if (head == null) return { ok: false, head: '', branch: '', dirty: 0, dirtyPaths: [] };
|
|
142
|
+
const lines = (status || '').split('\n').filter(Boolean);
|
|
143
|
+
return {
|
|
144
|
+
ok: true, head: head.trim(), branch: (branch || '').trim(), dirty: lines.length,
|
|
145
|
+
dirtyPaths: lines.slice(0, 10).map((l) => redact(l.slice(3).slice(0, 120))),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function readJsonSafe(file, maxBytes = LEDGER_MAX_BYTES) {
|
|
150
|
+
try {
|
|
151
|
+
const st = await fsp.stat(file);
|
|
152
|
+
if (st.size > maxBytes) return null;
|
|
153
|
+
return JSON.parse(await fsp.readFile(file, 'utf8'));
|
|
154
|
+
} catch { return null; }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function findLedger(root, sessionId) {
|
|
158
|
+
const dir = path.join(root, '.ukit', 'storage', 'cache', 'exec-ledger');
|
|
159
|
+
const safe = (s) => String(s).replace(/[^A-Za-z0-9_.-]/g, '_');
|
|
160
|
+
if (sessionId) {
|
|
161
|
+
const j = await readJsonSafe(path.join(dir, `${safe(sessionId)}.json`));
|
|
162
|
+
if (j) return { file: path.join(dir, `${safe(sessionId)}.json`), ledger: j };
|
|
163
|
+
}
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const isPassingVerification = (r) => r && r.success === true
|
|
168
|
+
&& (r.kind === 'verification' || r.kind === 'write' || r.kind === 'operation' || r.kind === 'source')
|
|
169
|
+
&& (r.kind !== 'verification' || r.exitCode === 0 || r.exitCode === undefined || r.verdict?.kind === 'test-verified' || r.verdict?.kind === 'live-verified');
|
|
170
|
+
const MIGRATE_RE = /\bmigrat(?:e|ion|ions)\b/i;
|
|
171
|
+
|
|
172
|
+
async function readJournal(root) {
|
|
173
|
+
const res = { missionId: null, prompts: [], note: '' };
|
|
174
|
+
try {
|
|
175
|
+
const active = await readJsonSafe(path.join(root, '.ukit', 'storage', 'mission', 'active.json'), 1024 * 1024);
|
|
176
|
+
if (!active) return res;
|
|
177
|
+
res.missionId = active.activeMissionId || null;
|
|
178
|
+
if (!res.missionId) return res;
|
|
179
|
+
const url = pathToFileURL(path.join(MODULE_DIR, '..', 'mission', 'journal.mjs')).href;
|
|
180
|
+
let mod = null;
|
|
181
|
+
try { mod = await import(url); } catch { res.note = 'mission journal module unavailable'; return res; }
|
|
182
|
+
if (typeof mod.listPrompts !== 'function') return res;
|
|
183
|
+
const list = mod.listPrompts(root, res.missionId, { origin: 'user' }) || [];
|
|
184
|
+
res.prompts = list.slice(-PROMPT_KEEP_TAIL).map((p) => ({ id: String(p.promptId), ts: p.ts || null, text: redact(String(p.text || '').slice(0, PROMPT_TEXT_MAX)), supersedes: SUPERSEDE_RE.test(String(p.text || '')) }));
|
|
185
|
+
} catch { res.note = 'mission journal unreadable'; }
|
|
186
|
+
return res;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const norm = (s) => String(s || '').replace(/\s+/g, ' ').trim().slice(0, 200).toLowerCase();
|
|
190
|
+
|
|
191
|
+
export async function reconstructMission({ projectRoot, transcriptPath, sessionId, expected, now = Date.now() } = {}) {
|
|
192
|
+
const root = projectRoot || process.cwd();
|
|
193
|
+
const notes = [];
|
|
194
|
+
const [tx, jr, gi] = await Promise.all([scanTranscript(transcriptPath), readJournal(root), readGit(root)]);
|
|
195
|
+
if (transcriptPath && !tx.ok) notes.push('transcript unreadable');
|
|
196
|
+
if (tx.skippedLines) notes.push(`${tx.skippedLines} transcript line(s) skipped (corrupt or oversized)`);
|
|
197
|
+
if (jr.note) notes.push(jr.note);
|
|
198
|
+
const sid = sessionId || tx.sessionId || (transcriptPath ? path.basename(String(transcriptPath), '.jsonl') : '');
|
|
199
|
+
const items = [];
|
|
200
|
+
const add = (item) => { items.push({ ...item, id: item.id || `${item.kind}-${items.length + 1}` }); };
|
|
201
|
+
|
|
202
|
+
// Prompts: journal wins; transcript prompts not present in the journal are added.
|
|
203
|
+
const jnorm = new Set(jr.prompts.map((p) => norm(p.text)));
|
|
204
|
+
const tnorm = new Set(tx.prompts.map((p) => norm(p.text)));
|
|
205
|
+
const prompts = [...jr.prompts.map((p) => ({ ...p, source: 'journal' })),
|
|
206
|
+
...tx.prompts.filter((p) => !jnorm.has(norm(p.text))).map((p) => ({ ...p, source: 'transcript' }))];
|
|
207
|
+
prompts.sort((a, b) => (Date.parse(a.ts) || 0) - (Date.parse(b.ts) || 0));
|
|
208
|
+
// Case 9: journaled after the last executed (transcript) prompt, never seen in the transcript.
|
|
209
|
+
let pendingPrompts = [];
|
|
210
|
+
if (tx.ok && tx.prompts.length) {
|
|
211
|
+
const lastT = Math.max(...tx.prompts.map((p) => Date.parse(p.ts) || 0));
|
|
212
|
+
pendingPrompts = jr.prompts.filter((p) => !tnorm.has(norm(p.text)) && (Date.parse(p.ts) || p.ts || 0) > lastT).map((p) => p.id);
|
|
213
|
+
}
|
|
214
|
+
prompts.forEach((p, i) => {
|
|
215
|
+
add({ kind: 'prompt', id: p.id, text: p.text, class: 'RECOVERED_FROM_SOURCE', source: p.source, supersedes: p.supersedes,
|
|
216
|
+
pendingExecution: pendingPrompts.includes(p.id), order: i });
|
|
217
|
+
});
|
|
218
|
+
if (!prompts.length) add({ kind: 'prompt-missing', text: 'No original user prompt recovered; do not invent requirements.', class: 'UNKNOWN', source: 'none' });
|
|
219
|
+
|
|
220
|
+
// Todos: always INFERRED_UNVERIFIED regardless of "completed".
|
|
221
|
+
const todoList = tx.todos.length ? tx.todos : [...tx.tasks.values()];
|
|
222
|
+
for (const t of todoList) add({ kind: 'todo', text: t.content, status: t.status, class: 'INFERRED_UNVERIFIED', source: 'transcript-todo' });
|
|
223
|
+
|
|
224
|
+
// Ledger receipts.
|
|
225
|
+
const led = await findLedger(root, sid);
|
|
226
|
+
const receipts = Array.isArray(led?.ledger?.receipts) ? led.ledger.receipts.slice(-40) : [];
|
|
227
|
+
for (const r of receipts) {
|
|
228
|
+
const label = redact(String(r.command || r.file || r.toolName || r.kind || '').slice(0, 160));
|
|
229
|
+
const denied = r.status === 'denied' || r.class === 'denied' || r.verdict?.kind === 'blocked';
|
|
230
|
+
if (denied) add({ kind: 'denied', text: label, class: 'BLOCKED', source: 'ledger' });
|
|
231
|
+
else if (isPassingVerification(r)) {
|
|
232
|
+
add({ kind: 'receipt', text: label, receiptKind: r.kind, class: 'VERIFIED', source: 'ledger', migration: MIGRATE_RE.test(String(r.command || '')) });
|
|
233
|
+
} else if (r.success === false) add({ kind: 'failure', text: label, receiptKind: r.kind, class: 'RECOVERED_FROM_SOURCE', source: 'ledger' });
|
|
234
|
+
}
|
|
235
|
+
if (led?.ledger?.blocker) add({ kind: 'blocker', text: redact(typeof led.ledger.blocker === 'string' ? led.ledger.blocker : JSON.stringify(led.ledger.blocker)).slice(0, 200), class: 'BLOCKED', source: 'ledger' });
|
|
236
|
+
|
|
237
|
+
// Case 10/11: tool calls (incl. subagents) with no result may have executed.
|
|
238
|
+
for (const t of tx.pendingTools.slice(-8)) {
|
|
239
|
+
const sub = t.name === 'Task' || t.name === 'Agent';
|
|
240
|
+
add({ kind: sub ? 'subagent-active' : 'tool-unresolved', text: `${t.name} call without recorded result; it may have executed`, class: 'UNKNOWN', source: 'transcript' });
|
|
241
|
+
}
|
|
242
|
+
if (tx.lastAssistantText) add({ kind: 'assistant-claim', text: tx.lastAssistantText, class: 'INFERRED_UNVERIFIED', source: 'transcript-assistant' });
|
|
243
|
+
|
|
244
|
+
// Git.
|
|
245
|
+
if (gi.ok) {
|
|
246
|
+
add({ kind: 'git', text: `HEAD ${gi.head.slice(0, 12)} on ${gi.branch}`, class: 'RECOVERED_FROM_SOURCE', source: 'git' });
|
|
247
|
+
if (gi.dirty) add({ kind: 'git-dirty', text: `${gi.dirty} uncommitted path(s): ${gi.dirtyPaths.join(', ')}`, class: 'RECOVERED_FROM_SOURCE', source: 'git' });
|
|
248
|
+
} else add({ kind: 'git', text: 'git state unavailable', class: 'UNKNOWN', source: 'git' });
|
|
249
|
+
|
|
250
|
+
// Owner STOP (route-state sidecar for the session).
|
|
251
|
+
let ownerStop = false;
|
|
252
|
+
if (sid) {
|
|
253
|
+
const rs = await readJsonSafe(path.join(root, '.ukit', 'storage', 'cache', 'route-state', `${String(sid).replace(/[^A-Za-z0-9_.-]/g, '_')}.json`), 1024 * 1024);
|
|
254
|
+
ownerStop = rs?.ownerControl?.kind === 'stop';
|
|
255
|
+
}
|
|
256
|
+
if (ownerStop) add({ kind: 'owner-stop', text: 'Owner STOP in effect', class: 'RECOVERED_FROM_SOURCE', source: 'route-state' });
|
|
257
|
+
|
|
258
|
+
// Identity expectation: explicit > transcript branch/cwd.
|
|
259
|
+
const exp = { branch: expected?.branch || tx.gitBranch || '', head: expected?.head || '', cwd: expected?.cwd || tx.cwd || '' };
|
|
260
|
+
const mismatch = [];
|
|
261
|
+
if (gi.ok && exp.branch && gi.branch && exp.branch !== gi.branch) mismatch.push(`branch ${exp.branch} -> ${gi.branch}`);
|
|
262
|
+
if (gi.ok && exp.head && gi.head && !gi.head.startsWith(exp.head) && !exp.head.startsWith(gi.head)) mismatch.push(`HEAD ${exp.head.slice(0, 12)} -> ${gi.head.slice(0, 12)}`);
|
|
263
|
+
if (exp.cwd && path.resolve(exp.cwd) !== path.resolve(root)) mismatch.push(`cwd ${exp.cwd} -> ${root}`);
|
|
264
|
+
|
|
265
|
+
return {
|
|
266
|
+
schema: 1, now, projectRoot: root, sessionId: sid, transcriptPath: transcriptPath || '', missionId: jr.missionId,
|
|
267
|
+
ledgerFile: led?.file || '', git: gi, ownerStop, identityMismatch: mismatch, expected: exp, notes,
|
|
268
|
+
promptCount: tx.promptCount || jr.prompts.length, items,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** Alias consumed by `ukit rescue rebuild`. */
|
|
273
|
+
export const reconstruct = reconstructMission;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// recovery-state.mjs - recovery state machine (WP-R2): allowed-transition table, atomic tmp+rename
|
|
2
|
+
// under a lock, eventId dedupe ring, CONFLICT on stale `from`, epoch fencing, circuit breaker.
|
|
3
|
+
import fsp from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { withAsyncLock } from '../async-lock.mjs';
|
|
6
|
+
|
|
7
|
+
export const STATES = Object.freeze([
|
|
8
|
+
'HEALTHY', 'PRESSURE', 'CHECKPOINTED', 'COMPACTING', 'COMPACT_FAILED', 'RECOVERING',
|
|
9
|
+
'RECONSTRUCTED', 'ROLLOVER_PENDING', 'ROLLED_OVER', 'RESTORED', 'BLOCKED', 'PAUSED_OWNER_STOP',
|
|
10
|
+
]);
|
|
11
|
+
export const TERMINAL = Object.freeze(['BLOCKED', 'PAUSED_OWNER_STOP']);
|
|
12
|
+
|
|
13
|
+
const ACTIVE = STATES.filter((s) => !TERMINAL.includes(s));
|
|
14
|
+
export const TRANSITIONS = Object.freeze(Object.fromEntries(STATES.map((s) => {
|
|
15
|
+
const base = {
|
|
16
|
+
HEALTHY: ['PRESSURE', 'COMPACT_FAILED'],
|
|
17
|
+
PRESSURE: ['CHECKPOINTED', 'HEALTHY'],
|
|
18
|
+
CHECKPOINTED: ['COMPACTING'],
|
|
19
|
+
COMPACTING: ['HEALTHY', 'COMPACT_FAILED'],
|
|
20
|
+
COMPACT_FAILED: ['RECOVERING', 'COMPACTING', 'HEALTHY'],
|
|
21
|
+
RECOVERING: ['RECONSTRUCTED', 'COMPACT_FAILED'],
|
|
22
|
+
RECONSTRUCTED: ['ROLLOVER_PENDING', 'HEALTHY'],
|
|
23
|
+
ROLLOVER_PENDING: ['ROLLED_OVER', 'COMPACT_FAILED'],
|
|
24
|
+
ROLLED_OVER: ['RESTORED'],
|
|
25
|
+
RESTORED: ['HEALTHY'],
|
|
26
|
+
BLOCKED: [],
|
|
27
|
+
PAUSED_OWNER_STOP: [],
|
|
28
|
+
}[s];
|
|
29
|
+
// Any live state may end in a terminal state (auth block, owner stop/cancel) and may observe a failure.
|
|
30
|
+
const extra = ACTIVE.includes(s) ? ['BLOCKED', 'PAUSED_OWNER_STOP', ...(s === 'HEALTHY' ? [] : s === 'COMPACT_FAILED' ? [] : ['COMPACT_FAILED'])] : [];
|
|
31
|
+
return [s, [...new Set([...base, ...extra])]];
|
|
32
|
+
})));
|
|
33
|
+
|
|
34
|
+
export const RING_SIZE = 64;
|
|
35
|
+
export const MAX_ATTEMPTS = 2;
|
|
36
|
+
export const BREAKER_FAILURES = 3;
|
|
37
|
+
export const BREAKER_WINDOW_MS = 15 * 60 * 1000;
|
|
38
|
+
export const BREAKER_OPEN_MS = 15 * 60 * 1000;
|
|
39
|
+
const ATTEMPT_STATES = new Set(['RECOVERING', 'ROLLOVER_PENDING']);
|
|
40
|
+
const LOCK_MS = 8000;
|
|
41
|
+
|
|
42
|
+
export function stateFile(root, missionId) {
|
|
43
|
+
const base = path.join(root, '.ukit', 'storage');
|
|
44
|
+
return missionId
|
|
45
|
+
? path.join(base, 'mission', String(missionId).replace(/[^A-Za-z0-9_.-]/g, '_'), 'recovery.json')
|
|
46
|
+
: path.join(base, 'rescue', 'recovery.json');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const fresh = () => ({ state: 'HEALTHY', epoch: 0, version: 0, ring: [], breaker: {}, history: [] });
|
|
50
|
+
|
|
51
|
+
export async function readState({ root, missionId }) {
|
|
52
|
+
try { return { ...fresh(), ...JSON.parse(await fsp.readFile(stateFile(root, missionId), 'utf8')) }; } catch { return fresh(); }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function writeAtomic(file, data) {
|
|
56
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
57
|
+
await fsp.writeFile(tmp, JSON.stringify(data));
|
|
58
|
+
await fsp.rename(tmp, file);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function breakerStatus(st, fingerprint, now = Date.now()) {
|
|
62
|
+
const b = st.breaker?.[fingerprint];
|
|
63
|
+
if (!b) return { open: false, attempts: 0 };
|
|
64
|
+
return { open: !!b.openUntil && b.openUntil > now, openUntil: b.openUntil || 0, attempts: b.attempts || 0 };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* transition({root, missionId?, from, to, eventId, reason, epoch?, fingerprint?, failure?, now?})
|
|
69
|
+
* Returns {ok:true, state, applied, duplicate?} or {ok:false, code}:
|
|
70
|
+
* INVALID | INVALID_TRANSITION | CONFLICT | STALE_EPOCH | BREAKER_OPEN | BUSY.
|
|
71
|
+
*/
|
|
72
|
+
export async function transition({ root, missionId, from, to, eventId, reason = '', epoch, fingerprint, failure = false, now = Date.now() } = {}) {
|
|
73
|
+
if (!root || !STATES.includes(from) || !STATES.includes(to) || !eventId) return { ok: false, code: 'INVALID' };
|
|
74
|
+
const file = stateFile(root, missionId);
|
|
75
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
76
|
+
const res = await withAsyncLock(file, { deadlineMs: LOCK_MS }, async () => {
|
|
77
|
+
const st = await readState({ root, missionId });
|
|
78
|
+
if (st.ring.includes(eventId)) return { ok: true, state: st.state, applied: false, duplicate: true };
|
|
79
|
+
if (Number.isFinite(epoch) && epoch < st.epoch) return { ok: false, code: 'STALE_EPOCH', epoch: st.epoch };
|
|
80
|
+
if (st.state !== from) return { ok: false, code: 'CONFLICT', current: st.state };
|
|
81
|
+
if (!TRANSITIONS[from].includes(to)) return { ok: false, code: 'INVALID_TRANSITION' };
|
|
82
|
+
if (fingerprint && ATTEMPT_STATES.has(to)) {
|
|
83
|
+
const bs = breakerStatus(st, fingerprint, now);
|
|
84
|
+
if (bs.open || bs.attempts >= MAX_ATTEMPTS) return { ok: false, code: 'BREAKER_OPEN', openUntil: bs.openUntil };
|
|
85
|
+
}
|
|
86
|
+
const next = { ...st, state: to, version: st.version + 1, updatedAt: now, reason: String(reason).slice(0, 120) };
|
|
87
|
+
if (Number.isFinite(epoch)) next.epoch = epoch;
|
|
88
|
+
next.ring = [...st.ring, eventId].slice(-RING_SIZE);
|
|
89
|
+
next.history = [...(st.history || []), { at: now, from, to, eventId }].slice(-32);
|
|
90
|
+
if (fingerprint) {
|
|
91
|
+
const b = { attempts: 0, failures: [], ...(st.breaker[fingerprint] || {}) };
|
|
92
|
+
if (ATTEMPT_STATES.has(to)) b.attempts += 1;
|
|
93
|
+
if (failure) {
|
|
94
|
+
b.failures = [...b.failures.filter((t) => now - t < BREAKER_WINDOW_MS), now];
|
|
95
|
+
if (b.failures.length >= BREAKER_FAILURES) b.openUntil = now + BREAKER_OPEN_MS;
|
|
96
|
+
}
|
|
97
|
+
next.breaker = { ...st.breaker, [fingerprint]: b };
|
|
98
|
+
}
|
|
99
|
+
await writeAtomic(file, next);
|
|
100
|
+
return { ok: true, state: to, applied: true, version: next.version };
|
|
101
|
+
});
|
|
102
|
+
return res.ok ? res.value : { ok: false, code: 'BUSY' };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Record a same-state failure for the breaker (no state change). Deduped by eventId. */
|
|
106
|
+
export async function recordFailure({ root, missionId, fingerprint, eventId, now = Date.now() } = {}) {
|
|
107
|
+
if (!root || !fingerprint || !eventId) return { ok: false, code: 'INVALID' };
|
|
108
|
+
const file = stateFile(root, missionId);
|
|
109
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
110
|
+
const res = await withAsyncLock(file, { deadlineMs: LOCK_MS }, async () => {
|
|
111
|
+
const st = await readState({ root, missionId });
|
|
112
|
+
if (st.ring.includes(eventId)) return { ok: true, applied: false, duplicate: true };
|
|
113
|
+
const b = { attempts: 0, failures: [], ...(st.breaker[fingerprint] || {}) };
|
|
114
|
+
b.failures = [...b.failures.filter((t) => now - t < BREAKER_WINDOW_MS), now];
|
|
115
|
+
if (b.failures.length >= BREAKER_FAILURES) b.openUntil = now + BREAKER_OPEN_MS;
|
|
116
|
+
await writeAtomic(file, { ...st, ring: [...st.ring, eventId].slice(-RING_SIZE), breaker: { ...st.breaker, [fingerprint]: b } });
|
|
117
|
+
return { ok: true, applied: true, open: !!b.openUntil && b.openUntil > now };
|
|
118
|
+
});
|
|
119
|
+
return res.ok ? res.value : { ok: false, code: 'BUSY' };
|
|
120
|
+
}
|