From 9fbc6477283f4422f5d5b23c014e77ae1b0c48e1 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Sun, 27 Sep 2026 15:03:23 +1000 Subject: [PATCH 1/6] Hooks: compare against each file's first baseline in a session The Stop hook kept the latest pre-edit entry per file, so a second edit to the same file took a baseline that already contained errors the first edit introduced, and they went unreported. It now keeps the earliest entry, and the pre-edit hook skips files it has already recorded, which avoids a full-space validation on every repeat edit. A Write over an existing file was recorded with no baseline, so all of the file's existing issues were reported as new. It now records a baseline like an Edit. Claude-Session: https://claude.ai/code/session_01EJgagmpxDYVYr7fp9C6cZi --- hook-test/unit/on-stop.test.ts | 34 +++++++++++++++++++++++++++++-- hook-test/unit/pre-edit.test.ts | 25 +++++++++++++++++++++++ plugin/.claude-plugin/plugin.json | 2 +- plugin/scripts/on-stop.ts | 14 ++++++------- plugin/scripts/pre-edit.ts | 22 +++++++++++++++----- 5 files changed, 82 insertions(+), 15 deletions(-) diff --git a/hook-test/unit/on-stop.test.ts b/hook-test/unit/on-stop.test.ts index a1e7f1f..ff9085c 100644 --- a/hook-test/unit/on-stop.test.ts +++ b/hook-test/unit/on-stop.test.ts @@ -134,11 +134,11 @@ describe('Multiple files', () => { expect(result.hasNewErrors).toBe(false); }); - it('uses only the latest entry per file when there are duplicates', async () => { + it('uses only the earliest entry per file when there are duplicates', async () => { const sessionId = crypto.randomUUID(); const validPath = join(fixtures.vaultDir, 'valid.md'); - // Two entries for same file: first has no baseline errors (clean), second was the most recent edit + // Two entries for same file: both clean, so the file is compared against its first baseline const entries = [ stateEntry(validPath, 'Edit', {}, Date.now() - 1000), stateEntry(validPath, 'Edit', {}, Date.now()), @@ -148,6 +148,36 @@ describe('Multiple files', () => { const result = await runOnStop({ session_id: sessionId }, opts()); expect(result.hasNewErrors).toBe(false); }); + + it('reports an error introduced by an earlier edit when the same file is edited again', async () => { + const sessionId = crypto.randomUUID(); + const validPath = join(fixtures.vaultDir, 'valid.md'); + // First edit starts clean and introduces a broken link; the second edit's baseline already contains it + const introduced = { 'broken-link:[[Ghost Node]]': { kind: 'broken-link', message: 'test' } }; + writeStateFile(sessionId, [ + stateEntry(validPath, 'Edit', {}, Date.now() - 1000), + stateEntry(validPath, 'Edit', introduced, Date.now()), + ]); + writeFileSync(validPath, '---\ntype: mission\nparent: "[[Ghost Node]]"\nstatus: identified\n---\n\n# Test Title\n'); + + const result = await runOnStop({ session_id: sessionId }, opts()); + expect(result.hasNewErrors).toBe(true); + expect(result.errorMessage).toContain('Ghost Node'); + }); + + it('treats a file as new when it was written and then edited in the same session', async () => { + const sessionId = crypto.randomUUID(); + const brokenPath = join(fixtures.vaultDir, 'broken.md'); + const baseline = { 'broken-link:[[Nonexistent Node]]': { kind: 'broken-link', message: 'test' } }; + writeStateFile(sessionId, [ + stateEntry(brokenPath, 'Write', null, Date.now() - 1000), + stateEntry(brokenPath, 'Edit', baseline, Date.now()), + ]); + + const result = await runOnStop({ session_id: sessionId }, opts()); + expect(result.hasNewErrors).toBe(true); + expect(result.errorMessage).toContain('broken-link'); + }); }); describe('State file lifecycle', () => { diff --git a/hook-test/unit/pre-edit.test.ts b/hook-test/unit/pre-edit.test.ts index 7c26155..61453dc 100644 --- a/hook-test/unit/pre-edit.test.ts +++ b/hook-test/unit/pre-edit.test.ts @@ -65,6 +65,18 @@ describe('Write operations', () => { expect(existsSync(deepStateDir)).toBe(true); }); + + it('records a baseline when writing over an existing file', async () => { + const sessionId = crypto.randomUUID(); + const filePath = join(fixtures.vaultDir, 'broken.md'); + + await runPreEdit({ tool_name: 'Write', tool_input: { file_path: filePath }, session_id: sessionId }, opts()); + + const entries = readState(sessionId); + expect(entries).toHaveLength(1); + expect(entries[0]).toMatchObject({ tool: 'Edit', file: filePath }); + expect(Object.keys((entries[0] as { errors: object }).errors)).toContain('broken-link:[[Nonexistent Node]]'); + }); }); describe('Edit operations', () => { @@ -136,6 +148,19 @@ describe('Edit operations', () => { expect(entries.map((e) => (e as { file: string }).file)).toContain(join(fixtures.vaultDir, 'valid.md')); expect(entries.map((e) => (e as { file: string }).file)).toContain(join(fixtures.vaultDir, 'broken.md')); }); + + it('keeps only the first baseline when the same file is edited again', async () => { + const sessionId = crypto.randomUUID(); + const filePath = join(fixtures.vaultDir, 'valid.md'); + + await runPreEdit({ tool_name: 'Edit', tool_input: { file_path: filePath }, session_id: sessionId }, opts()); + writeFileSync(filePath, '---\ntype: mission\nparent: "[[Ghost Node]]"\nstatus: identified\n---\n\n# Test Title\n'); + await runPreEdit({ tool_name: 'Edit', tool_input: { file_path: filePath }, session_id: sessionId }, opts()); + + const entries = readState(sessionId); + expect(entries).toHaveLength(1); + expect((entries[0] as { errors: object }).errors).toEqual({}); + }); }); describe('Edge cases', () => { diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index c8e1cba..5c3e17c 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "structured-context", - "version": "0.11.4", + "version": "0.11.5", "description": "Structured content authoring for Obsidian — automatic validation hooks, slash commands, and agent skills to keep markdown files compliant with your schema.", "homepage": "https://github.com/mindsocket/structured-context", "repository": "https://github.com/mindsocket/structured-context", diff --git a/plugin/scripts/on-stop.ts b/plugin/scripts/on-stop.ts index a5cad54..c7bb081 100755 --- a/plugin/scripts/on-stop.ts +++ b/plugin/scripts/on-stop.ts @@ -84,19 +84,19 @@ export async function runOnStop(input: OnStopInput, options?: OnStopOptions): Pr const newErrors: string[] = []; const newWarnings: string[] = []; - // Read all entries and keep only the latest per file (by timestamp) + // Read all entries and keep the earliest per file (by timestamp): its baseline is the file's + // state before this session's first change, so later edits can't absorb issues earlier ones introduced const lines = (await stateFile.text()) .trim() .split('\n') .filter((l) => l); const entries: HookState[] = lines.map((l) => JSON.parse(l)); - // Group by file and keep latest - const latestByFile = new Map(); + const earliestByFile = new Map(); for (const entry of entries) { - const existing = latestByFile.get(entry.file); - if (!existing || entry.timestamp > existing.timestamp) { - latestByFile.set(entry.file, entry); + const existing = earliestByFile.get(entry.file); + if (!existing || entry.timestamp < existing.timestamp) { + earliestByFile.set(entry.file, entry); } } @@ -106,7 +106,7 @@ export async function runOnStop(input: OnStopInput, options?: OnStopOptions): Pr env.SCTX_CONFIG = options.configPath; } - for (const [FILE, entry] of latestByFile) { + for (const [FILE, entry] of earliestByFile) { const { tool } = entry; const fileExists = await Bun.file(FILE).exists(); diff --git a/plugin/scripts/pre-edit.ts b/plugin/scripts/pre-edit.ts index 5eee7d1..d46dbab 100755 --- a/plugin/scripts/pre-edit.ts +++ b/plugin/scripts/pre-edit.ts @@ -1,12 +1,12 @@ #!/usr/bin/env bun /** * PreToolUse hook for Write and Edit on *.md files. - * Write (new files): records the filename with no baseline errors. - * Edit (existing files): validates before the edit and records baseline errors and warnings. + * Write of a new file: records the filename with no baseline errors. + * Edit, or Write over an existing file: validates before the change and records baseline errors and warnings. * Appends one JSONL line to a per-session state file for the Stop hook to analyse. */ -import { appendFileSync, mkdirSync } from 'node:fs'; +import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'; export interface PreEditInput { tool_name?: string; @@ -40,6 +40,13 @@ interface ValidationResult { warnings?: object; } +function alreadyTracked(stateFile: string, filePath: string): boolean { + if (!existsSync(stateFile)) return false; + return readFileSync(stateFile, 'utf-8') + .split('\n') + .some((line) => line && (JSON.parse(line) as HookState).file === filePath); +} + export async function runPreEdit(input: PreEditInput, options?: PreEditOptions): Promise { const TOOL = input.tool_name ?? ''; const FILE_PATH = input.tool_input?.file_path; @@ -53,7 +60,12 @@ export async function runPreEdit(input: PreEditInput, options?: PreEditOptions): const STATE_FILE = `${STATE_DIR}/sctx-hook-${SESSION_ID}.jsonl`; const TIMESTAMP = Date.now(); - if (TOOL === 'Write') { + // The Stop hook compares against a file's first baseline this session, so later edits need none + if (alreadyTracked(STATE_FILE, FILE_PATH)) { + return; + } + + if (TOOL === 'Write' && !existsSync(FILE_PATH)) { const entry: HookState = { session_id: SESSION_ID, timestamp: TIMESTAMP, @@ -67,7 +79,7 @@ export async function runPreEdit(input: PreEditInput, options?: PreEditOptions): return; } - // Edit — validate current state as pre-edit baseline + // Edit or overwrite — validate current state as pre-edit baseline const BIN = options?.sctxBin ?? process.env.SCTX_BIN; const env: Record = { ...process.env }; if (options?.configPath) { From 45380d1c193157e3330eeb35b529c2874b0ed14a Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Sun, 27 Sep 2026 18:28:13 +1000 Subject: [PATCH 2/6] Hooks: whole-space baseline at prompt submit, compared at Stop (#127) The UserPromptSubmit hook baselines every space inside or containing the session directory; the Stop hook validates changed spaces and reports issues missing from the baseline in any file, so breakage in files that weren't edited and edits made through Bash are caught. The pre-edit hook remains as a fallback for spaces outside the session directory. Baselines store issue keys only. A hash of each space's markdown, schema and config file stats skips validation when nothing changed, and the last Stop's keys are reused at the next prompt. A baseline that survives an interrupted turn is kept. The hooks use `sctx validate --json` and the new `sctx spaces --json`. The CLI now routes console.log through process.stdout.write: once node:process is loaded, Bun dropped piped output past 64KB for slow readers. Claude-Session: https://claude.ai/code/session_01EJgagmpxDYVYr7fp9C6cZi --- docs/use-cases.md | 4 +- hook-test/harness.ts | 35 ++-- hook-test/hooks.test.ts | 30 ++-- hook-test/unit/on-prompt.test.ts | 108 ++++++++++++ hook-test/unit/on-stop.test.ts | 263 ++++++++++++------------------ hook-test/unit/pre-edit.test.ts | 187 ++++++--------------- plugin/.claude-plugin/plugin.json | 2 +- plugin/hooks/hooks.json | 25 ++- plugin/scripts/on-prompt.ts | 40 +++++ plugin/scripts/on-session-end.ts | 13 ++ plugin/scripts/on-stop.ts | 185 ++++++++------------- plugin/scripts/pre-edit.ts | 107 ++---------- plugin/scripts/state.ts | 204 +++++++++++++++++++++++ src/commands/spaces.ts | 13 +- src/index.ts | 17 +- 15 files changed, 679 insertions(+), 554 deletions(-) create mode 100644 hook-test/unit/on-prompt.test.ts create mode 100644 plugin/scripts/on-prompt.ts create mode 100644 plugin/scripts/on-session-end.ts create mode 100644 plugin/scripts/state.ts diff --git a/docs/use-cases.md b/docs/use-cases.md index 62333f7..60ae94f 100644 --- a/docs/use-cases.md +++ b/docs/use-cases.md @@ -18,8 +18,8 @@ A catalog of use cases for structured-context, covering both direct CLI usage an | Use case | Description | Status | Coverage | |---|---|---|---| | **Validate content** | Verify that space content conforms to schema, link integrity, rules, and hierarchy | | | -| — Validate a space | Check all files in a space in one pass | done | `sctx validate` · `/validate-space` command | -| — Validate a single file | Validate one file in context of its space | done | `sctx validate-file` · auto-validation hook on `.md` save | +| — Validate a space | Check all files in a space in one pass | done | `sctx validate` · `/validate-space` command · plugin hooks report issues introduced during a Claude turn | +| — Validate a single file | Validate one file in context of its space | done | `sctx validate-file` | | — Watch for changes | Continuously re-validate as files are edited | done | `sctx validate --watch` | | **Resolve validation errors** | Investigate and fix schema, link, or rule violations once identified | agent | structured-context skill (troubleshooting guide; `dump` for rule debugging) | diff --git a/hook-test/harness.ts b/hook-test/harness.ts index b30996f..58c659d 100644 --- a/hook-test/harness.ts +++ b/hook-test/harness.ts @@ -6,11 +6,13 @@ * can inspect them after the run without relying on in-process buffering. */ -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { mkdirSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { query } from '@anthropic-ai/claude-agent-sdk'; +import { runOnPrompt } from '../plugin/scripts/on-prompt'; import { runOnStop } from '../plugin/scripts/on-stop'; import { runPreEdit } from '../plugin/scripts/pre-edit'; +import { loadState, type SessionState, stateFilePath } from '../plugin/scripts/state'; const SCTX_BIN = join(import.meta.dir, '..', 'src', 'index.ts'); @@ -33,11 +35,8 @@ export interface RunClaudeResult { outputDir: string; /** Directory where hook state files live during the session */ stateDir: string; - /** - * State entries captured by the PreToolUse hook before the Stop hook deletes the file. - * Each entry describes an Edit or Write operation on a .md file in a configured space. - */ - stateEntries: object[]; + /** Session state as the Stop hook found it, before it cleared the baselines */ + stateAtStop: SessionState; /** All SDK messages written as JSONL */ messagesFile: string; } @@ -53,7 +52,7 @@ export async function runClaude(options: RunClaudeOptions): Promise { + await runOnPrompt({ session_id: input.session_id, cwd: input.cwd }, hookOpts); + return {}; + }, + ], + }, + ], PreToolUse: [ { matcher: 'Write|Edit', @@ -87,15 +96,7 @@ export async function runClaude(options: RunClaudeOptions): Promise { - // Capture state entries before runOnStop deletes the state file - const stateFile = join(stateDir, `sctx-hook-${input.session_id}.jsonl`); - if (existsSync(stateFile)) { - capturedStateEntries = readFileSync(stateFile, 'utf-8') - .trim() - .split('\n') - .filter(Boolean) - .map((l) => JSON.parse(l)); - } + stateAtStop = loadState(stateFilePath(input.session_id, hookOpts)); stopResult = await runOnStop( { @@ -144,7 +145,7 @@ export async function runClaude(options: RunClaudeOptions): Promise { it( - 'captures an Edit state entry, exits 0, and cleans up the state file', + 'baselines the space when the prompt is submitted and exits 0', async () => { fixtures = isolateFixtures(); const outputDir = makeOutputDir(); - const validFile = join(fixtures.vaultDir, 'valid.md'); const result = await runClaude({ prompt: `Read valid.md, then change the title to "Modified Title". Only edit the file, no other output.`, @@ -45,29 +45,25 @@ describe('clean edit of valid file', () => { expect(result.exitCode).toBe(0); expect(existsSync(join(outputDir, 'stop-hook-errors.txt'))).toBe(false); - - const editEntry = result.stateEntries.find((e) => (e as { tool: string }).tool === 'Edit'); - expect(editEntry).toBeDefined(); - expect((editEntry as { file: string }).file).toBe(validFile); - - // State entries captured before deletion — confirms the file was written - expect(result.stateEntries.length).toBeGreaterThan(0); - // Stop hook must delete the state file after analysis - expect(existsSync(join(result.stateDir, `sctx-hook-${result.sessionId}.jsonl`))).toBe(false); + expect(result.stateAtStop.baseline['test-space']?.path).toBe(fixtures.vaultDir); + // The Stop hook clears the baseline and keeps the results for the next prompt + const after = loadState(stateFilePath(result.sessionId, { stateDir: result.stateDir })); + expect(after.baseline).toEqual({}); + expect(after.latest['test-space']).toBeDefined(); }, TEST_TIMEOUT, ); }); -describe('Write hook', () => { +describe('Write', () => { it( - 'captures a state entry with null errors when Claude writes a new .md file', + 'exits 0 when Claude writes a valid new .md file', async () => { fixtures = isolateFixtures(); const outputDir = makeOutputDir(); const result = await runClaude({ - prompt: `Create a new file called new-note.md in the current directory with this exact content: + prompt: `Create a new file at the relative path vault/new-note.md (inside the current working directory) with this exact content: --- type: mission parent: "[[Root]]" @@ -83,10 +79,8 @@ A new note.`, }); expect(result.exitCode).toBe(0); - - const writeEntry = result.stateEntries.find((e) => (e as { tool: string }).tool === 'Write'); - expect(writeEntry).toBeDefined(); - expect((writeEntry as { errors: null }).errors).toBeNull(); + expect(existsSync(join(fixtures.vaultDir, 'new-note.md'))).toBe(true); + expect(result.stateAtStop.baseline['test-space']?.issues['new-note.md']).toBeUndefined(); }, TEST_TIMEOUT, ); diff --git a/hook-test/unit/on-prompt.test.ts b/hook-test/unit/on-prompt.test.ts new file mode 100644 index 0000000..1f49cde --- /dev/null +++ b/hook-test/unit/on-prompt.test.ts @@ -0,0 +1,108 @@ +/** + * Unit tests for plugin/scripts/on-prompt.ts + * + * Tests call runOnPrompt() directly — no Claude process involved. + */ + +import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; +import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { runOnPrompt } from '../../plugin/scripts/on-prompt'; +import { loadState, saveState, stateFilePath } from '../../plugin/scripts/state'; +import { type IsolatedFixtures, isolateFixtures } from '../fixture-utils'; + +const SCTX_BIN = join(import.meta.dir, '../../src/index.ts'); + +let fixtures: IsolatedFixtures; +let stateDir: string; +let sessionId: string; + +beforeEach(() => { + fixtures = isolateFixtures(); + stateDir = join(tmpdir(), `ost-on-prompt-state-${crypto.randomUUID()}`); + sessionId = crypto.randomUUID(); +}); + +afterEach(() => { + fixtures.cleanup(); + rmSync(stateDir, { recursive: true, force: true }); +}); + +const opts = () => ({ stateDir, sctxBin: SCTX_BIN, configPath: fixtures.configPath }); +const stateFile = () => stateFilePath(sessionId, opts()); + +describe('Baselines', () => { + it('baselines a space inside the session directory', async () => { + await runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + + const { baseline, latest } = loadState(stateFile()); + expect(Object.keys(baseline)).toEqual(['test-space']); + expect(baseline['test-space']!.path).toBe(fixtures.vaultDir); + expect(Object.keys(baseline['test-space']!.issues)).toEqual(['broken.md']); + expect(baseline['test-space']!.issues['broken.md']).toContain('broken-link:[[Nonexistent Node]]'); + expect(latest).toEqual(baseline); + }); + + it('baselines a space that contains the session directory', async () => { + const subdir = join(fixtures.vaultDir, 'sub'); + mkdirSync(subdir); + + await runOnPrompt({ session_id: sessionId, cwd: subdir }, opts()); + + expect(Object.keys(loadState(stateFile()).baseline)).toEqual(['test-space']); + }); + + it('writes no state when no space is related to the session directory', async () => { + await runOnPrompt({ session_id: sessionId, cwd: tmpdir() }, opts()); + + expect(existsSync(stateFile())).toBe(false); + }); + + it('does nothing without a cwd', async () => { + await runOnPrompt({ session_id: sessionId }, opts()); + + expect(existsSync(stateFile())).toBe(false); + }); +}); + +describe('Existing state', () => { + it('keeps an existing baseline when the previous Stop never ran', async () => { + await runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + writeFileSync( + join(fixtures.vaultDir, 'valid.md'), + '---\ntype: mission\nparent: "[[Ghost Node]]"\nstatus: identified\n---\n\n# Test Title\n', + ); + + await runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + + expect(loadState(stateFile()).baseline['test-space']!.issues['valid.md']).toBeUndefined(); + }); + + it('reuses the latest results without validating when the space is unchanged', async () => { + await runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + // Simulate a completed turn, and mark the latest results so reuse is observable + const state = loadState(stateFile()); + const latest = state.latest['test-space']!; + latest.issues = { 'marker.md': [] }; + saveState(stateFile(), { baseline: {}, latest: { 'test-space': latest } }); + + await runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + + expect(Object.keys(loadState(stateFile()).baseline['test-space']!.issues)).toEqual(['marker.md']); + }); + + it('validates again when the space has changed since the latest results', async () => { + await runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + const state = loadState(stateFile()); + saveState(stateFile(), { baseline: {}, latest: state.latest }); + writeFileSync( + join(fixtures.vaultDir, 'broken.md'), + '---\ntype: mission\nparent: "[[Root]]"\nstatus: identified\n---\n\n# Broken Note\n', + ); + + await runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + + expect(loadState(stateFile()).baseline['test-space']!.issues).toEqual({}); + }); +}); diff --git a/hook-test/unit/on-stop.test.ts b/hook-test/unit/on-stop.test.ts index ff9085c..841db06 100644 --- a/hook-test/unit/on-stop.test.ts +++ b/hook-test/unit/on-stop.test.ts @@ -1,26 +1,33 @@ /** * Unit tests for plugin/scripts/on-stop.ts * - * Tests call runOnStop() directly — no Claude process involved. - * State files are written manually to set up each scenario. + * Tests call the hooks directly — no Claude process involved. Each test takes a baseline with + * the prompt hook, changes files the way Claude would, then runs the Stop hook. */ import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; -import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { renameSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { runOnPrompt } from '../../plugin/scripts/on-prompt'; import { runOnStop } from '../../plugin/scripts/on-stop'; +import { loadState, stateFilePath } from '../../plugin/scripts/state'; import { type IsolatedFixtures, isolateFixtures } from '../fixture-utils'; const SCTX_BIN = join(import.meta.dir, '../../src/index.ts'); +const validWithParent = (parent: string) => + `---\ntype: mission\nparent: "[[${parent}]]"\nstatus: identified\n---\n\n# Test Title\n`; +const validWithContentLink = `${validWithParent('Root')}\nSee [[Missing Note]].\n`; + let fixtures: IsolatedFixtures; let stateDir: string; +let sessionId: string; beforeEach(() => { fixtures = isolateFixtures(); stateDir = join(tmpdir(), `ost-on-stop-state-${crypto.randomUUID()}`); - mkdirSync(stateDir, { recursive: true }); + sessionId = crypto.randomUUID(); }); afterEach(() => { @@ -28,198 +35,136 @@ afterEach(() => { rmSync(stateDir, { recursive: true, force: true }); }); -const opts = () => ({ - stateDir, - sctxBin: SCTX_BIN, - configPath: fixtures.configPath, -}); - -function writeStateFile(sessionId: string, entries: object[]): string { - const file = join(stateDir, `sctx-hook-${sessionId}.jsonl`); - writeFileSync(file, `${entries.map((e) => JSON.stringify(e)).join('\n')}\n`); - return file; -} - -function stateEntry(file: string, tool: 'Edit' | 'Write', errors: object | null = null, timestamp = Date.now()) { - return { session_id: 'test', timestamp, tool, file, errors }; -} +const opts = () => ({ stateDir, sctxBin: SCTX_BIN, configPath: fixtures.configPath }); +const prompt = () => runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); +const stop = (stop_hook_active = false) => runOnStop({ session_id: sessionId, stop_hook_active }, opts()); +const write = (file: string, content: string) => writeFileSync(join(fixtures.vaultDir, file), content); describe('No-op cases', () => { - it('returns no errors when state file does not exist', async () => { - const result = await runOnStop({ session_id: crypto.randomUUID() }, opts()); - expect(result).toEqual({ hasNewErrors: false }); + it('returns no errors when there is no state', async () => { + expect(await stop()).toEqual({ hasNewErrors: false }); }); - it('returns no errors when stop_hook_active is true (loop guard)', async () => { - const sessionId = crypto.randomUUID(); - writeStateFile(sessionId, [stateEntry(join(fixtures.vaultDir, 'valid.md'), 'Edit', {})]); + it('returns no errors and keeps the baseline when stop_hook_active is true (loop guard)', async () => { + await prompt(); + write('valid.md', validWithParent('Ghost Node')); - const result = await runOnStop({ session_id: sessionId, stop_hook_active: true }, opts()); - expect(result).toEqual({ hasNewErrors: false }); + expect(await stop(true)).toEqual({ hasNewErrors: false }); + expect(Object.keys(loadState(stateFilePath(sessionId, opts())).baseline)).toEqual(['test-space']); }); -}); -describe('Write entries', () => { - it('returns no errors for a new file that is still valid', async () => { - const sessionId = crypto.randomUUID(); - writeStateFile(sessionId, [stateEntry(join(fixtures.vaultDir, 'valid.md'), 'Write', null)]); - - const result = await runOnStop({ session_id: sessionId }, opts()); - expect(result.hasNewErrors).toBe(false); + it('returns no errors when nothing changed', async () => { + await prompt(); + expect(await stop()).toEqual({ hasNewErrors: false }); }); +}); - it('returns errors for a new file that has validation errors', async () => { - const sessionId = crypto.randomUUID(); - writeStateFile(sessionId, [stateEntry(join(fixtures.vaultDir, 'broken.md'), 'Write', null)]); +describe('Errors', () => { + it('reports an error introduced by an edit', async () => { + await prompt(); + write('valid.md', validWithParent('Ghost Node')); - const result = await runOnStop({ session_id: sessionId }, opts()); + const result = await stop(); expect(result.hasNewErrors).toBe(true); expect(result.errorMessage).toContain('structured-context: new validation errors'); - expect(result.errorMessage).toContain('broken-link'); - }); -}); - -describe('Edit entries', () => { - it('returns no errors when the file still has the same errors as the baseline', async () => { - const sessionId = crypto.randomUUID(); - // broken.md already has broken-link error — baseline captures it - const baseline = { 'broken-link:[[Nonexistent Node]]': { kind: 'broken-link', message: 'test' } }; - writeStateFile(sessionId, [stateEntry(join(fixtures.vaultDir, 'broken.md'), 'Edit', baseline)]); - - const result = await runOnStop({ session_id: sessionId }, opts()); - expect(result.hasNewErrors).toBe(false); + expect(result.errorMessage).toContain('valid.md (space: test-space)'); + expect(result.errorMessage).toContain('Ghost Node'); }); - it('returns errors when a new error is introduced by an edit', async () => { - const sessionId = crypto.randomUUID(); - // valid.md had no errors at baseline, but now we point it at a broken parent - const validPath = join(fixtures.vaultDir, 'valid.md'); - writeStateFile(sessionId, [stateEntry(validPath, 'Edit', {})]); - - // Simulate the edit: change parent to a non-existent node - writeFileSync(validPath, '---\ntype: mission\nparent: "[[Ghost Node]]"\nstatus: identified\n---\n\n# Test Title\n'); + it('does not report errors a file already had', async () => { + await prompt(); + write( + 'broken.md', + '---\ntype: mission\nparent: "[[Nonexistent Node]]"\nstatus: identified\n---\n\n# Still Broken\n', + ); - const result = await runOnStop({ session_id: sessionId }, opts()); - expect(result.hasNewErrors).toBe(true); - expect(result.errorMessage).toContain('broken-link'); - expect(result.errorMessage).toContain('Ghost Node'); + expect((await stop()).hasNewErrors).toBe(false); }); it('returns no errors when a pre-existing error is fixed', async () => { - const sessionId = crypto.randomUUID(); - const brokenPath = join(fixtures.vaultDir, 'broken.md'); - const baseline = { 'broken-link:[[Nonexistent Node]]': { kind: 'broken-link', message: 'test' } }; - writeStateFile(sessionId, [stateEntry(brokenPath, 'Edit', baseline)]); + await prompt(); + write('broken.md', '---\ntype: mission\nparent: "[[Root]]"\nstatus: identified\n---\n\n# Broken Note\n'); - // Fix the file - writeFileSync(brokenPath, '---\ntype: mission\nparent: "[[Root]]"\nstatus: identified\n---\n\n# Broken Note\n'); - - const result = await runOnStop({ session_id: sessionId }, opts()); - expect(result.hasNewErrors).toBe(false); + expect((await stop()).hasNewErrors).toBe(false); }); -}); -describe('Multiple files', () => { - it('reports errors only for the file that introduced them', async () => { - const sessionId = crypto.randomUUID(); - const validPath = join(fixtures.vaultDir, 'valid.md'); - const brokenPath = join(fixtures.vaultDir, 'broken.md'); + it('reports every issue in a new file', async () => { + await prompt(); + write('new-note.md', validWithParent('Ghost Node').replace('Test Title', 'New Note')); - // valid.md: clean edit, no new errors - // broken.md: had broken-link at baseline, still has it - const baseline = { 'broken-link:[[Nonexistent Node]]': { kind: 'broken-link', message: 'test' } }; - writeStateFile(sessionId, [stateEntry(validPath, 'Edit', {}), stateEntry(brokenPath, 'Edit', baseline)]); - - const result = await runOnStop({ session_id: sessionId }, opts()); - expect(result.hasNewErrors).toBe(false); + const result = await stop(); + expect(result.hasNewErrors).toBe(true); + expect(result.errorMessage).toContain('new-note.md'); }); - it('uses only the earliest entry per file when there are duplicates', async () => { - const sessionId = crypto.randomUUID(); - const validPath = join(fixtures.vaultDir, 'valid.md'); - - // Two entries for same file: both clean, so the file is compared against its first baseline - const entries = [ - stateEntry(validPath, 'Edit', {}, Date.now() - 1000), - stateEntry(validPath, 'Edit', {}, Date.now()), - ]; - writeStateFile(sessionId, entries); + it('reports breakage in a file that was not edited', async () => { + await prompt(); + // Renaming Root.md (e.g. with `mv` in Bash) breaks valid.md's parent link + renameSync(join(fixtures.vaultDir, 'Root.md'), join(fixtures.vaultDir, 'Renamed Root.md')); - const result = await runOnStop({ session_id: sessionId }, opts()); - expect(result.hasNewErrors).toBe(false); - }); - - it('reports an error introduced by an earlier edit when the same file is edited again', async () => { - const sessionId = crypto.randomUUID(); - const validPath = join(fixtures.vaultDir, 'valid.md'); - // First edit starts clean and introduces a broken link; the second edit's baseline already contains it - const introduced = { 'broken-link:[[Ghost Node]]': { kind: 'broken-link', message: 'test' } }; - writeStateFile(sessionId, [ - stateEntry(validPath, 'Edit', {}, Date.now() - 1000), - stateEntry(validPath, 'Edit', introduced, Date.now()), - ]); - writeFileSync(validPath, '---\ntype: mission\nparent: "[[Ghost Node]]"\nstatus: identified\n---\n\n# Test Title\n'); - - const result = await runOnStop({ session_id: sessionId }, opts()); + const result = await stop(); expect(result.hasNewErrors).toBe(true); - expect(result.errorMessage).toContain('Ghost Node'); + expect(result.errorMessage).toContain('valid.md (space: test-space)'); + expect(result.errorMessage).toContain('[[Root]]'); }); - it('treats a file as new when it was written and then edited in the same session', async () => { - const sessionId = crypto.randomUUID(); - const brokenPath = join(fixtures.vaultDir, 'broken.md'); - const baseline = { 'broken-link:[[Nonexistent Node]]': { kind: 'broken-link', message: 'test' } }; - writeStateFile(sessionId, [ - stateEntry(brokenPath, 'Write', null, Date.now() - 1000), - stateEntry(brokenPath, 'Edit', baseline, Date.now()), - ]); + it('reports errors from edits made before an interrupted turn', async () => { + await prompt(); + write('valid.md', validWithParent('Ghost Node')); + // The turn is interrupted, so Stop never runs before the next prompt + await prompt(); - const result = await runOnStop({ session_id: sessionId }, opts()); + const result = await stop(); expect(result.hasNewErrors).toBe(true); - expect(result.errorMessage).toContain('broken-link'); + expect(result.errorMessage).toContain('Ghost Node'); }); -}); -describe('State file lifecycle', () => { - it('deletes the state file after running, regardless of result', async () => { - const sessionId = crypto.randomUUID(); - const stateFile = writeStateFile(sessionId, [stateEntry(join(fixtures.vaultDir, 'valid.md'), 'Edit', {})]); + it('reports an issue once when overlapping spaces both contain the file', async () => { + writeFileSync( + fixtures.configPath, + JSON.stringify({ + spaces: [ + { name: 'test-space', path: fixtures.vaultDir, schema: 'strategy_general.json' }, + { name: 'overlap', path: fixtures.vaultDir, schema: 'strategy_general.json' }, + ], + }), + ); + await prompt(); + write('valid.md', validWithParent('Ghost Node')); - await runOnStop({ session_id: sessionId }, opts()); - - expect(existsSync(stateFile)).toBe(false); + const result = await stop(); + expect(result.errorMessage!.match(/valid\.md \(space:/g)).toHaveLength(1); }); +}); - it('deletes the state file even when new errors are found', async () => { - const sessionId = crypto.randomUUID(); - const stateFile = writeStateFile(sessionId, [stateEntry(join(fixtures.vaultDir, 'broken.md'), 'Write', null)]); +describe('State', () => { + it('clears the baseline and keeps the results for the next prompt', async () => { + await prompt(); + write('valid.md', validWithParent('Ghost Node')); - await runOnStop({ session_id: sessionId }, opts()); + await stop(); - expect(existsSync(stateFile)).toBe(false); + const { baseline, latest } = loadState(stateFilePath(sessionId, opts())); + expect(baseline).toEqual({}); + expect(latest['test-space']!.issues['valid.md']).toContain('broken-link:[[Ghost Node]]'); }); - it('skips files that no longer exist without crashing', async () => { - const sessionId = crypto.randomUUID(); - writeStateFile(sessionId, [stateEntry(join(fixtures.vaultDir, 'deleted.md'), 'Edit', {})]); + it('does not report the same error again at the next Stop', async () => { + await prompt(); + write('valid.md', validWithParent('Ghost Node')); + await stop(); - const result = await runOnStop({ session_id: sessionId }, opts()); - expect(result.hasNewErrors).toBe(false); + await prompt(); + expect((await stop()).hasNewErrors).toBe(false); }); }); describe('Warnings', () => { - const validWithContentLink = - '---\ntype: mission\nparent: "[[Root]]"\nstatus: identified\n---\n\n# Test Title\n\nSee [[Missing Note]].\n'; - const contentLinkWarning = { 'content-link:Missing Note': { kind: 'content-link', message: 'test' } }; - it('reports a new warning without blocking', async () => { - const sessionId = crypto.randomUUID(); - const validPath = join(fixtures.vaultDir, 'valid.md'); - writeStateFile(sessionId, [{ ...stateEntry(validPath, 'Edit', {}), warnings: {} }]); - writeFileSync(validPath, validWithContentLink); + await prompt(); + write('valid.md', validWithContentLink); - const result = await runOnStop({ session_id: sessionId }, opts()); + const result = await stop(); expect(result.hasNewErrors).toBe(false); expect(result.errorMessage).toBeUndefined(); expect(result.warningMessage).toContain('structured-context: new validation warnings'); @@ -227,22 +172,18 @@ describe('Warnings', () => { }); it('does not report warnings already present in the baseline', async () => { - const sessionId = crypto.randomUUID(); - const validPath = join(fixtures.vaultDir, 'valid.md'); - writeFileSync(validPath, validWithContentLink); - writeStateFile(sessionId, [{ ...stateEntry(validPath, 'Edit', {}), warnings: contentLinkWarning }]); + write('valid.md', validWithContentLink); + await prompt(); + write('valid.md', `${validWithContentLink}\nMore text.\n`); - const result = await runOnStop({ session_id: sessionId }, opts()); - expect(result).toEqual({ hasNewErrors: false }); + expect(await stop()).toEqual({ hasNewErrors: false }); }); it('reports both errors and warnings when both are new', async () => { - const sessionId = crypto.randomUUID(); - const validPath = join(fixtures.vaultDir, 'valid.md'); - writeStateFile(sessionId, [stateEntry(validPath, 'Write', null)]); - writeFileSync(validPath, validWithContentLink.replace('[[Root]]', '[[Ghost Node]]')); + await prompt(); + write('valid.md', validWithContentLink.replace('[[Root]]', '[[Ghost Node]]')); - const result = await runOnStop({ session_id: sessionId }, opts()); + const result = await stop(); expect(result.hasNewErrors).toBe(true); expect(result.errorMessage).toContain('Ghost Node'); expect(result.warningMessage).toContain('Missing Note'); diff --git a/hook-test/unit/pre-edit.test.ts b/hook-test/unit/pre-edit.test.ts index 61453dc..2d7a037 100644 --- a/hook-test/unit/pre-edit.test.ts +++ b/hook-test/unit/pre-edit.test.ts @@ -5,20 +5,24 @@ */ import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; -import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { runOnPrompt } from '../../plugin/scripts/on-prompt'; import { runPreEdit } from '../../plugin/scripts/pre-edit'; +import { loadState, stateFilePath } from '../../plugin/scripts/state'; import { type IsolatedFixtures, isolateFixtures } from '../fixture-utils'; const SCTX_BIN = join(import.meta.dir, '../../src/index.ts'); let fixtures: IsolatedFixtures; let stateDir: string; +let sessionId: string; beforeEach(() => { fixtures = isolateFixtures(); stateDir = join(tmpdir(), `ost-pre-edit-state-${crypto.randomUUID()}`); + sessionId = crypto.randomUUID(); }); afterEach(() => { @@ -26,171 +30,80 @@ afterEach(() => { rmSync(stateDir, { recursive: true, force: true }); }); -const opts = () => ({ - stateDir, - sctxBin: SCTX_BIN, - configPath: fixtures.configPath, -}); - -function readState(sessionId: string): object[] { - const file = join(stateDir, `sctx-hook-${sessionId}.jsonl`); - if (!existsSync(file)) return []; - return readFileSync(file, 'utf-8') - .trim() - .split('\n') - .filter(Boolean) - .map((l) => JSON.parse(l)); -} - -describe('Write operations', () => { - it('records entry with null errors for a new .md file', async () => { - const sessionId = crypto.randomUUID(); - const filePath = join(fixtures.vaultDir, 'new-note.md'); - - await runPreEdit({ tool_name: 'Write', tool_input: { file_path: filePath }, session_id: sessionId }, opts()); - - const entries = readState(sessionId); - expect(entries).toHaveLength(1); - expect(entries[0]).toMatchObject({ tool: 'Write', file: filePath, errors: null }); +const opts = () => ({ stateDir, sctxBin: SCTX_BIN, configPath: fixtures.configPath }); +const stateFile = () => stateFilePath(sessionId, opts()); +const edit = (file: string, tool = 'Edit') => + runPreEdit( + { tool_name: tool, tool_input: { file_path: join(fixtures.vaultDir, file) }, session_id: sessionId }, + opts(), + ); + +describe('Fallback baseline', () => { + it("baselines the edited file's whole space when it has no baseline", async () => { + await edit('valid.md'); + + const { baseline, latest } = loadState(stateFile()); + expect(Object.keys(baseline)).toEqual(['test-space']); + expect(baseline['test-space']!.issues['broken.md']).toContain('broken-link:[[Nonexistent Node]]'); + expect(latest).toEqual(baseline); }); - it('creates the state directory if it does not exist', async () => { - const deepStateDir = join(stateDir, 'a', 'b', 'c'); - const sessionId = crypto.randomUUID(); + it('baselines the space before a Write creates a new file', async () => { + await edit('new-note.md', 'Write'); - await runPreEdit( - { tool_name: 'Write', tool_input: { file_path: join(fixtures.vaultDir, 'x.md') }, session_id: sessionId }, - { ...opts(), stateDir: deepStateDir }, - ); - - expect(existsSync(deepStateDir)).toBe(true); + expect(Object.keys(loadState(stateFile()).baseline['test-space']!.issues)).toEqual(['broken.md']); }); - it('records a baseline when writing over an existing file', async () => { - const sessionId = crypto.randomUUID(); - const filePath = join(fixtures.vaultDir, 'broken.md'); - - await runPreEdit({ tool_name: 'Write', tool_input: { file_path: filePath }, session_id: sessionId }, opts()); - - const entries = readState(sessionId); - expect(entries).toHaveLength(1); - expect(entries[0]).toMatchObject({ tool: 'Edit', file: filePath }); - expect(Object.keys((entries[0] as { errors: object }).errors)).toContain('broken-link:[[Nonexistent Node]]'); - }); -}); - -describe('Edit operations', () => { - it('records entry with empty errors for a valid in-space .md file', async () => { - const sessionId = crypto.randomUUID(); - const filePath = join(fixtures.vaultDir, 'valid.md'); - - await runPreEdit({ tool_name: 'Edit', tool_input: { file_path: filePath }, session_id: sessionId }, opts()); - - const entries = readState(sessionId); - expect(entries).toHaveLength(1); - expect(entries[0]).toMatchObject({ tool: 'Edit', file: filePath }); - expect((entries[0] as { errors: object }).errors).toEqual({}); - }); - - it('records pre-existing errors for a broken in-space .md file', async () => { - const sessionId = crypto.randomUUID(); - const filePath = join(fixtures.vaultDir, 'broken.md'); - - await runPreEdit({ tool_name: 'Edit', tool_input: { file_path: filePath }, session_id: sessionId }, opts()); - - const entries = readState(sessionId); - expect(entries).toHaveLength(1); - const errors = (entries[0] as { errors: Record }).errors; - expect(Object.keys(errors)).toContain('broken-link:[[Nonexistent Node]]'); - }); - - it('records pre-existing warnings as a separate baseline', async () => { - const sessionId = crypto.randomUUID(); - const filePath = join(fixtures.vaultDir, 'valid.md'); + it('keeps the baseline from the first edit when the space is edited again', async () => { + await edit('valid.md'); writeFileSync( - filePath, - '---\ntype: mission\nparent: "[[Root]]"\nstatus: identified\n---\n\n# Test Title\n\nSee [[Missing Note]].\n', + join(fixtures.vaultDir, 'valid.md'), + '---\ntype: mission\nparent: "[[Ghost Node]]"\nstatus: identified\n---\n\n# Test Title\n', ); + await edit('valid.md'); - await runPreEdit({ tool_name: 'Edit', tool_input: { file_path: filePath }, session_id: sessionId }, opts()); - - const entries = readState(sessionId); - expect(entries).toHaveLength(1); - expect((entries[0] as { errors: object }).errors).toEqual({}); - const warnings = (entries[0] as { warnings: Record }).warnings; - expect(Object.keys(warnings)).toContain('content-link:Missing Note'); + expect(loadState(stateFile()).baseline['test-space']!.issues['valid.md']).toBeUndefined(); }); - it('does not write a state entry for a .md file not in any space', async () => { - const sessionId = crypto.randomUUID(); - // File outside the fixture vault — not registered in any space - const filePath = join(tmpdir(), 'unrelated.md'); + it('leaves a baseline from the prompt hook alone', async () => { + await runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + const before = loadState(stateFile()); + writeFileSync( + join(fixtures.vaultDir, 'valid.md'), + '---\ntype: mission\nparent: "[[Ghost Node]]"\nstatus: identified\n---\n\n# Test Title\n', + ); - await runPreEdit({ tool_name: 'Edit', tool_input: { file_path: filePath }, session_id: sessionId }, opts()); + await edit('valid.md'); - expect(readState(sessionId)).toHaveLength(0); + expect(loadState(stateFile())).toEqual(before); }); +}); - it('appends separate entries for multiple edits in the same session', async () => { - const sessionId = crypto.randomUUID(); - - await runPreEdit( - { tool_name: 'Edit', tool_input: { file_path: join(fixtures.vaultDir, 'valid.md') }, session_id: sessionId }, - opts(), - ); +describe('Edge cases', () => { + it('writes no state for a .md file not in any space', async () => { await runPreEdit( - { tool_name: 'Edit', tool_input: { file_path: join(fixtures.vaultDir, 'broken.md') }, session_id: sessionId }, + { tool_name: 'Edit', tool_input: { file_path: join(tmpdir(), 'unrelated.md') }, session_id: sessionId }, opts(), ); - const entries = readState(sessionId); - expect(entries).toHaveLength(2); - expect(entries.map((e) => (e as { file: string }).file)).toContain(join(fixtures.vaultDir, 'valid.md')); - expect(entries.map((e) => (e as { file: string }).file)).toContain(join(fixtures.vaultDir, 'broken.md')); - }); - - it('keeps only the first baseline when the same file is edited again', async () => { - const sessionId = crypto.randomUUID(); - const filePath = join(fixtures.vaultDir, 'valid.md'); - - await runPreEdit({ tool_name: 'Edit', tool_input: { file_path: filePath }, session_id: sessionId }, opts()); - writeFileSync(filePath, '---\ntype: mission\nparent: "[[Ghost Node]]"\nstatus: identified\n---\n\n# Test Title\n'); - await runPreEdit({ tool_name: 'Edit', tool_input: { file_path: filePath }, session_id: sessionId }, opts()); - - const entries = readState(sessionId); - expect(entries).toHaveLength(1); - expect((entries[0] as { errors: object }).errors).toEqual({}); + expect(existsSync(stateFile())).toBe(false); }); -}); -describe('Edge cases', () => { it('returns without writing when file_path is missing', async () => { - const sessionId = crypto.randomUUID(); - await runPreEdit({ tool_name: 'Edit', tool_input: {}, session_id: sessionId }, opts()); - - expect(readState(sessionId)).toHaveLength(0); - }); - - it('returns without writing when tool_input is missing', async () => { - const sessionId = crypto.randomUUID(); - await runPreEdit({ tool_name: 'Edit', session_id: sessionId }, opts()); - expect(readState(sessionId)).toHaveLength(0); + expect(existsSync(stateFile())).toBe(false); }); - it('includes session_id and timestamp in every entry', async () => { - const sessionId = crypto.randomUUID(); - const before = Date.now(); + it('creates the state directory if it does not exist', async () => { + const deepStateDir = join(stateDir, 'a', 'b', 'c'); await runPreEdit( - { tool_name: 'Write', tool_input: { file_path: join(fixtures.vaultDir, 'x.md') }, session_id: sessionId }, - opts(), + { tool_name: 'Edit', tool_input: { file_path: join(fixtures.vaultDir, 'valid.md') }, session_id: sessionId }, + { ...opts(), stateDir: deepStateDir }, ); - const [entry] = readState(sessionId) as Array<{ session_id: string; timestamp: number }>; - expect(entry!.session_id).toBe(sessionId); - expect(entry!.timestamp).toBeGreaterThanOrEqual(before); + expect(existsSync(deepStateDir)).toBe(true); }); }); diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 5c3e17c..1cf02a2 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "structured-context", - "version": "0.11.5", + "version": "0.11.6", "description": "Structured content authoring for Obsidian — automatic validation hooks, slash commands, and agent skills to keep markdown files compliant with your schema.", "homepage": "https://github.com/mindsocket/structured-context", "repository": "https://github.com/mindsocket/structured-context", diff --git a/plugin/hooks/hooks.json b/plugin/hooks/hooks.json index 6dd262a..1ad2601 100644 --- a/plugin/hooks/hooks.json +++ b/plugin/hooks/hooks.json @@ -1,5 +1,16 @@ { "hooks": { + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "bun run ${CLAUDE_PLUGIN_ROOT}/scripts/on-prompt.ts", + "timeout": 60 + } + ] + } + ], "PreToolUse": [ { "matcher": "Write|Edit", @@ -8,13 +19,13 @@ "if": "Write(*.md)", "type": "command", "command": "bun run ${CLAUDE_PLUGIN_ROOT}/scripts/pre-edit.ts", - "timeout": 30 + "timeout": 60 }, { "if": "Edit(*.md)", "type": "command", "command": "bun run ${CLAUDE_PLUGIN_ROOT}/scripts/pre-edit.ts", - "timeout": 30 + "timeout": 60 } ] } @@ -29,6 +40,16 @@ } ] } + ], + "SessionEnd": [ + { + "hooks": [ + { + "type": "command", + "command": "bun run ${CLAUDE_PLUGIN_ROOT}/scripts/on-session-end.ts" + } + ] + } ] } } diff --git a/plugin/scripts/on-prompt.ts b/plugin/scripts/on-prompt.ts new file mode 100644 index 0000000..be316be --- /dev/null +++ b/plugin/scripts/on-prompt.ts @@ -0,0 +1,40 @@ +#!/usr/bin/env bun +/** + * UserPromptSubmit hook: baseline every space inside or containing the session's directory. + * A space keeps an existing baseline, which means the previous turn's Stop hook never ran + * (e.g. the turn was interrupted), so its changes are still compared at the next Stop. + */ + +import { contains, type HookOptions, listSpaces, loadState, recordBaselines, saveState, stateFilePath } from './state'; + +export interface OnPromptInput { + session_id?: string; + cwd?: string; +} + +export async function runOnPrompt(input: OnPromptInput, options?: HookOptions): Promise { + if (!input.cwd) return; + + const CWD = input.cwd; + const { configFiles, spaces } = await listSpaces(options); + const related = spaces.filter((space) => contains(CWD, space.path) || contains(space.path, CWD)); + if (related.length === 0) return; + + const STATE_FILE = stateFilePath(input.session_id, options); + const state = loadState(STATE_FILE); + if (await recordBaselines(state, related, configFiles, options)) { + saveState(STATE_FILE, state); + } +} + +async function main() { + const INPUT = JSON.parse(await Bun.stdin.text()) as OnPromptInput; + await runOnPrompt(INPUT); +} + +if (import.meta.main) { + main().catch((err) => { + console.error(err); + process.exit(1); + }); +} diff --git a/plugin/scripts/on-session-end.ts b/plugin/scripts/on-session-end.ts new file mode 100644 index 0000000..2d9c3ac --- /dev/null +++ b/plugin/scripts/on-session-end.ts @@ -0,0 +1,13 @@ +#!/usr/bin/env bun +/** SessionEnd hook: remove the session's state file. */ + +import { rmSync } from 'node:fs'; +import { type HookOptions, stateFilePath } from './state'; + +export function runOnSessionEnd(input: { session_id?: string }, options?: HookOptions): void { + rmSync(stateFilePath(input.session_id, options), { force: true }); +} + +if (import.meta.main) { + runOnSessionEnd(JSON.parse(await Bun.stdin.text())); +} diff --git a/plugin/scripts/on-stop.ts b/plugin/scripts/on-stop.ts index c7bb081..aeed104 100755 --- a/plugin/scripts/on-stop.ts +++ b/plugin/scripts/on-stop.ts @@ -1,19 +1,27 @@ #!/usr/bin/env bun +/** + * Stop hook: validate each space baselined this turn and report issues missing from its baseline, + * in any file of the space. New errors block the stop; new warnings are passed back as context. + */ + +import { join } from 'node:path'; +import { + type HookOptions, + hashSpace, + issueKeys, + listSpaces, + loadState, + saveState, + stateFilePath, + type ValidationIssue, + validateSpace, +} from './state'; export interface OnStopInput { session_id?: string; stop_hook_active?: boolean; } -export interface OnStopOptions { - /** Overrides SCTX_STATE_DIR env var */ - stateDir?: string; - /** Path to structured-context entry point. When set, uses `bun run ` instead of `bunx structured-context`. */ - sctxBin?: string; - /** Path to config file. When set, passed as SCTX_CONFIG to validate-file subprocess. */ - configPath?: string; -} - export interface OnStopResult { hasNewErrors: boolean; /** Present when hasNewErrors is true */ @@ -22,135 +30,82 @@ export interface OnStopResult { warningMessage?: string; } -interface HookState { - session_id: string; - timestamp: number; - tool: 'Write' | 'Edit'; - file: string; - errors: object | null; - /** Absent in state written by older versions of the pre-edit hook */ - warnings?: object | null; -} - -interface ValidationIssue { - kind: string; - message: string; - severity?: 'error' | 'warning' | 'info'; -} - -interface ValidationResult { - inSpace?: boolean; - label?: string; - space?: string; - errors?: Record; - warnings?: Record; -} - -/** Issues in `fresh` that are not in the baseline. A Write has no baseline, so every issue is new. */ -function newIssues( - tool: HookState['tool'], - fresh: Record, - baseline: object | null | undefined, -): ValidationIssue[] { - const baselineKeys = tool === 'Write' ? new Set() : new Set(Object.keys(baseline ?? {})); - return Object.entries(fresh) - .filter(([key]) => !baselineKeys.has(key)) - .map(([, issue]) => issue); -} - function formatIssues(header: string, issues: ValidationIssue[], noun: string): string { const lines = issues.map((issue) => ` [${issue.kind}] ${issue.message}`).join('\n'); return ` ${header} — ${issues.length} new ${noun}(s):\n${lines}`; } -export async function runOnStop(input: OnStopInput, options?: OnStopOptions): Promise { - const SESSION_ID = input.session_id ?? 'unknown'; - const STOP_HOOK_ACTIVE = input.stop_hook_active ?? false; - +export async function runOnStop(input: OnStopInput, options?: HookOptions): Promise { // Guard against infinite loop: stop hooks can trigger another stop cycle - if (STOP_HOOK_ACTIVE === true) { + if (input.stop_hook_active === true) { return { hasNewErrors: false }; } - const STATE_DIR = options?.stateDir ?? process.env.SCTX_STATE_DIR ?? '/tmp'; - const STATE_FILE = `${STATE_DIR}/sctx-hook-${SESSION_ID}.jsonl`; - - const stateFile = Bun.file(STATE_FILE); - const stateFileExists = await stateFile.exists(); - if (!stateFileExists) { + const STATE_FILE = stateFilePath(input.session_id, options); + const state = loadState(STATE_FILE); + if (Object.keys(state.baseline).length === 0) { return { hasNewErrors: false }; } + const { configFiles, spaces } = await listSpaces(options); + const newErrors: string[] = []; const newWarnings: string[] = []; - - // Read all entries and keep the earliest per file (by timestamp): its baseline is the file's - // state before this session's first change, so later edits can't absorb issues earlier ones introduced - const lines = (await stateFile.text()) - .trim() - .split('\n') - .filter((l) => l); - const entries: HookState[] = lines.map((l) => JSON.parse(l)); - - const earliestByFile = new Map(); - for (const entry of entries) { - const existing = earliestByFile.get(entry.file); - if (!existing || entry.timestamp < existing.timestamp) { - earliestByFile.set(entry.file, entry); - } - } - - const BIN = options?.sctxBin ?? process.env.SCTX_BIN; - const env: Record = { ...process.env }; - if (options?.configPath) { - env.SCTX_CONFIG = options.configPath; - } - - for (const [FILE, entry] of earliestByFile) { - const { tool } = entry; - - const fileExists = await Bun.file(FILE).exists(); - if (!fileExists) { - continue; - } - - const proc = BIN - ? Bun.$`bun run ${[BIN]} validate-file ${[FILE]} --json`.env(env).quiet().nothrow() - : Bun.$`bunx structured-context validate-file ${[FILE]} --json`.env(env).quiet().nothrow(); - const resultText = await proc.text(); - const result = resultText ? (JSON.parse(resultText) as ValidationResult) : {}; - - const IN_SPACE = result.inSpace ?? false; - if (IN_SPACE !== true) { - continue; + // Spaces can overlap, so report each issue in a file once + const reported = new Set(); + const unreported = (file: string, key: string) => { + const id = `${file}\0${key}`; + if (reported.has(id)) return false; + reported.add(id); + return true; + }; + + // A space whose hash still matches its baseline hasn't changed, so it needs no validation + const hashes = new Map( + spaces.filter((space) => state.baseline[space.name]).map((space) => [space.name, hashSpace(space, configFiles)]), + ); + const changed = spaces.filter( + (space) => hashes.has(space.name) && hashes.get(space.name) !== state.baseline[space.name]!.hash, + ); + const results = await Promise.all(changed.map((space) => validateSpace(space.name, options))); + + changed.forEach((space, i) => { + const byFile = results[i]!; + const before = state.baseline[space.name]!.issues; + + for (const [label, issues] of Object.entries(byFile)) { + const file = join(space.path, label); + const HEADER = label ? `${label} (space: ${space.name})` : `space ${space.name}`; + const known = new Set(before[label] ?? []); + + const fileErrors = Object.entries(issues.errors) + .filter(([key]) => !known.has(key) && unreported(file, key)) + .map(([, issue]) => issue); + if (fileErrors.length > 0) { + newErrors.push(formatIssues(HEADER, fileErrors, 'error')); + } + + const fileWarnings = Object.entries(issues.warnings) + .filter(([key]) => !known.has(key) && unreported(file, key)) + .map(([, issue]) => issue); + if (fileWarnings.length > 0) { + newWarnings.push(formatIssues(HEADER, fileWarnings, 'warning')); + } } - const HEADER = `${result.label ?? FILE} (space: ${result.space ?? 'unknown'})`; - - const fileErrors = newIssues(tool, result.errors ?? {}, entry.errors); - if (fileErrors.length > 0) { - newErrors.push(formatIssues(HEADER, fileErrors, 'error')); - } - - // Info-level rule violations are not worth another turn from Claude - const fileWarnings = newIssues(tool, result.warnings ?? {}, entry.warnings).filter( - (issue) => issue.severity !== 'info', - ); - if (fileWarnings.length > 0) { - newWarnings.push(formatIssues(HEADER, fileWarnings, 'warning')); - } - } + state.latest[space.name] = { path: space.path, hash: hashes.get(space.name)!, issues: issueKeys(byFile) }; + }); - // Clean up state file - await Bun.$`rm -f ${STATE_FILE}`; + state.baseline = {}; + saveState(STATE_FILE, state); const warningMessage = newWarnings.length > 0 - ? `structured-context: new validation warnings introduced this session - fix them with the structured-context skill if appropriate, otherwise mention them to the user:\n${newWarnings.join('\n')}` + ? `structured-context: new validation warnings introduced this turn - fix them with the structured-context skill if appropriate, otherwise mention them to the user:\n${newWarnings.join('\n')}` : undefined; if (newErrors.length > 0) { - const errorMessage = `structured-context: new validation errors introduced this session - use structured-context skill to resolve:\n${newErrors.join('\n')}`; + const errorMessage = `structured-context: new validation errors introduced this turn - use structured-context skill to resolve:\n${newErrors.join('\n')}`; return { hasNewErrors: true, errorMessage, ...(warningMessage && { warningMessage }) }; } diff --git a/plugin/scripts/pre-edit.ts b/plugin/scripts/pre-edit.ts index d46dbab..612d595 100755 --- a/plugin/scripts/pre-edit.ts +++ b/plugin/scripts/pre-edit.ts @@ -1,12 +1,11 @@ #!/usr/bin/env bun /** * PreToolUse hook for Write and Edit on *.md files. - * Write of a new file: records the filename with no baseline errors. - * Edit, or Write over an existing file: validates before the change and records baseline errors and warnings. - * Appends one JSONL line to a per-session state file for the Stop hook to analyse. + * Fallback for spaces the prompt hook didn't cover (outside the session's directory): the first + * edit to such a space this turn baselines the whole space before the change. */ -import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'; +import { contains, type HookOptions, listSpaces, loadState, recordBaselines, saveState, stateFilePath } from './state'; export interface PreEditInput { tool_name?: string; @@ -16,103 +15,23 @@ export interface PreEditInput { session_id?: string; } -export interface PreEditOptions { - /** Overrides SCTX_STATE_DIR env var */ - stateDir?: string; - /** Path to structured-context entry point. When set, uses `bun run ` instead of `bunx structured-context`. */ - sctxBin?: string; - /** Path to config file. When set, passed as SCTX_CONFIG to validate-file subprocess. */ - configPath?: string; -} - -interface HookState { - session_id: string; - timestamp: number; - tool: 'Write' | 'Edit'; - file: string; - errors: object | null; - warnings: object | null; -} - -interface ValidationResult { - inSpace?: boolean; - errors?: object; - warnings?: object; -} - -function alreadyTracked(stateFile: string, filePath: string): boolean { - if (!existsSync(stateFile)) return false; - return readFileSync(stateFile, 'utf-8') - .split('\n') - .some((line) => line && (JSON.parse(line) as HookState).file === filePath); -} - -export async function runPreEdit(input: PreEditInput, options?: PreEditOptions): Promise { - const TOOL = input.tool_name ?? ''; +export async function runPreEdit(input: PreEditInput, options?: HookOptions): Promise { const FILE_PATH = input.tool_input?.file_path; - const SESSION_ID = input.session_id ?? 'unknown'; - - if (!FILE_PATH) { - return; - } + if (!FILE_PATH) return; - const STATE_DIR = options?.stateDir ?? process.env.SCTX_STATE_DIR ?? '/tmp'; - const STATE_FILE = `${STATE_DIR}/sctx-hook-${SESSION_ID}.jsonl`; - const TIMESTAMP = Date.now(); + const STATE_FILE = stateFilePath(input.session_id, options); + const state = loadState(STATE_FILE); + if (Object.values(state.baseline).some((snap) => contains(snap.path, FILE_PATH))) return; - // The Stop hook compares against a file's first baseline this session, so later edits need none - if (alreadyTracked(STATE_FILE, FILE_PATH)) { - return; + const { configFiles, spaces } = await listSpaces(options); + const containing = spaces.filter((space) => contains(space.path, FILE_PATH)); + if (await recordBaselines(state, containing, configFiles, options)) { + saveState(STATE_FILE, state); } - - if (TOOL === 'Write' && !existsSync(FILE_PATH)) { - const entry: HookState = { - session_id: SESSION_ID, - timestamp: TIMESTAMP, - tool: 'Write', - file: FILE_PATH, - errors: null, - warnings: null, - }; - mkdirSync(STATE_DIR, { recursive: true }); - appendFileSync(STATE_FILE, `${JSON.stringify(entry)}\n`); - return; - } - - // Edit or overwrite — validate current state as pre-edit baseline - const BIN = options?.sctxBin ?? process.env.SCTX_BIN; - const env: Record = { ...process.env }; - if (options?.configPath) { - env.SCTX_CONFIG = options.configPath; - } - - const proc = BIN - ? Bun.$`bun run ${[BIN]} validate-file ${[FILE_PATH]} --json`.env(env).quiet().nothrow() - : Bun.$`bunx structured-context validate-file ${[FILE_PATH]} --json`.env(env).quiet().nothrow(); - - const resultText = await proc.text(); - const result = resultText ? (JSON.parse(resultText) as ValidationResult) : {}; - const IN_SPACE = result.inSpace ?? false; - - if (IN_SPACE !== true) { - return; - } - - const entry: HookState = { - session_id: SESSION_ID, - timestamp: TIMESTAMP, - tool: 'Edit', - file: FILE_PATH, - errors: result.errors ?? {}, - warnings: result.warnings ?? {}, - }; - mkdirSync(STATE_DIR, { recursive: true }); - appendFileSync(STATE_FILE, `${JSON.stringify(entry)}\n`); } async function main() { - const INPUT_TEXT = await Bun.stdin.text(); - const INPUT = JSON.parse(INPUT_TEXT) as PreEditInput; + const INPUT = JSON.parse(await Bun.stdin.text()) as PreEditInput; await runPreEdit(INPUT); } diff --git a/plugin/scripts/state.ts b/plugin/scripts/state.ts new file mode 100644 index 0000000..945f319 --- /dev/null +++ b/plugin/scripts/state.ts @@ -0,0 +1,204 @@ +/** + * Session state shared by the hooks, and the CLI calls that fill it. + * + * Each space gets a baseline when a prompt is submitted (or at the first edit to a space the + * prompt hook didn't cover). The Stop hook validates the space again, reports issues missing + * from the baseline, and clears it. `latest` keeps each space's most recent issue keys, which + * are reused without validating while the space's content hash still matches. + */ + +import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; + +export interface HookOptions { + /** Overrides SCTX_STATE_DIR env var */ + stateDir?: string; + /** Path to structured-context entry point. When set, uses `bun run ` instead of `bunx structured-context`. */ + sctxBin?: string; + /** Path to config file. When set, passed as SCTX_CONFIG to the CLI subprocess. */ + configPath?: string; +} + +export interface ValidationIssue { + kind: string; + message: string; + severity?: 'error' | 'warning' | 'info'; +} + +export interface FileIssues { + errors: Record; + warnings: Record; +} + +/** A space's issue keys at a point in time */ +export interface SpaceIssueKeys { + path: string; + hash: string; + /** Issue keys by file label; files without issues are omitted. Space-level issues use the label ''. */ + issues: Record; +} + +export interface SessionState { + /** Per space: issue keys before this turn's changes. Cleared by the Stop hook. */ + baseline: Record; + /** Per space: the most recent issue keys, reused while the hash still matches */ + latest: Record; +} + +export interface SpaceInfo { + name: string; + path: string; + schema?: string; +} + +interface SpacesOutput { + configFiles: string[]; + spaces: SpaceInfo[]; +} + +interface ValidateOutput { + errors?: Record>; + ruleViolations?: { file?: string; ruleId: string; severity: 'error' | 'warning' | 'info'; description: string }[]; + parseIssues?: { file: string; severity: 'error' | 'warning'; type: string; message?: string }[]; + unresolvedContentLinks?: { file: string; target: string }[]; +} + +export function stateFilePath(sessionId: string | undefined, options?: HookOptions): string { + const dir = options?.stateDir ?? process.env.SCTX_STATE_DIR ?? '/tmp'; + return join(dir, `sctx-hook-${sessionId ?? 'unknown'}.json`); +} + +export function loadState(file: string): SessionState { + if (!existsSync(file)) return { baseline: {}, latest: {} }; + const state = JSON.parse(readFileSync(file, 'utf-8')) as Partial; + return { baseline: state.baseline ?? {}, latest: state.latest ?? {} }; +} + +export function saveState(file: string, state: SessionState): void { + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(state)); +} + +export function contains(dir: string, path: string): boolean { + return path === dir || path.startsWith(dir.endsWith('/') ? dir : `${dir}/`); +} + +async function sctx(args: string[], options?: HookOptions): Promise { + const BIN = options?.sctxBin ?? process.env.SCTX_BIN; + const env: Record = { ...process.env }; + if (options?.configPath) { + env.SCTX_CONFIG = options.configPath; + } + const proc = BIN + ? Bun.$`bun run ${[BIN]} ${args}`.env(env).quiet().nothrow() + : Bun.$`bunx structured-context ${args}`.env(env).quiet().nothrow(); + return proc.text(); +} + +/** Configured spaces whose path exists, and the config files they came from */ +export async function listSpaces(options?: HookOptions): Promise { + const text = await sctx(['spaces', '--json'], options); + if (!text) return { configFiles: [], spaces: [] }; + const output = JSON.parse(text) as SpacesOutput; + return { ...output, spaces: output.spaces.filter((space) => existsSync(space.path)) }; +} + +/** + * Hash the paths, sizes and modification times of every input to a space's validation: + * its markdown files, the files in its schema's directory, and the config files. + */ +export function hashSpace(space: SpaceInfo, configFiles: string[]): string { + const markdown = statSync(space.path).isDirectory() + ? [...new Bun.Glob('**/*.md').scanSync({ cwd: space.path, absolute: true, followSymlinks: true })] + : [space.path]; + // The schema's directory holds the partials it can reference + const schemaDir = space.schema && existsSync(space.schema) ? dirname(space.schema) : undefined; + const schemaFiles = schemaDir ? [...new Bun.Glob('*.json').scanSync({ cwd: schemaDir, absolute: true })] : []; + + const hasher = new Bun.CryptoHasher('sha1'); + for (const file of [...markdown, ...schemaFiles, ...configFiles].sort()) { + try { + const { size, mtimeMs } = statSync(file); + hasher.update(`${file}\t${size}\t${mtimeMs}\n`); + } catch { + hasher.update(`${file}\tmissing\n`); + } + } + return hasher.digest('hex'); +} + +/** + * Validate a whole space and group its errors and warnings by file label. + * Info-level rule violations are left out: they are not worth another turn from Claude. + */ +export async function validateSpace(name: string, options?: HookOptions): Promise> { + const text = await sctx(['validate', name, '--json'], options); + if (!text) return {}; + const output = JSON.parse(text) as ValidateOutput; + + const byFile: Record = {}; + const issuesFor = (label: string): FileIssues => { + byFile[label] ??= { errors: {}, warnings: {} }; + return byFile[label]; + }; + + for (const [label, errors] of Object.entries(output.errors ?? {})) { + Object.assign(issuesFor(label).errors, errors); + } + for (const issue of output.parseIssues ?? []) { + if (issue.severity === 'error') { + issuesFor(issue.file).errors[`parse:${issue.type}`] = { + kind: 'parse', + message: issue.message ?? `Could not parse (${issue.type})`, + }; + } + } + for (const v of output.ruleViolations ?? []) { + const issue = { kind: 'rule', message: `[${v.ruleId}] ${v.description}`, severity: v.severity }; + // File-level rule errors are already in `errors` + if (v.severity === 'error' && !v.file) issuesFor('').errors[`rule:${v.ruleId}`] = issue; + if (v.severity === 'warning') issuesFor(v.file ?? '').warnings[`rule:${v.ruleId}`] = issue; + } + for (const { file, target } of output.unresolvedContentLinks ?? []) { + issuesFor(file).warnings[`content-link:${target}`] = { + kind: 'content-link', + message: `Unresolved content link: ${target}`, + }; + } + return byFile; +} + +export function issueKeys(byFile: Record): Record { + return Object.fromEntries( + Object.entries(byFile).map(([label, { errors, warnings }]) => [ + label, + [...Object.keys(errors), ...Object.keys(warnings)], + ]), + ); +} + +/** + * Record a baseline for each space that doesn't have one yet, reusing the latest issue keys + * when the space's hash still matches them. Returns whether anything was recorded. + */ +export async function recordBaselines( + state: SessionState, + spaces: SpaceInfo[], + configFiles: string[], + options?: HookOptions, +): Promise { + const pending = spaces.filter((space) => !state.baseline[space.name]); + await Promise.all( + pending.map(async (space) => { + const hash = hashSpace(space, configFiles); + const latest = state.latest[space.name]; + const keys = + latest?.hash === hash + ? latest + : { path: space.path, hash, issues: issueKeys(await validateSpace(space.name, options)) }; + state.latest[space.name] = keys; + state.baseline[space.name] = keys; + }), + ); + return pending.length > 0; +} diff --git a/src/commands/spaces.ts b/src/commands/spaces.ts index 49886c3..876b717 100644 --- a/src/commands/spaces.ts +++ b/src/commands/spaces.ts @@ -1,14 +1,23 @@ import { basename, resolve } from 'node:path'; -import { configPath, loadConfig } from '../config'; +import { configPath, getConfigSourceFiles, loadConfig } from '../config'; function renderConfigValue(v: unknown): string { if (typeof v === 'object' && v !== null) return JSON.stringify(v); return String(v); } -export function listSpaces(): void { +export function listSpaces(options: { json?: boolean } = {}): void { const path = resolve(configPath()); const config = loadConfig(); + if (options.json) { + const spaces = config.spaces.map((space) => ({ + name: space.name, + path: space.path, + schema: space.schema ?? config.schema, + })); + console.log(JSON.stringify({ configFiles: [...getConfigSourceFiles()], spaces })); + return; + } console.log(`Config: ${path}\n`); for (const space of config.spaces) { console.log(`${space.name}`); diff --git a/src/index.ts b/src/index.ts index ead7a56..6605b2c 100755 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,6 @@ #!/usr/bin/env bun import { createRequire } from 'node:module'; +import { format } from 'node:util'; import { Command } from 'commander'; import { diagram } from './commands/diagram'; import { docs } from './commands/docs'; @@ -18,6 +19,12 @@ import { CLI_NAME } from './constants'; import { createSpaceContext, SpaceNotFoundError } from './space-context'; import type { SpaceContext } from './types'; +// Once node:process is loaded (vfile, via unified, loads it), Bun's console.log drops piped output +// past 64KB when the reader is slow. process.stdout.write delivers all of it before exit. +console.log = (...args: unknown[]) => { + process.stdout.write(`${format(...args)}\n`); +}; + export function buildSpaceContext(spaceName: string): SpaceContext { try { return createSpaceContext(spaceName, loadConfig()); @@ -51,8 +58,7 @@ program .argument('', 'Path to the file to validate') .option('--json', 'Output results as JSON (machine-readable, for hooks)') .action(async (filePath, options) => { - const exitCode = await validateFileCommand(filePath, { json: options.json }); - process.exit(exitCode); + process.exitCode = await validateFileCommand(filePath, { json: options.json }); }); program @@ -66,8 +72,8 @@ program if (options.watch) { await watchValidate(context); } else { - const exitCode = await validate(context, { json: options.json }); - process.exit(exitCode); + // exitCode rather than process.exit(): exiting straight away can cut off large piped output + process.exitCode = await validate(context, { json: options.json }); } }); @@ -123,7 +129,8 @@ const spacesCmd = new Command('spaces').description('List configured spaces'); spacesCmd .command('list', { isDefault: true }) .description('List all configured spaces and their paths') - .action(listSpaces); + .option('--json', 'Output as JSON: config files, and each space with its path and schema') + .action((options) => listSpaces(options)); program.addCommand(spacesCmd); const schemasCmd = new Command('schemas').alias('schema').description('List and inspect schemas'); From e7b7ba8e2ffb8d645331b2f86b7a760e303e3312 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Sun, 27 Sep 2026 18:42:02 +1000 Subject: [PATCH 3/6] Hook e2e harness: load no user settings or CLAUDE.md The Agent SDK loads ~/.claude settings and CLAUDE.md when settingSources is omitted. Claude-Session: https://claude.ai/code/session_01EJgagmpxDYVYr7fp9C6cZi --- hook-test/harness.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/hook-test/harness.ts b/hook-test/harness.ts index 58c659d..ea2e490 100644 --- a/hook-test/harness.ts +++ b/hook-test/harness.ts @@ -63,6 +63,8 @@ export async function runClaude(options: RunClaudeOptions): Promise Date: Sun, 27 Sep 2026 19:07:32 +1000 Subject: [PATCH 4/6] Use cases: keep validate-file command and API usage for single-file validation Claude-Session: https://claude.ai/code/session_01EJgagmpxDYVYr7fp9C6cZi --- docs/use-cases.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/use-cases.md b/docs/use-cases.md index 60ae94f..c62158f 100644 --- a/docs/use-cases.md +++ b/docs/use-cases.md @@ -19,7 +19,7 @@ A catalog of use cases for structured-context, covering both direct CLI usage an |---|---|---|---| | **Validate content** | Verify that space content conforms to schema, link integrity, rules, and hierarchy | | | | — Validate a space | Check all files in a space in one pass | done | `sctx validate` · `/validate-space` command · plugin hooks report issues introduced during a Claude turn | -| — Validate a single file | Validate one file in context of its space | done | `sctx validate-file` | +| — Validate a single file | Validate one file in context of its space | done | `sctx validate-file` · `validateFile` API, e.g. for validation on save in an editor | | — Watch for changes | Continuously re-validate as files are edited | done | `sctx validate --watch` | | **Resolve validation errors** | Investigate and fix schema, link, or rule violations once identified | agent | structured-context skill (troubleshooting guide; `dump` for rule debugging) | From cc03ef3493906ff9b6909bd9d7a1d27f831ccf74 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Sun, 27 Sep 2026 19:07:33 +1000 Subject: [PATCH 5/6] Fix on-prompt test using tmpdir() as unrelated cwd On Linux the fixture space lives directly under tmpdir(), so it counted as related and a baseline was written. Use a fresh sibling directory instead. Claude-Session: https://claude.ai/code/session_01EJgagmpxDYVYr7fp9C6cZi --- hook-test/unit/on-prompt.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/hook-test/unit/on-prompt.test.ts b/hook-test/unit/on-prompt.test.ts index 1f49cde..9f8d0cc 100644 --- a/hook-test/unit/on-prompt.test.ts +++ b/hook-test/unit/on-prompt.test.ts @@ -54,7 +54,10 @@ describe('Baselines', () => { }); it('writes no state when no space is related to the session directory', async () => { - await runOnPrompt({ session_id: sessionId, cwd: tmpdir() }, opts()); + // A sibling of the fixture dir, not tmpdir() itself: on Linux the fixture lives under tmpdir() + const unrelated = join(tmpdir(), `ost-on-prompt-unrelated-${crypto.randomUUID()}`); + + await runOnPrompt({ session_id: sessionId, cwd: unrelated }, opts()); expect(existsSync(stateFile())).toBe(false); }); From af6afef330365591ad0ec33d56c16f3f0514bdd6 Mon Sep 17 00:00:00 2001 From: Roger Barnes Date: Sun, 27 Sep 2026 20:29:50 +1000 Subject: [PATCH 6/6] Update docs/use-cases.md wording for plugin hook redesign Two rows still described the old per-file save-time validation hook; align with the whole-space baseline/compare design already reflected elsewhere in the file. Claude-Session: https://claude.ai/code/session_01Vu78JfVBQXdqVtBZUPdu2E --- docs/use-cases.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/use-cases.md b/docs/use-cases.md index c62158f..593cfcd 100644 --- a/docs/use-cases.md +++ b/docs/use-cases.md @@ -60,7 +60,7 @@ A catalog of use cases for structured-context, covering both direct CLI usage an | Use case | Description | Status | Coverage | |---|---|---|---| -| **Author new content compliantly** | Create or edit nodes in Obsidian while staying schema-conformant | partial | Validation hook on `.md` save; schema-driven templates; structured-context skill for inline guidance | +| **Author new content compliantly** | Create or edit nodes in Obsidian while staying schema-conformant | partial | Plugin hooks report issues introduced during a Claude turn; schema-driven templates; structured-context skill for inline guidance | | **Discover and curate inputs** | Identify new information (research, signals, events) to add to a space and integrate it | none | — | --- @@ -91,4 +91,4 @@ A catalog of use cases for structured-context, covering both direct CLI usage an | Use case | Description | Status | Coverage | |---|---|---|---| | **Automate workflow rituals** | Run planning, review, or triage workflows against space content on a schedule or trigger | none | — | -| **Automate gardening and hygiene** | Scheduled or triggered cleanup: link repair, status updates, orphan triage | partial | `validate --watch` for live feedback; hooks for save-time checks; manual agent-driven triage | +| **Automate gardening and hygiene** | Scheduled or triggered cleanup: link repair, status updates, orphan triage | partial | `validate --watch` for live feedback; plugin hooks report issues introduced during a Claude turn; manual agent-driven triage |