@fractalsynapse/dsh-chapters 0.2.56 → 0.2.58
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/docs/project-state.md +16 -0
- package/lib/commands.d.ts +1 -0
- package/lib/commands.js +6 -4
- package/lib/commands.js.map +1 -1
- package/lib/engine.js +1 -0
- package/lib/engine.js.map +1 -1
- package/lib/enrich-lease.d.ts +35 -0
- package/lib/enrich-lease.js +60 -0
- package/lib/enrich-lease.js.map +1 -0
- package/lib/enrich-queue.d.ts +6 -0
- package/lib/enrich-queue.js +72 -32
- package/lib/enrich-queue.js.map +1 -1
- package/lib/enrich-wire.d.ts +13 -0
- package/lib/enrich-wire.js +227 -4
- package/lib/enrich-wire.js.map +1 -1
- package/lib/index.js +3 -0
- package/lib/index.js.map +1 -1
- package/lib/rules-commands.d.ts +8 -0
- package/lib/rules-commands.js +23 -1
- package/lib/rules-commands.js.map +1 -1
- package/lib/version.d.ts +1 -1
- package/lib/version.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* #578: THE DRAIN LEASE, one predicate for every pump that touches the shared per-home registry.
|
|
3
|
+
* Extracted from #571's queue-internal lease so the enrichment drain and the human-only rules
|
|
4
|
+
* reprocess cannot each invent their own idea of "someone else is pumping this" — two pumps, one
|
|
5
|
+
* lock, one stale-lease takeover rule. The holder writes {plane, at, token} under one settings
|
|
6
|
+
* key; fresh means under TTL; a stale lease is taken over LOUDLY (the caller logs it) because a
|
|
7
|
+
* lease that permanently starves every pump is worse than the race it prevents.
|
|
8
|
+
*/
|
|
9
|
+
export const LEASE_KEY = 'enrichment.drainLease';
|
|
10
|
+
export const LEASE_TTL_MS = 20 * 60_000;
|
|
11
|
+
export function createDrainLease(spine, label) {
|
|
12
|
+
const token = Math.random().toString(36).slice(2);
|
|
13
|
+
const read = () => {
|
|
14
|
+
try {
|
|
15
|
+
const raw = spine.get(LEASE_KEY);
|
|
16
|
+
if (raw === undefined || raw === '')
|
|
17
|
+
return undefined;
|
|
18
|
+
return JSON.parse(raw);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
const fresh = (l) => l !== undefined && typeof l.at === 'number' && Date.now() - l.at < LEASE_TTL_MS;
|
|
25
|
+
return {
|
|
26
|
+
label,
|
|
27
|
+
read,
|
|
28
|
+
heldByOther: () => {
|
|
29
|
+
const cur = read();
|
|
30
|
+
return fresh(cur) && cur?.token !== token ? (typeof cur?.plane === 'string' ? cur.plane : 'another pump') : undefined;
|
|
31
|
+
},
|
|
32
|
+
claim: () => {
|
|
33
|
+
const cur = read();
|
|
34
|
+
if (fresh(cur) && cur?.token !== token)
|
|
35
|
+
return false;
|
|
36
|
+
spine.put(LEASE_KEY, JSON.stringify({ plane: label, at: Date.now(), token }));
|
|
37
|
+
return true;
|
|
38
|
+
},
|
|
39
|
+
release: () => {
|
|
40
|
+
const cur = read();
|
|
41
|
+
if (cur?.token === token)
|
|
42
|
+
spine.put(LEASE_KEY, undefined);
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** One route decision for every mining caller (#578): spec → {provider, model} or undefined for
|
|
47
|
+
* "rides the annotation route". ladder and reprocess share it so the printed mining route and
|
|
48
|
+
* the route actually used cannot drift apart. */
|
|
49
|
+
export function mineRouteOf(spec, fallback) {
|
|
50
|
+
const s = spec.trim();
|
|
51
|
+
if (s === '' || s === 'conversation')
|
|
52
|
+
return undefined;
|
|
53
|
+
const sep = s.indexOf('/');
|
|
54
|
+
if (sep > 0)
|
|
55
|
+
return { provider: s.slice(0, sep), model: s.slice(sep + 1) };
|
|
56
|
+
return fallback !== null && fallback !== undefined
|
|
57
|
+
? { provider: fallback.provider, model: s }
|
|
58
|
+
: undefined;
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=enrich-lease.js.map
|
|
@@ -0,0 +1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SAAS,CAAA;AACf,CAAC"}
|
package/lib/enrich-queue.d.ts
CHANGED
|
@@ -33,6 +33,7 @@ export interface EnrichQueueDeps {
|
|
|
33
33
|
enrichOne: (key: string) => Promise<{
|
|
34
34
|
ok: boolean;
|
|
35
35
|
skipped?: string;
|
|
36
|
+
resynced?: boolean;
|
|
36
37
|
}>;
|
|
37
38
|
/** current enrichment model id ('' = resolver said: conversation model — queue still needs a concrete string for keys) */
|
|
38
39
|
resolveModel: () => Promise<string>;
|
|
@@ -41,6 +42,10 @@ export interface EnrichQueueDeps {
|
|
|
41
42
|
idleMs: number;
|
|
42
43
|
batchCap: number;
|
|
43
44
|
log: (msg: string) => void;
|
|
45
|
+
/** #571: shared drain lease over the per-home registry (settings spine). */
|
|
46
|
+
getSetting?: (key: string) => string | undefined;
|
|
47
|
+
putSetting?: (key: string, value: string | undefined) => void | Promise<void>;
|
|
48
|
+
planeId?: string;
|
|
44
49
|
/** injectable timer for tests */
|
|
45
50
|
setTimer?: (fn: () => void, ms: number) => {
|
|
46
51
|
cancel: () => void;
|
|
@@ -60,6 +65,7 @@ export interface EnrichQueue {
|
|
|
60
65
|
started: boolean;
|
|
61
66
|
alreadyRunning: boolean;
|
|
62
67
|
pendingEstimate: number;
|
|
68
|
+
leaseHeldBy?: string;
|
|
63
69
|
};
|
|
64
70
|
/** #565: is a full drain currently running (the report surface prints its state). */
|
|
65
71
|
isDraining: () => boolean;
|
package/lib/enrich-queue.js
CHANGED
|
@@ -1,28 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
* P2 S2 — the enrichment queue: one queue, pluggable triggers, hard idle
|
|
3
|
-
* guarantee (record §6.2, plan decisions).
|
|
4
|
-
*
|
|
5
|
-
* Isomorphic factory (host plane + realm engine each own an instance, like
|
|
6
|
-
* createSyncScheduler). Providers are the ONLY variance:
|
|
7
|
-
* afterPush — schedule(reason) called after each completed sync pass
|
|
8
|
-
* idle — a resettable debounce timer (enrichment.idleMs)
|
|
9
|
-
* both — the default
|
|
10
|
-
* manual — no auto triggers; the /chapters-enrich run command drains
|
|
11
|
-
*
|
|
12
|
-
* Invariants this module owns:
|
|
13
|
-
* - NEVER in a hot path: enrichOne is only reached from drain(), and
|
|
14
|
-
* drain() is only fired by trigger events that already completed the
|
|
15
|
-
* user's work (post-push) or by silence (idle) or a command.
|
|
16
|
-
* - Idempotency key = chapter number + rootSession + model. Re-enqueue
|
|
17
|
-
* after vocab change is NOT needed (vocab affects canonicalization at
|
|
18
|
-
* index build, not the model call); after a MODEL change it IS (key
|
|
19
|
-
* includes model, so the key naturally changes).
|
|
20
|
-
* - enabled:false ⇒ every entry point is a pure no-op (kill-switch exit
|
|
21
|
-
* criterion: the corpus stays fully functional, signatures-only).
|
|
22
|
-
* - Cross-plane double-run: the caller-supplied lock (store-dir, same
|
|
23
|
-
* pattern as sync's acquireLock) makes the realm + host queues safe on
|
|
24
|
-
* one workspace.
|
|
25
|
-
*/
|
|
1
|
+
import { createDrainLease } from "./enrich-lease.js";
|
|
26
2
|
export function createEnrichQueue(deps) {
|
|
27
3
|
let idleTimer = null;
|
|
28
4
|
let draining = null;
|
|
@@ -40,6 +16,19 @@ export function createEnrichQueue(deps) {
|
|
|
40
16
|
};
|
|
41
17
|
let fullDrain = null;
|
|
42
18
|
let disposed = false;
|
|
19
|
+
// #571 CROSS-PLANE LEASE. Two queues (host-plane manual, realm-plane boundary) drain the SAME
|
|
20
|
+
// per-home registry; concurrent pumps are what split file writes from registry commits (354
|
|
21
|
+
// stale records, live-measured). The holder writes {plane, at, token} to the settings spine;
|
|
22
|
+
// freshness is bounded — a crashed holder's lease goes stale and the next claimer takes it
|
|
23
|
+
// LOUDLY, because a lease that permanently starves every drain is worse than the race it
|
|
24
|
+
// prevents. Unwired planes (tests, old wiring) fall back to today's per-queue behavior.
|
|
25
|
+
const lease = createDrainLease(deps.getSetting !== undefined && deps.putSetting !== undefined
|
|
26
|
+
? { get: deps.getSetting, put: (k, v) => void deps.putSetting(k, v) }
|
|
27
|
+
: { get: () => undefined, put: () => undefined }, // unwired: legacy per-queue behavior
|
|
28
|
+
deps.planeId ?? 'plane');
|
|
29
|
+
// #571: per-pass outcome split — the pump distinguishes transient failure from done.
|
|
30
|
+
let lastAttempted = 0;
|
|
31
|
+
let lastErrored = 0;
|
|
43
32
|
const setTimer = deps.setTimer ?? ((fn, ms) => {
|
|
44
33
|
const t = setTimeout(fn, ms);
|
|
45
34
|
return { cancel: () => clearTimeout(t) };
|
|
@@ -55,6 +44,10 @@ export function createEnrichQueue(deps) {
|
|
|
55
44
|
deps.log('enrichment drain skipped: disabled (enrichmentEnabled=false)');
|
|
56
45
|
return Promise.resolve(0);
|
|
57
46
|
}
|
|
47
|
+
if (!forced && lease.heldByOther() !== undefined) {
|
|
48
|
+
deps.log(`enrichment drain skipped: ${lease.heldByOther()} holds the drain lease (#571)`);
|
|
49
|
+
return Promise.resolve(0);
|
|
50
|
+
}
|
|
58
51
|
if (!forced && deps.trigger === 'manual') {
|
|
59
52
|
deps.log('enrichment drain skipped: trigger=manual — only /chapters-enrich run drains it');
|
|
60
53
|
return Promise.resolve(0);
|
|
@@ -75,6 +68,8 @@ export function createEnrichQueue(deps) {
|
|
|
75
68
|
if (pending.length === 0)
|
|
76
69
|
deps.log(`enrichment drain: pending=0 via ${model} (trigger=${deps.trigger}, idleMs=${String(deps.idleMs)})`);
|
|
77
70
|
let done = 0;
|
|
71
|
+
lastAttempted = pending.length;
|
|
72
|
+
lastErrored = 0;
|
|
78
73
|
for (const item of pending) {
|
|
79
74
|
const r = await deps.enrichOne(item.key);
|
|
80
75
|
if (r.ok)
|
|
@@ -83,8 +78,18 @@ export function createEnrichQueue(deps) {
|
|
|
83
78
|
// had nothing, because only successes were ever written. A skip IS a decision with a cause
|
|
84
79
|
// (`skipped:` is the ladder's own label), and an unreported one turns a 420-second poll into
|
|
85
80
|
// an argument — the third time today a queue knew and said nothing (#61a).
|
|
86
|
-
else
|
|
81
|
+
else {
|
|
82
|
+
// #577: and NOTHING ELSE may steal this else. The #571 insertion of the resynced note
|
|
83
|
+
// ABOVE this clause silently re-paired it, so every SUCCESSFUL chapter logged a bogus
|
|
84
|
+
// 'skipped … no reason given' — the misreport that hid successes as failures in the
|
|
85
|
+
// heartbeat. Successes (healed or not) log below; only !r.ok reaches this branch.
|
|
87
86
|
deps.log(`enrichment skipped ${item.key}: ${r.skipped ?? 'no reason given by the ladder'}`);
|
|
87
|
+
if ((r.skipped ?? '').startsWith('error'))
|
|
88
|
+
lastErrored += 1;
|
|
89
|
+
}
|
|
90
|
+
// #577: the resynced note rides AFTER the pairing — additive, never in the if/else chain
|
|
91
|
+
if (r.resynced === true)
|
|
92
|
+
deps.log(`enrichment resynced registry receipt from file: ${item.key} (#571)`);
|
|
88
93
|
}
|
|
89
94
|
lastBatch = done;
|
|
90
95
|
if (done > 0)
|
|
@@ -120,6 +125,11 @@ export function createEnrichQueue(deps) {
|
|
|
120
125
|
const scheduleChase = () => {
|
|
121
126
|
if (!deps.enabled || deps.trigger === 'manual')
|
|
122
127
|
return;
|
|
128
|
+
const chaseHeld = lease.heldByOther(); // #571: a manual drain owns the registry right now — this beat is redundant
|
|
129
|
+
if (chaseHeld !== undefined) {
|
|
130
|
+
deps.log(`enrichment chase deferred: ${chaseHeld} holds the drain lease`);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
123
133
|
stopChase();
|
|
124
134
|
chaseTimer = setTimer(() => {
|
|
125
135
|
chaseTimer = null;
|
|
@@ -156,14 +166,27 @@ export function createEnrichQueue(deps) {
|
|
|
156
166
|
}
|
|
157
167
|
if (fullDrain !== null)
|
|
158
168
|
return { started: false, alreadyRunning: true, pendingEstimate };
|
|
169
|
+
if (!lease.claim()) {
|
|
170
|
+
const held = lease.read();
|
|
171
|
+
return { started: false, alreadyRunning: false, pendingEstimate, leaseHeldBy: typeof held?.plane === 'string' ? held.plane : 'another plane' };
|
|
172
|
+
}
|
|
159
173
|
const budget = limit !== undefined && limit > 0 ? limit : Number.POSITIVE_INFINITY;
|
|
160
174
|
let processed = 0;
|
|
161
175
|
let passes = 0;
|
|
176
|
+
let backoffStreak = 0;
|
|
177
|
+
let transientGaveUp = false;
|
|
178
|
+
let prevDone = 0;
|
|
179
|
+
const BACKOFF_RETRIES = 3;
|
|
180
|
+
const BACKOFF_BASE_MS = 60_000; // 60s, 3m, 9m — setTimer-injected; tests fire by hand, #456-safe
|
|
181
|
+
const sleep = (ms) => new Promise((res) => { setTimer(() => res(), ms); });
|
|
162
182
|
let lastHead;
|
|
163
183
|
fullDrain = (async () => {
|
|
164
184
|
while (!disposed && processed < budget) {
|
|
165
185
|
const head = await nextHead();
|
|
166
|
-
|
|
186
|
+
// #571 refinement: the breaker judges a head that SURVIVED a successful pass — if the
|
|
187
|
+
// last pass processed nothing (errored), retrying the same head is the backoff's job,
|
|
188
|
+
// not stagnation.
|
|
189
|
+
if (head !== undefined && head === lastHead && prevDone > 0) {
|
|
167
190
|
// #565 circuit-breaker: the ladder claimed success but the SAME chapter is still at
|
|
168
191
|
// the head — pending is not shrinking. A chained pump against a non-depleting queue
|
|
169
192
|
// would spin the model forever; stop loudly instead. (The unit fake that never shrinks
|
|
@@ -174,14 +197,31 @@ export function createEnrichQueue(deps) {
|
|
|
174
197
|
}
|
|
175
198
|
lastHead = head;
|
|
176
199
|
const done = await drain(true, Number.isFinite(budget) ? budget - processed : undefined);
|
|
177
|
-
if (done === 0)
|
|
178
|
-
|
|
200
|
+
if (done === 0) {
|
|
201
|
+
// #571: zero processed SPLITS by cause. Items attempted but errored = TRANSIENT (rate
|
|
202
|
+
// limits ride out with exponential backoff — maintainer: 'maybe we have backoff retries
|
|
203
|
+
// so it doesn't just quit'). Zero with no errors = done at this head; end normally.
|
|
204
|
+
if (lastAttempted > 0 && lastErrored > 0 && backoffStreak < BACKOFF_RETRIES) {
|
|
205
|
+
backoffStreak += 1;
|
|
206
|
+
const waitMs = BACKOFF_BASE_MS * 3 ** (backoffStreak - 1);
|
|
207
|
+
deps.log(`enrichment drain: transient model failures (${lastErrored}/${lastAttempted} errored) — retry ${backoffStreak}/${BACKOFF_RETRIES} after ${waitMs / 1000}s`);
|
|
208
|
+
await sleep(waitMs);
|
|
209
|
+
if (disposed)
|
|
210
|
+
break;
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
if (backoffStreak >= BACKOFF_RETRIES && lastErrored > 0)
|
|
214
|
+
transientGaveUp = true;
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
backoffStreak = 0;
|
|
218
|
+
prevDone = done; // empty, failing, or model-unresolvable — drain() names which
|
|
179
219
|
processed += done;
|
|
180
220
|
passes += 1;
|
|
181
221
|
stopChase(); // a boundary chase is redundant under a full drain — one pump at a time
|
|
182
222
|
}
|
|
183
|
-
deps.log(`enrichment full drain ended: ${processed} chapter(s) across ${passes} pass(es)`);
|
|
184
|
-
})().finally(() => { fullDrain = null; });
|
|
223
|
+
deps.log(`enrichment full drain ended: ${processed} chapter(s) across ${passes} pass(es)${transientGaveUp ? ' — TRANSIENT FAILURES PERSISTED after 3 backoff retries; retry later' : ''}`);
|
|
224
|
+
})().finally(() => { fullDrain = null; lease.release(); });
|
|
185
225
|
return { started: true, alreadyRunning: false, pendingEstimate };
|
|
186
226
|
},
|
|
187
227
|
isDraining: () => fullDrain !== null,
|
|
@@ -201,7 +241,7 @@ export function createEnrichQueue(deps) {
|
|
|
201
241
|
lastBatch,
|
|
202
242
|
model: modelCache,
|
|
203
243
|
}),
|
|
204
|
-
dispose: () => { disposed = true; idleTimer?.cancel(); idleTimer = null; stopChase(); }, // #565: the full drain loop checks disposed
|
|
244
|
+
dispose: () => { disposed = true; idleTimer?.cancel(); idleTimer = null; stopChase(); lease.release(); }, // #565: the full drain loop checks disposed
|
|
205
245
|
};
|
|
206
246
|
}
|
|
207
247
|
//# sourceMappingURL=enrich-queue.js.map
|
package/lib/enrich-queue.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"enrich-queue.js","sourceRoot":"","sources":["../src/en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,CAAA;QAC1B,CAAC;QACD,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;YACZ,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,eAAe;YACf,SAAS;YACT,KAAK,EAAE,UAAU;SAClB,CAAC;QACF,OAAO,EAAE,GAAG,EAAE,GAAG,QAAQ,GAAG,IAAI,CAAC,CAAC,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,EAAE,CAAA,CAAC,CAAC,EAAE,4CAA4C;KACtJ,CAAA;AACH,CAAC"}
|
package/lib/enrich-wire.d.ts
CHANGED
|
@@ -109,6 +109,8 @@ export interface EnrichWiringDeps {
|
|
|
109
109
|
};
|
|
110
110
|
/** #557: the registry's own project workspaces as bounded, deterministic resolution candidates. */
|
|
111
111
|
projectCwds?: (() => string[]) | undefined;
|
|
112
|
+
/** #571: which pump surface this wiring is ('host' | 'realm') — names the lease holder. */
|
|
113
|
+
planeId?: string;
|
|
112
114
|
/** #561: the row's own durable session header cwd — the authoritative locator for UNLINKED workspaces. */
|
|
113
115
|
sessionCwdOf?: ((sid: string) => Promise<string | undefined>) | undefined;
|
|
114
116
|
}
|
|
@@ -120,11 +122,22 @@ export interface EnrichWiring {
|
|
|
120
122
|
remaining: number;
|
|
121
123
|
draining: boolean;
|
|
122
124
|
alreadyRunning: boolean;
|
|
125
|
+
leaseHeldBy?: string;
|
|
123
126
|
}>;
|
|
124
127
|
/** the configured per-pass cap (#565: the reply names it; the cap itself never changes at runtime) */
|
|
125
128
|
batchCap(): number;
|
|
126
129
|
/** #565: the background drain's live state (surfaces and tests await it). */
|
|
127
130
|
isDraining(): boolean;
|
|
131
|
+
/** #578: human-only RULE reprocessing across every existing transcript chapter. Background;
|
|
132
|
+
* never touches annotations; shares the drain lease and the backoff/breaker discipline. */
|
|
133
|
+
reprocessAll: (limit?: number) => Promise<{
|
|
134
|
+
started: boolean;
|
|
135
|
+
alreadyRunning: boolean;
|
|
136
|
+
leaseHeldBy?: string;
|
|
137
|
+
total: number;
|
|
138
|
+
}>;
|
|
139
|
+
isReprocessing: () => boolean;
|
|
140
|
+
reprocessState: () => string | undefined;
|
|
128
141
|
setModelOverride(v: string | null): Promise<void>;
|
|
129
142
|
modelOverride(): string | null;
|
|
130
143
|
statusLine(): string;
|
package/lib/enrich-wire.js
CHANGED
|
@@ -22,7 +22,9 @@ import fs from 'node:fs';
|
|
|
22
22
|
import { createEnrichQueue } from "./enrich-queue.js";
|
|
23
23
|
import { buildEnrichInput, buildMineInput, parseEnrichResult, parseMinedRules, applyEnrich } from "./enrich.js";
|
|
24
24
|
import { parseChapterFile, updateChapterFrontmatter } from "./enrich-store.js";
|
|
25
|
+
import { sha256 } from "./render.js";
|
|
25
26
|
import { resolveStoredPath } from "./archive.js";
|
|
27
|
+
import { createDrainLease, mineRouteOf } from "./enrich-lease.js";
|
|
26
28
|
import { isActiveChapter } from "./registry.js";
|
|
27
29
|
/** #557: the boot witness row is a status probe, not archived conversation — one predicate,
|
|
28
30
|
* every queue-facing loop obeys it (pending listing AND counting). */
|
|
@@ -101,6 +103,7 @@ function chaptersOf(state) {
|
|
|
101
103
|
// tests/unit/one-predicate.test.ts keeps comparisons against tombstone statuses inside registry.ts.
|
|
102
104
|
return Array.isArray(c) ? c.filter(isActiveChapter) : [];
|
|
103
105
|
}
|
|
106
|
+
const splitHumanRequests = (body) => body.split(/\*\*User[^*\n]*:\*\*/g).slice(1).map(stripFence);
|
|
104
107
|
export function createEnrichWiring(deps) {
|
|
105
108
|
const resolveRoute = () => {
|
|
106
109
|
const override = deps.store.getSetting('enrichment.model') ?? '';
|
|
@@ -124,6 +127,84 @@ export function createEnrichWiring(deps) {
|
|
|
124
127
|
return r !== null && r.model !== '' ? `${r.provider}/${r.model}` : 'conversation';
|
|
125
128
|
};
|
|
126
129
|
let rememberedCwd;
|
|
130
|
+
// #578 reprocess state
|
|
131
|
+
const REPROCESS_STATE_KEY = 'rules.reprocess.state';
|
|
132
|
+
let reprocessRun = null;
|
|
133
|
+
let reprocessTotal = 0;
|
|
134
|
+
let reprocessDisposed = false;
|
|
135
|
+
const reprocessLease = createDrainLease({ get: (k) => deps.store.getSetting(k), put: (k, v) => { void deps.store.putSetting(k, v ?? ''); } }, `${deps.planeId ?? 'host'}:reprocess`);
|
|
136
|
+
const reprocessSetState = (line) => {
|
|
137
|
+
void deps.store.putSetting(REPROCESS_STATE_KEY, JSON.stringify({ at: new Date().toISOString(), line }));
|
|
138
|
+
};
|
|
139
|
+
const reprocessSnapshot = async () => {
|
|
140
|
+
const out = [];
|
|
141
|
+
for (const [sid, st] of deps.store.sessions()) {
|
|
142
|
+
if (isWitnessRow(sid))
|
|
143
|
+
continue;
|
|
144
|
+
for (const c of chaptersOf(st)) {
|
|
145
|
+
if ((c.messages ?? 1) === 0)
|
|
146
|
+
continue;
|
|
147
|
+
const base = String(c.path ?? '').split('/').pop() ?? '';
|
|
148
|
+
if (base.startsWith('plan-'))
|
|
149
|
+
continue; // plan documents are directives — never mined, never annotated
|
|
150
|
+
out.push({ key: `${sid}#${c.number}`, label: String(c.title ?? '').slice(0, 48) });
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return out;
|
|
154
|
+
};
|
|
155
|
+
const mineRouteNow = () => {
|
|
156
|
+
const spec = (deps.store.getSetting('rules.model') ?? deps.config.rulesModel ?? '').trim();
|
|
157
|
+
const dedicated = mineRouteOf(spec, resolveRoute());
|
|
158
|
+
return dedicated ?? resolveRoute(); // reprocess always makes its OWN call: no spec ⇒ conversation route
|
|
159
|
+
};
|
|
160
|
+
const mineChapterRules = async (key) => {
|
|
161
|
+
const sep = key.lastIndexOf('#');
|
|
162
|
+
const sid = key.slice(0, sep);
|
|
163
|
+
const num = Number(key.slice(sep + 1));
|
|
164
|
+
const state = await deps.store.get(sid);
|
|
165
|
+
const rec = state.chapters.find((c) => c.number === num);
|
|
166
|
+
if (rec === undefined)
|
|
167
|
+
return { ok: false, candidates: 0, written: 0, skipped: 'record gone' };
|
|
168
|
+
const roots = [state.cwd, deps.cwd() ?? rememberedCwd, ...(deps.projectCwds?.() ?? [])];
|
|
169
|
+
if (deps.sessionCwdOf !== undefined)
|
|
170
|
+
roots.push(await deps.sessionCwdOf(sid).catch(() => undefined));
|
|
171
|
+
let cwd;
|
|
172
|
+
let file = '';
|
|
173
|
+
for (const r of roots) {
|
|
174
|
+
if (r === undefined || r === '')
|
|
175
|
+
continue;
|
|
176
|
+
const cand = resolveStoredPath(r, rec.path);
|
|
177
|
+
if (fs.existsSync(cand)) {
|
|
178
|
+
cwd = r;
|
|
179
|
+
file = cand;
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (cwd === undefined)
|
|
184
|
+
return { ok: false, candidates: 0, written: 0, skipped: 'chapter file absent under all known roots' };
|
|
185
|
+
const doc = parseChapterFile(fs.readFileSync(file, 'utf8'));
|
|
186
|
+
if (doc.fmLines.some((l) => /^kind:\s*plan\s*$/.test(l)))
|
|
187
|
+
return { ok: false, candidates: 0, written: 0, skipped: 'plan document' };
|
|
188
|
+
const humanText = humanBytesOf(doc.body);
|
|
189
|
+
const route = mineRouteNow();
|
|
190
|
+
if (route === null || route.provider === '')
|
|
191
|
+
return { ok: false, candidates: 0, written: 0, skipped: 'no routable mining model' };
|
|
192
|
+
const rules = parseMinedRules(await deps.fetch(buildMineInput({ requests: splitHumanRequests(doc.body) }, doc.body.slice(0, 6000)), route));
|
|
193
|
+
if (rules.length === 0)
|
|
194
|
+
return { ok: true, candidates: 0, written: 0 };
|
|
195
|
+
if (deps.config.mineRules === false || deps.onMinedRules === undefined)
|
|
196
|
+
return { ok: true, candidates: rules.length, written: 0 };
|
|
197
|
+
const got = await deps.onMinedRules({
|
|
198
|
+
cwd, sessionId: sid, chapterNumber: num, humanText, rules,
|
|
199
|
+
max: deps.config.mineCap ?? 3, autoActivate: deps.config.rulesAutoActivate !== false,
|
|
200
|
+
});
|
|
201
|
+
return { ok: true, candidates: rules.length, written: got.written };
|
|
202
|
+
};
|
|
203
|
+
const rpTimer = (fn, ms) => {
|
|
204
|
+
const arm = deps.setTimer;
|
|
205
|
+
return arm !== undefined ? arm(fn, ms) : (() => { const id = setTimeout(fn, ms); return { cancel: () => clearTimeout(id) }; })();
|
|
206
|
+
};
|
|
207
|
+
const rpSleep = (ms) => new Promise((res) => { rpTimer(() => res(), ms); });
|
|
127
208
|
const ladder = async (key) => {
|
|
128
209
|
const sep = key.lastIndexOf('#');
|
|
129
210
|
const sid = key.slice(0, sep);
|
|
@@ -197,6 +278,61 @@ export function createEnrichWiring(deps) {
|
|
|
197
278
|
// as they are; only transcript chapters are ever annotated.
|
|
198
279
|
if (doc.fmLines.some((l) => /^kind:\s*plan\s*$/.test(l)))
|
|
199
280
|
return { ok: false, skipped: 'plan documents are directives — never annotated' };
|
|
281
|
+
// #571 HEAL (dual-queue split receipts): when the FILE already carries this model key's
|
|
282
|
+
// annotation (the enrichment write landed but the registry commit did not — measured at
|
|
283
|
+
// 354 records), the guarded rewrite would refuse FOREVER and head-block the queue. If the
|
|
284
|
+
// file is body-self-consistent (the declared anchor matches the parsed body — so this is a
|
|
285
|
+
// stale RECEIPT, not corruption) the ladder resyncs the registry record from the file and
|
|
286
|
+
// counts it done, without any model call. Self-consistency failing stays a loud refusal:
|
|
287
|
+
// real damage keeps the alarm that caught it.
|
|
288
|
+
{
|
|
289
|
+
const keyNow = modelKey();
|
|
290
|
+
const genIdx = doc.fmLines.findIndex((l) => /^generated:/.test(l));
|
|
291
|
+
const fileHasModelMark = genIdx >= 0 && doc.fmLines.slice(genIdx).some((l) => l.includes(`model: ${keyNow}`));
|
|
292
|
+
if (fileHasModelMark) {
|
|
293
|
+
const anchor = doc.fmLines.find((l) => /^(?:bodySha256|sha256):/.test(l))?.split(': ')[1]?.trim();
|
|
294
|
+
const bodyText = doc.body;
|
|
295
|
+
const selfConsistent = anchor === undefined || anchor === sha256(bodyText) || anchor === sha256(bodyText.replace(/\n$/, ''));
|
|
296
|
+
if (selfConsistent) {
|
|
297
|
+
const fmGet = (k) => doc.fmLines.find((l) => l.startsWith(`${k}:`))?.slice(k.length + 1).trim();
|
|
298
|
+
const unq = (v) => {
|
|
299
|
+
if (v === undefined)
|
|
300
|
+
return undefined;
|
|
301
|
+
try {
|
|
302
|
+
return JSON.parse(v);
|
|
303
|
+
}
|
|
304
|
+
catch {
|
|
305
|
+
return v.replace(/^"|"$/g, '');
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
let topics;
|
|
309
|
+
const rawTopics = fmGet('topics');
|
|
310
|
+
if (rawTopics !== undefined) {
|
|
311
|
+
try {
|
|
312
|
+
topics = JSON.parse(rawTopics);
|
|
313
|
+
}
|
|
314
|
+
catch {
|
|
315
|
+
topics = undefined;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
const atLine = doc.fmLines.slice(doc.fmLines.findIndex((l) => l.includes(`model: ${keyNow}`)) + 1, doc.fmLines.findIndex((l) => l.includes(`model: ${keyNow}`)) + 3).find((l) => /at:/.test(l));
|
|
319
|
+
const at = atLine?.split(': ')[1]?.trim().replace(/^'|'$/g, '') ?? new Date().toISOString();
|
|
320
|
+
const fileText = fs.readFileSync(file, 'utf8');
|
|
321
|
+
await deps.store.mutate(sid, (fresh) => {
|
|
322
|
+
const cur = fresh.chapters.find((c) => c.number === num);
|
|
323
|
+
if (cur === undefined)
|
|
324
|
+
return fresh;
|
|
325
|
+
return {
|
|
326
|
+
...fresh,
|
|
327
|
+
chapters: fresh.chapters.map((c) => c.number === num
|
|
328
|
+
? { ...c, title: unq(fmGet('title')) ?? c.title, summary: unq(fmGet('summary')) ?? c.summary, topics: topics ?? c.topics, generated: { ...(c.generated ?? {}), title: [{ by: 'model', model: keyNow, at }] }, sha256: sha256(fileText) }
|
|
329
|
+
: c),
|
|
330
|
+
};
|
|
331
|
+
});
|
|
332
|
+
return { ok: true, resynced: true };
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
200
336
|
const body = doc.body;
|
|
201
337
|
const userChunks = body.split(/\*\*User[^*\n]*:\*\*/g).slice(1);
|
|
202
338
|
const asstChunks = body.split(/\*\*Assistant[^*\n]*:\*\*/g).slice(1);
|
|
@@ -355,6 +491,9 @@ export function createEnrichWiring(deps) {
|
|
|
355
491
|
void deps.store.putSetting(STATE_KEY, JSON.stringify({ at: new Date().toISOString(), line: m })).catch(() => undefined);
|
|
356
492
|
},
|
|
357
493
|
...(deps.setTimer !== undefined ? { setTimer: deps.setTimer } : {}),
|
|
494
|
+
getSetting: (k) => deps.store.getSetting(k),
|
|
495
|
+
putSetting: async (k, v) => { await deps.store.putSetting(k, v ?? ''); },
|
|
496
|
+
planeId: deps.planeId ?? 'host',
|
|
358
497
|
});
|
|
359
498
|
return {
|
|
360
499
|
queue,
|
|
@@ -382,7 +521,7 @@ export function createEnrichWiring(deps) {
|
|
|
382
521
|
// not what finished; `report` follows the count down.
|
|
383
522
|
const d = queue.drainAll(limit);
|
|
384
523
|
const remaining = await this.pendingCount();
|
|
385
|
-
return { processed: 0, remaining, draining: d.started, alreadyRunning: d.alreadyRunning };
|
|
524
|
+
return { processed: 0, remaining, draining: d.started, alreadyRunning: d.alreadyRunning, ...(d.leaseHeldBy !== undefined ? { leaseHeldBy: d.leaseHeldBy } : {}) };
|
|
386
525
|
},
|
|
387
526
|
async setModelOverride(v) {
|
|
388
527
|
if (v === null)
|
|
@@ -405,13 +544,97 @@ export function createEnrichWiring(deps) {
|
|
|
405
544
|
last = ` · last: ${JSON.parse(heartbeat ?? '{}').line ?? 'idle'}`;
|
|
406
545
|
}
|
|
407
546
|
catch { /* cosmetic */ }
|
|
408
|
-
|
|
547
|
+
// #575: the wording must match the 2026-10-21 amendment's semantics: the quote check
|
|
548
|
+
// CLASSIFIES warrants (stated/inferred), it does not authorize; authority is rulesAutoActivate.
|
|
549
|
+
const mine = deps.config.mineRules === false ? ' · rule mining OFF' : ` · rule mining ON (≤${deps.config.mineCap ?? 3}/chapter, warrants labelled stated/inferred; auto-activate ${deps.config.rulesAutoActivate !== false ? 'on' : 'review-first'})`;
|
|
409
550
|
const drainState = queue.isDraining() ? ' · FULL DRAIN RUNNING' : '';
|
|
410
|
-
|
|
551
|
+
const mRoute = mineRouteNow();
|
|
552
|
+
const specSet = (deps.store.getSetting('rules.model') ?? deps.config.rulesModel ?? '').trim() !== '' && (deps.store.getSetting('rules.model') ?? deps.config.rulesModel ?? '').trim() !== 'conversation';
|
|
553
|
+
const minePart = deps.config.mineRules === false ? '' : ` · mining ${specSet && mRoute !== null ? `${mRoute.provider}/${mRoute.model} (dedicated)` : 'rides annotation route'}`;
|
|
554
|
+
const repart = reprocessRun !== null ? ' · RULE REPROCESS RUNNING' : '';
|
|
555
|
+
return `enrichment: ${deps.config.trigger}, model ${model}${mine}${minePart}${repart}${drainState}${last}`;
|
|
556
|
+
},
|
|
557
|
+
// #578: RULE REPROCESS. The repair verb for "re-observe every chapter's standing orders under
|
|
558
|
+
// the CURRENT mining route" — a model setting that changed, a window where mining was off, or
|
|
559
|
+
// simply proof instead of trust. It mines ONLY: no annotation reads through the ladder, no file
|
|
560
|
+
// writes at all — rules go through the same onMinedRules sink (dedupe, ≤cap written, stated/
|
|
561
|
+
// inferred warrants, never staged) that live sessions use. The snapshot is taken up front so
|
|
562
|
+
// the total is an announced number, not a vibe; progress and the end line land in their own
|
|
563
|
+
// settings row so the enrichment heartbeat stays honest about enrichment. Lease/backoff mirror
|
|
564
|
+
// #571/#565: one pump over the shared registry, transient failures ride out loudly.
|
|
565
|
+
reprocessAll: async (limit) => {
|
|
566
|
+
if (reprocessRun !== null) {
|
|
567
|
+
return { started: false, alreadyRunning: true, total: reprocessTotal };
|
|
568
|
+
}
|
|
569
|
+
const held = reprocessLease.heldByOther();
|
|
570
|
+
if (held !== undefined)
|
|
571
|
+
return { started: false, alreadyRunning: false, leaseHeldBy: held, total: 0 };
|
|
572
|
+
if (!reprocessLease.claim()) {
|
|
573
|
+
const cur = reprocessLease.read();
|
|
574
|
+
return { started: false, alreadyRunning: false, leaseHeldBy: typeof cur?.plane === 'string' ? cur.plane : 'another pump', total: 0 };
|
|
575
|
+
}
|
|
576
|
+
const all = await reprocessSnapshot();
|
|
577
|
+
const budget = limit !== undefined && limit > 0 ? limit : Number.POSITIVE_INFINITY;
|
|
578
|
+
reprocessTotal = Math.min(all.length, budget);
|
|
579
|
+
reprocessDisposed = false;
|
|
580
|
+
reprocessRun = (async () => {
|
|
581
|
+
let processed = 0;
|
|
582
|
+
let written = 0;
|
|
583
|
+
let candidates = 0;
|
|
584
|
+
let skipped = 0;
|
|
585
|
+
let backoffStreak = 0;
|
|
586
|
+
let gaveUp = false;
|
|
587
|
+
const BACKOFF_RETRIES = 3;
|
|
588
|
+
const BACKOFF_BASE_MS = 60_000;
|
|
589
|
+
let i = 0;
|
|
590
|
+
while (i < all.length && processed < budget && !reprocessDisposed) {
|
|
591
|
+
const room = Number.isFinite(budget) ? budget - processed : deps.config.batchCap;
|
|
592
|
+
const chunk = all.slice(i, i + Math.min(deps.config.batchCap, room));
|
|
593
|
+
i += chunk.length;
|
|
594
|
+
let chunkErrored = 0;
|
|
595
|
+
for (const item of chunk) {
|
|
596
|
+
try {
|
|
597
|
+
const r = await mineChapterRules(item.key);
|
|
598
|
+
processed += 1;
|
|
599
|
+
candidates += r.candidates;
|
|
600
|
+
written += r.written;
|
|
601
|
+
if (r.skipped !== undefined)
|
|
602
|
+
skipped += 1;
|
|
603
|
+
if (!r.ok)
|
|
604
|
+
skipped += 0;
|
|
605
|
+
}
|
|
606
|
+
catch (error) {
|
|
607
|
+
chunkErrored += 1;
|
|
608
|
+
deps.warn(`rule reprocess failed for ${item.key}: ${String(error?.message ?? error).slice(0, 140)}`);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
if (chunkErrored === chunk.length && chunkErrored > 0) {
|
|
612
|
+
if (backoffStreak < BACKOFF_RETRIES) {
|
|
613
|
+
backoffStreak += 1;
|
|
614
|
+
const waitMs = BACKOFF_BASE_MS * 3 ** (backoffStreak - 1);
|
|
615
|
+
reprocessSetState(`transient failures (${chunkErrored}/${chunk.length}) — retry ${backoffStreak}/${BACKOFF_RETRIES} after ${waitMs / 1000}s`);
|
|
616
|
+
await rpSleep(waitMs);
|
|
617
|
+
i -= chunk.length; // re-attempt the chunk
|
|
618
|
+
processed -= chunkErrored;
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
gaveUp = true;
|
|
622
|
+
break;
|
|
623
|
+
}
|
|
624
|
+
backoffStreak = 0;
|
|
625
|
+
reprocessSetState(`running — processed ${processed}/${String(reprocessTotal)} chapter(s), ${written} rule(s) written of ${candidates} candidate(s)`);
|
|
626
|
+
}
|
|
627
|
+
const line = `rules.reprocess ${gaveUp ? 'GAVE UP after backoff retries' : 'ended'}: ${processed} chapter(s) mined, ${written} rule(s) written, ${candidates - written} deduped/capped, ${skipped} skipped`;
|
|
628
|
+
reprocessSetState(line.replace(/^.*: /, '') === line ? line : line);
|
|
629
|
+
deps.log(line);
|
|
630
|
+
})().finally(() => { reprocessRun = null; reprocessLease.release(); });
|
|
631
|
+
return { started: true, alreadyRunning: false, total: reprocessTotal };
|
|
411
632
|
},
|
|
633
|
+
isReprocessing: () => reprocessRun !== null,
|
|
634
|
+
reprocessState: () => (deps.store.getSetting(REPROCESS_STATE_KEY) ?? ''),
|
|
412
635
|
batchCap: () => deps.config.batchCap,
|
|
413
636
|
isDraining: () => queue.isDraining(),
|
|
414
|
-
dispose() { queue.dispose(); },
|
|
637
|
+
dispose() { reprocessDisposed = true; queue.dispose(); reprocessLease.release(); },
|
|
415
638
|
};
|
|
416
639
|
}
|
|
417
640
|
//# sourceMappingURL=enrich-wire.js.map
|