A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: degrade eager-layer sections by levels instead of collapsing them whole (#308)
Brenno Ferrarif44a94bc4700
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.tsindex d60bf2e..2b52be9 100644--- a/.claude/scripts/lib/session-start.ts+++ b/.claude/scripts/lib/session-start.ts@@ -30,6 +30,8 @@ export function formatInjectionSize(opts?: {readonly budgetBytes?: number | undefined;readonly collapsed?: readonly string[] | undefined;+ /** Sections held between full and pointer, named with their level (#304). */+ readonly degraded?: readonly { readonly section: string; readonly level: string }[] | undefined;/** The configured budget, when it was clamped to the hook output cap. */readonly clampedFrom?: number | undefined;/** True when the output was truncated to fit its limit. */@@ -52,6 +54,8 @@ export function formatInjectionSize(let line = `_context injected: ${size} / ${kb(budget)} budget${clamp}`;const collapsed = opts?.collapsed ?? [];if (collapsed.length > 0) line += ` — collapsed: ${collapsed.join(", ")}`;+ const degraded = opts?.degraded ?? [];+ if (degraded.length > 0) line += ` — degraded: ${degraded.map((d) => `${d.section} → ${d.level}`).join(", ")}`;if (opts?.cut === true) line += ` — truncated to fit ${opts.cutTo ?? "the hook output cap"}`;return `${line}_`;}@@ -63,6 +67,11 @@ export function formatInjectionSize(* `priority` orders SURRENDER, not importance: the highest number is given* up first. A section with no `fallback` is load-bearing and never dropped* (identity, the date header) regardless of priority.+ *+ * A degradable section's ladder runs from `body` (level "full") through its+ * optional `levels`, richest to leanest, down to `fallback` (level+ * "pointer"). With no `levels` it is the two-step full/pointer ladder every+ * section had before (#304).*/export type BudgetSection = {/** Section heading, e.g. "### Vault File Listing". Empty for preamble. */@@ -70,13 +79,29 @@ export type BudgetSection = {readonly body: string;readonly priority: number;readonly fallback?: string | undefined;+ readonly levels?: readonly BudgetLevel[] | undefined;+};++/**+ * One rung between a section's full body and its pointer. `body` is the+ * whole rendering at this level. A level whose content depends on the room+ * left (the first N items that fit) gives `fit` instead: handed the bytes its+ * body may take, it returns the richest body within them, or null when+ * nothing useful fits.+ */+export type BudgetLevel = {+ readonly name: string;+ readonly body?: string | undefined;+ readonly fit?: ((maxBytes: number) => string | null) | undefined;};export type BudgetResult = {readonly text: string;readonly bytes: number;- /** Headers (heading markup stripped) that were degraded, in drop order. */+ /** Headers (heading markup stripped) left at their pointer, in surrender order. */readonly collapsed: readonly string[];+ /** Sections held at a level between full and pointer, in section order. */+ readonly degraded: readonly { readonly section: string; readonly level: string }[];};function renderSections(sections: readonly BudgetSection[]): string {@@ -86,16 +111,27 @@ function renderSections(sections: readonly BudgetSection[]): string {}/**- * Hold the eager layer under a byte ceiling by degrading the cheapest-to-lose- * sections to their pointers, highest `priority` first, until it fits.+ * Hold the eager layer under a byte ceiling by stepping sections down their+ * degradation ladders (full → … → pointer).** Why bytes and not lines: the pre-existing caps in this file (`take`,* `formatActiveWork`, `collectOpenTasks`) are all LINE caps, and a line cap* cannot bound an injection — shortening entries just slides the window* deeper and refills it. Only a byte budget actually holds.*- * Degradation is never silent truncation: a section is replaced whole by its- * fallback pointer, so the content is missing but its existence is not.+ * Allocation, when everything at full does not fit (#304):+ * 1. every degradable section starts at its pointer;+ * 2. sections are then raised best-first (lowest `priority` first), each to+ * the richest level that keeps the whole render within budget;+ * 3. a section is never revisited, so a better section is never lowered to+ * raise a worse one.+ * This replaced a worst-first collapse that stopped at the first fit. That+ * one could give up the listing and brain index and then the oversized+ * section anyway, leaving 0.4 kB of a 9.1 kB budget with no way back, and it+ * had no level between whole and pointer.+ *+ * Degradation is never silent: a level is a whole rendering chosen by the+ * section, and the meter names every section not at full.** A non-finite or non-positive budget is a no-op — as with the size meter,* the budget must never be the thing that breaks the hook.@@ -104,34 +140,56 @@ export function applyInjectionBudget(sections: readonly BudgetSection[],budgetBytes: number,): BudgetResult {- const render = (s: readonly BudgetSection[]): BudgetResult => ({+ const size = (s: readonly BudgetSection[]): number => Buffer.byteLength(renderSections(s), "utf-8");+ const whole = (s: readonly BudgetSection[]): BudgetResult => ({text: renderSections(s),- bytes: Buffer.byteLength(renderSections(s), "utf-8"),+ bytes: size(s),collapsed: [],+ degraded: [],});- if (!Number.isFinite(budgetBytes) || budgetBytes <= 0) return render(sections);+ if (!Number.isFinite(budgetBytes) || budgetBytes <= 0) return whole(sections);+ if (size(sections) <= budgetBytes) return whole(sections);- let current = [...sections];- if (render(current).bytes <= budgetBytes) return render(current);+ const canDegrade = (s: BudgetSection): boolean => s.fallback !== undefined && s.fallback !== s.body;+ let current = sections.map((s) => (canDegrade(s) ? { ...s, body: s.fallback ?? s.body } : s));+ const level = new Map<number, string>();- // Candidates are only those that can degrade, surrendered worst-first.- const order = current- .map((s, i) => ({ s, i }))- .filter(({ s }) => s.fallback !== undefined && s.fallback !== s.body)- .sort((a, b) => b.s.priority - a.s.priority || a.i - b.i);+ const indices = sections.map((s, i) => ({ s, i })).filter(({ s }) => canDegrade(s));+ for (const { i } of indices) level.set(i, "pointer");+ const bestFirst = [...indices].sort((a, b) => a.s.priority - b.s.priority || a.i - b.i);- const collapsed: string[] = [];- for (const { i } of order) {- const target = current[i];- if (target === undefined) continue;- current[i] = { ...target, body: target.fallback ?? target.body };- collapsed.push(target.header.replace(/^#+\s*/, ""));- if (Buffer.byteLength(renderSections(current), "utf-8") <= budgetBytes) break;+ for (const { s, i } of bestFirst) {+ const rungs: readonly BudgetLevel[] = [{ name: "full", body: s.body }, ...(s.levels ?? [])];+ for (const rung of rungs) {+ let body: string | null | undefined = rung.body;+ if (rung.fit !== undefined) {+ const empty = [...current];+ empty[i] = { ...s, body: "" };+ const room = budgetBytes - size(empty);+ body = room > 0 ? rung.fit(room) : null;+ }+ if (body === null || body === undefined || body === "") continue;+ const probe = [...current];+ probe[i] = { ...s, body };+ if (size(probe) <= budgetBytes) {+ current = probe;+ level.set(i, rung.name);+ break;+ }+ }}+ const name = (i: number): string => (sections[i]?.header ?? "").replace(/^#+\s*/, "");+ const collapsed = [...indices]+ .sort((a, b) => b.s.priority - a.s.priority || a.i - b.i)+ .filter(({ i }) => level.get(i) === "pointer")+ .map(({ i }) => name(i));+ const degraded = indices+ .filter(({ i }) => level.get(i) !== "pointer" && level.get(i) !== "full")+ .map(({ i }) => ({ section: name(i), level: level.get(i) as string }));const text = renderSections(current);- return { text, bytes: Buffer.byteLength(text, "utf-8"), collapsed };+ return { text, bytes: Buffer.byteLength(text, "utf-8"), collapsed, degraded };}/**@@ -824,3 +882,151 @@ export function resolveIndexStorePath(export function injectionMode(source: unknown): "full" | "pointer" {return source === "resume" || source === "compact" ? "pointer" : "full";}++// ---------------------------------------------------------------------------+// North Star degradation ladder (#304)+// ---------------------------------------------------------------------------++/** A headline is at most this long. */+export const HEADLINE_MAX_CHARS = 200;++/** A first sentence shorter than this is a label; the headline takes more. */+export const HEADLINE_MIN_CHARS = 40;++export const NORTH_STAR_POINTER = "Read brain/North Star.md before suggesting priorities or deciding what to work on.";++const LIST_ITEM = /^(\s*)(?:[-*+]|\d+[.)])\s+(.*)$/;++/** A list item that is finished: struck through, or a checked box. */+function isDeadItem(text: string): boolean {+ return text.startsWith("~~") || /^\[[xX]\]/.test(text);+}++/**+ * Drop finished items (struck, or `[x]`) together with everything indented+ * under them — sub-bullets and continuation lines. Returns the kept lines and+ * how many items were dropped.+ */+function dropDeadItems(lines: readonly string[]): { readonly kept: string[]; readonly dropped: number } {+ const kept: string[] = [];+ let dropped = 0;+ let skipDeeperThan = -1;+ for (const line of lines) {+ const indent = (/^\s*/.exec(line)?.[0] ?? "").length;+ if (skipDeeperThan >= 0) {+ if (line.trim() !== "" && indent > skipDeeperThan) continue;+ skipDeeperThan = -1;+ }+ const item = LIST_ITEM.exec(line);+ if (item && isDeadItem((item[2] ?? "").trim())) {+ dropped++;+ skipDeeperThan = (item[1] ?? "").length;+ continue;+ }+ kept.push(line);+ }+ return { kept, dropped };+}++/** Lines from `start` up to (not including) the next `## ` heading. */+function untilNextH2(lines: readonly string[], start: number): string[] {+ const end = lines.findIndex((l, i) => i > start && /^##\s/.test(l));+ return lines.slice(start, end === -1 ? lines.length : end);+}++/**+ * One goal as a line. The bullet's first sentence, with wikilinks shown as+ * their text and emphasis markers dropped. A first sentence under+ * HEADLINE_MIN_CHARS is a label ("Atlas."), so sentences are taken until+ * the headline reaches it or the bullet ends. Never cut at a dash: a+ * `[[Project]] — clause` bullet would keep only the project name. Capped at+ * HEADLINE_MAX_CHARS on a word boundary with "…". Null for anything that is+ * not a live, non-empty list item.+ */+export function goalHeadline(line: string): string | null {+ const item = LIST_ITEM.exec(line);+ if (!item) return null;+ let t = (item[2] ?? "").trim();+ if (t === "" || isDeadItem(t)) return null;+ t = t.replace(/^\[ \]\s+/, "");+ t = t.replace(/\[\[([^\]|#]*)(?:#[^\]|]*)?(?:\|([^\]]*))?\]\]/g, (_m, target: string, alias?: string) => (alias ?? target).trim());+ t = t.replace(/(\*\*|__)(.+?)\1/g, "$2");+ const ends = [...t.matchAll(/[.?!](?=\s)/g)].map((e) => (e.index ?? 0) + 1);+ const stop = ends.find((i) => i >= HEADLINE_MIN_CHARS) ?? t.length;+ t = t.slice(0, stop).trim();+ if (t.length > HEADLINE_MAX_CHARS) {+ const cut = t.slice(0, HEADLINE_MAX_CHARS - 1);+ const space = cut.lastIndexOf(" ");+ t = `${(space > HEADLINE_MAX_CHARS * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,;:—–-]+$/, "")}…`;+ }+ return t === "" ? null : t;+}++export type NorthStarLadder = {+ /** Current Focus to end of file, cleaned: finished items and the Shifts Log out. */+ readonly full: string;+ /** Current Focus only, finished items out. Null when there is no Current Focus. */+ readonly focus: string | null;+ /** One headline per live top-level Current Focus bullet. */+ readonly headlines: readonly string[];+};++/**+ * The North Star at each level of its ladder (#304), from the file's text.+ *+ * `full` keeps what the eager layer has always shown — `## Current Focus` to+ * the end of the file, 30 lines — minus what is not a goal: finished items+ * (struck, or `[x]`) WITH their sub-bullets and continuation lines, which the+ * old filter left behind, and the `## Shifts Log`, which is history. It is+ * not byte-cut: the budget bounds it, and a cut `full` would outrank the+ * level that shows every goal.+ */+export function northStarLadder(raw: string): NorthStarLadder {+ const lines = stripFrontmatter(raw).split(/\r?\n/);+ const anchor = lines.findIndex((l) => l.trim().startsWith("## Current Focus"));+ const scoped = anchor >= 0 ? lines.slice(anchor) : lines;++ const log = scoped.findIndex((l) => /^##\s+Shifts Log\b/.test(l));+ const withoutLog = log === -1 ? scoped : [...scoped.slice(0, log), ...scoped.slice(log).slice(untilNextH2(scoped, log).length)];++ const { kept, dropped } = dropDeadItems(withoutLog);+ if (dropped > 0) {+ kept.splice(1, 0, `_(${dropped} completed item${dropped === 1 ? "" : "s"} hidden — full history in brain/North Star.md)_`);+ }+ // No byte cut here: a cut `full` would fit where the whole does not and+ // outrank `headlines`, showing a third of the goals where the next level+ // shows all of them. The budget already bounds this level.+ const full = take(kept.join("\n"), 30);++ if (anchor < 0) {+ const heads = dropDeadItems(lines).kept.filter((l) => LIST_ITEM.exec(l)?.[1] === "").map(goalHeadline);+ return { full, focus: null, headlines: heads.filter((h): h is string => h !== null) };+ }+ const focusLines = dropDeadItems(untilNextH2(scoped, 0));+ if (focusLines.dropped > 0) {+ focusLines.kept.splice(1, 0, `_(${focusLines.dropped} completed item${focusLines.dropped === 1 ? "" : "s"} hidden — full history in brain/North Star.md)_`);+ }+ const headlines = focusLines.kept+ .filter((l) => LIST_ITEM.exec(l)?.[1] === "")+ .map(goalHeadline)+ .filter((h): h is string => h !== null);+ return { full, focus: focusLines.kept.join("\n").trimEnd(), headlines };+}++/** The headlines as a list body. */+export function renderHeadlines(headlines: readonly string[]): string {+ return headlines.map((h) => `- ${h}`).join("\n");+}++/**+ * The first N headlines that fit in `maxBytes`, with a line saying how many+ * more there are. Null when not even one fits, or when all of them do (that+ * is the `headlines` level, not this one).+ */+export function topHeadlines(headlines: readonly string[], maxBytes: number): string | null {+ for (let n = headlines.length - 1; n >= 1; n--) {+ const body = `${renderHeadlines(headlines.slice(0, n))}\n_(+${headlines.length - n} more goals in brain/North Star.md)_`;+ if (Buffer.byteLength(body, "utf-8") <= maxBytes) return body;+ }+ return null;+}diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.tsindex 9a96d3a..3e8d3ef 100644--- a/.claude/scripts/session-start.ts+++ b/.claude/scripts/session-start.ts@@ -64,6 +64,12 @@ import {formatCollapsedDir,DEFAULT_LISTING_COLLAPSE_THRESHOLD,type BudgetSection,+ type BudgetLevel,+ type NorthStarLadder,+ northStarLadder,+ renderHeadlines,+ topHeadlines,+ NORTH_STAR_POINTER,} from "./lib/session-start.ts";import {buildQmdCommand,@@ -303,41 +309,36 @@ function runCmd(}-function northStar(): string {+function northStar(): NorthStarLadder | null {// Filesystem-only: the path is fixed by template convention, so there's no// wikilink-resolution value worth a CLI hop — and `spawnSync("obsidian", …)`// launches the Electron app on macOS when no instance is running (#83).//- // The 30-line budget must carry LIVE goals (#107): anchor at- // "## Current Focus" (skipping frontmatter + preamble) and drop- // struck-through completed bullets, which otherwise consume the slice- // and truncate current strategy.+ // The slice must carry LIVE goals (#107), and degrade by levels rather+ // than vanish when it does not fit (#304): see `northStarLadder`.try {- const raw = readFileSync("brain/North Star.md", { encoding: "utf-8" });- const lines = stripFrontmatter(raw).split("\n");- const anchor = lines.findIndex((l) =>- l.trim().startsWith("## Current Focus"),- );- const scoped = anchor >= 0 ? lines.slice(anchor) : lines;- const struckCount = scoped.filter((l) =>- l.trimStart().startsWith("- ~~"),- ).length;- const live = scoped.filter((l) => !l.trimStart().startsWith("- ~~"));- if (struckCount > 0) {- // Struck bullets can carry live tails — keep a pointer so sessions- // know completed context exists in the file.- live.splice(- 1,- 0,- `_(${struckCount} completed item${struckCount === 1 ? "" : "s"} hidden — full history in brain/North Star.md)_`,- );- }- return take(live.join("\n"), 30);+ return northStarLadder(readFileSync("brain/North Star.md", { encoding: "utf-8" }));} catch {- return "(not found)";+ return null;}}+/** The North Star section, with its ladder: full → focus → headlines → top-N → pointer. */+function northStarSection(priority: number): BudgetSection {+ const ladder = northStar();+ const header = "### North Star (current goals)";+ if (ladder === null) return { header, body: "(not found)", priority, fallback: NORTH_STAR_POINTER };+ const levels: BudgetLevel[] = [];+ if (ladder.focus !== null) levels.push({ name: "focus", body: ladder.focus });+ if (ladder.headlines.length > 0) {+ levels.push(+ { name: "headlines", body: renderHeadlines(ladder.headlines) },+ { name: "top-N", fit: (room) => topHeadlines(ladder.headlines, room) },+ );+ }+ return { header, body: ladder.full, priority, fallback: NORTH_STAR_POINTER, levels };+}+function recentChanges(): string {const r = runCmd("git", ["log",@@ -569,12 +570,7 @@ const sections: BudgetSection[] = [];if (mode === "full") {sections.push(- {- header: "### North Star (current goals)",- body: northStar(),- priority: PRIORITY.NORTH_STAR,- fallback: "(Over budget — re-read brain/North Star.md on demand.)",- },+ northStarSection(PRIORITY.NORTH_STAR),{header: "### Brain Topics (read on demand)",body: brainIndex(),@@ -665,6 +661,7 @@ process.stdout.write(formatInjectionSize(bodyBytes, {budgetBytes: budget.bytes,collapsed: budgeted.collapsed,+ degraded: budgeted.degraded,clampedFrom: budget.clampedFrom,cut,cutTo: limit.name,diff --git a/.claude/scripts/tests/budget-ladder.test.ts b/.claude/scripts/tests/budget-ladder.test.tsnew file mode 100644index 0000000..c10a8d7--- /dev/null+++ b/.claude/scripts/tests/budget-ladder.test.ts@@ -0,0 +1,266 @@+/**+ * #304: the eager layer degrades by levels, not all-or-nothing.+ *+ * Before, `applyInjectionBudget` collapsed sections worst-first and stopped at+ * the first fit, with nothing between a whole section and its pointer. A long+ * North Star could not fit whole, so after the file listing and brain index+ * were given up — though they fitted — it collapsed too: 0.4 kB injected of a+ * 9.1 kB budget, and no goals. These pin the ladder that replaced it.+ */++import { test, describe } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import {+ applyInjectionBudget,+ formatInjectionSize,+ goalHeadline,+ northStarLadder,+ renderHeadlines,+ stripFrontmatter,+ take,+ topHeadlines,+ HEADLINE_MAX_CHARS,+ NORTH_STAR_POINTER,+ type BudgetSection,+} from "../lib/session-start.ts";+import { runScript as spawnHook, rmTemp } from "./_helpers.ts";++const bytes = (s: string): number => Buffer.byteLength(s, "utf-8");+const render = (s: readonly BudgetSection[]): number =>+ bytes(s.map((x) => (x.header === "" ? x.body : `${x.header}\n${x.body}`)).join("\n\n"));++describe("applyInjectionBudget — the ladder", () => {+ const ns = (full: string, levels: BudgetSection["levels"]): BudgetSection => ({+ header: "### North Star (current goals)",+ body: full,+ priority: 30,+ fallback: NORTH_STAR_POINTER,+ levels,+ });+ const listing: BudgetSection = { header: "### Vault File Listing", body: "l".repeat(400), priority: 50, fallback: "(l)" };+ const brain: BudgetSection = { header: "### Brain Topics (read on demand)", body: "b".repeat(400), priority: 40, fallback: "(b)" };++ test("#304's shape: an oversized North Star degrades to headlines; the listing and brain index stay whole", () => {+ const r = applyInjectionBudget(+ [listing, brain, ns("n".repeat(12_000), [{ name: "headlines", body: "- goal one\n- goal two" }])],+ 2_000,+ );+ assert.ok(r.text.includes("l".repeat(400)));+ assert.ok(r.text.includes("b".repeat(400)));+ assert.ok(r.text.includes("- goal one\n- goal two"));+ assert.deepEqual(r.collapsed, []);+ assert.deepEqual(r.degraded, [{ section: "North Star (current goals)", level: "headlines" }]);+ });++ test("a better section is never lowered to raise a worse one", () => {+ // Budget fits Better at full with Worse at its pointer, OR Better at+ // its middle level with Worse whole. Best-first keeps Better whole.+ const better: BudgetSection = { header: "### Better", body: "B".repeat(100), priority: 10, fallback: "(B)", levels: [{ name: "mid", body: "B".repeat(40) }] };+ const worse: BudgetSection = { header: "### Worse", body: "W".repeat(60), priority: 20, fallback: "(W)" };+ const r = applyInjectionBudget([better, worse], 130);+ assert.ok(r.text.includes("B".repeat(100)), r.text);+ assert.deepEqual(r.collapsed, ["Worse"]);+ assert.deepEqual(r.degraded, []);+ });++ test("each level is chosen at its boundary: fits exactly, and one byte over drops a level", () => {+ const fixed: BudgetSection = { header: "", body: "x", priority: 0 };+ const levels = [{ name: "focus", body: "f".repeat(50) }, { name: "headlines", body: "h".repeat(20) }];+ const sections = (full: string) => [fixed, ns(full, levels)];+ const atFocus = render([fixed, { ...ns("", levels), body: "f".repeat(50) }]);+ const atHeadlines = render([fixed, { ...ns("", levels), body: "h".repeat(20) }]);++ const exactFocus = applyInjectionBudget(sections("F".repeat(80)), atFocus);+ assert.deepEqual(exactFocus.degraded, [{ section: "North Star (current goals)", level: "focus" }]);+ assert.equal(exactFocus.bytes, atFocus);++ const overFocus = applyInjectionBudget(sections("F".repeat(80)), atFocus - 1);+ assert.deepEqual(overFocus.degraded, [{ section: "North Star (current goals)", level: "headlines" }]);++ const overHeadlines = applyInjectionBudget(sections("F".repeat(80)), atHeadlines - 1);+ assert.deepEqual(overHeadlines.degraded, []);+ assert.deepEqual(overHeadlines.collapsed, ["North Star (current goals)"]);+ });++ test("a `fit` level is handed exactly the room its body may take", () => {+ const fixed: BudgetSection = { header: "", body: "x".repeat(10), priority: 0 };+ let handed = -1;+ const s = ns("F".repeat(500), [{ name: "top-N", fit: (room) => ((handed = room), "t".repeat(room)) }]);+ const r = applyInjectionBudget([fixed, s], 200);+ assert.equal(r.bytes, 200, "a body of exactly the room handed fills the budget to the byte");+ assert.equal(handed, 200 - render([fixed, { ...s, body: "" }]));+ assert.deepEqual(r.degraded, [{ section: "North Star (current goals)", level: "top-N" }]);+ });++ test("a section whose last given-up rival was the oversized one gets restored (two-step ladders)", () => {+ const big: BudgetSection = { header: "### Big", body: "g".repeat(5_000), priority: 30, fallback: "(g)" };+ const r = applyInjectionBudget([listing, brain, big], 1_000);+ assert.deepEqual(r.collapsed, ["Big"]);+ assert.ok(r.text.includes("l".repeat(400)) && r.text.includes("b".repeat(400)));+ });+});++describe("formatInjectionSize — degraded sections are named with their level", () => {+ test("collapsed keeps its token and meaning; degraded is added after it", () => {+ assert.equal(+ formatInjectionSize(5_000, {+ budgetBytes: 9_100,+ collapsed: ["Vault File Listing"],+ degraded: [{ section: "North Star (current goals)", level: "headlines" }],+ }),+ "_context injected: 5.0kB / 9.1kB budget — collapsed: Vault File Listing — degraded: North Star (current goals) → headlines_",+ );+ });+ test("each level name prints as given", () => {+ for (const level of ["focus", "headlines", "top-N"]) {+ assert.match(+ formatInjectionSize(1_000, { budgetBytes: 2_000, degraded: [{ section: "North Star (current goals)", level }] }),+ new RegExp(`degraded: North Star \\(current goals\\) → ${level}_$`),+ );+ }+ });+ test("nothing degraded → the meter is unchanged", () => {+ assert.equal(formatInjectionSize(1_000, { budgetBytes: 2_000, degraded: [] }), "_context injected: 1.0kB / 2.0kB budget_");+ });+});++describe("goalHeadline", () => {+ test("a [[link]] — clause bullet keeps the whole first sentence, never a dash stub", () => {+ assert.equal(+ goalHeadline("- [[Atlas]] — move the release build onto tagged artifacts so nobody hand-edits. Measure it by releases."),+ "Atlas — move the release build onto tagged artifacts so nobody hand-edits.",+ );+ });+ test("short goals come through whole", () => {+ assert.equal(goalHeadline("- Ship the auth refactor behind a flag by end of Q3"), "Ship the auth refactor behind a flag by end of Q3");+ });+ test("a first sentence under 40 chars is a label: sentences are added until it is not", () => {+ assert.equal(goalHeadline("- [[Atlas]]. Move the release build onto tagged artifacts. Then measure."), "Atlas. Move the release build onto tagged artifacts.");+ });+ test("with nothing to extend into, a short bullet stays whole", () => {+ assert.equal(goalHeadline("- Q4. Two talks."), "Q4. Two talks.");+ });+ test("wikilink aliases and headings render as text; emphasis markers drop", () => {+ assert.equal(goalHeadline("- Write the retro for [[INC 7|the outage]] and **[[Runbook#Paging]]** fixes"), "Write the retro for the outage and Runbook fixes");+ });+ test("capped at the limit on a word boundary with an ellipsis", () => {+ const h = goalHeadline(`- ${"word ".repeat(100)}end`) ?? "";+ assert.ok(h.length <= HEADLINE_MAX_CHARS && h.endsWith("…"), h);+ });+ test("empty, struck, checked and non-list lines are not goals", () => {+ for (const l of ["-", "- ~~done~~", "- [x] done", "## Goals", "_prompt_"]) assert.equal(goalHeadline(l), null, l);+ });+});++/**+ * The old `northStar()` slice, kept verbatim as the oracle for `full`: the+ * new level must equal it except for the documented delta.+ */+function oldNorthStar(raw: string): string {+ const lines = stripFrontmatter(raw).split("\n");+ const anchor = lines.findIndex((l) => l.trim().startsWith("## Current Focus"));+ const scoped = anchor >= 0 ? lines.slice(anchor) : lines;+ const struckCount = scoped.filter((l) => l.trimStart().startsWith("- ~~")).length;+ const live = scoped.filter((l) => !l.trimStart().startsWith("- ~~"));+ if (struckCount > 0) {+ live.splice(1, 0, `_(${struckCount} completed item${struckCount === 1 ? "" : "s"} hidden — full history in brain/North Star.md)_`);+ }+ return take(live.join("\n"), 30);+}++describe("northStarLadder", () => {+ const VAULT = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");++ test("full equals the old slice on a file with nothing to clean (the shipped template, minus its Shifts Log)", () => {+ const raw = `---\ndate:\n---\n# North Star\n\n## Current Focus\n\n- Ship it\n\n## Goals\n\n- Grow\n`;+ assert.equal(northStarLadder(raw).full, oldNorthStar(raw));+ });++ test("full differs from the old slice by exactly: finished items' children, [x] items, and the Shifts Log", () => {+ const raw = [+ "## Current Focus",+ "- Live goal",+ "- ~~Old goal~~",+ " - a sub-bullet of the old goal",+ "- [x] Checked goal",+ " continuation of the checked goal",+ "- Another live goal",+ "",+ "## Shifts Log",+ "",+ "| Date | Shift | Reason |",+ "| 2026-01-01 | Created | Setup |",+ "",+ "## Anti-goals",+ "- Not this",+ ].join("\n");+ const before = oldNorthStar(raw).split("\n");+ const after = northStarLadder(raw).full.split("\n");+ const gone = before.filter((l) => !after.includes(l));+ assert.deepEqual(gone, [+ "_(1 completed item hidden — full history in brain/North Star.md)_",+ " - a sub-bullet of the old goal",+ "- [x] Checked goal",+ " continuation of the checked goal",+ "## Shifts Log",+ "| Date | Shift | Reason |",+ "| 2026-01-01 | Created | Setup |",+ ]);+ assert.ok(after.includes("_(2 completed items hidden — full history in brain/North Star.md)_"));+ assert.ok(after.includes("## Anti-goals") && after.includes("- Not this"), "later goal sections stay in full");+ });++ test("focus is Current Focus only; headlines are its live top-level bullets", () => {+ const raw = "## Current Focus\n- [[Alpha]] — the first goal, stated in one full sentence. More.\n - detail\n- ~~done~~\n\n## Goals\n- Later";+ const l = northStarLadder(raw);+ assert.equal(l.focus, "## Current Focus\n_(1 completed item hidden — full history in brain/North Star.md)_\n- [[Alpha]] — the first goal, stated in one full sentence. More.\n - detail");+ assert.deepEqual(l.headlines, ["Alpha — the first goal, stated in one full sentence."]);+ });++ test("the shipped template yields no headlines (its bullets are empty), so the ladder skips those levels", () => {+ const l = northStarLadder(readFileSync(join(VAULT, "brain", "North Star.md"), "utf-8"));+ assert.deepEqual(l.headlines, []);+ assert.ok(!l.full.includes("Shifts Log"));+ });+});++describe("topHeadlines", () => {+ const heads = ["one", "two", "three"];+ test("the first N that fit, and how many more", () => {+ const two = `${renderHeadlines(["one", "two"])}\n_(+1 more goals in brain/North Star.md)_`;+ assert.equal(topHeadlines(heads, bytes(two)), two);+ assert.equal(topHeadlines(heads, bytes(two) - 1), `${renderHeadlines(["one"])}\n_(+2 more goals in brain/North Star.md)_`);+ });+ test("null when not one fits", () => {+ assert.equal(topHeadlines(heads, 5), null);+ });+});++describe("session-start — #304's fixture on the hook path", () => {+ test("30 long [[link]] — clause bullets: goals reach the session, listing and brain index stay", () => {+ const dir = mkdtempSync(join(tmpdir(), "session-start-ladder-"));+ try {+ mkdirSync(join(dir, "brain"));+ const clause = "move the release build onto tagged artifacts so nobody edits the changelog by hand. ";+ const bullets = Array.from({ length: 30 }, (_, i) => `- [[Project ${i}]] — ${clause}${"More detail on how it is measured and what counts. ".repeat(5)}`);+ writeFileSync(join(dir, "brain", "North Star.md"), `---\ndescription: d\n---\n# North Star\n\n## Current Focus\n\n${bullets.join("\n")}\n`);+ writeFileSync(join(dir, "brain", "Gotchas.md"), "---\ndescription: pitfalls\n---\n# G\n");+ const { stdout, code } = spawnHook(resolve(dirname(fileURLToPath(import.meta.url)), "../session-start.ts"), { source: "startup" }, { CLAUDE_PROJECT_DIR: dir });+ assert.equal(code, 0);+ const ns = stdout.slice(stdout.indexOf("### North Star"), stdout.indexOf("\n### ", stdout.indexOf("### North Star") + 5));+ assert.match(ns, /- Project 0 — move the release build onto tagged artifacts/);+ assert.ok(!ns.includes(NORTH_STAR_POINTER), "goals, not the pointer");+ assert.match(stdout, /### Brain Topics[^\n]*\n[^(]*Gotchas/);+ const meter = stdout.trim().split("\n").pop() ?? "";+ assert.doesNotMatch(meter, /collapsed:/, meter);+ assert.match(meter, /degraded: North Star \(current goals\) → (headlines|top-N)_$/);+ } finally {+ rmTemp(dir);+ }+ });+});diff --git a/.github/scripts/delivery-gate.ts b/.github/scripts/delivery-gate.tsindex 968aa31..fd8af88 100644--- a/.github/scripts/delivery-gate.ts+++ b/.github/scripts/delivery-gate.ts@@ -202,8 +202,11 @@ export function answers(answer: string, want: Expected): boolean {/** The delivered size on a context's meter line (`15.2` from `_context injected: 15.2kB / ...`), or undefined. */export const meterSize = (line: string): string | undefined => line.match(/(\d+(?:\.\d+)?)\s*kB/i)?.[1];-/** Whether a meter line says the context collapsed sections to fit its budget. */-const collapsed = (line: string): boolean => line.includes("collapsed");+/**+ * Whether a meter line says the context gave anything up to fit its budget:+ * a section collapsed to its pointer, or held at a lower level (#304).+ */+const collapsed = (line: string): boolean => line.includes("collapsed") || line.includes("degraded");/*** Whether a text carries enough to rebuild what a checkpoint expects: the