Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(fence-repair): close unclosed fences ahead of trailing text; tail classifier (#6377 lanes A2/A3)
garrytanf6efb9ae31d2
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 4081f81232..02fe5d66a9 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1418,7 +1418,7 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| A facts or takes fence in the page cannot be imported without dropping or guessing rows, so the page (or the file) was not written. | Facts and takes fences are the page's structured rows. Importing a fence that does not parse, repeats a marker or reuses a row number would silently drop or renumber rows, so coordinated writers refuse it and managed sync holds the one file while the rest of the source syncs. | A refused write: fix the fence the message names (fence, section and rows; the reason says what is wrong) and send the page again with a new request_id, or write rows with remember / takes_add. A held file or stored page: the maintenance run repairs it; preview it now with gbrain repair fences --source <id> on the brain host. | agent | `repeat the read that failed` | 1 | no |-Reasons: `header_unmapped`, `no_header`, `row_before_header`, `short_row`, `extra_cells`, `claim_split`, `holder_unresolved`, `missing_begin`, `split_rows`, `unclosed_trailing_content`, `marker_near_miss`, `repeated_marker`, `takes_in_facts`, `superseded_ambiguous`, `enum_unmapped`, `weight_missing`, `holder_missing`, `confidence_out_of_range`, `claim_value_invalid`, `takes_kind_unsupported`, `unparseable`, `row_collision`, `quoted_fence_rows`, `stored_row_collision`, `withdrawn_claim_in_malformed_fence`, `target_fence_malformed`, `prepare_time`, `normalizer_failed`, `llm_unavailable`, `llm_empty`, `llm_refused`, `llm_malformed`, `llm_truncated`, `llm_declined`, `llm_disabled`, `no_measured_model`, `budget_exhausted`, `no_pricing`, `ledger_unavailable`, `owner_unavailable`, `owner_cli_required`, `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`, `sync_in_progress`, `time_budget`, `changed_since_read`, `changed_since_preview`, `still_invalid`, `claim_changed`, `row_number_changed`, `visibility_loosened`, `row_count_changed`, `cell_changed`, `protection_loosened`.+Reasons: `header_unmapped`, `no_header`, `row_before_header`, `short_row`, `extra_cells`, `claim_split`, `holder_unresolved`, `missing_begin`, `split_rows`, `unclosed_trailing_content`, `unclosed_ambiguous_tail`, `tail_exposure_approval`, `marker_near_miss`, `repeated_marker`, `takes_in_facts`, `superseded_ambiguous`, `enum_unmapped`, `weight_missing`, `holder_missing`, `confidence_out_of_range`, `claim_value_invalid`, `takes_kind_unsupported`, `unparseable`, `row_collision`, `quoted_fence_rows`, `stored_row_collision`, `withdrawn_claim_in_malformed_fence`, `target_fence_malformed`, `prepare_time`, `normalizer_failed`, `llm_unavailable`, `llm_empty`, `llm_refused`, `llm_malformed`, `llm_truncated`, `llm_declined`, `llm_disabled`, `no_measured_model`, `budget_exhausted`, `no_pricing`, `ledger_unavailable`, `owner_unavailable`, `owner_cli_required`, `host_mismatch`, `transfer_in_progress`, `clone_in_progress`, `incarnation_changed`, `local_path_missing`, `coordination_path_missing`, `sync_in_progress`, `time_budget`, `changed_since_read`, `changed_since_preview`, `still_invalid`, `claim_changed`, `row_number_changed`, `visibility_loosened`, `row_count_changed`, `cell_changed`, `protection_loosened`.More: [docs/guides/write-refusals.md#invalid_fence](../../docs/guides/write-refusals.md#invalid_fence)diff --git a/docs/guides/fence-format.md b/docs/guides/fence-format.mdindex 4f5bf8a393..9782260882 100644--- a/docs/guides/fence-format.md+++ b/docs/guides/fence-format.md@@ -170,6 +170,7 @@ These rules run on every write path for free. They edit or move cell text and ne| --- | --- || `merge_fences` | A section with more than one fence of a kind becomes one fence when every fence has both markers, the same canonical header and nothing but table lines inside: the later fences' rows are appended to the first in document order, a later row whose cells (every column but `#`) equal a kept row's as written is dropped, a number that now collides is renumbered (see [row numbers](#row-numbers)) and a `superseded by #N` reference follows its own fence's row N, and the later markers, tables and a repeated section heading above them are removed. Anything else stays `repeated_marker` and a person merges the fences. || `close_fence` | A fence with no end marker gets one directly after its table, when nothing but blank lines follows the last row up to the end of the section. |+| `close_fence_trailing` | A fence with no end marker whose table is followed by page text gets the end marker directly after its last row, so the text that followed becomes visible, when every trailing line is prose (no `|`, no fence marker; a line with a `|` only after the repair model read the tail as prose) and either the page is private (its body is never shown to remote readers, so nothing new is disclosed) or the user approved those exact lines through the hash-bound apply the preview prints. A world-visible page with no approval is `tail_exposure_approval`; a tail the model read as rows, or a marker mention, is `unclosed_ambiguous_tail` and a person closes the fence. || `marker_form` | Two-dash takes markers (`<!-- gbrain:takes:begin -->`) directly above a takes table become the three-dash markers. Two-dash facts markers are not a fence and are left alone. || `stray_empty_cell` | A row with more cells than its header (with no header: than the narrow layout, or 14 facts cells) loses empty cells, only when exactly one choice of empty cells to remove leaves every checked column (`#`, kind, confidence, visibility, notability, `claim_value`; takes kind, holder, weight) valid. Otherwise the row is `extra_cells` and a person fixes it. || `renumber` | A row number that is zero, negative, not a number or a duplicate gets a new number (see [row numbers](#row-numbers)). |@@ -218,9 +219,9 @@ Header cells are compared case-insensitively, with spaces, `_` and `-` treated aA problem the rules above cannot fix exactly is held or refused with a reason. The reason says which tier clears it:-- **llm** (Tier 3, the repair model rewrites only the named rows, or answers HOLD when a row has two readings): [`header_unmapped`](write-refusals.md#fence-header_unmapped), [`no_header`](write-refusals.md#fence-no_header), [`row_before_header`](write-refusals.md#fence-row_before_header), [`short_row`](write-refusals.md#fence-short_row).+- **llm** (Tier 3, the repair model rewrites only the named rows, or answers HOLD when a row has two readings): [`header_unmapped`](write-refusals.md#fence-header_unmapped), [`no_header`](write-refusals.md#fence-no_header), [`row_before_header`](write-refusals.md#fence-row_before_header), [`short_row`](write-refusals.md#fence-short_row), [`unclosed_trailing_content`](write-refusals.md#fence-unclosed_trailing_content).- **resolver** (Tier 2, verified holder lookup, free): [`holder_unresolved`](write-refusals.md#fence-holder_unresolved).-- **manual** (a person edits the fence; gbrain never guesses): [`extra_cells`](write-refusals.md#fence-extra_cells), [`claim_split`](write-refusals.md#fence-claim_split), [`missing_begin`](write-refusals.md#fence-missing_begin), [`split_rows`](write-refusals.md#fence-split_rows), [`unclosed_trailing_content`](write-refusals.md#fence-unclosed_trailing_content), [`marker_near_miss`](write-refusals.md#fence-marker_near_miss), [`repeated_marker`](write-refusals.md#fence-repeated_marker), [`takes_in_facts`](write-refusals.md#fence-takes_in_facts), [`superseded_ambiguous`](write-refusals.md#fence-superseded_ambiguous), [`enum_unmapped`](write-refusals.md#fence-enum_unmapped), [`weight_missing`](write-refusals.md#fence-weight_missing), [`holder_missing`](write-refusals.md#fence-holder_missing), [`confidence_out_of_range`](write-refusals.md#fence-confidence_out_of_range), [`claim_value_invalid`](write-refusals.md#fence-claim_value_invalid), [`takes_kind_unsupported`](write-refusals.md#fence-takes_kind_unsupported).+- **manual** (a person edits the fence; gbrain never guesses): [`extra_cells`](write-refusals.md#fence-extra_cells), [`claim_split`](write-refusals.md#fence-claim_split), [`missing_begin`](write-refusals.md#fence-missing_begin), [`split_rows`](write-refusals.md#fence-split_rows), [`marker_near_miss`](write-refusals.md#fence-marker_near_miss), [`repeated_marker`](write-refusals.md#fence-repeated_marker), [`takes_in_facts`](write-refusals.md#fence-takes_in_facts), [`superseded_ambiguous`](write-refusals.md#fence-superseded_ambiguous), [`enum_unmapped`](write-refusals.md#fence-enum_unmapped), [`weight_missing`](write-refusals.md#fence-weight_missing), [`holder_missing`](write-refusals.md#fence-holder_missing), [`confidence_out_of_range`](write-refusals.md#fence-confidence_out_of_range), [`claim_value_invalid`](write-refusals.md#fence-claim_value_invalid), [`takes_kind_unsupported`](write-refusals.md#fence-takes_kind_unsupported).<a id="gates"></a>### Gates every repair passes@@ -235,5 +236,5 @@ No tier writes a fence until all of these hold, and the result is one the rules| (d) | [`visibility_loosened`](write-refusals.md#fence-visibility_loosened) | No row becomes more visible: `private` never turns `world`. || (e) | [`row_count_changed`](write-refusals.md#fence-row_count_changed) | No row is added or dropped, and every row of the fence stays inside it; under `merge_fences` the only rows dropped are the exact duplicates its mapping names. || (f) | [`cell_changed`](write-refusals.md#fence-cell_changed) | A cell valid in its column keeps its text; a misaligned cell may only move, and text changes only through a named rule. |-| (g) | [`protection_loosened`](write-refusals.md#fence-protection_loosened) | Text the privacy boundary hid before the repair stays hidden after it. |+| (g) | [`protection_loosened`](write-refusals.md#fence-protection_loosened) | Text the privacy boundary hid before the repair stays hidden after it, except the trailing lines a `close_fence_trailing` fix shows (admitted only on a private page or under the user's approval). |<!-- END GENERATED fence-format -->diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 1e0a0ef617..ba274d6717 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -318,7 +318,9 @@ clears or retries it with no one acting.| <a id="fence-holder_unresolved"></a>`holder_unresolved` | A takes `who` cell is not `world`, `brain`, `people/<slug>` or `companies/<slug>` (for example a person's display name). | `resolver` | yes | Rewritten by the next maintenance run when it resolves to exactly one verified `people/` or `companies/` page (never a private page on a world-visible page). Otherwise write one of those forms by hand. Format: [holders](fence-format.md#holders). || <a id="fence-missing_begin"></a>`missing_begin` | An end marker has no begin marker before it. | `manual` | no | Add the begin marker above the table, or delete the stray end marker. Format: [markers](fence-format.md#markers). || <a id="fence-split_rows"></a>`split_rows` | A fence has no end marker and its rows are split by blank lines or text, so gbrain cannot tell which rows belong to it. | `manual` | no | Join the rows into one table and add the end marker after the last row. Format: [markers](fence-format.md#markers). |-| <a id="fence-unclosed_trailing_content"></a>`unclosed_trailing_content` | A fence has no end marker and other text follows its table, so closing it automatically could expose text the privacy boundary hides. | `manual` | no | Add the end marker directly after the last table row, or wrap a mere mention of the marker in backticks. Format: [markers](fence-format.md#markers). |+| <a id="fence-unclosed_trailing_content"></a>`unclosed_trailing_content` | A fence has no end marker and lines holding a pipe follow its table, so the rules cannot tell table rows from prose. | `llm` | yes | The maintenance run asks the repair model whether the tail is prose; a prose tail closes the fence after its last row (on a private page by itself; on a world-visible page after the user approves the lines it shows, see `tail_exposure_approval`). A tail of plain prose with no pipe never reaches the model: it closes by itself on a private page and waits for approval on a world page. By hand: add the end marker directly after the last table row. Format: [markers](fence-format.md#markers). |+| <a id="fence-unclosed_ambiguous_tail"></a>`unclosed_ambiguous_tail` | A fence has no end marker and the lines after its table are not plain prose: a row written without pipes, a mention of a fence marker, or a tail the repair model read as rows or could not classify. | `manual` | no | Add the end marker directly after the last table row and fix the rows below it, or wrap a marker mention in backticks; gbrain does not guess where the fence ends. Format: [markers](fence-format.md#markers). |+| <a id="fence-tail_exposure_approval"></a>`tail_exposure_approval` | A fence on a world-visible page has no end marker and prose follows its table; gbrain can close it after the last row, but the lines after the table would then be visible to readers of the page, so the close waits for the user. | `deterministic` | no | `gbrain repair fences --source <source> --only <path>` previews the close and prints the lines that would become visible with the apply command (`--apply --expect <hash>`); run it once the user agrees. Unattended runs never close it. Format: [markers](fence-format.md#markers). || <a id="fence-marker_near_miss"></a>`marker_near_miss` | A line uses the two-dash takes marker (`<!-- gbrain:takes:begin -->`) or mentions it with no takes table after it. Two-dash markers directly above a takes table are rewritten by themselves. | `manual` | no | Use the exact three-dash markers around the takes table, or wrap a mere mention in backticks. Format: [markers](fence-format.md#markers). || <a id="fence-repeated_marker"></a>`repeated_marker` | A body or timeline section has a second begin or end marker for the same fence outside code. Two or more fences that each have both markers, the same canonical header and nothing but table lines inside are merged by themselves (`merge_fences`: later rows appended, exact duplicates dropped, colliding numbers renumbered, a repeated section heading removed). | `manual` | no | Give the extra fence both markers and the first fence's header and move any other text out of it, so the next write or maintenance run merges them; or merge by hand, keeping one begin and one end marker per fence in that section with every row in one table. Format: [markers](fence-format.md#markers), [what gbrain rewrites](fence-format.md#normalized). || <a id="fence-takes_in_facts"></a>`takes_in_facts` | A facts fence holds a takes table. | `manual` | no | Move the rows into a takes fence (or add them with `takes_add`), or rewrite them as facts rows. Format: [takes](fence-format.md#takes-columns). |diff --git a/scripts/build-fence-format.ts b/scripts/build-fence-format.tsindex 29c900d792..76a28df436 100644--- a/scripts/build-fence-format.ts+++ b/scripts/build-fence-format.ts@@ -77,7 +77,7 @@ const GATE_TEXT = {d: 'No row becomes more visible: `private` never turns `world`.',e: 'No row is added or dropped, and every row of the fence stays inside it; under `merge_fences` the only rows dropped are the exact duplicates its mapping names.',f: 'A cell valid in its column keeps its text; a misaligned cell may only move, and text changes only through a named rule.',- g: 'Text the privacy boundary hid before the repair stays hidden after it.',+ g: 'Text the privacy boundary hid before the repair stays hidden after it, except the trailing lines a `close_fence_trailing` fix shows (admitted only on a private page or under the user\'s approval).',} satisfies Record<GateLetter, string>;const TIER_TEXT: Record<Exclude<FenceTier, 'deterministic'>, string> = {@@ -187,6 +187,7 @@ function normalizedTable(): string {const text = {merge_fences: 'A section with more than one fence of a kind becomes one fence when every fence has both markers, the same canonical header and nothing but table lines inside: the later fences\' rows are appended to the first in document order, a later row whose cells (every column but `#`) equal a kept row\'s as written is dropped, a number that now collides is renumbered (see [row numbers](#row-numbers)) and a `superseded by #N` reference follows its own fence\'s row N, and the later markers, tables and a repeated section heading above them are removed. Anything else stays `repeated_marker` and a person merges the fences.',close_fence: 'A fence with no end marker gets one directly after its table, when nothing but blank lines follows the last row up to the end of the section.',+ close_fence_trailing: 'A fence with no end marker whose table is followed by page text gets the end marker directly after its last row, so the text that followed becomes visible, when every trailing line is prose (no `|`, no fence marker; a line with a `|` only after the repair model read the tail as prose) and either the page is private (its body is never shown to remote readers, so nothing new is disclosed) or the user approved those exact lines through the hash-bound apply the preview prints. A world-visible page with no approval is `tail_exposure_approval`; a tail the model read as rows, or a marker mention, is `unclosed_ambiguous_tail` and a person closes the fence.',marker_form: 'Two-dash takes markers (`<!-- gbrain:takes:begin -->`) directly above a takes table become the three-dash markers. Two-dash facts markers are not a fence and are left alone.',stray_empty_cell: 'A row with more cells than its header (with no header: than the narrow layout, or 14 facts cells) loses empty cells, only when exactly one choice of empty cells to remove leaves every checked column (`#`, kind, confidence, visibility, notability, `claim_value`; takes kind, holder, weight) valid. Otherwise the row is `extra_cells` and a person fixes it.',renumber: 'A row number that is zero, negative, not a number or a duplicate gets a new number (see [row numbers](#row-numbers)).',diff --git a/src/core/fence-repair/hold-fix.ts b/src/core/fence-repair/hold-fix.tsindex 77e9d47819..d0ba63d6b4 100644--- a/src/core/fence-repair/hold-fix.ts+++ b/src/core/fence-repair/hold-fix.ts@@ -13,7 +13,10 @@* or a model failure the run does not retry: the preview names the exact* edit), `paid` (waits on spend the user controls: the exact config or* pricing command with consent `paid`, so it renders `ask_user`), `owner`- * (repairs run on the canonical owner host). Remote callers get the+ * (repairs run on the canonical owner host), `approval` (#6377: closing the+ * fence would show its trailing lines to readers of a world-visible page, so+ * the user approves the exact lines through the hash-bound apply the preview+ * prints). Remote callers get the* owner-host command as a relay (`tell_user_to_run`) and a `user_message`* saying whether the hold clears by itself; never a path.*@@ -63,7 +66,7 @@ export async function readFenceAutoRepair(engine: Exec, now: Date = new Date()):active: enabled && last !== null && now.getTime() - last <= FENCE_MAINTENANCE_ACTIVE_MS };}-export type FenceHoldState = 'auto' | 'apply' | 'manual' | 'paid' | 'owner';+export type FenceHoldState = 'auto' | 'apply' | 'manual' | 'paid' | 'owner' | 'approval';export interface FenceHoldStatus {state: FenceHoldState;@@ -101,7 +104,7 @@ export function fenceHoldStatus(meta: HoldMeta, auto?: FenceAutoRepair): FenceHoconst spec = FENCE_REASONS[reason];const retries = !llmOff && (last ? last.next_attempt_after !== null : spec.autoRetry && !spec.manualOnly);const needsEdit = spec.manualOnly || spec.tier === 'manual' || !!spec.gate || reason.startsWith('llm_');- const state: FenceHoldState = PAID.includes(reason) ? 'paid' : OWNER.includes(reason) ? 'owner' : !retries && needsEdit ? 'manual' : retries && auto?.active ? 'auto' : 'apply';+ const state: FenceHoldState = reason === 'tail_exposure_approval' ? 'approval' : PAID.includes(reason) ? 'paid' : OWNER.includes(reason) ? 'owner' : !retries && needsEdit ? 'manual' : retries && auto?.active ? 'auto' : 'apply';return { state, reason, tier, auto_retry: retries && auto?.active === true, next_attempt_after: last?.next_attempt_after ?? null };}@@ -208,6 +211,14 @@ export function fenceHoldFix(record: Pick<GitHoldRecord, 'source_id' | 'path' |return { ...base, actor: 'host_admin', argv: preview, why: `${held} Fence repairs write files only on the source's canonical owner host, and this host is not it (${status.reason}). `+ `On the owner host run ${command} to preview the repair, then the apply command it prints. ${rest}`,user_message: `Please run '${command}' on the brain's owner host to preview the repair of a malformed facts or takes table, then run the apply command it prints.` };+ case 'approval':+ return { ...base, actor: 'user', argv: preview, docs: 'docs/guides/write-refusals.md#fence-tail_exposure_approval',+ why: `${held} gbrain can close the fence directly after its last table row, but the lines after the table would then be visible to readers of this world-visible page, `+ + `so no unattended run closes it. The preview (read-only, no model call) prints those exact lines and the apply command with --expect <hash>; show them to the user and run that command only if they agree. ${rest}`,+ user_message: `A facts or takes table in ${path} has no end marker, and some text follows it. gbrain can close the table after its last row, which would make that text visible to readers of the page. `+ + `May I show you the lines ('${command}' prints them) and, if they look right, apply the close?`,+ then: { ...step, argv: [...preview, '--apply', '--expect', '<hash>'], inputs: [{ name: 'hash', how: 'The hash the preview printed; it binds the exact file bytes and the lines that become visible.' }],+ why: `Closes the fence in ${path} exactly as previewed and clears the hold; the lines the preview listed become visible.` } };}}@@ -219,6 +230,7 @@ function relayText(status: FenceHoldStatus, auto: FenceAutoRepair | undefined, rcase 'manual': return `It does not clear by itself: it needs an edit gbrain will not guess. Please run ${run} on the brain host; it names the exact edit to make in the file, then commit and sync.`;case 'paid': return `It does not clear by itself: its repair needs the paid repair model, and ${paidWait(status.reason)}. Raising spend or enabling the model is your call: if you agree, run '${paid}' on the brain host; otherwise ${run} there names the rows to fix by hand.`;case 'owner': return `Fence repairs run on the brain's owner host: please run ${run} there, then the apply command it prints.`;+ case 'approval': return `It does not clear by itself: closing the table would make the text after it visible to readers of the page, so it waits for your approval. On the brain host, ${run} prints those lines and the apply command; run that command if they look right.`;}}diff --git a/src/core/fence-repair/llm-tail.ts b/src/core/fence-repair/llm-tail.tsnew file mode 100644index 0000000000..4e834edb7d--- /dev/null+++ b/src/core/fence-repair/llm-tail.ts@@ -0,0 +1,154 @@+/**+ * Tier 3 tail classification (#6377): one question to the configured chat+ * model about an unclosed fence whose trailing lines contain a pipe, so the+ * structural rules cannot tell table rows from prose.+ *+ * What the model sees: the fence kind and section, the begin marker line,+ * the header, every row as written, and the trailing lines from the last+ * row to the end of the section. Never the rest of the page, never tools.+ *+ * What it must return: one JSON object `{"tail": "prose" | "rows" |+ * "unsure"}` and nothing else (a single wrapping code fence is tolerated).+ * `prose`: the trailing lines are ordinary page text, so the fence ends+ * after its last row; `rows`: some trailing line is a table row written+ * without pipes or with a broken shape, so closing after the last row would+ * leave rows outside the fence; `unsure` or the single word HOLD: a person+ * decides. Failure classes are the row prompt's (`llm_unavailable`,+ * `llm_empty`, `llm_refused`, `llm_malformed`, `llm_truncated`,+ * `llm_declined`).+ *+ * What the answer does is decided by the caller (`repair-tiers.ts`): a+ * `prose` tail on a private page lets Tier 1 close the fence; on a+ * world-visible page it records `tail_exposure_approval`, because the close+ * would show those lines to readers of the page and only a hash-bound apply+ * may do that. `rows` and `unsure` record `unclosed_ambiguous_tail`. Pure+ * helpers do no I/O; `callTailClassifier` is the one gateway call.+ */+import { chat, isThinkingModel, THINKING_MODEL_MAX_OUTPUT_TOKENS, type ChatMessage, type ChatResult } from '../ai/gateway.ts';+import { thinkingOffControl, thinkingOffMaxOutputTokens } from '../ai/thinking-off.ts';+import { extractRawRows, primaryFence } from './raw-rows.ts';+import { sectionsOf } from './page-checks.ts';+import { tailAmbiguous, trailingLines } from './structure.ts';++export { tailAmbiguous };+import { TIER3_DECLINE, TIER3_REASONING_TOKENS, type Tier3Failure } from './llm.ts';+import type { FenceIssue, FenceKind, FencePage, FenceSection } from './types.ts';++/** Bump when the prompt text changes: it is part of the attempt-memo key, so a new prompt retries rejected tails. */+export const TAIL_PROMPT_VERSION = 1;++export type TailVerdict = 'prose' | 'rows' | 'unsure';++/** One unclosed fence the model is asked about. */+export interface TailRequest {+ kind: FenceKind;+ section: FenceSection;+ pageVisibility: 'private' | 'world';+ /** The begin marker line as written. */+ begin: string;+ header: string | null;+ /** Every row as written, in fence order. */+ rows: string[];+ /** The trailing lines (non-blank, as written) from the last row to the section end. */+ tail: string[];+ /** 1-based section line of the last table row (where the end marker would go). */+ lastRowLine: number | null;+}++/** The tail request for an `unclosed_trailing_content` issue, or null when the fence is not in that state any more. */+export function tailRequest(page: FencePage, issue: Pick<FenceIssue, 'fence' | 'section'>, pageVisibility: 'private' | 'world'): TailRequest | null {+ const text = new Map(sectionsOf(page)).get(issue.section) ?? '';+ const fence = primaryFence(extractRawRows(text, issue.section), issue.fence);+ if (!fence || fence.end) return null;+ const lines = [fence.header, ...fence.separators, ...fence.rows].filter((r): r is NonNullable<typeof r> => r !== null).sort((a, b) => a.line - b.line);+ const last = lines[lines.length - 1];+ const after = last ? last.end : fence.begin.end;+ const tail = trailingLines(text.slice(after, fence.regionEnd));+ if (!tail.length) return null;+ return { kind: fence.kind, section: fence.section, pageVisibility, begin: text.slice(fence.begin.start, fence.begin.end),+ header: fence.header ? text.slice(fence.header.start, fence.header.end) : null,+ rows: fence.rows.map(row => text.slice(row.start, row.end)), tail, lastRowLine: last?.line ?? null };+}++/** The system and first user message: the fence region and its tail; no other page text. */+export function buildTailPrompt(req: TailRequest): { system: string; user: string } {+ const system = [+ `You read one gbrain ${req.kind} fence whose end marker is missing. After its last table row come more lines. Decide whether those trailing lines are part of the table or ordinary page text.`,+ '',+ 'Return exactly one JSON object and nothing else (no prose, no explanation, no code fence):',+ '{"tail": "prose"} when every trailing line is ordinary page text (a paragraph, a list item, a heading, a link) and none of them is a table row, even a broken one.',+ '{"tail": "rows"} when any trailing line is a table row: it carries cells of the same shape as the rows above (a claim, a kind word, a confidence, a date), with or without pipes.',+ `{"tail": "unsure"} (or the single word ${TIER3_DECLINE}) when you cannot tell.`,+ '',+ 'Rules:',+ '1. Judge only the trailing lines. Do not repair, rewrite or quote anything.',+ '2. A line that merely mentions a table, a fact or a take in prose is prose.',+ '3. A line with pipes that has fewer or more cells than the header can still be a row; a line with one pipe inside a sentence is prose.',+ '4. When in doubt, answer unsure.',+ ].join('\n');+ const user = [+ `Fence: ${req.kind} (${req.section} section). Page visibility: ${req.pageVisibility}.`,+ 'Begin marker as written:',+ req.begin,+ 'Header as written:',+ req.header ?? '(none)',+ `Rows as written (${req.rows.length}):`,+ ...req.rows,+ '',+ `Trailing lines after the last row (${req.tail.length}):`,+ ...req.tail,+ ].join('\n');+ return { system, user };+}++const REFUSAL = /\b(cannot|can['’]t|unable to|won['’]t|will not|refuse|not able to)\b/i;++/** The verdict in a model answer, or why there is none. */+export function parseTailAnswer(text: string): { ok: true; tail: TailVerdict } | { ok: false; reason: 'llm_empty' | 'llm_refused' | 'llm_malformed' | 'llm_declined' } {+ let body = text.trim();+ if (!body) return { ok: false, reason: 'llm_empty' };+ const fenced = /^```[\w-]*\n([\s\S]*?)\n```$/.exec(body);+ if (fenced) body = fenced[1]!.trim();+ if (body.replace(/[.*_`]/g, '').trim() === TIER3_DECLINE) return { ok: false, reason: 'llm_declined' };+ let parsed: unknown;+ try { parsed = JSON.parse(body); } catch { return { ok: false, reason: REFUSAL.test(body) ? 'llm_refused' : 'llm_malformed' }; }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return { ok: false, reason: 'llm_malformed' };+ const tail = (parsed as Record<string, unknown>).tail;+ if (tail !== 'prose' && tail !== 'rows' && tail !== 'unsure') return { ok: false, reason: 'llm_malformed' };+ return { ok: true, tail };+}++function mayReason(model: string): boolean {+ return isThinkingModel(model) || !thinkingOffControl(model)?.disables;+}++/** Token bounds for one call: the prompt's size and a small JSON answer, plus a reasoning allowance for a model that may reason. */+export function tailTokenBudget(req: TailRequest, model: string): { inputTokens: number; maxOutputTokens: number } {+ const prompt = buildTailPrompt(req);+ const requested = 64 + (mayReason(model) ? TIER3_REASONING_TOKENS : 0);+ return { inputTokens: Math.ceil((prompt.system.length + prompt.user.length) / 3) + 64,+ maxOutputTokens: thinkingOffMaxOutputTokens(model, requested, isThinkingModel(model), THINKING_MODEL_MAX_OUTPUT_TOKENS) };+}++export type TailAnswer =+ | { ok: true; tail: TailVerdict; text: string; result: ChatResult }+ | { ok: false; reason: Tier3Failure; text?: string; result?: ChatResult; error?: string };++/** One gateway call (no tools, no fallback model, thinking off where the route allows), classified. */+export async function callTailClassifier(req: TailRequest, opts: { model: string; timeoutMs?: number; signal?: AbortSignal }): Promise<TailAnswer> {+ const prompt = buildTailPrompt(req);+ const messages: ChatMessage[] = [{ role: 'user', content: prompt.user }];+ const budget = tailTokenBudget(req, opts.model);+ let result: ChatResult;+ try {+ result = await chat({ model: opts.model, system: prompt.system, messages, maxTokens: budget.maxOutputTokens, allowFallback: false,+ thinking: 'off', purpose: 'fence_repair', ...(opts.timeoutMs ? { timeoutMs: opts.timeoutMs } : {}), ...(opts.signal ? { abortSignal: opts.signal } : {}) });+ } catch (error) {+ return { ok: false, reason: 'llm_unavailable', error: error instanceof Error ? error.name : 'Error' };+ }+ if (result.stopReason === 'refusal' || result.stopReason === 'content_filter') return { ok: false, reason: 'llm_refused', text: result.text, result };+ if (result.stopReason !== 'end') return { ok: false, reason: result.text.trim() ? 'llm_truncated' : 'llm_empty', text: result.text, result };+ const parsed = parseTailAnswer(result.text);+ if (!parsed.ok) return { ok: false, reason: parsed.reason, text: result.text, result };+ return { ok: true, tail: parsed.tail, text: result.text, result };+}diff --git a/src/core/fence-repair/normalize.ts b/src/core/fence-repair/normalize.tsindex 15b480d921..4ed8a5f997 100644--- a/src/core/fence-repair/normalize.ts+++ b/src/core/fence-repair/normalize.ts@@ -43,7 +43,7 @@ export function normalizeFences<T extends FencePage>(page: T, ctx: FenceCtx): Noconst texts: Record<FenceSection, string> = { body: '', timeline: '' };const merges: MergeOrigins[] = [];for (const [section, text] of sectionsOf(page)) {- const pass = structuralPass(text, section);+ const pass = structuralPass(text, section, ctx);const stray = strayCellPass(pass.text, section);texts[section] = stray.text;fixes.push(...pass.fixes, ...stray.fixes);diff --git a/src/core/fence-repair/reasons.ts b/src/core/fence-repair/reasons.tsindex 60565dee7b..652f80e987 100644--- a/src/core/fence-repair/reasons.ts+++ b/src/core/fence-repair/reasons.ts@@ -61,7 +61,9 @@ const SPECS: Record<FenceReason, Omit<FenceReasonSpec, 'docs'>> = {'Column `who` of row(s) {rows} in the {fence} fence ({section}, line {line}) is not a holder gbrain recognizes. Write `world`, `brain`, `people/<slug>` or `companies/<slug>`.'),missing_begin: entry(manual, 'The {fence} fence in the {section} has an end marker at line {line} with no begin marker before it. Add the begin marker above the table, or delete the stray end marker.'),split_rows: entry(manual, 'The {fence} fence that begins at line {line} in the {section} has no end marker and its rows are split by blank lines or text. Join the rows into one table and add the end marker after the last row.'),- unclosed_trailing_content: entry(manual, 'The {fence} fence that begins at line {line} in the {section} has no end marker and other text follows its table. Add the end marker directly after the last table row, or wrap the marker in backticks if the text only mentions it; gbrain does not guess where the fence ends.'),+ unclosed_trailing_content: entry(tier3, 'The {fence} fence that begins at line {line} in the {section} has no end marker and lines holding a pipe follow its table, so the rules cannot tell rows from prose. The repair model classifies the tail; a prose tail closes the fence after its last row (on a world-visible page after the user approves the lines it shows). ' + REPAIR),+ unclosed_ambiguous_tail: entry({ ...manual, stage: 'repair' }, 'The {fence} fence that begins at line {line} in the {section} has no end marker, and the lines after its table are not plain prose (a row written without pipes, a marker mention, or a tail the repair model could not classify). Add the end marker directly after the last table row and fix the rows below it, or wrap a marker mention in backticks; gbrain does not guess where the fence ends.'),+ tail_exposure_approval: entry({ stage: 'screen', tier: 'deterministic', manualOnly: false, autoRetry: false }, 'The {fence} fence that begins at line {line} in the {section} has no end marker; gbrain can close it after its last table row, but the lines after the table would then be visible to readers of this world-visible page. Preview the close with `gbrain repair fences` (read-only: it prints those lines and the apply command with --expect <hash>), and run that command once the user approves.', { actor: 'user' }),marker_near_miss: entry(manual, 'Line {line} of the {section} mentions the takes begin marker but is not a fence followed by a table. Wrap the mention in backticks, or use the exact three-dash marker above a takes table.'),repeated_marker: entry(manual, 'The {section} repeats a {fence} fence marker (line {line}); a section holds at most one facts fence and one takes fence. gbrain merges the fences itself when each has a begin and an end marker, the same canonical header and nothing but table lines inside (`merge_fences`: later rows appended, exact duplicates dropped, colliding numbers renumbered). Otherwise, give the fence at line {line} both markers, the same header as the first fence, and move any other text out of it, or delete the extra marker.'),takes_in_facts: entry(manual, 'The {fence} fence in the {section} at line {line} holds a takes table. Move the rows into a takes fence (or use `takes_add`), or rewrite them as facts rows.'),diff --git a/src/core/fence-repair/repair-tiers.ts b/src/core/fence-repair/repair-tiers.tsindex 1f0e78f8a0..dbc7662a3f 100644--- a/src/core/fence-repair/repair-tiers.ts+++ b/src/core/fence-repair/repair-tiers.ts@@ -31,13 +31,16 @@ import { GATE_REASONS, renderFenceFix, type FenceMessageLocation } from './reasoimport { residualLocation } from './tier1.ts';import { validateFenceRepair } from './validate.ts';import { callTier3, FENCE_REPAIR_PROMPT_VERSION, spliceTier3, tier3Requests, tier3TokenBudget, TIER3_REASONS, type Tier3Request, type Tier3Table } from './llm.ts';+import { callTailClassifier, TAIL_PROMPT_VERSION, tailRequest, tailTokenBudget, type TailRequest } from './llm-tail.ts';import type { FenceCtx, FenceFix, FenceIssue, FencePage, FenceReason, GateLetter } from './types.ts';import type { FenceTarget } from './repair-io.ts';export type FenceAnalysis =| { status: 'clean' }| { status: 'proposal'; tier: 'deterministic' | 'resolver'; after: FencePage; fixes: FenceFix[]; ctx: FenceCtx }- | { status: 'llm'; base: FencePage; fixes: FenceFix[]; residual: FenceIssue[]; requests: Tier3Request[]; ctx: FenceCtx }+ | { status: 'llm'; base: FencePage; fixes: FenceFix[]; residual: FenceIssue[]; requests: Tier3Request[];+ /** #6377: unclosed fences whose tail holds a pipe; the classifier runs before the row requests. */+ tails: TailRequest[]; ctx: FenceCtx }| { status: 'manual'; reason: FenceReason; location: FenceMessageLocation; resolution: string; gate?: GateLetter; rows?: number[] };/** The holder text of the row an issue names, read from the bytes as written. */@@ -80,10 +83,18 @@ function settled(page: FencePage, ctx: FenceCtx): boolean {* a validated `proposal`, `llm` (only Tier 3 residuals are left, with the* model requests), or `manual` with the exact location-only edit.*/-export async function analyzeFences(engine: BrainEngine, target: FenceTarget, opts: { pageId: number | null }): Promise<FenceAnalysis> {+export interface AnalyzeOpts {+ pageId: number | null;+ /** #6377: the caller holds the user's hash-bound approval to close fences ahead of trailing text on a world page (explicit previews and `--expect` applies). */+ approveTailExposure?: boolean;+ /** #6377: fences (`<section>:<kind>`, or `*`) whose tail the classifier judged prose. */+ tailProse?: ReadonlySet<string>;+}++export async function analyzeFences(engine: BrainEngine, target: FenceTarget, opts: AnalyzeOpts): Promise<FenceAnalysis> {const page = target.page;if (!scanCanonicalFences(page).defects.length) return { status: 'clean' };- let ctx: FenceCtx = { ...target.ctx };+ let ctx: FenceCtx = { ...target.ctx, ...(opts.approveTailExposure ? { approveTailExposure: true } : {}), ...(opts.tailProse ? { tailProse: opts.tailProse } : {}) };let base = safeNormalizeFences(page, ctx);if (base.fixes.some(f => f.class === 'renumber')) {ctx = { ...ctx, storedRows: await storedFenceRows(engine, target.sourceId, target.slug, opts.pageId) };@@ -105,11 +116,17 @@ export async function analyzeFences(engine: BrainEngine, target: FenceTarget, opif (!settled(base.page, ctx)) return manual(base.fixes.map(f => ({ ...f, reason: 'normalizer_failed' as const })), { reason: 'normalizer_failed' });return { status: 'proposal', tier, after: base.page, fixes: base.fixes, ctx };}- const manualIssues = base.residual.filter(i => !TIER3_REASONS.has(i.reason));+ // #6377: a tail the classifier must judge is its own request; row issues of that still-unclosed fence wait for the close.+ const tailIssues = base.residual.filter(i => i.reason === 'unclosed_trailing_content');+ const rowIssues = base.residual.filter(i => i.reason !== 'unclosed_trailing_content');+ const manualIssues = rowIssues.filter(i => !TIER3_REASONS.has(i.reason));if (manualIssues.length) return manual(manualIssues);- const { requests, ineligible } = tier3Requests(base.page, base.residual, ctx.pageVisibility);- if (ineligible.length || !requests.length) return manual(base.residual);- return { status: 'llm', base: base.page, fixes: base.fixes, residual: base.residual, requests, ctx };+ const tails = tailIssues.map(i => tailRequest(base.page, i, ctx.pageVisibility)).filter((t): t is TailRequest => t !== null);+ if (tails.length !== tailIssues.length) return manual(tailIssues);+ const { requests, ineligible } = tier3Requests(base.page, rowIssues, ctx.pageVisibility);+ const blocking = ineligible.filter(x => !(x.why === 'no_end_marker' && tails.some(t => t.kind === x.kind && t.section === x.section)));+ if (blocking.length || (!requests.length && !tails.length)) return manual(base.residual);+ return { status: 'llm', base: base.page, fixes: base.fixes, residual: base.residual, requests, tails, ctx };}function scanIssue(page: FencePage): Pick<FenceIssue, 'fence' | 'section' | 'reason' | 'line'> {@@ -118,12 +135,12 @@ function scanIssue(page: FencePage): Pick<FenceIssue, 'fence' | 'section' | 'rea}/** The first call's worst-case estimate for every request of a page. */-export function tier3Estimate(requests: readonly Tier3Request[], pricing: { model: string; overrides?: PricingOverrides; capSource: CapSource }):+export function tier3Estimate(requests: readonly Tier3Request[], pricing: { model: string; overrides?: PricingOverrides; capSource: CapSource }, tails: readonly TailRequest[] = []):{ ok: true; usd: number; estimated: boolean } | { ok: false; reason: 'no_pricing'; guidance: NoPricingGuidance } {let usd = 0;let estimated = false;- for (const req of requests) {- const budget = tier3TokenBudget(req, pricing.model);+ const budgets = [...tails.map(req => tailTokenBudget(req, pricing.model)), ...requests.map(req => tier3TokenBudget(req, pricing.model))];+ for (const budget of budgets) {const quote = estimateChatCallUsd({ model: pricing.model, inputTokens: budget.inputTokens, maxOutputTokens: budget.maxOutputTokens, overrides: pricing.overrides, capSource: pricing.capSource });if (!quote.ok) return quote;usd += quote.quote.usd;@@ -145,6 +162,8 @@ export interface Tier3Deps {/** Per-call provider timeout. */timeoutMs: number;now: () => Date;+ /** #6377: re-run the analysis once the classifier judged tails prose (the fences it names may close). */+ reanalyze?: (tailProse: ReadonlySet<string>) => Promise<FenceAnalysis>;}export type Tier3Outcome =@@ -159,7 +178,7 @@ export function attemptCandidate(target: FenceTarget, incarnation: string) {}export function tier3Memo(target: FenceTarget, model: string): string {- return attemptMemoKey({ contentSha256: target.before, model, fenceVersion: FENCE_RULES_VERSION, promptVersion: FENCE_REPAIR_PROMPT_VERSION });+ return attemptMemoKey({ contentSha256: target.before, model, fenceVersion: FENCE_RULES_VERSION, promptVersion: `${FENCE_REPAIR_PROMPT_VERSION}.${TAIL_PROMPT_VERSION}` });}/**@@ -170,7 +189,8 @@ export function tier3Memo(target: FenceTarget, model: string): string {* On success the claim is left `settled`: the caller publishes it after the* write lands, or marks it transient when the write could not run.*/-export async function runTier3(target: FenceTarget, analysis: Extract<FenceAnalysis, { status: 'llm' }>, incarnation: string, deps: Tier3Deps): Promise<Tier3Outcome> {+export async function runTier3(target: FenceTarget, initial: Extract<FenceAnalysis, { status: 'llm' }>, incarnation: string, deps: Tier3Deps): Promise<Tier3Outcome> {+ let analysis = initial;const claimed = await deps.store.claim(attemptCandidate(target, incarnation), tier3Memo(target, deps.model));if (!claimed.ok) {if (claimed.reason === 'claimed_elsewhere') return { ok: false, reason: 'claimed_elsewhere', spentUsd: 0, message: 'Another repair run holds this candidate; it is left to that run.' };@@ -191,6 +211,57 @@ export async function runTier3(target: FenceTarget, analysis: Extract<FenceAnalyawait deps.store.reject(claim, { reason, ...(gate ? { gate } : {}), ...(rows ? { rows } : {}) });return { ok: false, reason, spentUsd: spent, message, ...(gate ? { gate } : {}), ...(rows ? { rows } : {}) };};+ // #6377: the tail classifier first. A prose verdict lets the structural rule close the fence (private page, or the+ // caller's approval); the re-analysis then decides whether rows still need the model.+ if (analysis.tails.length) {+ const prose = new Set<string>();+ for (const req of analysis.tails) {+ const budget = tailTokenBudget(req, deps.model);+ const quote = estimateChatCallUsd({ model: deps.model, inputTokens: budget.inputTokens, maxOutputTokens: budget.maxOutputTokens, overrides: deps.overrides, capSource: deps.capSource });+ if (!quote.ok) return transient('no_pricing', `A spend cap is set but gbrain has no price for ${deps.model}; no call was made.`, { guidance: quote.guidance });+ const estimate = quote.quote.usd;+ if (spent + estimate > deps.perPageUsd + 1e-9) return transient('budget_exhausted', `The estimated model cost ($${estimate.toFixed(4)}) exceeds fences.repair.max_usd_per_page ($${deps.perPageUsd.toFixed(2)}).`);+ if (deps.allowanceUsd !== undefined && spent + estimate > deps.allowanceUsd + 1e-9) {+ return transient('budget_exhausted', `This run's paid-model allowance ($${deps.allowanceUsd.toFixed(4)} left) cannot cover the estimate ($${estimate.toFixed(4)}).`, { stop: true });+ }+ const reserved = await deps.ledger.reserve(estimate, { capUsd: deps.perDayUsd });+ if (!reserved.ok) {+ if (reserved.reason === 'ledger_unavailable') return transient('ledger_unavailable', 'The spend ledger could not be read, so no model call was made; the next run retries.');+ return transient('budget_exhausted', `The daily fence-repair budget is spent ($${(reserved.committedUsd + reserved.reservedUsd).toFixed(4)} of $${reserved.capUsd.toFixed(2)} committed or reserved today; `+ + `this call needs $${reserved.estimateUsd.toFixed(4)}). It resets at ${reserved.resetsAt}.`, { stop: true, resetsAt: reserved.resetsAt });+ }+ const moved = await deps.store.dispatched(claim, reserved.reservation.id);+ if (!moved.ok) {+ await deps.ledger.release(reserved.reservation.id);+ if (moved.reason === 'lost_claim') return { ok: false, reason: 'claimed_elsewhere', spentUsd: spent, message: 'Another repair run took over this candidate.' };+ return reject('llm_malformed', 'The attempt reached its call limit.');+ }+ claim = moved.claim;+ if (!await deps.ledger.dispatch(reserved.reservation.id)) {+ await deps.ledger.release(reserved.reservation.id);+ await deps.store.settled(claim).then(r => { if (r.ok) claim = r.claim; });+ return transient('ledger_unavailable', 'The spend ledger refused to dispatch the reservation, so no model call was made.');+ }+ const answer = await callTailClassifier(req, { model: deps.model, timeoutMs: deps.timeoutMs });+ const actual = answer.result ? chatCallUsd(deps.model, { inputTokens: answer.result.usage.input_tokens, outputTokens: answer.result.usage.output_tokens }, deps.overrides).usd : estimate;+ const settle = await deps.ledger.settle(reserved.reservation.id, actual);+ spent += settle.settled ? settle.actualUsd : actual;+ const done = await deps.store.settled(claim);+ if (done.ok) claim = done.claim;+ if (!answer.ok && answer.reason === 'llm_unavailable') return transient('llm_unavailable', `The repair model was unavailable (${answer.error ?? 'provider error'}); the next run retries.`);+ if (!answer.ok && answer.reason === 'llm_declined') return reject('unclosed_ambiguous_tail', 'The repair model could not tell the lines after the table from rows; the fence needs a person to close it.');+ if (!answer.ok) return reject(answer.reason, `The repair model's answer was unusable (${answer.reason}).`);+ if (answer.tail !== 'prose') return reject('unclosed_ambiguous_tail', `The repair model read the lines after the table as ${answer.tail === 'rows' ? 'table rows' : 'unclear'}; the fence needs a person to close it.`);+ prose.add(`${req.section}:${req.kind}`);+ }+ if (!deps.reanalyze) return reject('still_invalid', 'The tail was judged prose but the run cannot re-analyze the page.');+ const next = await deps.reanalyze(prose);+ if (next.status === 'clean') return reject('still_invalid', 'The page came back clean after the tail verdict, so there was nothing to close.');+ if (next.status === 'manual') return reject(next.reason, next.resolution, next.gate, next.rows);+ if (next.status === 'proposal') return { ok: true, after: next.after, spentUsd: spent, claim, cleared: ['unclosed_trailing_content'] };+ if (next.tails.length) return reject('still_invalid', 'The fence did not close after the tail verdict.');+ analysis = { ...next, requests: next.requests };+ }let correction: { index: number; gate: GateLetter; rows: number[] } | null = null;for (let round = 0; round < 2; round++) {const indexes = correction ? [correction.index] : analysis.requests.map((_, i) => i);@@ -257,7 +328,7 @@ export async function runTier3(target: FenceTarget, analysis: Extract<FenceAnaly}}if (after) {- const cleared = [...new Set(analysis.residual.map(i => i.reason))].sort();+ const cleared = [...new Set([...initial.residual, ...analysis.residual].map(i => i.reason))].sort();return { ok: true, after, spentUsd: spent, claim, cleared };}// Only a structural failure earns the re-ask: naming gate (f) steers a model toward whatever placement the gates allow.diff --git a/src/core/fence-repair/structure.ts b/src/core/fence-repair/structure.tsindex 718528b34f..ac210e7fc7 100644--- a/src/core/fence-repair/structure.ts+++ b/src/core/fence-repair/structure.ts@@ -1,7 +1,8 @@/**- * Structural Tier 1 rules for one section (#6188): `merge_fences` (several- * balanced fences of a kind, #6377, merge.ts), `marker_form` (takes two-dash- * markers) and `close_fence` (a missing end marker).+ * Structural Tier 1 rules for one section (#6188, #6377): `merge_fences`+ * (balanced same-kind fences, merge.ts), `marker_form` (takes two-dash+ * markers), `close_fence` (a missing end marker) and `close_fence_trailing`+ * (a missing end marker with page text after the table).** `close_fence` inserts the end marker after the last table row only when* every row of the before-region is one contiguous block and nothing but@@ -9,12 +10,23 @@* hides everything after an unpaired begin marker, so closing the fence* early would publish whatever trails it (gate (g)). Every structural edit* is also checked against `exposedLines` before it is kept.+ *+ * `close_fence_trailing` (#6377) is the one rule that shows hidden lines on+ * purpose, and only when showing them discloses nothing or the user agreed:+ * the trailing lines hold no pipe and no fence marker (so no parser can read+ * them as rows), or the tail classifier judged them prose (`ctx.tailProse`),+ * and the page is private (remote readers never see its body) or the caller+ * holds the user's hash-bound approval (`ctx.approveTailExposure`). A+ * pipe-free tail on a world page without approval is `tail_exposure_approval`;+ * a tail with a pipe the classifier has not judged is+ * `unclosed_trailing_content` (Tier 3); a marker mention is+ * `unclosed_ambiguous_tail` (manual).*/import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';import { mergeEdits, mergeOrigins, mergePlan, type MergeOrigins, type MergePlan } from './merge.ts';import { exposedLines } from './page-checks.ts';import { extractRawRows, MARKERS, parseRowSpans, primaryFence, type RawFence, type RawSection } from './raw-rows.ts';-import type { FenceFix, FenceIssue, FenceReason, FenceSection, FixClass } from './types.ts';+import type { FenceCtx, FenceFix, FenceIssue, FenceReason, FenceSection, FixClass } from './types.ts';export interface Edit {start: number;@@ -46,12 +58,14 @@ export function applyEdits(text: string, edits: readonly Edit[]): string {}/** Run the structural rules until they settle (a converted marker may then need closing). */-export function structuralPass(text: string, section: FenceSection): PassResult {+export type StructuralCtx = Pick<FenceCtx, 'pageVisibility' | 'approveTailExposure' | 'tailProse'>;++export function structuralPass(text: string, section: FenceSection, ctx: StructuralCtx = { pageVisibility: 'world' }): PassResult {let current = text;const fixes: FenceFix[] = [];const merges: MergeOrigins[] = [];for (let round = 0; round < 3; round++) {- const step = structuralStep(current, section);+ const step = structuralStep(current, section, ctx);if (!step.edits.length) return { text: current, fixes, residual: step.residual, merges };current = applyEdits(current, step.edits);fixes.push(...step.fixes);@@ -66,7 +80,7 @@ export function fenceBlocked(raw: RawSection, fence: RawFence): boolean {|| raw.issues.some(i => i.fence === fence.kind && i.reason === 'missing_begin');}-function structuralStep(text: string, section: FenceSection): Step {+function structuralStep(text: string, section: FenceSection, ctx: StructuralCtx): Step {const raw = extractRawRows(text, section);const step: Step = { edits: [], fixes: [], residual: [], merged: [] };for (const kind of ['facts', 'takes'] as const) {@@ -89,7 +103,7 @@ function structuralStep(text: string, section: FenceSection): Step {continue;}if (edits.length) keep(step, text, fence, edits, 'marker_form', 'marker_near_miss');- else if (!fence.end) planClose(step, text, fence);+ else if (!fence.end) planClose(step, text, fence, ctx);}return step;}@@ -131,7 +145,7 @@ function tableFollows(text: string, from: number): boolean {return false;}-function planClose(step: Step, text: string, fence: RawFence): void {+function planClose(step: Step, text: string, fence: RawFence, ctx: StructuralCtx): void {const lines = [fence.header, ...fence.separators, ...fence.rows].filter(r => r !== null).sort((a, b) => a.line - b.line);const last = lines[lines.length - 1];if (lines.some((row, i) => i > 0 && row.line !== lines[i - 1]!.line + 1)) {@@ -139,11 +153,52 @@ function planClose(step: Step, text: string, fence: RawFence): void {return;}const after = last ? last.end : fence.begin.end;- if (text.slice(after, fence.regionEnd).trim()) {+ const tail = trailingLines(text.slice(after, fence.regionEnd));+ if (!tail.length) {+ keep(step, text, fence, [closeEdit(text, after, MARKERS[fence.kind].end)], 'close_fence', 'unclosed_trailing_content');+ return;+ }+ if (tail.some(line => line.includes('gbrain:'))) {+ step.residual.push(fenceIssue(fence, 'unclosed_ambiguous_tail', fence.begin.line));+ return;+ }+ const judged = tailAmbiguous(tail) ? ctx.tailProse?.has(`${fence.section}:${fence.kind}`) === true || ctx.tailProse?.has('*') === true : true;+ if (!judged) {step.residual.push(fenceIssue(fence, 'unclosed_trailing_content', fence.begin.line));return;}- keep(step, text, fence, [closeEdit(text, after, MARKERS[fence.kind].end)], 'close_fence', 'unclosed_trailing_content');+ if (ctx.pageVisibility !== 'private' && !ctx.approveTailExposure) {+ step.residual.push(fenceIssue(fence, 'tail_exposure_approval', fence.begin.line));+ return;+ }+ step.edits.push(closeEdit(text, after, MARKERS[fence.kind].end));+ step.fixes.push({ fence: fence.kind, section: fence.section, row: null, column: null, line: fence.begin.line, class: 'close_fence_trailing' });+}++/** The non-blank lines of a fence's tail, trimmed, as written. */+export function trailingLines(tail: string): string[] {+ return tail.split(/\r\n|\r|\n/).map(line => line.trim()).filter(Boolean);+}++/** The tail holds a pipe, so a line could be a table row; without one every line is prose under every parser. */+export function tailAmbiguous(tail: readonly string[]): boolean {+ return tail.some(line => line.includes('|'));+}++/**+ * The trailing lines a `close_fence_trailing` fix shows, per unclosed fence of+ * the before section: what gate (g) may accept as exposed, and nothing else.+ */+export function trailingLinesOf(text: string, section: FenceSection): Map<string, string[]> {+ const out = new Map<string, string[]>();+ const raw = extractRawRows(text, section);+ for (const fence of raw.fences) {+ if (!fence.primary || fence.end) continue;+ const lines = [fence.header, ...fence.separators, ...fence.rows].filter(r => r !== null).sort((a, b) => a.line - b.line);+ const last = lines[lines.length - 1];+ out.set(`${section}:${fence.kind}`, trailingLines(text.slice(last ? last.end : fence.begin.end, fence.regionEnd)));+ }+ return out;}/** Insert `marker` on its own line after the line that ends at or after `at`, keeping that line's ending. */diff --git a/src/core/fence-repair/types.ts b/src/core/fence-repair/types.tsindex 4ce6553c7f..1487fe1edf 100644--- a/src/core/fence-repair/types.ts+++ b/src/core/fence-repair/types.ts@@ -24,6 +24,8 @@ export type GateLetter = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g';export type FixClass =| 'merge_fences'| 'close_fence'+ /** #6377: the end marker inserted after the last row of a fence that trailing page text followed. */+ | 'close_fence_trailing'| 'marker_form'| 'stray_empty_cell'| 'renumber'@@ -37,12 +39,14 @@ export type FixClass =/** Every fence reason; `FENCE_REASONS` (reasons.ts) holds one entry per code. */export type FenceReason =- // Screen residual, Tier 3.- | 'header_unmapped' | 'no_header' | 'row_before_header' | 'short_row'+ // Screen residual, Tier 3 (`unclosed_trailing_content`: the tail classifier, #6377).+ | 'header_unmapped' | 'no_header' | 'row_before_header' | 'short_row' | 'unclosed_trailing_content'// Screen residual, Tier 2 then manual.| 'holder_unresolved'// Screen residual, manual only.- | 'extra_cells' | 'claim_split' | 'missing_begin' | 'split_rows' | 'unclosed_trailing_content' | 'marker_near_miss' | 'repeated_marker'+ | 'extra_cells' | 'claim_split' | 'missing_begin' | 'split_rows' | 'marker_near_miss' | 'repeated_marker' | 'unclosed_ambiguous_tail'+ // Screen residual, the user's hash-bound approval (#6377): closing the fence would show its trailing lines to readers of a world-visible page.+ | 'tail_exposure_approval'| 'takes_in_facts' | 'superseded_ambiguous' | 'enum_unmapped' | 'weight_missing' | 'holder_missing'| 'confidence_out_of_range' | 'claim_value_invalid' | 'takes_kind_unsupported'// Preparation and publication.@@ -99,6 +103,14 @@ export interface FenceCtx {takesPackKinds?: readonly string[];/** Row numbers of rows hidden from a remote caller; never renumbered or reallocated. */hiddenRows?: ReadonlySet<number>;+ /**+ * #6377: the caller holds the user's hash-bound approval to close an unclosed fence ahead of trailing text on a+ * world-visible page (the lines become visible to the page's readers). Private pages never need it: closing+ * shows nothing to anyone new. Unattended runs never set it.+ */+ approveTailExposure?: boolean;+ /** #6377: fences (`<section>:<kind>`) whose trailing lines the tail classifier judged prose, so the close may run although a tail line holds a pipe. */+ tailProse?: ReadonlySet<string>;}/** The two canonical body sections. Callers pass their full page type and get it back. */diff --git a/src/core/fence-repair/validate.ts b/src/core/fence-repair/validate.tsindex 746dcb1122..a604bb9864 100644--- a/src/core/fence-repair/validate.ts+++ b/src/core/fence-repair/validate.ts@@ -10,7 +10,9 @@* (f) cell_changed per row, a valid non-claim cell keeps its column and text; a misaligned cell may move* with its text unchanged; text changes only where an issue names the row and column* and a named rule produced it (TE2)- * (g) protection_loosened nothing the privacy boundary hid is shown after+ * (g) protection_loosened nothing the privacy boundary hid is shown after, except the trailing lines of a fence a+ * `close_fence_trailing` fix closed (#6377): the structural rule admits that fix only on a private+ * page or under the user's hash-bound approval, and the gate accepts exactly those lines** Gates (b), (c), (e) and (f) read the raw-row extraction of the* before-region, never strict-parser output. (e) runs before (b) so a dropped@@ -31,6 +33,7 @@ import { mergePlans, rowKey, type MergePlan } from './merge.ts';import { normalizeFences } from './normalize.ts';import { exposedLines, sectionsOf, strictFailures } from './page-checks.ts';import { extractRawRows, primaryFence, rowNumOf, type RawFence, type RawRow } from './raw-rows.ts';+import { trailingLinesOf } from './structure.ts';import { cellsChanged } from './validate-cells.ts';import { GATE_REASONS } from './reasons.ts';import { cellValid, collapse, enumSynonym, supersededRef } from './schema.ts';@@ -105,7 +108,7 @@ function firstFailure(before: FencePage, after: FencePage, ctx: ValidateCtx): Faconst failed = check(pairs, ctx);if (failed) return failed;}- return protection(before, after);+ return protection(before, after, ctx);}/** Null when the fixes name a merge the before page does not admit (nothing the mapping could vouch for). */@@ -238,11 +241,20 @@ function withFollowedRef(pair: FencePair, p: Paired): RawRow {}/** (g) */-function protection(before: FencePage, after: FencePage): Failure | null {+function protection(before: FencePage, after: FencePage, ctx: ValidateCtx): Failure | null {const afterSections = new Map(sectionsOf(after));for (const [section, text] of sectionsOf(before)) {- if (exposedLines(text, afterSections.get(section) ?? '').length) {- return { gate: 'g', fence: null, section, rows: [] };+ const exposed = exposedLines(text, afterSections.get(section) ?? '');+ if (!exposed.length) continue;+ const closed = ctx.issues.filter((i): i is FenceLocation & { class: 'close_fence_trailing' } => 'class' in i && i.class === 'close_fence_trailing' && i.section === section);+ if (!closed.length) return { gate: 'g', fence: null, section, rows: [] };+ const allowed = new Map<string, number>();+ const tails = trailingLinesOf(text, section);+ for (const fix of closed) for (const line of tails.get(`${section}:${fix.fence}`) ?? []) allowed.set(line, (allowed.get(line) ?? 0) + 1);+ for (const line of exposed) {+ const left = allowed.get(line) ?? 0;+ if (left <= 0) return { gate: 'g', fence: closed[0]!.fence, section, rows: [] };+ allowed.set(line, left - 1);}}return null;diff --git a/src/core/repair/fences.ts b/src/core/repair/fences.tsindex 9c79c580e6..b2463e537e 100644--- a/src/core/repair/fences.ts+++ b/src/core/repair/fences.ts@@ -61,7 +61,7 @@ import { FENCE_REPAIR_ACTOR, type MergedFenceReceipt } from '../fence-repair/recimport { checkoutFileExists, loadFenceSource, pageSha, readFenceTarget, spliceFileSections, writeFenceRepair, type FenceRepairMode, type FenceSource, type FenceTarget } from '../fence-repair/repair-io.ts';import type { OwnerRefusal } from '../persistence/owner-refusal.ts';import { repairBusy, repairBusyMessage } from '../persistence/repair-busy.ts';-import { analyzeFences, attemptCandidate, runTier3, tier3Estimate, tier3Memo, type FenceAnalysis } from '../fence-repair/repair-tiers.ts';+import { analyzeFences, attemptCandidate, runTier3, tier3Estimate, tier3Memo, type AnalyzeOpts, type FenceAnalysis } from '../fence-repair/repair-tiers.ts';import type { FenceFix, FenceIssue, FencePage, FenceReason, FenceTier, GateLetter } from '../fence-repair/types.ts';import { lineDiff } from './frontmatter.ts';import type { RepairHandler, RepairItem, RepairItemOutcome, RepairListing, RepairPlan, RepairPlanOptions, RepairResult, RepairScope } from './core.ts';@@ -288,7 +288,7 @@ export const fencesRepair: RepairHandler = {continue;}const target = read.target;- const analysis = await analyzeFences(engine, target, { pageId: target.snapshot?.page.id ?? null });+ const analysis = await analyzeFences(engine, target, await analysisOpts(engine, target, src, { apply: opts?.apply === true, expect: opts?.expect, model: s.model }));if (analysis.status === 'clean') { residuals.already_clean = (residuals.already_clean ?? 0) + 1; continue; }if (analysis.status === 'manual') {await keep({ item: name, reason: analysis.reason, tier: 'manual', resolution: analysis.resolution, ...(analysis.gate ? { gate: analysis.gate } : {}), ...(analysis.rows ? { rows: analysis.rows } : {}) });@@ -322,7 +322,7 @@ export const fencesRepair: RepairHandler = {continue;}}- const estimate = tier3Estimate(analysis.requests, { model, overrides: s.overrides, capSource: s.capSource });+ const estimate = tier3Estimate(analysis.requests, { model, overrides: s.overrides, capSource: s.capSource }, analysis.tails);if (!estimate.ok) {await llmHeld('no_pricing', `A spend cap is set but gbrain has no price for ${model}. ${estimate.guidance.lookup} Register it with: ${estimate.guidance.register_command}`);continue;@@ -442,7 +442,10 @@ async function applyFence(ctx: OperationContext, entry: ApprovedFence, opts: Appif (target.before !== entry.before || (target.snapshot?.revision ?? null) !== entry.revision && target.mode !== 'managed' && target.mode !== 'legacy') {return skipped(moved, `${entry.path ?? entry.slug} changed since it was ${opts.expect ? 'previewed' : 'read'}; preview again with gbrain repair fences --source ${src.id}.`);}- const analysis = await analyzeFences(engine, target, { pageId: target.snapshot?.page.id ?? null });+ const runModel = (await settings(engine, { noLlm: opts.noLlm })).model;+ const analysisFor = (tailProse?: ReadonlySet<string>) => analysisOpts(engine, target, src, { apply: true, expect: opts.expect ?? null, model: runModel })+ .then(base => analyzeFences(engine, target, tailProse ? { ...base, tailProse } : base));+ const analysis = await analysisFor();if (analysis.status === 'clean') return skipped('already_clean', `${entry.path ?? entry.slug} no longer has a malformed fence.`);if (analysis.status === 'manual') return heldOutcome(analysis.reason, analysis.resolution, { ...(analysis.gate ? { gate: analysis.gate } : {}), ...(analysis.rows ? { rows: analysis.rows } : {}) });if (analysis.status === 'proposal') {@@ -450,7 +453,21 @@ async function applyFence(ctx: OperationContext, entry: ApprovedFence, opts: Appif (opts.expect && bytes?.sha !== entry.after) return skipped('changed_since_preview', `The repair of ${entry.path ?? entry.slug} differs from the preview; preview again.`);return write(ctx, src, target, analysis.after, { tier: analysis.tier, classes: classesOf(analysis.fixes), ...fixLocation(analysis.fixes, []), model: null, cost: 0, merged: mergedReceipt(target.page, analysis.fixes) }, opts, heldOutcome);}- return tier3(ctx, src, target, analysis, entry, opts, heldOutcome);+ return tier3(ctx, src, target, analysis, entry, opts, heldOutcome, analysisFor);+}++/**+ * #6377: how a run may treat an unclosed fence with trailing text. An explicit preview, and an apply bound to one+ * (`--expect`), carry the user's approval to show the tail of a world-visible page; a bare apply (the cycle,+ * `sync unblock`) never does. A memo that recorded the classifier's prose verdict (`tail_exposure_approval`) lets the+ * approved run close without asking the model again.+ */+async function analysisOpts(engine: BrainEngine, target: FenceTarget, src: FenceSource, run: { apply: boolean; expect?: string | null; model: string | null }): Promise<AnalyzeOpts> {+ const approve = !run.apply || !!run.expect;+ const base: AnalyzeOpts = { pageId: target.snapshot?.page.id ?? null, ...(approve ? { approveTailExposure: true } : {}) };+ if (!approve || !run.model) return base;+ const memo = await attemptStore(engine).read(attemptCandidate(target, src.incarnation)).catch(() => null);+ return memo && memo.memo === tier3Memo(target, run.model) && memo.state === 'rejected' && memo.reason === 'tail_exposure_approval' ? { ...base, tailProse: new Set(['*']) } : base;}type HeldFn = (reason: string, message: string, extra?: { gate?: GateLetter; rows?: number[]; next?: string | null; tier?: FenceTier }) => Promise<RepairItemOutcome>;@@ -470,7 +487,8 @@ async function write(ctx: OperationContext, src: FenceSource, target: FenceTargereturn { applied: true, outcome: 'repaired', detail: { tier: r.tier, classes: r.classes.join(', '), slug: target.slug, ...outcome.detail }, ...(r.cost ? { llm_usd: r.cost } : {}) };}-async function tier3(ctx: OperationContext, src: FenceSource, target: FenceTarget, analysis: Extract<FenceAnalysis, { status: 'llm' }>, entry: ApprovedFence, opts: ApplyOptions, held: HeldFn): Promise<RepairItemOutcome> {+async function tier3(ctx: OperationContext, src: FenceSource, target: FenceTarget, analysis: Extract<FenceAnalysis, { status: 'llm' }>, entry: ApprovedFence, opts: ApplyOptions, held: HeldFn,+ reanalyze: (tailProse: ReadonlySet<string>) => Promise<FenceAnalysis>): Promise<RepairItemOutcome> {const engine = ctx.engine;const s = await settings(engine, { noLlm: opts.noLlm, ...(opts.allowanceUsd !== undefined ? { maxLlmUsd: opts.allowanceUsd } : {}) });const rows = fixLocation(analysis.fixes, analysis.residual).rows;@@ -481,7 +499,7 @@ async function tier3(ctx: OperationContext, src: FenceSource, target: FenceTargeconst now = () => new Date();const timeoutMs = Math.max(5_000, Math.min(CALL_TIMEOUT_MS(), opts.deadline !== undefined ? opts.deadline - Date.now() : Infinity));const result = await runTier3(target, analysis, src.incarnation, { ledger: dailyLedger(engine, FENCE_REPAIR_LEDGER), store: attemptStore(engine), model, overrides: s.overrides,- capSource: s.capSource, perPageUsd: s.perPageUsd, perDayUsd: s.perDayUsd, ...(opts.allowanceUsd !== undefined ? { allowanceUsd: opts.allowanceUsd } : {}), timeoutMs, now });+ capSource: s.capSource, perPageUsd: s.perPageUsd, perDayUsd: s.perDayUsd, ...(opts.allowanceUsd !== undefined ? { allowanceUsd: opts.allowanceUsd } : {}), timeoutMs, now, reanalyze });if (!result.ok) {if (result.reason === 'claimed_elsewhere') return { applied: false, outcome: 'skipped', reason: 'claimed_elsewhere', detail: { path: target.path, slug: target.slug, message: result.message } };const next = result.reason === 'budget_exhausted' ? result.resetsAt ?? nextUtcMidnight(new Date()) : null;diff --git a/test/fence-repair-llm-tail.test.ts b/test/fence-repair-llm-tail.test.tsnew file mode 100644index 0000000000..3fa397c70c--- /dev/null+++ b/test/fence-repair-llm-tail.test.ts@@ -0,0 +1,172 @@+/**+ * #6377: Tier 3 tail classification (src/core/fence-repair/llm-tail.ts).+ *+ * Protects: the model sees only the unclosed fence's region (begin line,+ * header, rows, trailing lines), never prose before the fence and never the+ * other section; a pipe-free tail is never ambiguous; each answer and failure+ * class is distinct (prose/rows/unsure, HOLD = llm_declined, prose refusal =+ * llm_refused, anything else = llm_malformed, truncation rejected even when+ * it parses); the call sends no tools and no fallback; the prompt bytes are+ * pinned (a change must bump TAIL_PROMPT_VERSION).+ * Fails when: page text outside the fence region leaks into the prompt, a+ * malformed answer is treated as a verdict, or the prompt changes silently.+ * Why new: the tail classifier is new in #6377.+ * Seams: the gateway's chat transport seam (__setChatTransportForTests).+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { __setChatTransportForTests, configureGateway, resetGateway, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';+import { buildTailPrompt, callTailClassifier, parseTailAnswer, TAIL_PROMPT_VERSION, tailAmbiguous, tailRequest, tailTokenBudget } from '../src/core/fence-repair/llm-tail.ts';+import { dailyLedger, FENCE_REPAIR_LEDGER } from '../src/core/budget/daily-ledger.ts';+import { attemptStore } from '../src/core/fence-repair/attempts.ts';+import { pageSha, type FenceTarget } from '../src/core/fence-repair/repair-io.ts';+import { analyzeFences, attemptCandidate, runTier3, type FenceAnalysis } from '../src/core/fence-repair/repair-tiers.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';++const TB = '<!--- gbrain:takes:begin -->';+const TH = '| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|';+const PROSE = 'Bodyproseqz9 sits above the fence';+const ROW = '| 1 | Takeclaimzq9 holds | take | brain | 0.5 | 2026-01-01 | chat |';+const BULLET_A = '- 2026-03-01: metqz9 for coffee';+const BULLET_B = '- 2026-03-02: pipe | inside a sentence';+const page = (tail: string) => ({ compiled_truth: `${PROSE}\n`, timeline: `## Timeline\n\n${TB}\n${TH}\n${ROW}\n${tail}\n` });++const result = (text: string, stopReason: ChatResult['stopReason'] = 'end'): ChatResult => ({ text, blocks: [], stopReason,+ usage: { input_tokens: 200, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-opus-5-5', providerId: 'anthropic' });++function stub(answers: Array<ChatResult | Error>) {+ const calls: ChatOpts[] = [];+ __setChatTransportForTests(async opts => {+ calls.push(opts);+ const next = answers.shift()!;+ if (next instanceof Error) throw next;+ return next;+ });+ return calls;+}++beforeAll(() => configureGateway({ providers: { anthropic: { apiKey: 'test' } } } as never));+afterEach(() => __setChatTransportForTests(null));+afterAll(() => resetGateway());++describe('tail request', () => {+ test('carries the fence region and the trailing lines only', () => {+ const req = tailRequest(page(`${BULLET_A}\n${BULLET_B}`), { fence: 'takes', section: 'timeline' }, 'world')!;+ expect(req.kind).toBe('takes');+ expect(req.rows).toEqual([ROW]);+ expect(req.tail).toEqual([BULLET_A, BULLET_B]);+ expect(req.lastRowLine).toBe(6);+ const prompt = buildTailPrompt(req);+ expect(prompt.user).not.toContain(PROSE);+ expect(prompt.user).not.toContain('## Timeline');+ expect(prompt.user).toContain(BULLET_B);+ });++ test('null for a closed fence or an empty tail', () => {+ expect(tailRequest(page(''), { fence: 'takes', section: 'timeline' }, 'world')).toBeNull();+ expect(tailRequest({ compiled_truth: `${TB}\n${TH}\n${ROW}\n<!--- gbrain:takes:end -->\n${BULLET_A}\n`, timeline: '' }, { fence: 'takes', section: 'body' }, 'world')).toBeNull();+ });++ test('a tail is ambiguous only when a line holds a pipe', () => {+ expect(tailAmbiguous([BULLET_A])).toBe(false);+ expect(tailAmbiguous([BULLET_A, BULLET_B])).toBe(true);+ });+});++describe('answers', () => {+ test('each verdict and failure class is distinct', () => {+ expect(parseTailAnswer('{"tail":"prose"}')).toEqual({ ok: true, tail: 'prose' });+ expect(parseTailAnswer('```json\n{"tail": "rows"}\n```')).toEqual({ ok: true, tail: 'rows' });+ expect(parseTailAnswer('{"tail":"unsure"}')).toEqual({ ok: true, tail: 'unsure' });+ expect(parseTailAnswer('HOLD')).toEqual({ ok: false, reason: 'llm_declined' });+ expect(parseTailAnswer('')).toEqual({ ok: false, reason: 'llm_empty' });+ expect(parseTailAnswer('I cannot help with that.')).toEqual({ ok: false, reason: 'llm_refused' });+ expect(parseTailAnswer('{"tail":"maybe"}')).toEqual({ ok: false, reason: 'llm_malformed' });+ expect(parseTailAnswer('The tail is prose.')).toEqual({ ok: false, reason: 'llm_malformed' });+ expect(parseTailAnswer('[1]')).toEqual({ ok: false, reason: 'llm_malformed' });+ });++ test('the call sends no tools and no fallback, and a truncated answer is rejected even when it parses', async () => {+ const req = tailRequest(page(BULLET_B), { fence: 'takes', section: 'timeline' }, 'private')!;+ const calls = stub([result('{"tail":"prose"}'), result('{"tail":"prose"}', 'length'), new Error('boom')]);+ const first = await callTailClassifier(req, { model: 'anthropic:claude-opus-5-5' });+ expect(first).toMatchObject({ ok: true, tail: 'prose' });+ expect(calls[0]!.tools).toBeUndefined();+ expect(calls[0]!.allowFallback).toBe(false);+ expect(calls[0]!.maxTokens).toBe(tailTokenBudget(req, 'anthropic:claude-opus-5-5').maxOutputTokens);+ expect(await callTailClassifier(req, { model: 'anthropic:claude-opus-5-5' })).toMatchObject({ ok: false, reason: 'llm_truncated' });+ expect(await callTailClassifier(req, { model: 'anthropic:claude-opus-5-5' })).toMatchObject({ ok: false, reason: 'llm_unavailable' });+ });++ test('prompt bytes are pinned to TAIL_PROMPT_VERSION', () => {+ const req = tailRequest(page(BULLET_B), { fence: 'takes', section: 'timeline' }, 'world')!;+ const prompt = buildTailPrompt(req);+ const digest = createHash('sha256').update(`${TAIL_PROMPT_VERSION}\n${prompt.system}`).digest('hex').slice(0, 16);+ expect(digest).toBe('529e70be1ef8b25b');+ });+});++describe('the tail tier through runTier3 (#6377)', () => {+ let engine: PGLiteEngine;+ let incarnation: string;+ const model = 'anthropic:claude-opus-5-5';+ const piped = { compiled_truth: `${PROSE}\n`, timeline: `## Timeline\n\n${TB}\n${TH}\n${ROW}\n${BULLET_A}\n${BULLET_B}\n` };+ const closed = `## Timeline\n\n${TB}\n${TH}\n${ROW}\n<!--- gbrain:takes:end -->\n${BULLET_A}\n${BULLET_B}\n`;++ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ const [src] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='default'");+ incarnation = src!.incarnation;+ });+ afterAll(async () => { await engine.disconnect(); });++ async function attempt(slug: string, visibility: 'private' | 'world', answers: Array<ChatResult | Error>, approve = false) {+ const target = { mode: 'db', sourceId: 'default', key: slug, slug, path: null, sourcePath: null, page: piped, content: null, before: pageSha(piped), snapshot: null, hold: null,+ ctx: { pageVisibility: visibility } } as FenceTarget;+ const opts = { pageId: null, ...(approve ? { approveTailExposure: true } : {}) };+ const analysis = await analyzeFences(engine, target, opts);+ expect(analysis.status).toBe('llm');+ expect((analysis as Extract<FenceAnalysis, { status: 'llm' }>).tails).toHaveLength(1);+ const calls = stub(answers);+ const out = await runTier3(target, analysis as Extract<FenceAnalysis, { status: 'llm' }>, incarnation, { ledger: dailyLedger(engine, FENCE_REPAIR_LEDGER), store: attemptStore(engine),+ model, capSource: 'default', perPageUsd: 1, perDayUsd: 10, timeoutMs: 30_000, now: () => new Date(),+ reanalyze: prose => analyzeFences(engine, target, { ...opts, tailProse: prose }) });+ return { out, calls, target };+ }++ test('a prose verdict closes the fence on a private page; the prompt carried only the fence region', async () => {+ const { out, calls } = await attempt('tail/private', 'private', [result('{"tail":"prose"}')]);+ expect(calls).toHaveLength(1);+ const sent = JSON.stringify(calls[0]!.messages) + calls[0]!.system;+ expect(sent).toContain(BULLET_B);+ expect(sent).not.toContain(PROSE);+ expect(out).toMatchObject({ ok: true, cleared: ['unclosed_trailing_content'] });+ expect((out as Extract<typeof out, { ok: true }>).after.timeline).toBe(closed);+ });++ test('a prose verdict on a world page waits for the user (tail_exposure_approval); the memo stores it, and the approved apply closes without a second call', async () => {+ const first = await attempt('tail/world', 'world', [result('{"tail":"prose"}')]);+ expect(first.calls).toHaveLength(1);+ expect(first.out).toMatchObject({ ok: false, reason: 'tail_exposure_approval' });+ const memo = await attemptStore(engine).read(attemptCandidate(first.target, incarnation));+ expect(memo).toMatchObject({ state: 'rejected', reason: 'tail_exposure_approval' });+ const again = await attempt('tail/world', 'world', [result('{"tail":"prose"}')]);+ expect(again.calls).toHaveLength(0);+ expect(again.out).toMatchObject({ ok: false, reason: 'tail_exposure_approval', memoHit: true });+ const approved = await analyzeFences(engine, first.target, { pageId: null, approveTailExposure: true, tailProse: new Set(['*']) });+ expect(approved).toMatchObject({ status: 'proposal', tier: 'deterministic' });+ expect((approved as Extract<FenceAnalysis, { status: 'proposal' }>).after.timeline).toBe(closed);+ expect((approved as Extract<FenceAnalysis, { status: 'proposal' }>).fixes.map(f => f.class)).toEqual(['close_fence_trailing']);+ });++ test('rows, unsure, HOLD and a provider error each leave the fence open with their own reason', async () => {+ expect((await attempt('tail/rows', 'private', [result('{"tail":"rows"}')])).out).toMatchObject({ ok: false, reason: 'unclosed_ambiguous_tail' });+ expect((await attempt('tail/unsure', 'private', [result('{"tail":"unsure"}')])).out).toMatchObject({ ok: false, reason: 'unclosed_ambiguous_tail' });+ expect((await attempt('tail/hold', 'private', [result('HOLD')])).out).toMatchObject({ ok: false, reason: 'unclosed_ambiguous_tail' });+ expect((await attempt('tail/down', 'private', [new Error('ECONNRESET')])).out).toMatchObject({ ok: false, reason: 'llm_unavailable' });+ const memo = await attemptStore(engine).read({ sourceId: 'default', incarnation, key: 'slug:tail/down' });+ expect(memo?.state).not.toBe('rejected');+ });+});diff --git a/test/fence-repair-normalize.test.ts b/test/fence-repair-normalize.test.tsindex 69a497cb7a..c2823383c4 100644--- a/test/fence-repair-normalize.test.ts+++ b/test/fence-repair-normalize.test.ts@@ -150,13 +150,38 @@ describe('close_fence and the protection boundary', () => {expect(r.page.compiled_truth).toBe(body);});- test('prose after the table keeps the fence open (manual) so the boundary never shows it', () => {+ test('prose after the table on a world page keeps the fence open (tail_exposure_approval) so the boundary never shows it unasked (#6377)', () => {const body = [FB, FH, FS, factsRow(1, 'Psi claim'), '', 'TRAILING-PROSE-CANARY stays hidden'].join('\n');- const r = run(body);- expect(reasons(r)).toEqual(['unclosed_trailing_content']);+ const r = run(body, WORLD);+ expect(reasons(r)).toEqual(['tail_exposure_approval']);expect(r.page.compiled_truth).toBe(body);expect(sanitizeRemoteBody(r.page.compiled_truth)).not.toContain('TRAILING-PROSE-CANARY');- expect(FENCE_REASONS.unclosed_trailing_content.manualOnly).toBe(true);+ expect(FENCE_REASONS.tail_exposure_approval.autoRetry).toBe(false);+ expect(FENCE_REASONS.tail_exposure_approval.actor).toBe('user');+ });++ test('prose after the table closes the fence on a private page, or on a world page under the user\'s approval (close_fence_trailing, #6377)', () => {+ const body = [FB, FH, FS, factsRow(1, 'Psi claim'), '', 'TRAILING-PROSE-CANARY becomes visible'].join('\n');+ for (const ctx of [PRIVATE, { ...WORLD, approveTailExposure: true }]) {+ const r = run(body, ctx);+ expect(r.fixes.map(f => f.class)).toEqual(['close_fence_trailing']);+ expect(r.residual).toEqual([]);+ expect(r.page.compiled_truth).toBe([FB, FH, FS, factsRow(1, 'Psi claim'), FE, '', 'TRAILING-PROSE-CANARY becomes visible'].join('\n'));+ expect(sanitizeRemoteBody(r.page.compiled_truth)).toContain('TRAILING-PROSE-CANARY');+ expectRepaired(r, ctx);+ }+ });++ test('a trailing line with a pipe waits for the tail classifier; a marker mention is manual (#6377)', () => {+ const piped = [FB, FH, FS, factsRow(1, 'Psi claim'), '', 'a note with a | in it'].join('\n');+ expect(reasons(run(piped))).toEqual(['unclosed_trailing_content']);+ expect(FENCE_REASONS.unclosed_trailing_content.tier).toBe('llm');+ const judged = run(piped, { ...PRIVATE, tailProse: new Set(['body:facts']) });+ expect(judged.fixes.map(f => f.class)).toEqual(['close_fence_trailing']);+ expect(judged.page.compiled_truth).toContain(`${FE}\n\na note with a | in it`);+ expect(reasons(run(piped, { ...WORLD, tailProse: new Set(['*']) }))).toEqual(['tail_exposure_approval']);+ const mention = [FB, FH, FS, factsRow(1, 'Psi claim'), '', 'the marker gbrain:facts:end is only mentioned here'].join('\n');+ expect(reasons(run(mention))).toEqual(['unclosed_ambiguous_tail']);});test('an end marker with no begin is never guessed', () => {diff --git a/test/fence-repair-reasons.test.ts b/test/fence-repair-reasons.test.tsindex af0814df34..d82992f08a 100644--- a/test/fence-repair-reasons.test.ts+++ b/test/fence-repair-reasons.test.ts@@ -15,13 +15,15 @@ const SPEC_MANUAL: FenceReason[] = ['weight_missing', 'confidence_out_of_range', 'claim_value_invalid', 'takes_kind_unsupported',];/** Manual-only residuals this module adds where the spec says "residual" without naming one. */-const ADDED_MANUAL: FenceReason[] = ['unclosed_trailing_content', 'marker_near_miss', 'holder_missing'];+const ADDED_MANUAL: FenceReason[] = ['marker_near_miss', 'holder_missing', 'unclosed_ambiguous_tail'];/*** Manual since the Tier 3 eval (#6188 T4): a row whose extra cells empty-cell removal cannot line up, and a facts kind* cell that holds text rather than a kind word; no gate can tell a claim cut by an unescaped `|` from a misplaced cell.*/const EVAL_MANUAL: FenceReason[] = ['extra_cells', 'claim_split'];-const SPEC_TIER3: FenceReason[] = ['header_unmapped', 'no_header', 'row_before_header', 'short_row'];+const SPEC_TIER3: FenceReason[] = ['header_unmapped', 'no_header', 'row_before_header', 'short_row', 'unclosed_trailing_content'];+/** #6377: the user's hash-bound approval to close a fence ahead of trailing text on a world-visible page; nothing retries it by itself. */+const APPROVAL: FenceReason[] = ['tail_exposure_approval'];/** #6278: the owner conditions the `owner_unavailable` reasons matrix names (persistence/owner-refusal.ts); `owner_unavailable` stays the generic fallback. */const OWNER_CONDITIONS: FenceReason[] = ['host_mismatch', 'transfer_in_progress', 'clone_in_progress', 'incarnation_changed', 'local_path_missing', 'coordination_path_missing'];const SPEC_OTHERS: FenceReason[] = [@@ -36,7 +38,7 @@ const SPEC_OTHERS: FenceReason[] = [describe('FENCE_REASONS', () => {test('holds exactly the reasons the spec names (plus the documented additions)', () => {- expect([...FENCE_REASON_CODES].sort()).toEqual([...SPEC_MANUAL, ...ADDED_MANUAL, ...EVAL_MANUAL, ...SPEC_TIER3, ...OWNER_CONDITIONS, ...SPEC_OTHERS].sort());+ expect([...FENCE_REASON_CODES].sort()).toEqual([...SPEC_MANUAL, ...ADDED_MANUAL, ...EVAL_MANUAL, ...SPEC_TIER3, ...APPROVAL, ...OWNER_CONDITIONS, ...SPEC_OTHERS].sort());});test('owner conditions match the owner_unavailable reasons matrix: host_admin acts, only the in-progress ones retry by themselves', () => {@@ -53,6 +55,7 @@ describe('FENCE_REASONS', () => {for (const reason of [...SPEC_MANUAL, ...ADDED_MANUAL, ...EVAL_MANUAL]) {expect([reason, FENCE_REASONS[reason].tier, FENCE_REASONS[reason].manualOnly, FENCE_REASONS[reason].autoRetry]).toEqual([reason, 'manual', true, false]);}+ for (const reason of APPROVAL) expect([reason, FENCE_REASONS[reason].manualOnly, FENCE_REASONS[reason].autoRetry, FENCE_REASONS[reason].actor]).toEqual([reason, false, false, 'user']);for (const reason of SPEC_TIER3) expect([reason, FENCE_REASONS[reason].tier, FENCE_REASONS[reason].manualOnly]).toEqual([reason, 'llm', false]);expect(FENCE_REASONS.holder_unresolved.tier).toBe('resolver');expect(FENCE_REASONS.stored_row_collision.manualOnly).toBe(true);diff --git a/test/fence-repair-validate.test.ts b/test/fence-repair-validate.test.tsindex 064e777260..e4d16c48d9 100644--- a/test/fence-repair-validate.test.ts+++ b/test/fence-repair-validate.test.ts@@ -105,7 +105,16 @@ describe('one adversarial repair per gate', () => {test('(g) protection_loosened: closing a fence before trailing prose would publish the prose', () => {const before = page([FB, FH, ROW2, '', 'TRAILING-NOTE stays private'].join('\n'));const after = page([FB, FH, ROW2, FE, '', 'TRAILING-NOTE stays private'].join('\n'));- expect(check(before, after)).toMatchObject({ ok: false, gate: 'g', reason: 'protection_loosened' });+ expect(check(before, after, { pageVisibility: 'world' })).toMatchObject({ ok: false, gate: 'g', reason: 'protection_loosened' });+ expect(validateFenceRepair(before, after, { pageVisibility: 'private', tier: 'llm', issues: [] })).toMatchObject({ ok: false, gate: 'g' });+ });++ test('(g) admits exactly the tail a close_fence_trailing fix shows, and nothing else (#6377)', () => {+ const before = page([FB, FH, ROW2, '', 'TRAILING-NOTE becomes visible'].join('\n'));+ const after = page([FB, FH, ROW2, FE, '', 'TRAILING-NOTE becomes visible'].join('\n'));+ expect(check(before, after)).toEqual({ ok: true });+ const more = page([FB, FH, ROW2, FE, '', 'TRAILING-NOTE becomes visible', 'ANOTHER line nobody approved'].join('\n'));+ expect(check(before, more)).toMatchObject({ ok: false, gate: 'g', reason: 'protection_loosened' });});test('failures are location-only', () => {