A self-organizing Obsidian vault that gives AI coding agents persistent memory.
TypeScript ai-agentsclaude-codecodex-cligemini-cliknowledge-managementobsidianobsidian-vaultpersistent-memorysecond-braintemplate
fix: deliver every live goal at North Star's full level, and report any cut in the meter (#314)
Brenno Ferrari91e8db0c0cef
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.tsindex 2b52be9..9cca858 100644--- a/.claude/scripts/lib/session-start.ts+++ b/.claude/scripts/lib/session-start.ts@@ -32,6 +32,8 @@ export function formatInjectionSize(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;+ /** Sections delivered whole but built from a cut of their source, with what was kept. */+ readonly cutSections?: readonly { readonly section: string; readonly note: 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. */@@ -56,6 +58,8 @@ export function formatInjectionSize(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(", ")}`;+ const cutSections = opts?.cutSections ?? [];+ if (cutSections.length > 0) line += ` — cut: ${cutSections.map((c) => `${c.section} (${c.note})`).join(", ")}`;if (opts?.cut === true) line += ` — truncated to fit ${opts.cutTo ?? "the hook output cap"}`;return `${line}_`;}@@ -80,6 +84,12 @@ export type BudgetSection = {readonly priority: number;readonly fallback?: string | undefined;readonly levels?: readonly BudgetLevel[] | undefined;+ /**+ * Set when `body` is itself a cut of its source (the first 10 of 14 open+ * tasks): what was kept, e.g. "10 of 14". Reported by the meter whenever+ * the section is delivered at full, so no path presents a cut as whole.+ */+ readonly cut?: string | undefined;};/**@@ -102,6 +112,8 @@ export type BudgetResult = {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 }[];+ /** Sections delivered at full whose body is a cut of their source, in section order. */+ readonly cut: readonly { readonly section: string; readonly note: string }[];};function renderSections(sections: readonly BudgetSection[]): string {@@ -141,11 +153,19 @@ export function applyInjectionBudget(budgetBytes: number,): BudgetResult {const size = (s: readonly BudgetSection[]): number => Buffer.byteLength(renderSections(s), "utf-8");+ const name = (i: number): string => (sections[i]?.header ?? "").replace(/^#+\s*/, "");+ // A section delivered at full whose body is itself a cut says so.+ const cutOf = (delivered: readonly BudgetSection[]) =>+ sections+ .map((s, i) => ({ s, i }))+ .filter(({ s, i }) => s.cut !== undefined && delivered[i]?.body === s.body)+ .map(({ s, i }) => ({ section: name(i), note: s.cut as string }));const whole = (s: readonly BudgetSection[]): BudgetResult => ({text: renderSections(s),bytes: size(s),collapsed: [],degraded: [],+ cut: cutOf(s),});if (!Number.isFinite(budgetBytes) || budgetBytes <= 0) return whole(sections);@@ -180,7 +200,6 @@ export function applyInjectionBudget(}}- 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")@@ -189,7 +208,7 @@ export function applyInjectionBudget(.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, degraded };+ return { text, bytes: Buffer.byteLength(text, "utf-8"), collapsed, degraded, cut: cutOf(current) };}/**@@ -974,12 +993,16 @@ export type NorthStarLadder = {/*** 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.+ * `full` is everything live from `## Current Focus` to the end of the file,+ * 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 cut at all — no line cap, no byte cap. The old 30-line cap+ * silently dropped goals past the 30th line with room to spare and nothing+ * in the meter (a 30-goal Current Focus delivered 28). A cut `full` would+ * also outrank the `headlines` level, which shows every goal. The budget and+ * the ladder bound this level; nothing else may.*/export function northStarLadder(raw: string): NorthStarLadder {const lines = stripFrontmatter(raw).split(/\r?\n/);@@ -993,10 +1016,7 @@ export function northStarLadder(raw: string): NorthStarLadder {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);+ const full = kept.join("\n");if (anchor < 0) {const heads = dropDeadItems(lines).kept.filter((l) => LIST_ITEM.exec(l)?.[1] === "").map(goalHeadline);diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.tsindex 3e8d3ef..06620db 100644--- a/.claude/scripts/session-start.ts+++ b/.claude/scripts/session-start.ts@@ -339,15 +339,32 @@ function northStarSection(priority: number): BudgetSection {return { header, body: ladder.full, priority, fallback: NORTH_STAR_POINTER, levels };}-function recentChanges(): string {+/**+ * A section body with what was cut from its source, so the meter can say so+ * (no section may present a cut as whole).+ */+type Built = { readonly body: string; readonly cut?: string | undefined };++const keptOf = (kept: number, total: number): string | undefined =>+ total > kept ? `${kept} of ${total}` : undefined;++const RECENT_CHANGES_LIMIT = 15;+const ACTIVE_WORK_LIMIT = 10;+const OPEN_TASKS_LIMIT = 10;++function recentChanges(): Built {const r = runCmd("git", ["log","--oneline","--since=48 hours ago","--no-merges",]);- if (r.kind !== "ok") return "(no git history)";- return formatRecentChanges(r.stdout, 15);+ if (r.kind !== "ok") return { body: "(no git history)" };+ const total = r.stdout.split("\n").filter((l) => l.length > 0).length;+ return {+ body: formatRecentChanges(r.stdout, RECENT_CHANGES_LIMIT),+ cut: keptOf(RECENT_CHANGES_LIMIT, total),+ };}function readMarkdownSource(@@ -380,7 +397,7 @@ function listMarkdownSources(return sources;}-function openTasks(): string {+function openTasks(): Built {// Filesystem scan, not `obsidian tasks daily todo` (#83 — that CLI flashes// the Electron app on macOS). Order matters: project tasks in work/active/// surface first, then vault-root notes (which is where daily notes live by@@ -396,7 +413,11 @@ function openTasks(): string {(name) => isInfraFilename(name, infraRootFilenames),),];- return collectOpenTasks(sources, 10);+ const total = sources.reduce(+ (n, s) => n + s.content.split(/\r?\n/).filter((line) => /^\s*- \[ \]/.test(line)).length,+ 0,+ );+ return { body: collectOpenTasks(sources, OPEN_TASKS_LIMIT), cut: keptOf(OPEN_TASKS_LIMIT, total) };}function brainIndex(): string {@@ -426,15 +447,16 @@ function brainIndex(): string {return formatBrainIndex(parsed);}-function activeWork(): string {+function activeWork(): Built {let entries: Dirent[];try {entries = readdirSync("work/active", { withFileTypes: true });} catch {- return "(none)";+ return { body: "(none)" };}const files = entries.filter((e) => e.isFile()).map((e) => e.name);- return formatActiveWork(files, 10);+ const notes = files.filter((f) => isMarkdownFilename(f)).length;+ return { body: formatActiveWork(files, ACTIVE_WORK_LIMIT), cut: keptOf(ACTIVE_WORK_LIMIT, notes) };}// Machinery (shared with the oversize scan) plus `thinking/` — scratchpads@@ -582,12 +604,12 @@ if (mode === "full") {sections.push({header: "### Recent Changes (last 48h)",- body: recentChanges(),+ ...recentChanges(),priority: PRIORITY.RECENT_CHANGES,fallback: "(Over budget — run git log on demand.)",},- { header: "### Open Tasks", body: openTasks(), priority: PRIORITY.VOLATILE },- { header: "### Active Work", body: activeWork(), priority: PRIORITY.VOLATILE },+ { header: "### Open Tasks", ...openTasks(), priority: PRIORITY.VOLATILE },+ { header: "### Active Work", ...activeWork(), priority: PRIORITY.VOLATILE },);if (mode === "full") {sections.push({@@ -662,6 +684,7 @@ process.stdout.write(budgetBytes: budget.bytes,collapsed: budgeted.collapsed,degraded: budgeted.degraded,+ cutSections: budgeted.cut,clampedFrom: budget.clampedFrom,cut,cutTo: limit.name,diff --git a/.claude/scripts/tests/budget-ladder.test.ts b/.claude/scripts/tests/budget-ladder.test.tsindex c10a8d7..56717bc 100644--- a/.claude/scripts/tests/budget-ladder.test.ts+++ b/.claude/scripts/tests/budget-ladder.test.ts@@ -264,3 +264,77 @@ describe("session-start — #304's fixture on the hook path", () => {}});});++/**+ * Every live goal is delivered at `full`, and any cut is in the meter.+ *+ * `full` kept the old 30-line cap, counted from the `## Current Focus`+ * heading, so on a 30-goal North Star goals 29 and 30 were dropped with 7.9 kB+ * of a 20 kB budget unused — no trailer, and the meter said nothing was+ * degraded. A session not reading the file reported 28 of 30 goals.+ */+describe("North Star full level — no silent cut", () => {+ const goals = Array.from(+ { length: 30 },+ (_, i) => `- [[Area ${i + 1}]] — GOAL-${String(i + 1).padStart(2, "0")} keep the release pipeline building from tags. ${"How it is measured and what counts as done. ".repeat(6)}`,+ );+ const northStar = `---\ndescription: d\n---\n# North Star\n\n## Current Focus\n\n${goals.join("\n")}\n`;++ test("full carries every live goal: no line cap", () => {+ const full = northStarLadder(northStar).full;+ for (let i = 1; i <= 30; i++) assert.ok(full.includes(`GOAL-${String(i).padStart(2, "0")}`), `goal ${i} missing`);+ });++ test("on the 20 kB instruction budget all 30 goals are delivered, and the meter reports no cut or degradation", () => {+ const dir = mkdtempSync(join(tmpdir(), "session-start-thirty-"));+ try {+ mkdirSync(join(dir, "brain"));+ writeFileSync(join(dir, "brain", "North Star.md"), northStar);+ const { stdout, code } = spawnHook(+ resolve(dirname(fileURLToPath(import.meta.url)), "../session-start.ts"),+ { source: "startup", om_mod: "deliver" },+ { CLAUDE_PROJECT_DIR: dir },+ );+ assert.equal(code, 0);+ for (let i = 1; i <= 30; i++) assert.ok(stdout.includes(`GOAL-${String(i).padStart(2, "0")}`), `goal ${i} not delivered`);+ const meter = stdout.trim().split("\n").pop() ?? "";+ assert.match(meter, /\/ 20\.0kB budget_$/, `nothing degraded, collapsed, cut or truncated: ${meter}`);+ } finally {+ rmTemp(dir);+ }+ });++ test("a section delivered from a cut of its source is named in the meter, with what was kept", () => {+ const dir = mkdtempSync(join(tmpdir(), "session-start-cutmeter-"));+ try {+ const tasks = Array.from({ length: 14 }, (_, i) => `- [ ] task ${i + 1}`).join("\n");+ writeFileSync(join(dir, "Tasks.md"), `# Tasks\n\n${tasks}\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 meter = stdout.trim().split("\n").pop() ?? "";+ assert.match(meter, / — cut: Open Tasks \(10 of 14\)/, meter);+ } finally {+ rmTemp(dir);+ }+ });++ test("the allocator reports a cut section only while it is delivered at full", () => {+ const cutSection: BudgetSection = { header: "### Recent", body: "r".repeat(200), priority: 20, fallback: "(r)", cut: "15 of 22" };+ const whole = applyInjectionBudget([cutSection], 10_000);+ assert.deepEqual(whole.cut, [{ section: "Recent", note: "15 of 22" }]);+ const pointer = applyInjectionBudget([cutSection], 50);+ assert.deepEqual(pointer.cut, [], "at its pointer the section is collapsed, which the meter already says");+ assert.deepEqual(pointer.collapsed, ["Recent"]);+ });++ test("the meter prints cuts after degradation", () => {+ assert.equal(+ formatInjectionSize(2_000, { budgetBytes: 9_100, cutSections: [{ section: "Open Tasks", note: "10 of 14" }] }),+ "_context injected: 2.0kB / 9.1kB budget — cut: Open Tasks (10 of 14)_",+ );+ });+});