agent-recall-core 3.4.50 → 3.4.51

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.
Files changed (65) hide show
  1. package/dist/helpers/transcript-project.d.ts +69 -0
  2. package/dist/helpers/transcript-project.d.ts.map +1 -0
  3. package/dist/helpers/transcript-project.js +212 -0
  4. package/dist/helpers/transcript-project.js.map +1 -0
  5. package/dist/index.d.ts +20 -3
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +47 -2
  8. package/dist/index.js.map +1 -1
  9. package/dist/palace/awareness.d.ts +6 -0
  10. package/dist/palace/awareness.d.ts.map +1 -1
  11. package/dist/palace/awareness.js +10 -4
  12. package/dist/palace/awareness.js.map +1 -1
  13. package/dist/retrieval/activation.d.ts +202 -0
  14. package/dist/retrieval/activation.d.ts.map +1 -0
  15. package/dist/retrieval/activation.js +313 -0
  16. package/dist/retrieval/activation.js.map +1 -0
  17. package/dist/storage/corrections.d.ts +140 -2
  18. package/dist/storage/corrections.d.ts.map +1 -1
  19. package/dist/storage/corrections.js +97 -4
  20. package/dist/storage/corrections.js.map +1 -1
  21. package/dist/storage/heed-tiers.d.ts +206 -0
  22. package/dist/storage/heed-tiers.d.ts.map +1 -0
  23. package/dist/storage/heed-tiers.js +318 -0
  24. package/dist/storage/heed-tiers.js.map +1 -0
  25. package/dist/supabase/sync.d.ts +1 -1
  26. package/dist/supabase/sync.d.ts.map +1 -1
  27. package/dist/supabase/sync.js +47 -11
  28. package/dist/supabase/sync.js.map +1 -1
  29. package/dist/tools-logic/association.d.ts +260 -0
  30. package/dist/tools-logic/association.d.ts.map +1 -0
  31. package/dist/tools-logic/association.js +502 -0
  32. package/dist/tools-logic/association.js.map +1 -0
  33. package/dist/tools-logic/check-action.d.ts.map +1 -1
  34. package/dist/tools-logic/check-action.js +14 -0
  35. package/dist/tools-logic/check-action.js.map +1 -1
  36. package/dist/tools-logic/implicit-harvest.d.ts +196 -0
  37. package/dist/tools-logic/implicit-harvest.d.ts.map +1 -0
  38. package/dist/tools-logic/implicit-harvest.js +675 -0
  39. package/dist/tools-logic/implicit-harvest.js.map +1 -0
  40. package/dist/tools-logic/insight-promotion.d.ts.map +1 -1
  41. package/dist/tools-logic/insight-promotion.js +53 -1
  42. package/dist/tools-logic/insight-promotion.js.map +1 -1
  43. package/dist/tools-logic/retier.d.ts +274 -0
  44. package/dist/tools-logic/retier.d.ts.map +1 -0
  45. package/dist/tools-logic/retier.js +511 -0
  46. package/dist/tools-logic/retier.js.map +1 -0
  47. package/dist/tools-logic/session-end.d.ts +35 -0
  48. package/dist/tools-logic/session-end.d.ts.map +1 -1
  49. package/dist/tools-logic/session-end.js +26 -7
  50. package/dist/tools-logic/session-end.js.map +1 -1
  51. package/dist/tools-logic/session-start.d.ts +11 -0
  52. package/dist/tools-logic/session-start.d.ts.map +1 -1
  53. package/dist/tools-logic/session-start.js +34 -4
  54. package/dist/tools-logic/session-start.js.map +1 -1
  55. package/dist/tools-logic/smart-recall.d.ts +11 -0
  56. package/dist/tools-logic/smart-recall.d.ts.map +1 -1
  57. package/dist/tools-logic/smart-recall.js +11 -0
  58. package/dist/tools-logic/smart-recall.js.map +1 -1
  59. package/dist/tools-logic/transcript-audit.d.ts +128 -0
  60. package/dist/tools-logic/transcript-audit.d.ts.map +1 -0
  61. package/dist/tools-logic/transcript-audit.js +428 -0
  62. package/dist/tools-logic/transcript-audit.js.map +1 -0
  63. package/dist/types.d.ts +1 -1
  64. package/dist/types.js +1 -1
  65. package/package.json +1 -1
@@ -0,0 +1,511 @@
1
+ /**
2
+ * retier.ts — evolution p4 (Phase 4): the soft-constraint ladder,
3
+ * `ar corrections retier`.
4
+ *
5
+ * WHY: `severity` (p0/p1) is a binary, capture-time, NEVER-revisited label —
6
+ * once a rule is p0 it stays hard-enforced forever even if its evidence
7
+ * (heeded/recurred/retrieved) never shows up again. "Rules must die unless
8
+ * data renews them": this module adds a THREE-tier ladder — gate (hard
9
+ * enforcement) / nudge (advisory) / watch (background) — computed FRESH
10
+ * from each record's own evidence, plus an automatic, reversible one-step
11
+ * DEMOTION when that evidence goes stale. Nothing here ever deletes,
12
+ * retracts, or archives a record — see CONSTRAINTS below.
13
+ *
14
+ * ---------------------------------------------------------------------------
15
+ * tierOf — HAND-TUNED v1 formula (every constant named + justified; not fit
16
+ * to any labeled outcome set, same "chosen by feel" status as activation.ts's
17
+ * S_DECAY/ACT_ALPHA)
18
+ * ---------------------------------------------------------------------------
19
+ * gate: severity p0 AND proof_confidence ≥ GATE_MIN_PROOF_CONFIDENCE (0.7)
20
+ * AND retrieved within GATE_RETRIEVED_WITHIN_DAYS (30d) of asOfDay.
21
+ * nudge: (severity p0 that did NOT meet gate) — OR —
22
+ * (severity p1 AND proof_confidence ≥ NUDGE_P1_MIN_PROOF_CONFIDENCE
23
+ * (0.6) AND retrieved within NUDGE_RETRIEVED_WITHIN_DAYS (60d)).
24
+ * watch: everything else.
25
+ *
26
+ * `proof_confidence` is read directly off the record (it is already the
27
+ * Beta posterior `(heeded+1)/(heeded+recurred+2)` when outcomes exist, and
28
+ * already falls back to `weight` when they don't — see corrections.ts's
29
+ * `applyCorrectionDefaults`/`recordOutcome`). `proofConfidenceOf` below adds
30
+ * ONE more defensive fallback layer (mirroring `decayClassOf`/
31
+ * `effectiveConfidenceOf`'s established defensive posture in corrections.ts)
32
+ * for a raw/un-defaulted record a caller hands in directly (e.g. a truth-
33
+ * table test fixture) rather than one that went through `readCorrections()`.
34
+ *
35
+ * COLD-START (stated explicitly, per the brief): a fresh record that has
36
+ * NEVER been retrieved (`last_retrieved` absent) fails BOTH the gate's and
37
+ * the nudge-p1-branch's retrieval-recency clause regardless of its
38
+ * `proof_confidence` (which for a truly fresh record is `weight`'s prior —
39
+ * ≈1.0 for p0, ≈0.7 for p1 — NOT literally 0.5; the brief's "prior≈0.5"
40
+ * describes the SHAPE of the argument, not a required literal value, and
41
+ * the derivation below holds for ANY confidence value, 0.5 included, since
42
+ * the p0-nudge branch never even reads confidence). Mechanically:
43
+ * - a fresh P0 record: gate fails (retrieval clause) → falls to the
44
+ * UNCONDITIONAL "severity p0 not meeting gate" nudge branch → **nudge**.
45
+ * - a fresh P1 record: gate fails (wrong severity) → nudge's p1 branch
46
+ * ALSO fails (retrieval clause) → **watch**.
47
+ * This is not a special case coded separately — it is what the formula
48
+ * above already produces for any record with `last_retrieved` absent; it is
49
+ * called out here (and pinned by a truth-table test row) because it is the
50
+ * single most consequential behavior an operator needs to know before
51
+ * trusting the ladder on a corpus with many never-yet-retrieved corrections.
52
+ *
53
+ * ---------------------------------------------------------------------------
54
+ * demotionOf — automatic, one-step-down triggers (pure)
55
+ * ---------------------------------------------------------------------------
56
+ * Fires independently of (and can pull a record BELOW) the raw `tierOf`
57
+ * result — this is what keeps a P0 record that is technically "not meeting
58
+ * gate" (and would therefore sit at "nudge" forever per the formula above,
59
+ * regardless of HOW stale it gets — the p0-nudge branch has no recency
60
+ * clause of its own) from getting stuck at nudge indefinitely once it goes
61
+ * genuinely dormant.
62
+ * - `not_violated_plateau`: `not_violated_count ≥ DEMOTE_NOT_VIOLATED_MIN`
63
+ * (3) AND `heeded_count === 0 && recurrence_count === 0`. DOCUMENTED
64
+ * APPROXIMATION: the brief's literal spec is "zero heeded/recurred IN
65
+ * THE LAST 60 DAYS", but `recordOutcome` (storage/corrections.ts)
66
+ * stamps `last_outcome` for heeded, recurred, AND not_violated alike —
67
+ * one shared timestamp, no per-kind history — so a record-only pure
68
+ * function (no ledger read) cannot distinguish "heeded happened but was
69
+ * >60d ago" from "heeded never happened". This checks lifetime-zero
70
+ * instead, which is a STRICT SUBSET of the windowed check (every record
71
+ * lifetime-zero-heeded/recurred is trivially also windowed-zero; a
72
+ * record with e.g. `heeded_count:1` whose one heeded event happened
73
+ * 400 days ago would satisfy the brief's literal windowed spec but is
74
+ * SKIPPED here). Flagged, not silently narrowed: a ledger-precision
75
+ * windowed version would need `readOutcomeEventsByCorrection`, which is
76
+ * a different function's job, not this pure per-record one's.
77
+ * - `retrieval_stale_90d`: no retrieval touch within
78
+ * `DEMOTE_RETRIEVAL_STALE_DAYS` (90) of `asOfDay`. Anchor is
79
+ * `last_retrieved ?? date` (record creation date) — mirrors
80
+ * `isStaleCorrection`'s existing `last_retrieved ?? last_outcome ?? date`
81
+ * touch-anchor convention in corrections.ts, narrowed to retrieval-only
82
+ * (not outcome) because the brief names "no RETRIEVED event"
83
+ * specifically. Falling back to `date` (never `last_outcome`) means a
84
+ * record created 5 days ago with zero retrievals does NOT yet trigger
85
+ * this — there has not been a 90-day WINDOW in which retrieval could
86
+ * have happened, so there is nothing to call "stale" yet. `currentTier
87
+ * === "watch"` short-circuits to `[]` — watch is the floor; there is no
88
+ * lower tier to step down to, so computing triggers for it is a no-op
89
+ * it can skip announcing.
90
+ *
91
+ * ---------------------------------------------------------------------------
92
+ * archiveCandidates / promoteToGateCandidates — PROPOSALS ONLY
93
+ * ---------------------------------------------------------------------------
94
+ * Both are pure REPORTS, read by `--dry-run` (and always computed, never
95
+ * gated behind the flag — `--write` just additionally persists tiers).
96
+ * Neither list is ever applied, retracted, or archived by this module or by
97
+ * `--write` — there is no `--apply-proposals` flag anywhere in this file.
98
+ * `archiveCandidates`: watch-tier records with no retrieval/outcome/
99
+ * prediction touch of ANY kind in `ARCHIVE_STALE_DAYS` (180) days — a human
100
+ * decides whether "dormant this long" means retract, keep watching, or
101
+ * something else; this module has no opinion past surfacing the list.
102
+ * `promoteToGateCandidates`: records where the RAW formula (`tierOf`) says
103
+ * "gate", NO demotion trigger fires for that same record (`demotionOf`
104
+ * re-checked internally — see FIX note on the function itself: a raw-gate
105
+ * record whose `not_violated_plateau`/`retrieval_stale_90d` trigger is
106
+ * active is NOT a candidate, because `--write` would persist it one step
107
+ * BELOW gate, not at gate — see `final_tier` below), and the record's
108
+ * LAST-PERSISTED `tier` field disagrees (absent, or a lower tier — this can
109
+ * happen legitimately: a record demoted for staleness gets freshly
110
+ * retrieved again and its raw formula recovers to "gate" before the next
111
+ * `--write` run catches up). `--write` persists `final_tier` — `tierOf`'s
112
+ * raw result stepped down once if `demotionOf` fired, exactly like every
113
+ * other tier — so a promotion INTO gate is not held back by anything
114
+ * OTHER than that same demotion check (only DEMOTION out of a tier is a
115
+ * separate, escalation-style path; there is no analogous "promotion
116
+ * approval" write-gate here). Inside `runRetier`, this list is additionally
117
+ * computed against each record's tier AS OF the end of this call (the tier
118
+ * `--write` just persisted this run, if any — never the pre-write snapshot;
119
+ * see the `writtenTierThisRun` remap in `runRetier`), so a record `--write`
120
+ * already promoted to gate THIS call is never simultaneously reported as
121
+ * "still pending". What "OWNER-GATED" (the brief's own words for this list)
122
+ * means concretely in v1: this list is the visibility mechanism — a human
123
+ * reviewing `--dry-run` output sees exactly which records are ABOUT TO
124
+ * become (or already are, pending the next --write) gate-tier BEFORE
125
+ * trusting anything downstream to key off `tier==="gate"` automatically. If
126
+ * a future phase wants `--write` to hold gate promotions for explicit human
127
+ * sign-off (a real write-time gate), that is a NEW, separate flag on top of
128
+ * this reporting list, not a silent change to what `--write` does today.
129
+ *
130
+ * ---------------------------------------------------------------------------
131
+ * CHALLENGE resolution — stored `tier` vs. `tierOf()` (read contract)
132
+ * ---------------------------------------------------------------------------
133
+ * DECIDED: the stored `CorrectionRecord.tier` field is a WRITE-TIME CACHE,
134
+ * never truth. `tierOf(record, asOfDay)` is the ONE source of truth for
135
+ * "what tier is this record right now" — see the field's own doc comment in
136
+ * storage/corrections.ts. This module's own `promoteToGateCandidates` is the
137
+ * proof this is load-bearing, not decorative: it exists BECAUSE the cached
138
+ * field can legitimately disagree with a fresh computation. The
139
+ * session_start rendering tag (goal 3) recomputes fresh at render time for
140
+ * the same reason — it never reads `record.tier`. Storing nothing at all
141
+ * (compute-on-every-read, everywhere) was the alternative considered and
142
+ * REJECTED: `--dry-run`'s whole value proposition is showing "stored vs.
143
+ * computed" drift (the CLI table's `current` column) and idempotency proof
144
+ * needs SOMETHING durable to compare a second `--write` run against; a
145
+ * cache with a documented, enforced "never trust me without recomputing"
146
+ * contract gets both without inventing a second source of truth for any
147
+ * consumer that matters (there is exactly one: `promoteToGateCandidates`,
148
+ * and it already treats the field as a stale-vs-fresh SIGNAL, never as an
149
+ * answer on its own).
150
+ *
151
+ * ---------------------------------------------------------------------------
152
+ * Determinism / store-root handling
153
+ * ---------------------------------------------------------------------------
154
+ * `runRetier` is deterministic given the same `asOfDay` and unchanged
155
+ * on-disk inputs (project slugs sorted, no wall-clock read once `asOfDay`
156
+ * is fixed). Unlike `association.ts`'s `--store` (which deliberately never
157
+ * mutates the process-global root because it does its OWN raw fs
158
+ * reads/writes), `runRetier`'s `--write` path MUST reuse corrections.ts's
159
+ * locked, atomic, index-regenerating write machinery (`setCorrectionTier`)
160
+ * — the brief's own "sanctioned record-write path under the project lock"
161
+ * requirement — and that machinery is hard-wired to `getRoot()` throughout.
162
+ * Reimplementing lock+atomic-write+index-regen here to avoid a root swap
163
+ * would duplicate exactly the mechanism the brief says to reuse. So this
164
+ * module swaps `setRoot()` for the duration of one `runRetier()` call (only
165
+ * when `storeRoot` is explicitly passed) and restores the PRIOR root in a
166
+ * `finally`, even on throw — see `withStoreRoot` below. This is the SAME
167
+ * mechanism the CLI's pre-existing global `--root` flag already uses
168
+ * (types.ts's `setRoot`), just scoped to one call instead of the whole
169
+ * process lifetime.
170
+ */
171
+ import * as fs from "node:fs";
172
+ import { getRoot, setRoot } from "../types.js";
173
+ import { projectsRootDir } from "../storage/paths.js";
174
+ import { isValidProjectSlug } from "../storage/project.js";
175
+ import { readActiveCorrections, setCorrectionTier, } from "../storage/corrections.js";
176
+ import { todayDayString } from "../retrieval/activation.js";
177
+ // ---------------------------------------------------------------------------
178
+ // HAND-TUNED constants (see this file's header for the full rationale)
179
+ // ---------------------------------------------------------------------------
180
+ export const GATE_MIN_PROOF_CONFIDENCE = 0.7;
181
+ export const GATE_RETRIEVED_WITHIN_DAYS = 30;
182
+ export const NUDGE_P1_MIN_PROOF_CONFIDENCE = 0.6;
183
+ export const NUDGE_RETRIEVED_WITHIN_DAYS = 60;
184
+ export const DEMOTE_NOT_VIOLATED_MIN = 3;
185
+ export const DEMOTE_RETRIEVAL_STALE_DAYS = 90;
186
+ export const ARCHIVE_STALE_DAYS = 180;
187
+ /** The ladder, strongest-first. Exported ordering used by `stepDownTier`. */
188
+ const LADDER = ["gate", "nudge", "watch"];
189
+ // ---------------------------------------------------------------------------
190
+ // Pure day-math (mirrors activation.ts's private `daysBetweenDayStrings` —
191
+ // kept INLINE here for the same reason corrections.ts's `betaPosterior`
192
+ // mirrors smart-recall.ts's canonical version instead of importing it: this
193
+ // is a tiny, stable primitive and importing it would pull a tools-logic
194
+ // module's private helper across an unrelated tools-logic boundary for one
195
+ // three-line function.)
196
+ // ---------------------------------------------------------------------------
197
+ /**
198
+ * Whole-day difference between two `YYYY-MM-DD` strings, parsed as UTC
199
+ * midnight (deterministic regardless of the calling process's timezone).
200
+ * Returns `null` on either unparseable string (degrade, never throw).
201
+ */
202
+ function daysBetweenDayStrings(fromDay, toDay) {
203
+ const from = Date.parse(`${fromDay}T00:00:00Z`);
204
+ const to = Date.parse(`${toDay}T00:00:00Z`);
205
+ if (Number.isNaN(from) || Number.isNaN(to))
206
+ return null;
207
+ return Math.round((to - from) / 86_400_000);
208
+ }
209
+ /**
210
+ * First 10 chars of an ISO timestamp (or an already-`YYYY-MM-DD` string) —
211
+ * its UTC calendar day. DEFENSIVE (found via the live-corpus dry-run,
212
+ * 2026-09-17): `CorrectionRecord.date` is typed as a required `string`, but
213
+ * a hand-crafted/corrupted on-disk record can violate that (a live store
214
+ * record was found with `date` literally absent). Total over anything —
215
+ * non-string/empty input returns `""`, which `daysBetweenDayStrings` above
216
+ * already degrades to `null` for (an empty string fails `Date.parse`) —
217
+ * never throws. Same defensive posture as `decayClassOf`/
218
+ * `effectiveConfidenceOf` in corrections.ts (out-of-contract disk data
219
+ * degrades to a safe default, never crashes the caller).
220
+ */
221
+ function utcDayOf(isoOrDay) {
222
+ return typeof isoOrDay === "string" ? isoOrDay.slice(0, 10) : "";
223
+ }
224
+ // ---------------------------------------------------------------------------
225
+ // tierOf (brief item 1)
226
+ // ---------------------------------------------------------------------------
227
+ /**
228
+ * Effective proof_confidence for tiering. DEFENSIVE fallback chain, mirroring
229
+ * `decayClassOf`/`effectiveConfidenceOf`'s posture in corrections.ts: records
230
+ * read via `readCorrections()` already carry a resolved `proof_confidence`
231
+ * (defaulted to `weight` by `applyCorrectionDefaults`, or the Beta posterior
232
+ * once outcomes exist), so in practice this just returns `record.proof_confidence`
233
+ * unchanged. The two extra fallback rungs (`weight`, then the p0/p1 authority
234
+ * prior) exist only for a raw/un-defaulted record a caller hands in directly
235
+ * (e.g. a truth-table test fixture) — never for anything that went through
236
+ * the real read path.
237
+ */
238
+ function proofConfidenceOf(record) {
239
+ if (typeof record.proof_confidence === "number")
240
+ return record.proof_confidence;
241
+ if (typeof record.weight === "number")
242
+ return record.weight;
243
+ return record.severity === "p0" ? 1.0 : 0.7;
244
+ }
245
+ /** True when `record.last_retrieved` falls within `days` of `asOfDay` (inclusive). Absent → false — a record with zero retrieval events has, by definition, no event "within" any window. */
246
+ function retrievedWithinDays(record, asOfDay, days) {
247
+ if (!record.last_retrieved)
248
+ return false;
249
+ const diff = daysBetweenDayStrings(utcDayOf(record.last_retrieved), asOfDay);
250
+ return diff !== null && diff <= days;
251
+ }
252
+ /**
253
+ * The soft-constraint ladder — HAND-TUNED v1 formula. See this file's header
254
+ * for the full derivation, every constant's name/value, and the cold-start
255
+ * worked example. Pure: no I/O, no wall-clock read (asOfDay is the caller's
256
+ * "now").
257
+ */
258
+ export function tierOf(record, asOfDay) {
259
+ const isP0 = record.severity === "p0";
260
+ const confidence = proofConfidenceOf(record);
261
+ const meetsGate = isP0 &&
262
+ confidence >= GATE_MIN_PROOF_CONFIDENCE &&
263
+ retrievedWithinDays(record, asOfDay, GATE_RETRIEVED_WITHIN_DAYS);
264
+ if (meetsGate)
265
+ return "gate";
266
+ // At this point a p0 record is, by construction, "p0 that did not meet
267
+ // gate" — the brief's nudge branch (a) — no extra recomputation needed.
268
+ const meetsNudge = isP0 ||
269
+ (confidence >= NUDGE_P1_MIN_PROOF_CONFIDENCE &&
270
+ retrievedWithinDays(record, asOfDay, NUDGE_RETRIEVED_WITHIN_DAYS));
271
+ if (meetsNudge)
272
+ return "nudge";
273
+ return "watch";
274
+ }
275
+ /** One step down the ladder (gate→nudge→watch→watch — watch is the floor). */
276
+ export function stepDownTier(tier) {
277
+ const idx = LADDER.indexOf(tier);
278
+ return LADDER[Math.min(idx + 1, LADDER.length - 1)];
279
+ }
280
+ // ---------------------------------------------------------------------------
281
+ // demotionOf (brief item 1)
282
+ // ---------------------------------------------------------------------------
283
+ /**
284
+ * One-step-down trigger list for `record` at `currentTier`/`asOfDay`. Pure —
285
+ * returns the trigger NAMES that fired (empty = no demotion). See this
286
+ * file's header for the exact rationale of each trigger, including the
287
+ * documented not_violated windowing approximation.
288
+ */
289
+ export function demotionOf(record, currentTier, asOfDay) {
290
+ if (currentTier === "watch")
291
+ return []; // already the floor — nothing to step down to
292
+ const triggers = [];
293
+ const notViolated = record.not_violated_count ?? 0;
294
+ const heeded = record.heeded_count ?? 0;
295
+ const recurred = record.recurrence_count ?? 0;
296
+ if (notViolated >= DEMOTE_NOT_VIOLATED_MIN && heeded === 0 && recurred === 0) {
297
+ triggers.push("not_violated_plateau");
298
+ }
299
+ const retrievalAnchor = record.last_retrieved ?? record.date;
300
+ const daysSinceRetrieval = retrievalAnchor
301
+ ? daysBetweenDayStrings(utcDayOf(retrievalAnchor), asOfDay)
302
+ : null;
303
+ if (daysSinceRetrieval !== null && daysSinceRetrieval >= DEMOTE_RETRIEVAL_STALE_DAYS) {
304
+ triggers.push("retrieval_stale_90d");
305
+ }
306
+ return triggers;
307
+ }
308
+ /** Most recent of last_retrieved/last_outcome/last_predicted; `record.date` if none exist (never touched at all). */
309
+ function lastTouchAnyKindOf(record) {
310
+ const touches = [record.last_retrieved, record.last_outcome, record.last_predicted].filter((t) => typeof t === "string" && t.length > 0);
311
+ // DEFENSIVE: `record.date` is typed as a required string, but a
312
+ // hand-crafted/corrupted on-disk record can violate that (see utcDayOf's
313
+ // doc comment — found live). Coerce to "" rather than propagate a
314
+ // non-string `date` as `touch`, which callers (archiveCandidates) treat
315
+ // as an ISO-ish string.
316
+ if (touches.length === 0)
317
+ return { touch: typeof record.date === "string" ? record.date : "", observed: null };
318
+ const latest = touches.reduce((a, b) => (b > a ? b : a));
319
+ return { touch: latest, observed: latest };
320
+ }
321
+ /**
322
+ * watch-tier records with no retrieval/outcome/prediction touch of ANY kind
323
+ * in `ARCHIVE_STALE_DAYS` days. PROPOSAL LIST ONLY — see this file's header.
324
+ * `tierOf` is recomputed here (never reads `record.tier`) per the CHALLENGE
325
+ * resolution above.
326
+ */
327
+ export function archiveCandidates(records, asOfDay) {
328
+ const out = [];
329
+ for (const r of records) {
330
+ if (tierOf(r, asOfDay) !== "watch")
331
+ continue;
332
+ const { touch, observed } = lastTouchAnyKindOf(r);
333
+ const days = daysBetweenDayStrings(utcDayOf(touch), asOfDay);
334
+ if (days !== null && days >= ARCHIVE_STALE_DAYS) {
335
+ out.push({ project: r.project, id: r.id, rule: r.rule, last_touch: observed });
336
+ }
337
+ }
338
+ return out;
339
+ }
340
+ /**
341
+ * Records where the RAW formula (`tierOf`) says "gate" but the record's
342
+ * last-PERSISTED `tier` field disagrees (absent, or a lower tier). PROPOSAL
343
+ * LIST ONLY (visibility, not a write-gate) — see this file's header.
344
+ */
345
+ export function promoteToGateCandidates(records, asOfDay) {
346
+ const out = [];
347
+ for (const r of records) {
348
+ const computed = tierOf(r, asOfDay);
349
+ if (computed !== "gate" || r.tier === "gate")
350
+ continue;
351
+ // FIX (found in review): a record whose RAW formula says "gate" but
352
+ // whose own demotion trigger fires (e.g. `not_violated_plateau`) is
353
+ // NOT a promotion candidate — `runRetier`'s own `final_tier` for this
354
+ // same record already steps it down to the demoted tier (see
355
+ // `demotionOf`'s doc comment above); listing it here anyway would
356
+ // contradict the row the human is looking at in the very same
357
+ // `--dry-run`/`--write` output. `currentTier` passed to `demotionOf`
358
+ // is always "gate" here (never "watch" — the `computed !== "gate"`
359
+ // guard above already excluded that), so its watch-floor
360
+ // short-circuit never applies to this call site.
361
+ if (demotionOf(r, computed, asOfDay).length > 0)
362
+ continue;
363
+ out.push({ project: r.project, id: r.id, rule: r.rule, severity: r.severity });
364
+ }
365
+ return out;
366
+ }
367
+ /** Sorted, valid-slug project directories directly under `projects/` — same enumeration convention as association.ts's `listProjectDirs`. */
368
+ function listProjectSlugs() {
369
+ let entries;
370
+ try {
371
+ entries = fs.readdirSync(projectsRootDir(), { withFileTypes: true });
372
+ }
373
+ catch {
374
+ return []; // no projects dir (or unreadable) — nothing to retier
375
+ }
376
+ return entries
377
+ .filter((e) => e.isDirectory())
378
+ .map((e) => e.name)
379
+ .filter((name) => isValidProjectSlug(name))
380
+ .sort();
381
+ }
382
+ /**
383
+ * Runs `fn` with the process-global root temporarily swapped to `storeRoot`
384
+ * (a no-op passthrough when `storeRoot` is undefined), restoring the PRIOR
385
+ * root afterward even if `fn` throws. See this file's header for why this
386
+ * module — unlike association.ts's `--store` — must do this: it reuses
387
+ * corrections.ts's `getRoot()`-coupled locked write machinery rather than
388
+ * reimplementing it.
389
+ */
390
+ async function withStoreRoot(storeRoot, fn) {
391
+ if (storeRoot === undefined)
392
+ return fn();
393
+ const previous = getRoot();
394
+ setRoot(storeRoot);
395
+ try {
396
+ return await fn();
397
+ }
398
+ finally {
399
+ setRoot(previous);
400
+ }
401
+ }
402
+ /**
403
+ * Cross-project retier run. Dry-run by default (computes and reports,
404
+ * writes nothing); pass `{ write: true }` to persist via `setCorrectionTier`
405
+ * — see this file's header for the exact write semantics (demotion always
406
+ * applied; promotion into "gate" is the raw formula, not held back;
407
+ * archive/promote-to-gate lists are NEVER applied here regardless of
408
+ * `write`). Idempotent given unchanged inputs and the same `asOfDay`: a
409
+ * second `{ write: true }` run persists zero records (both this function's
410
+ * own `changed` pre-filter AND `setCorrectionTier`'s independent fresh-read
411
+ * check guard this).
412
+ */
413
+ export async function runRetier(opts = {}) {
414
+ const asOfDay = opts.asOfDay ?? todayDayString();
415
+ const storeRoot = opts.storeRoot ?? getRoot();
416
+ const dryRun = !opts.write;
417
+ return withStoreRoot(opts.storeRoot, async () => {
418
+ const slugs = listProjectSlugs();
419
+ const rows = [];
420
+ const allRecords = [];
421
+ for (const project of slugs) {
422
+ let records;
423
+ try {
424
+ // Active-only: a retracted record is already dead — tiering it adds
425
+ // noise to every surface below (table, demotion, archive, promote)
426
+ // for no operational benefit.
427
+ records = readActiveCorrections(project);
428
+ }
429
+ catch {
430
+ continue; // unreadable project dir between enumeration and read — skip, never throw
431
+ }
432
+ for (const r of records) {
433
+ allRecords.push(r);
434
+ const computed = tierOf(r, asOfDay);
435
+ const triggers = demotionOf(r, computed, asOfDay);
436
+ const final = triggers.length > 0 ? stepDownTier(computed) : computed;
437
+ rows.push({
438
+ project,
439
+ id: r.id,
440
+ severity: r.severity,
441
+ rule: r.rule,
442
+ stored_tier: r.tier ?? null,
443
+ computed_tier: computed,
444
+ final_tier: final,
445
+ triggers,
446
+ changed: (r.tier ?? null) !== final,
447
+ });
448
+ }
449
+ }
450
+ let written = 0;
451
+ let writeErrors = 0;
452
+ // FIX (found in review): keyed by "project::id" -> the tier THIS call
453
+ // actually persisted for that record, so `promote_to_gate_candidates`
454
+ // below can compare against reality instead of `allRecords`'s pre-write
455
+ // snapshot (read once, up front, for the whole cross-project scan, and
456
+ // never mutated by this write loop).
457
+ const writtenTierThisRun = new Map();
458
+ if (opts.write) {
459
+ for (const row of rows) {
460
+ if (!row.changed)
461
+ continue;
462
+ try {
463
+ const result = await setCorrectionTier(row.project, row.id, row.final_tier);
464
+ if (result.written) {
465
+ written++;
466
+ writtenTierThisRun.set(`${row.project}::${row.id}`, row.final_tier);
467
+ }
468
+ else if (result.error)
469
+ writeErrors++;
470
+ }
471
+ catch {
472
+ writeErrors++;
473
+ }
474
+ }
475
+ }
476
+ const tierDistribution = { gate: 0, nudge: 0, watch: 0 };
477
+ for (const row of rows)
478
+ tierDistribution[row.final_tier]++;
479
+ // FIX (found in review): `promoteToGateCandidates` reads each record's
480
+ // `tier` field to decide "not already gate". Without this remap, a
481
+ // record this SAME `--write` call just persisted to "gate" would still
482
+ // read its pre-write `allRecords` snapshot's `tier` (anything below
483
+ // "gate") and get listed as "pending promotion" alongside its own
484
+ // `rows[]` entry showing `final_tier: "gate"` / already written —
485
+ // self-contradictory output. Only records this call actually wrote are
486
+ // remapped, to the EXACT tier just persisted (not assumed to be
487
+ // "gate" — a demoted record can be written as "nudge"); dry-run
488
+ // (writtenTierThisRun always empty) and untouched records pass through
489
+ // with their real last-persisted `tier` unchanged.
490
+ const recordsForPromotion = writtenTierThisRun.size === 0
491
+ ? allRecords
492
+ : allRecords.map((r) => {
493
+ const persisted = writtenTierThisRun.get(`${r.project}::${r.id}`);
494
+ return persisted === undefined ? r : { ...r, tier: persisted };
495
+ });
496
+ return {
497
+ as_of: asOfDay,
498
+ store_root: storeRoot,
499
+ dry_run: dryRun,
500
+ projects_scanned: slugs.length,
501
+ rows,
502
+ tier_distribution: tierDistribution,
503
+ demoted: rows.filter((r) => r.triggers.length > 0),
504
+ promote_to_gate_candidates: promoteToGateCandidates(recordsForPromotion, asOfDay),
505
+ archive_candidates: archiveCandidates(allRecords, asOfDay),
506
+ written,
507
+ write_errors: writeErrors,
508
+ };
509
+ });
510
+ }
511
+ //# sourceMappingURL=retier.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retier.js","sourceRoot":"","sources":["../../src/tools-logic/retier.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyKG;AAE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AkE;QAClE,kEAAkE;QAClE,uEAAuE;QACvE,gEAAgE;QAChE,gEAAgE;QAChE,uEAAuE;QACvE,mDAAmD;QACnD,MAAM,mBAAmB,GAAG,kBAAkB,CAAC,IAAI,KAAK,CAAC;YACvD,CAAC,CAAC,UAAU;YACZ,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;gBACnB,MAAM,SAAS,GAAG,kBAAkB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;gBAClE,OAAO,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;YACjE,CAAC,CAAC,CAAC;QAEP,OAAO;YACL,KAAK,EAAE,OAAO;YACd,UAAU,EAAE,SAAS;YACrB,OAAO,EAAE,MAAM;YACf,gBAAgB,EAAE,KAAK,CAAC,MAAM;YAC9B,IAAI;YACJ,iBAAiB,EAAE,gBAAgB;YACnC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC;YAClD,0BAA0B,EAAE,uBAAuB,CAAC,mBAAmB,EAAE,OAAO,CAAC;YACjF,kBAAkB,EAAE,iBAAiB,CAAC,UAAU,EAAE,OAAO,CAAC;YAC1D,OAAO;YACP,YAAY,EAAE,WAAW;SAC1B,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -97,6 +97,41 @@ export interface SessionEndResult {
97
97
  /** Path to the handoff artifact written at session_end. Present on success. */
98
98
  handoff_path?: string;
99
99
  }
100
+ /**
101
+ * C3 (2026-07-03) — recurrence markers, widened from the pre-C3 set.
102
+ * "same mistake" retained; added violated/violating/violation, "ignored the rule",
103
+ * "didn't follow". The bar for a `recurred` verdict is marker + trigger/topical
104
+ * evidence — widening markers alone does not produce more recurred verdicts.
105
+ *
106
+ * Exported (evolution p1a, transcript-audit) — the transcript-audit ladder
107
+ * needs the RAW regex (not just the whole-text boolean hasGenuineRecurrenceMarker
108
+ * gives) to test recurrence-marker-hit-AND-topic-co-occurrence on the SAME
109
+ * sentence. Exporting the regex avoids a second, drift-prone copy of this
110
+ * pattern living in packages/core/src/tools-logic/transcript-audit.ts.
111
+ */
112
+ export declare const RECURRENCE_MARKER: RegExp;
113
+ /**
114
+ * C3 meta-content guard — eval-vocabulary anchors. This project's own summaries
115
+ * routinely DISCUSS the measurement system ("the recurred count violated our
116
+ * baseline expectations") — report prose, not a first-person violation admission.
117
+ * A recurrence marker inside a sentence that carries one of these anchors is
118
+ * meta-content and must not produce a `recurred` verdict. Prefix-matched
119
+ * (\binstrument covers instrumented/instrumentation, \bbenchmark covers
120
+ * benchmarking) — recall-safe because a genuine violation admission has no
121
+ * reason to name the instrument.
122
+ *
123
+ * Exported for the same reason as RECURRENCE_MARKER above.
124
+ */
125
+ export declare const EVAL_VOCAB_ANCHOR: RegExp;
126
+ /**
127
+ * Unique, lowercase, ≥4-char content words in a correction's rule text —
128
+ * \W+-split. Single source for the "topical overlap" word set: session-end's
129
+ * heeded/recurred/not_violated split below computes matchCount against this
130
+ * exact set, and transcript-audit's CITED tier (evolution p1a) reuses it
131
+ * verbatim so the two adjudicators can never silently drift apart on what
132
+ * counts as a "content word". Pure; exported for direct unit testing.
133
+ */
134
+ export declare function ruleContentWords(rule: string): string[];
100
135
  /**
101
136
  * True when the summary contains a recurrence marker in a sentence that is NOT
102
137
  * eval-meta prose. Sentence granularity via the decimal-safe splitSentences —
@@ -1 +1 @@
1
- {"version":3,"file":"session-end.d.ts","sourceRoot":"","sources":["../../src/tools-logic/session-end.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAoBH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAMtD,OAAO,KAAK,EAAE,eAAe,EAAE,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AAEpH;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB,QACgG,CAAC;AAE/H;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAMvD;AAED;;;;;;;GAOG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAOnE;AAED,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,eAAe,CAAC,UAAU,CAAC,GACpC,qBAAqB,EAAE,CA6CzB;AAED,wBAAsB,UAAU,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAwyBlF"}
@@ -36,8 +36,14 @@ import { stagePendingCorrection, validateInsightCompleteness } from "../storage/
36
36
  * "same mistake" retained; added violated/violating/violation, "ignored the rule",
37
37
  * "didn't follow". The bar for a `recurred` verdict is marker + trigger/topical
38
38
  * evidence — widening markers alone does not produce more recurred verdicts.
39
+ *
40
+ * Exported (evolution p1a, transcript-audit) — the transcript-audit ladder
41
+ * needs the RAW regex (not just the whole-text boolean hasGenuineRecurrenceMarker
42
+ * gives) to test recurrence-marker-hit-AND-topic-co-occurrence on the SAME
43
+ * sentence. Exporting the regex avoids a second, drift-prone copy of this
44
+ * pattern living in packages/core/src/tools-logic/transcript-audit.ts.
39
45
  */
40
- const RECURRENCE_MARKER = /\b(again|recurred|repeated|violat(?:ed|ing|ion)|broke the rule|ignored the rule|didn'?t follow|same mistake)\b/i;
46
+ export const RECURRENCE_MARKER = /\b(again|recurred|repeated|violat(?:ed|ing|ion)|broke the rule|ignored the rule|didn'?t follow|same mistake)\b/i;
41
47
  /**
42
48
  * C3 meta-content guard — eval-vocabulary anchors. This project's own summaries
43
49
  * routinely DISCUSS the measurement system ("the recurred count violated our
@@ -47,8 +53,25 @@ const RECURRENCE_MARKER = /\b(again|recurred|repeated|violat(?:ed|ing|ion)|broke
47
53
  * (\binstrument covers instrumented/instrumentation, \bbenchmark covers
48
54
  * benchmarking) — recall-safe because a genuine violation admission has no
49
55
  * reason to name the instrument.
56
+ *
57
+ * Exported for the same reason as RECURRENCE_MARKER above.
50
58
  */
51
- const EVAL_VOCAB_ANCHOR = /\b(rmr|heed[_\s-]?rate|baseline|_outcomes|recurrence[_\s-]?count|verdict[_\s-]?coverage|instrument|predict-loo|benchmark)/i;
59
+ export const EVAL_VOCAB_ANCHOR = /\b(rmr|heed[_\s-]?rate|baseline|_outcomes|recurrence[_\s-]?count|verdict[_\s-]?coverage|instrument|predict-loo|benchmark)/i;
60
+ /**
61
+ * Unique, lowercase, ≥4-char content words in a correction's rule text —
62
+ * \W+-split. Single source for the "topical overlap" word set: session-end's
63
+ * heeded/recurred/not_violated split below computes matchCount against this
64
+ * exact set, and transcript-audit's CITED tier (evolution p1a) reuses it
65
+ * verbatim so the two adjudicators can never silently drift apart on what
66
+ * counts as a "content word". Pure; exported for direct unit testing.
67
+ */
68
+ export function ruleContentWords(rule) {
69
+ const words = rule
70
+ .toLowerCase()
71
+ .split(/\W+/)
72
+ .filter((w) => w.length >= 4);
73
+ return [...new Set(words)];
74
+ }
52
75
  /**
53
76
  * True when the summary contains a recurrence marker in a sentence that is NOT
54
77
  * eval-meta prose. Sentence granularity via the decimal-safe splitSentences —
@@ -256,11 +279,7 @@ export async function sessionEnd(input) {
256
279
  const hasTriggerEvidence = !!(firedToday && firedToday.has("triggered"));
257
280
  // Topical-overlap heuristic (weak supplementary source):
258
281
  // ≥2 content words (≥4 chars) from the rule appear in the session summary.
259
- const ruleWords = c.rule
260
- .toLowerCase()
261
- .split(/\W+/)
262
- .filter((w) => w.length >= 4);
263
- const uniqueRuleWords = [...new Set(ruleWords)];
282
+ const uniqueRuleWords = ruleContentWords(c.rule);
264
283
  const matchCount = uniqueRuleWords.filter((w) => summaryLower.includes(w)).length;
265
284
  const hasTopicalOverlap = matchCount >= 2;
266
285
  const hasRecurrenceMarker = genuineRecurrence;