@tpsdev-ai/flair 0.55.0 → 0.55.2

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.
@@ -0,0 +1,238 @@
1
+ /**
2
+ * wiring-spec.ts — the interim wiring-spec model (flair#1778 slice 2c-i-a1).
3
+ *
4
+ * ONE decoder + ONE partition for "what version does this wiring entry name?",
5
+ * replacing the extractor that reported a range/tag/unsupported source as
6
+ * `null` — i.e. as if the entry were ABSENT. That null is the bug: every guard
7
+ * downstream reads `null` as "no pin to protect" and OVERWRITES the spec (a
8
+ * `@^0.55.0` range, a `@latest` tag, a `file:` source).
9
+ *
10
+ * A LEAF module on purpose: it imports only `semver` and `isStrictSemver`
11
+ * (`./npm-registry.js`), so every consumer — doctor-client.ts (which owns the
12
+ * old extractor), owned-pins.ts, install/clients.ts — can migrate to it with
13
+ * no import cycle now or later.
14
+ *
15
+ * This PR adds the type and migrates consumers. It does NOT add the writers'
16
+ * guards (that is 2c-i-a2). The one behaviour change here is deliberate and
17
+ * named: a range/tag/unsupported/malformed spec is now PRESENT-BUT-
18
+ * NOT-COMPARABLE instead of null-therefore-absent; `version` and `none` tokens
19
+ * keep every caller's current outcome.
20
+ *
21
+ * ─── Partition rule (each step total, evaluated in this order) ─────────────
22
+ * 1. the spec's source is `file:` / `link:` / `git:` / `git+https:` /
23
+ * `github:` / `http(s):` → `unsupported`
24
+ * 2. no token after `@` (or nothing after `npm:`/`workspace:`) → `none`
25
+ * 3. the token matches /^v\d/ → `malformed`
26
+ * (checked BEFORE range recognition: semver's `validRange` ACCEPTS
27
+ * `v0.55.0`, so a range test first would misclassify it. The leading `v`
28
+ * is NOT normalised away — it is exactly what makes the token
29
+ * non-canonical, and normalising it is how `@v0.55.0` used to be read
30
+ * as the version `0.55.0`.)
31
+ * 4. `isStrictSemver(token)` → `version`
32
+ * (strict `X.Y.Z[-prerelease][+build]`, no leading `v`; a prerelease like
33
+ * `0.56.0-rc.1` IS a version.)
34
+ * 5. `semver.validRange(token)` or a dist-tag word
35
+ * (`latest` / `next` / `beta` / `alpha` / `rc` / `canary` / `stable` /
36
+ * `dev` / `experimental` / `*`) → `range-or-tag`
37
+ * (this catches `0.55`, `~0.55`, `^0.55.0`, `>=1 <2`; the tag set is the
38
+ * npm-conventional one — flair#1809 review carry-over — so `@beta`
39
+ * classifies as a tag rather than `malformed`. Either way it is
40
+ * PRESENT-BUT-NOT-COMPARABLE; only the label differs.)
41
+ * 6. anything else (a 4-part `1.2.3.4`, garbage) → `malformed`
42
+ *
43
+ * `raw` is always kept, so a consumer can preserve the exact bytes it read.
44
+ */
45
+ import semver from "semver";
46
+ import { isStrictSemver } from "./npm-registry.js";
47
+ /** A source spec that is never an installable version pin. */
48
+ const UNSUPPORTED_SOURCE_RE = /^(?:file:|link:|git:|git\+https:|git\+ssh:|github:|https?:)/;
49
+ /** The dist-tag words npm resolves by name, plus the `*` wildcard. */
50
+ const DIST_TAG_WORDS = new Set([
51
+ "latest",
52
+ "next",
53
+ "beta",
54
+ "alpha",
55
+ "rc",
56
+ "canary",
57
+ "stable",
58
+ "dev",
59
+ "experimental",
60
+ "*",
61
+ ]);
62
+ /** Strip the `workspace:` / `npm:` protocol from a dependency-field value. */
63
+ function stripSpecProtocol(spec) {
64
+ return spec.replace(/^(?:workspace|npm):/, "");
65
+ }
66
+ /** Partition one decoded spec token. Total; see the module doc for the rule. */
67
+ export function partitionWiringToken(rawToken) {
68
+ const token = (rawToken ?? "").trim();
69
+ if (UNSUPPORTED_SOURCE_RE.test(token))
70
+ return { kind: "unsupported", value: token };
71
+ if (token === "")
72
+ return { kind: "none", value: null };
73
+ if (/^v\d/.test(token))
74
+ return { kind: "malformed", value: token };
75
+ if (isStrictSemver(token))
76
+ return { kind: "version", value: token };
77
+ if (DIST_TAG_WORDS.has(token) || semver.validRange(token) !== null) {
78
+ return { kind: "range-or-tag", value: token };
79
+ }
80
+ return { kind: "malformed", value: token };
81
+ }
82
+ /**
83
+ * The token terminators for a `<pkg>@<token>` spec: whitespace, `"`, `'`, `,`,
84
+ * `]` (the delimiters an args array / hook command / TOML line can use).
85
+ */
86
+ function isTokenTerminator(ch) {
87
+ return ch === undefined || ch === "" || /\s/.test(ch) || ch === '"' || ch === "'" || ch === "," || ch === "]";
88
+ }
89
+ /**
90
+ * True when the match at `idx` starts at a token boundary — the start of the
91
+ * text, or a non-identifier character before it. This keeps `<pkg>@` from
92
+ * matching inside a LONGER sibling package name (e.g. `@tpsdev-ai/flair-mcp`
93
+ * inside `@tpsdev-ai/flair-mcp-extra@1.0`), or a name that merely ends with it.
94
+ */
95
+ function isTokenStart(s, idx) {
96
+ if (idx <= 0)
97
+ return true;
98
+ // A preceding "/" means this match is the TAIL OF A SCOPED SIBLING, not the
99
+ // package: in `npm:@other/@tpsdev-ai/flair-mcp@1.0.0` the `flair-mcp@` match
100
+ // begins right after the sibling scope's "/". Every pkg constant today is
101
+ // scoped (@tpsdev-ai/…), so the gap is unreachable in practice, but an
102
+ // unscoped caller would otherwise read the sibling's pinned tail as its own
103
+ // (flair#1809 review carry-over).
104
+ if (s[idx - 1] === "/")
105
+ return false;
106
+ return !/[A-Za-z0-9_\-.]/.test(s[idx - 1]);
107
+ }
108
+ /** Read from `from` up to the first token terminator. */
109
+ function readSpecToken(s, from) {
110
+ let i = from;
111
+ while (i < s.length && !isTokenTerminator(s[i]))
112
+ i++;
113
+ return s.slice(from, i);
114
+ }
115
+ /**
116
+ * Envelope A — every `<pkg>@<token>` occurrence, found by a plain `indexOf`
117
+ * scan (NO dynamic RegExp). One decoder for all of them: an
118
+ * `npx -y -p <pkg>@<spec>` command, an MCP client `args` array, a Codex TOML
119
+ * `args = [...]` line, a SessionStart hook command, or pi's
120
+ * `npm:<pkg>@<spec>` source all reduce to the same `<pkg>@<spec>` substring.
121
+ */
122
+ function findPackageSpecs(text, pkg) {
123
+ const needle = `${pkg}@`;
124
+ const out = [];
125
+ let from = 0;
126
+ for (;;) {
127
+ const idx = text.indexOf(needle, from);
128
+ if (idx === -1)
129
+ break;
130
+ if (isTokenStart(text, idx)) {
131
+ const token = readSpecToken(text, idx + needle.length);
132
+ out.push({ raw: needle + token, token });
133
+ }
134
+ from = idx + needle.length;
135
+ }
136
+ return out;
137
+ }
138
+ /**
139
+ * Envelope B — a dependency field `"pkg": "<spec>"` (package.json), whose
140
+ * value may carry the `workspace:` / `npm:` protocol (`workspace:^0.55.0` →
141
+ * `^0.55.0`). Found by string operations: the quoted key, optional whitespace,
142
+ * `:`, optional whitespace, a `"`, then the value up to the next `"`.
143
+ */
144
+ function decodeDependencyField(text, pkg) {
145
+ const key = `"${pkg}"`;
146
+ let from = 0;
147
+ for (;;) {
148
+ const idx = text.indexOf(key, from);
149
+ if (idx === -1)
150
+ return null;
151
+ if (isTokenStart(text, idx)) {
152
+ let i = idx + key.length;
153
+ while (i < text.length && /\s/.test(text[i]))
154
+ i++;
155
+ if (text[i] === ":") {
156
+ i++;
157
+ while (i < text.length && /\s/.test(text[i]))
158
+ i++;
159
+ if (text[i] === '"') {
160
+ const valueStart = i + 1;
161
+ const end = text.indexOf('"', valueStart);
162
+ if (end === -1)
163
+ return null;
164
+ return {
165
+ raw: text.slice(idx, end + 1),
166
+ pkg,
167
+ token: partitionWiringToken(stripSpecProtocol(text.slice(valueStart, end))),
168
+ };
169
+ }
170
+ }
171
+ }
172
+ from = idx + key.length;
173
+ }
174
+ }
175
+ /**
176
+ * Decode ONE wiring string into a WiringSpec, or null when `pkg` is not wired
177
+ * in it. Total: every envelope reduces to `<pkg>@<spec>` or a bare package.
178
+ * A bare package (no `@`) is `kind: "none"` — wired, no token.
179
+ */
180
+ export function decodeWiringSpec(text, pkg) {
181
+ if (typeof text !== "string" || !text.includes(pkg))
182
+ return null;
183
+ const first = findPackageSpecs(text, pkg)[0];
184
+ if (first)
185
+ return { raw: first.raw, pkg, token: partitionWiringToken(first.token) };
186
+ const byDep = decodeDependencyField(text, pkg);
187
+ if (byDep)
188
+ return byDep;
189
+ return { raw: pkg, pkg, token: { kind: "none", value: null } };
190
+ }
191
+ /**
192
+ * Decode EVERY `<pkg>@<spec>` occurrence in `text` (plus a dependency field
193
+ * when present) — one WiringSpec per entry, never collapsing to the first, in
194
+ * TEXT ORDER. Useful to a caller that must enumerate all wired artifacts
195
+ * (flair#1778 I6).
196
+ */
197
+ export function decodeWiringSpecs(text, pkg) {
198
+ if (typeof text !== "string" || !text.includes(pkg))
199
+ return [];
200
+ const out = [];
201
+ const seen = new Set();
202
+ for (const spec of findPackageSpecs(text, pkg)) {
203
+ if (seen.has(spec.raw))
204
+ continue;
205
+ seen.add(spec.raw);
206
+ out.push({ raw: spec.raw, pkg, token: partitionWiringToken(spec.token) });
207
+ }
208
+ const dep = decodeDependencyField(text, pkg);
209
+ if (dep && !seen.has(dep.raw))
210
+ out.push(dep);
211
+ if (out.length === 0)
212
+ out.push({ raw: pkg, pkg, token: { kind: "none", value: null } });
213
+ return out;
214
+ }
215
+ /**
216
+ * The pin string a consumer should treat as "what this wiring names".
217
+ *
218
+ * version → the version (compares as today)
219
+ * none (unpinned/absent) → null (today's outcome: nothing to protect)
220
+ * range-or-tag / unsupported / malformed
221
+ * → the token text — PRESENT, and not comparable.
222
+ *
223
+ * The last line is the whole point: feeding that text to
224
+ * `pinWriteWouldLowerOrIsUnknown` makes `comparePinVersions` return null, so the
225
+ * fail-closed guard HOLDS. Before this, those specs yielded null, which the
226
+ * guard reads as "absent — safe to write", and the entry was overwritten.
227
+ */
228
+ export function wiringPinString(spec) {
229
+ if (!spec)
230
+ return null;
231
+ if (spec.token.kind === "none")
232
+ return null;
233
+ return spec.token.value ?? spec.raw;
234
+ }
235
+ /** True when the spec names a concrete, comparable version. */
236
+ export function isComparableWiringPin(spec) {
237
+ return spec?.token.kind === "version";
238
+ }
@@ -202,3 +202,105 @@ export function validateHumanReviewerId(reviewerId) {
202
202
  }
203
203
  return null;
204
204
  }
205
+ // ─── Structural-truncation signal (flair#1756 slice 2, #1776 slice 3) ────────
206
+ // The SINGLE definition of the structural-truncation signal. The GATE for it
207
+ // lives server-side in resources/auto-promote-lib.ts (decideAutoPromote — the
208
+ // UNATTENDED path), which IMPORTS these from here. The direction is deliberate
209
+ // and established in this repo: a server file may import a PURE helper from src/
210
+ // (resources/PromoteMemoryCandidate.ts and resources/soul-adk-guard.ts already
211
+ // import this very module); it is a CLI file importing FROM resources/ that does
212
+ // not survive npm packaging. Defining it here lets the CLI side
213
+ // (src/commands/rem.ts, `flair rem candidates`) and the server gate share ONE
214
+ // implementation rather than a hand-kept pair.
215
+ //
216
+ // Detects STRUCTURAL imbalance (unclosed/unmatched backtick, bracket, paren,
217
+ // brace) — NOT semantic completeness. A balanced claim can still be a fragment.
218
+ //
219
+ // The delimiter set is an ENUMERATED table (STRUCTURAL_PAIRS, below): the ASCII
220
+ // pairs `( )`, `[ ]`, `{ }` AND the full-width/CJK pairs
221
+ // `()[]{}【】〔〕〖〗「」『』《》〈〉〘〙〚〛`. Both the opener set and the closer
222
+ // map are DERIVED from that one list, so a pair cannot be added to one side and
223
+ // missed on the other. The table IS the boundary: mathematical and ornamental
224
+ // brackets (`⟨⟩ ⟦⟧ ⌈⌉ ⌊⌋ ⁅⁆ ⦅⦆ ❨❩ ༺༻`) are deliberately EXCLUDED — they are used
225
+ // standalone in real text, so counting them by category would over-refuse. The
226
+ // set is deliberately NOT derived from Unicode general categories
227
+ // (`\p{Ps}` / `\p{Pe}`) and is NOT described as "Unicode-aware": category
228
+ // membership does not establish paired usage (Ogham `᚛` and bare `༺`/`༻`,
229
+ // `⸢`/`⸣`, `⌈`/`⌉` are permitted standalone by the core spec), and a category
230
+ // counter refuses ordinary COMPLETE prose — see the quotation-mark note
231
+ // immediately below. There is no vendored Unicode data and no codegen here.
232
+ //
233
+ // QUOTATION MARKS OF EVERY SCRIPT ARE OUT OF SCOPE. `“ ” ‘ ’ „ “ ‚ ‘ « »` are
234
+ // NOT counted, so a claim truncated mid-quotation is judged balanced. The reason
235
+ // is concrete, not a preference: U+201E `„` (and U+201A `‚`) is category Ps
236
+ // while its closing mark U+201C (U+2018) is Pi, so ANY category-based counter
237
+ // reports positive depth on the ordinary COMPLETE German quotation `„Fertig.“`
238
+ // and refuses it; and U+2019 `’` is the standard English apostrophe (category
239
+ // Pf), so a quote-counting leg refuses every English contraction (e.g. `isn’t`).
240
+ // Enumerating matched bracket pairs avoids both false positives. That is why
241
+ // categories were rejected in favour of this table.
242
+ //
243
+ // The check counts delimiters without interpreting context, so a complete claim
244
+ // that merely DISCUSSES an unmatched delimiter is also flagged/refused
245
+ // (fail-closed; nothing is lost — the candidate stays pending for the human
246
+ // `rem promote` path).
247
+ //
248
+ // Runtimes this signal was exercised against (2026-09-21): Node v22.22.1
249
+ // (process.versions.unicode = 17.0) and Bun 1.3.10 (process.versions.unicode =
250
+ // 15.1). Passing the check means NO DETECTED IMBALANCE for the enumerated
251
+ // pairs — never completeness, and never coverage of an unenumerated script.
252
+ // The one source of truth: [opener, closer]. The two lookups below are DERIVED,
253
+ // so there is no second hand-kept list that can drift out of step. All three are
254
+ // exported so the pair-table invariant can be pinned by a test without
255
+ // duplicating the list here.
256
+ export const STRUCTURAL_PAIRS = [
257
+ ["(", ")"], ["[", "]"], ["{", "}"],
258
+ ["(", ")"], ["[", "]"], ["{", "}"],
259
+ ["【", "】"], ["〔", "〕"], ["〖", "〗"],
260
+ ["「", "」"], ["『", "』"],
261
+ ["《", "》"], ["〈", "〉"], ["〘", "〙"], ["〚", "〛"],
262
+ ];
263
+ export const STRUCTURAL_OPENERS = new Map(STRUCTURAL_PAIRS);
264
+ export const STRUCTURAL_CLOSERS = new Map(STRUCTURAL_PAIRS.map(([opener, closer]) => [closer, opener]));
265
+ /**
266
+ * Return a description of the STRUCTURAL imbalance in `claim` (an unmatched or
267
+ * closing-first bracket, an unclosed opener, or an odd number of backticks), or
268
+ * null if it is balanced. The delimiter set is the ENUMERATED table above
269
+ * (ASCII + full-width/CJK pairs); a delimiter outside that set — in particular a
270
+ * quotation mark of any script — is not examined and does not make this
271
+ * non-null. Pure. The description is for diagnostics only — it is NOT surfaced
272
+ * as a claim about completeness.
273
+ */
274
+ export function structuralImbalance(claim) {
275
+ const stack = [];
276
+ for (const ch of claim) {
277
+ if (STRUCTURAL_OPENERS.has(ch)) {
278
+ stack.push(ch);
279
+ }
280
+ else {
281
+ const opener = STRUCTURAL_CLOSERS.get(ch);
282
+ if (opener !== undefined && stack.pop() !== opener)
283
+ return `unmatched '${ch}'`;
284
+ }
285
+ }
286
+ if (stack.length > 0)
287
+ return `unclosed '${stack[stack.length - 1]}'`;
288
+ if (((claim.match(/`/g) ?? []).length) % 2 !== 0)
289
+ return "unbalanced backtick";
290
+ return null;
291
+ }
292
+ /**
293
+ * True iff `claim` ends with terminal punctuation (optionally followed by a
294
+ * closing quote/bracket). This is a FLAG INPUT ONLY, never a refusal: plenty of
295
+ * legitimate claims end without a full stop, and on the UNATTENDED path a false
296
+ * refusal is silent. `flair rem candidates` surfaces it for the human reviewer.
297
+ *
298
+ * Terminators: ASCII `.` `!` `?` plus the full-width/CJK `。` (U+3002), `!`
299
+ * (U+FF01), `?` (U+FF1F). The trailing-suffix class accepts the quote/bracket
300
+ * closers it always did plus the enumerated bracket closers
301
+ * `」』)]}】〕〗》〉〙〛`. The single-dot leaders `…` `‥` `․` are deliberately NOT
302
+ * terminators — they are not interchangeable with a full stop.
303
+ */
304
+ export function hasTerminalPunctuation(claim) {
305
+ return /[.!?。!?]["')\]}»”’」』)]}】〕〗》〉〙〛]*$/.test(claim.trimEnd());
306
+ }
@@ -308,6 +308,16 @@ export class ReflectMemories extends Resource {
308
308
  // Static body (K&S) — never echo Harper version, backend lists, or endpoints.
309
309
  return new Response(JSON.stringify({ error: "No generative backend configured. See the models configuration docs." }), { status: 503 });
310
310
  }
311
+ if (distill.outcome.reason === "incomplete_generation") {
312
+ // The backend PROVED the generation was cut short (finishReason
313
+ // `length` or `content_filter`). Valid-looking JSON from an incomplete
314
+ // response must not stage as a finished thought (flair#1756). Static
315
+ // body — never echo backend detail.
316
+ return new Response(JSON.stringify({
317
+ error: "distillation_failed",
318
+ detail: "model output was incomplete — the backend reported the generation was cut short",
319
+ }), { status: 502 });
320
+ }
311
321
  return new Response(JSON.stringify({ error: "distillation_failed", detail: "model output did not validate after one retry" }), { status: 502 });
312
322
  }
313
323
  // Response omits rationalePrompt (spec §3A item 5: "no prompt field") —
@@ -40,6 +40,7 @@
40
40
  // the whole fail-closed/strict-safety decision is unit-testable directly with no
41
41
  // Harper process — the same split resources/memory-reflect-lib.ts uses.
42
42
  import { scanFields } from "./content-safety.js";
43
+ import { structuralImbalance } from "../src/rem/promote-policy.js";
43
44
  // ─── ADK scope tag (the per-user access-control boundary) ────────────────────
44
45
  // adk-flair collapses (app, user) → ONE Flair agentId, separating users ONLY by
45
46
  // a compound tag `adk:<app>:<user>`. That tag IS the access-control boundary, so
@@ -71,6 +72,51 @@ export const AUTO_PROMOTE_RATIONALE = "auto-promoted from ADK session distillati
71
72
  * path. Overflow stays `pending` and is swept on subsequent cycles.
72
73
  */
73
74
  export const DEFAULT_MAX_AUTO_PROMOTE_PER_CYCLE = 200;
75
+ // ─── Structural-truncation signal (flair#1756 slice 2) ───────────────────────
76
+ // The signal (structuralImbalance / hasTerminalPunctuation) is defined ONCE in
77
+ // src/rem/promote-policy.ts. This gate imports structuralImbalance from it; the
78
+ // CLI flag path (src/commands/rem.ts) uses hasTerminalPunctuation from the same
79
+ // module. A server file importing a PURE helper from src/ is established practice
80
+ // in this repo (resources/PromoteMemoryCandidate.ts and resources/soul-adk-guard.ts
81
+ // both import that module); what does not survive npm packaging is a CLI file
82
+ // importing FROM resources/. One definition lets the CLI and this gate share a
83
+ // single implementation rather than a hand-kept pair.
84
+ //
85
+ // Slice 1 handled a generation the backend LABELLED incomplete (finishReason
86
+ // `length` / `content_filter`). This handles the other case: a claim reaches
87
+ // staging STRUCTURALLY TRUNCATED while the response PARSES and VALIDATES — the
88
+ // observed candidate ended at an unclosed code span and parenthesis, and because
89
+ // validation checks only SHAPE, a truncated string is still a valid string in a
90
+ // valid object, so nothing upstream rejects it.
91
+ //
92
+ // WHY the model emitted a well-formed payload carrying an unfinished claim is NOT
93
+ // ESTABLISHED. It was NOT an unescaped inner quote terminating the JSON string:
94
+ // parseAndValidateCandidates calls JSON.parse and would return invalid_json, so
95
+ // such a payload never reaches staging at all. This signal keys on the SYMPTOM —
96
+ // structural imbalance — which is identical however the fragment arose, so the
97
+ // mechanism does not need to be known in order to refuse it.
98
+ //
99
+ // Such a fragment is not harmless. It reads as plausible, authoritative and
100
+ // INCOMPLETE, and once promoted it becomes durable recalled context asserting
101
+ // something it never finished saying.
102
+ //
103
+ // WHAT THIS DETECTS: STRUCTURAL imbalance — an unclosed/unmatched backtick,
104
+ // paren, bracket or brace. It does NOT detect semantic completeness. A balanced
105
+ // claim can still be a fragment, and a refusal here proves only that the text is
106
+ // structurally lopsided — never that a promoted claim is complete. Do not
107
+ // describe it otherwise anywhere (comment, changelog, skip reason) — we amended
108
+ // the 0.55.0 Metal entry for exactly this overclaim shape.
109
+ //
110
+ // The detection is ASCII-ONLY. It recognizes the ASCII backtick and the ASCII
111
+ // pairs ( ) [ ] { }. Non-ASCII pairs — full-width ()/[]/{} and CJK lenticular
112
+ // 【】/〔〕/〖〗 — are NOT covered, so a truncated claim written in those scripts
113
+ // is judged balanced and is NOT refused. Do not assume Unicode coverage.
114
+ //
115
+ // The check counts delimiters WITHOUT interpreting context, so it is deliberately
116
+ // over-broad: a COMPLETE claim that merely discusses an unmatched delimiter (an
117
+ // interval written half-open, prose quoting a lone bracket) is also refused. On
118
+ // this unattended path that is fail-closed and loses nothing — the candidate
119
+ // stays pending for the human `rem promote` path.
74
120
  /**
75
121
  * Decide whether an ADK-sourced candidate may be auto-promoted to own memory.
76
122
  *
@@ -110,6 +156,16 @@ export function decideAutoPromote(candidate) {
110
156
  if (!safety.safe) {
111
157
  return { promote: false, reason: `content_safety:${safety.flags.join(",")}` };
112
158
  }
159
+ // ── Structural truncation (flair#1756 slice 2) — APPENDED, so none of the
160
+ // refusals above is masked: each still fires in its own right when its own
161
+ // condition holds. An unbalanced delimiter set is the SYMPTOM of the observed
162
+ // defect (a claim staged mid-expression — it ended at `new Function(`), so it
163
+ // is REFUSED: the unattended path must never persist a fragment. Missing
164
+ // terminal punctuation is deliberately NOT checked here — it is a FLAG, not a
165
+ // refusal (see hasTerminalPunctuation).
166
+ if (structuralImbalance(claim) !== null) {
167
+ return { promote: false, reason: "incomplete_claim" };
168
+ }
113
169
  return {
114
170
  promote: true,
115
171
  scopeTag,
@@ -664,6 +664,32 @@ export class HealthDetail extends Resource {
664
664
  lastCycleAt: snapshot.lastCycleAt ?? null,
665
665
  lastCycleError: snapshot.lastCycleError ?? null,
666
666
  migrations: snapshot.migrations,
667
+ // flair#1800: the durable record can lag the in-memory outcome — a
668
+ // failed state.json write is surfaced here so "completed" here does
669
+ // not read as "recorded". Read-only; no new endpoint.
670
+ // { path: string | null, lastWriteError: { migrationId, at, message? } | null }
671
+ //
672
+ // flair#1800 review C2 (information disclosure): allowRead is
673
+ // allowVerified, so verified NON-admin agents reach this — and the path
674
+ // (an absolute <dataDir>/.migrations/state.json) plus the raw fs error
675
+ // message (which can embed that path) are absolute paths the resource
676
+ // keeps admin-only elsewhere (the disk block below does
677
+ // `isAdmin ? dataDir : redactHome(dataDir)`). Same idiom here.
678
+ stateFile: {
679
+ path: snapshot.stateFile.path
680
+ ? isAdmin
681
+ ? snapshot.stateFile.path
682
+ : redactHome(snapshot.stateFile.path)
683
+ : null,
684
+ lastWriteError: snapshot.stateFile.lastWriteError
685
+ ? isAdmin
686
+ ? snapshot.stateFile.lastWriteError
687
+ : {
688
+ migrationId: snapshot.stateFile.lastWriteError.migrationId,
689
+ at: snapshot.stateFile.lastWriteError.at,
690
+ }
691
+ : null,
692
+ },
667
693
  };
668
694
  for (const m of snapshot.migrations) {
669
695
  if (m.state === "halted" || m.state === "failed") {