Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

fix: fail charcount when the section is not found, and match ## headings (#290)

Brenno Ferrari8fa5e8fd822e
diff --git a/.claude/scripts/charcount.ts b/.claude/scripts/charcount.ts
index 72d2d00..45d025f 100644
--- a/.claude/scripts/charcount.ts
+++ b/.claude/scripts/charcount.ts
@@ -9,6 +9,11 @@
* charcount.ts review.md "Project Name" "" 1000 → 847/1000 ✓
* charcount.ts review.md "Project Name" "" 500 → 847/500 ✗ (over by 347)
* charcount.ts review.md "Competency Name" "Current Level" 1000
+ *
+ * Exit codes: 0 within the limit (or no limit given), 1 over the limit or a
+ * usage error, 2 when the section or sub-marker is not in the file. A missing
+ * section is never reported as a count — `0/limit ✓` would pass a check that
+ * never looked at anything.
*/
import { readFileSync, existsSync } from "node:fs";
@@ -39,6 +44,14 @@ if (limit !== undefined && (!Number.isFinite(limit) || limit < 0)) {
const content = readFileSync(file, { encoding: "utf-8" });
const count = countSection(content, sub ? { section, sub } : { section });
+if (count === null) {
+ process.stderr.write(
+ sub
+ ? `Marker not found: "**${sub}:**" in section "${section}"\n`
+ : `Section not found: "${section}" (looked for a ## or ### heading)\n`,
+ );
+ process.exit(2);
+}
const result = formatResult(count, limit);
process.stdout.write(result.output + "\n");
process.exit(result.ok ? 0 : 1);
diff --git a/.claude/scripts/lib/charcount.ts b/.claude/scripts/lib/charcount.ts
index 4ee00b1..f35c91f 100644
--- a/.claude/scripts/lib/charcount.ts
+++ b/.claude/scripts/lib/charcount.ts
@@ -1,14 +1,25 @@
/**
* Markdown section character counting.
*
- * Extracts the body of a `### <section>` heading (optionally scoped to a
- * `**<sub>:**` marker inside it) and returns the character count with
- * newlines stripped. Used by review-writing workflows to enforce section
- * length budgets.
+ * Extracts the body of a `## <section>` or `### <section>` heading
+ * (optionally scoped to a `**<sub>:**` marker inside it) and returns the
+ * character count with newlines stripped. Used by review-writing workflows
+ * to enforce section length budgets.
*
- * Section body ends at the next `### ` or `## ` heading. When a sub-marker
- * is given, capture starts at that marker and ends at the next `**` line
- * (the next bold marker) or at a heading boundary.
+ * A heading names the section when its text is exactly `<section>`, or is
+ * `<section>` followed by a separator and a suffix — `## Impact -- "What was
+ * delivered?"` is the section "Impact", as the review template writes it. A
+ * longer word (`### Impact Summary`) is a different section. An exact match
+ * wins over a suffixed one wherever it sits in the file.
+ *
+ * The section body ends at the next heading of the same or a higher level,
+ * so a `##` section keeps its `###` children. When a sub-marker is given,
+ * capture starts at that marker and ends at the next `**` line (the next
+ * bold marker) or at that same heading boundary.
+ *
+ * A section or marker that is not in the file returns `null`, never `0`: a
+ * zero count would pass every limit, and "checked and short" must stay
+ * distinguishable from "never found".
*/
export type CountArgs = {
@@ -16,38 +27,66 @@ export type CountArgs = {
readonly sub?: string;
};
-export function countSection(content: string, args: CountArgs): number {
- const lines = content.split("\n");
- const sectionHeader = `### ${args.section}`;
- const marker = args.sub ? `**${args.sub}:**` : null;
+const HEADING = /^(#{1,6})\s+(.*?)\s*$/;
- let inSection = false;
- let capturing = marker === null;
- const captured: string[] = [];
+/** Separators that may follow the section name before a heading's suffix. */
+const SUFFIX = /^\s*(?:--|—|–|-|:|\(|\|)/;
+
+type Heading = { readonly level: number; readonly text: string };
+
+function parseHeading(line: string): Heading | null {
+ const m = HEADING.exec(line);
+ if (!m) return null;
+ return { level: (m[1] as string).length, text: m[2] as string };
+}
- for (const line of lines) {
- if (!inSection) {
- if (line.includes(sectionHeader)) inSection = true;
- continue;
+/** 2 for an exact name match, 1 for name + separator suffix, 0 otherwise. */
+function matchRank(h: Heading, section: string): number {
+ if (h.level !== 2 && h.level !== 3) return 0;
+ const name = section.trim();
+ if (h.text === name) return 2;
+ if (h.text.startsWith(name) && SUFFIX.test(h.text.slice(name.length))) return 1;
+ return 0;
+}
+
+export function countSection(content: string, args: CountArgs): number | null {
+ const lines = content.split(/\r?\n/);
+
+ let start = -1;
+ let bestRank = 0;
+ for (let i = 0; i < lines.length && bestRank < 2; i++) {
+ const h = parseHeading(lines[i] as string);
+ if (!h) continue;
+ const rank = matchRank(h, args.section);
+ if (rank > bestRank) {
+ bestRank = rank;
+ start = i;
}
+ }
+ if (start === -1) return null;
+
+ const level = (parseHeading(lines[start] as string) as Heading).level;
+ const marker = args.sub ? `**${args.sub}:**` : null;
+ let capturing = marker === null;
+ const captured: string[] = [];
- // Exit on next top-level heading
- if (line.startsWith("### ")) break;
- if (marker === null && line.startsWith("## ")) break;
+ for (const line of lines.slice(start + 1)) {
+ const h = parseHeading(line);
+ if (h && h.level <= level) break;
if (marker !== null) {
if (!capturing) {
if (line.includes(marker)) capturing = true;
continue;
}
- // Capturing under a marker — stop at next bold marker or heading
+ // Capturing under a marker — stop at the next bold marker
if (line.startsWith("**")) break;
- if (line.startsWith("### ")) break;
}
if (line !== "") captured.push(line);
}
+ if (!capturing) return null;
return captured.join("").length;
}
diff --git a/.claude/scripts/tests/charcount.test.ts b/.claude/scripts/tests/charcount.test.ts
index d77920d..1fb6447 100644
--- a/.claude/scripts/tests/charcount.test.ts
+++ b/.claude/scripts/tests/charcount.test.ts
@@ -4,8 +4,16 @@
import { test, describe } from "node:test";
import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
import { countSection, formatResult } from "../lib/charcount.ts";
+const SCRIPTS = join(dirname(fileURLToPath(import.meta.url)), "..");
+const VAULT = join(SCRIPTS, "..", "..");
+
describe("countSection — plain section", () => {
const doc = [
"# Title",
@@ -42,8 +50,8 @@ describe("countSection — plain section", () => {
assert.equal(countSection(doc, { section: "Outro" }), "Closing.".length);
});
- test("returns 0 for missing section", () => {
- assert.equal(countSection(doc, { section: "Nope" }), 0);
+ test("returns null for a missing section, never 0", () => {
+ assert.equal(countSection(doc, { section: "Nope" }), null);
});
test("empty lines inside a section are skipped", () => {
@@ -81,21 +89,117 @@ describe("countSection — with sub-marker", () => {
);
});
- test("returns 0 when marker absent", () => {
+ test("returns null when marker absent", () => {
assert.equal(
countSection(doc, { section: "Project Name", sub: "Missing" }),
- 0,
+ null,
);
});
- test("returns 0 when section absent (even with sub)", () => {
+ test("returns null when section absent (even with sub)", () => {
assert.equal(
countSection(doc, { section: "Nope", sub: "Current Level" }),
- 0,
+ null,
);
});
});
+/**
+ * The review template writes its sections as `##` headings with a suffix
+ * (`## Impact -- "What was delivered?"`). A `###`-only matcher found none of
+ * them, counted 0, and every limit check passed on text it never read.
+ */
+describe("countSection — ## sections and heading names", () => {
+ test("counts a ## section", () => {
+ const d = ["## Summary", "abcdefghij", "## Next"].join("\n");
+ assert.equal(countSection(d, { section: "Summary" }), 10);
+ });
+
+ test("a ## section keeps its ### children and stops at the next ##", () => {
+ const d = ["## Impact", "ab", "### Detail", "cd", "## Growth", "zz"].join("\n");
+ assert.equal(countSection(d, { section: "Impact" }), "ab### Detailcd".length);
+ });
+
+ test("a ### section stops at a heading of any higher level", () => {
+ const d = ["### A", "ab", "# Top", "zz"].join("\n");
+ assert.equal(countSection(d, { section: "A" }), 2);
+ });
+
+ test("name followed by a separator suffix matches", () => {
+ const d = ['## Impact -- "What was delivered?"', "abc", "## Next"].join("\n");
+ assert.equal(countSection(d, { section: "Impact" }), 3);
+ });
+
+ test("a longer word is a different section", () => {
+ const d = ["### Impact Summary", "abc"].join("\n");
+ assert.equal(countSection(d, { section: "Impact" }), null);
+ });
+
+ test("a deeper heading does not open the section", () => {
+ const d = ["#### Impact", "abc"].join("\n");
+ assert.equal(countSection(d, { section: "Impact" }), null);
+ });
+
+ test("an exact heading wins over an earlier suffixed one", () => {
+ const d = ["## Impact -- intro", "aaaa", "## Impact", "bb"].join("\n");
+ assert.equal(countSection(d, { section: "Impact" }), 2);
+ });
+
+ test("CRLF files match and the carriage returns are not counted", () => {
+ const d = ["## Summary", "abc", "## Next"].join("\r\n");
+ assert.equal(countSection(d, { section: "Summary" }), 3);
+ });
+
+ test("every section heading in the shipped review template is found", () => {
+ const tpl = readFileSync(join(VAULT, "templates", "Review Template.md"), "utf-8");
+ for (const s of ["Summary", "Impact", "Competencies", "Principles", "Growth Plan"]) {
+ assert.notEqual(countSection(tpl, { section: s }), null, s);
+ }
+ });
+});
+
+describe("charcount CLI", () => {
+ function run(body: string, ...args: string[]) {
+ const dir = mkdtempSync(join(tmpdir(), "charcount-"));
+ try {
+ const file = join(dir, "review.md");
+ writeFileSync(file, body);
+ return spawnSync(
+ process.execPath,
+ [
+ "--disable-warning=ExperimentalWarning",
+ "--experimental-strip-types",
+ join(SCRIPTS, "charcount.ts"),
+ file,
+ ...args,
+ ],
+ { encoding: "utf-8" },
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+
+ test("a ## section over its limit fails", () => {
+ const r = run("## Summary\nabcdefghij\n", "Summary", "", "5");
+ assert.equal(r.status, 1);
+ assert.equal(r.stdout.trim(), "10/5 ✗ (over by 5)");
+ });
+
+ test("a missing section exits 2 and prints no count", () => {
+ const r = run("## Summary\nabc\n", "Nope", "", "5");
+ assert.equal(r.status, 2);
+ assert.equal(r.stdout, "");
+ assert.match(r.stderr, /Section not found: "Nope"/);
+ });
+
+ test("a missing sub-marker exits 2", () => {
+ const r = run("### Project\n**Current Level:**\nx\n", "Project", "Next Level", "5");
+ assert.equal(r.status, 2);
+ assert.match(r.stderr, /Marker not found/);
+ });
+});
+
describe("formatResult", () => {
test("no limit — prints bare count", () => {
assert.deepEqual(formatResult(847), { ok: true, output: "847" });