diff --git a/.claude/skills/doc-review/SKILL.md b/.claude/skills/doc-review/SKILL.md new file mode 100644 index 00000000..aef1dd01 --- /dev/null +++ b/.claude/skills/doc-review/SKILL.md @@ -0,0 +1,46 @@ +--- +name: doc-review +description: Review written content in this repo (README, docs/, AGENTS.md, plugin skills and references, CLI help and error text) against the project's documentation standards, then fix what it finds. Use after writing or changing any prose, before committing or opening a PR. +--- + +## Task + +Review the prose in the target named by `$ARGUMENTS`: a PR number, branch, commit, or list of files. With no +argument, use uncommitted changes, or if there are none, the branch against `main` (`git diff main...HEAD`). +Look at `*.md`, `plugin/**`, and user-facing strings in `src/` and tests. Apply the **Documentation Principles** in +`AGENTS.md`, then fix the findings. Re-read each finding in context: a flagged phrase is sometimes the right +wording. + +## Checks + +For every changed passage, ask: + +1. **Would someone new to the project understand it?** Flag decision history and internal jargon ("never merged by + location", "A′", phase names). Say what does happen. +2. **Does it earn its place?** Flag sentences that restate the previous one, state the obvious, spell out an + implication the reader can work out, or describe what is not the case without a likely wrong assumption to + correct. Flag error codes and flags the output already shows. +3. **Is it in the right place?** Flag duplicated explanations (owned once, linked elsewhere). A README section is + a sentence or two pointing to docs/. Detail used rarely belongs in `references/` or `sctx docs`. +4. **Is a recommendation labelled as one?** "It is recommended to..." rather than a rule stated as fact. +5. **Names:** `structured-context` in prose, `sctx` only in commands. Terms match `docs/concepts.md`. + +Skills and references (`plugin/skills/**`), also: + +6. **Trigger:** the `description` names structured-context (sctx) and the task in words a user or agent would + use, briefly. It does not rely on terms an agent session may not know (such as "space"). +7. **Every line is an action or a fact the agent lacks.** Flag instructions made redundant by the next command, + output that already says the same thing, steps that depend on a state check ("if there is no config yet") + when intent alone should trigger the skill, and rules that limit what a capable model would do unprompted. +8. **Offers and confirmations** only where the user's decision changes what happens next. +9. **Order follows the user's journey**, happy path first. + +Code comments and messages: + +10. Flag comments that restate code or explain history, and library errors that mention CLI flags. + +## Output + +List findings as `file:line, check number, proposed rewrite`, then apply them. Run `bun run lint` and, if +`plugin/` changed, `bun run test:hook`. Finish by checking the "Definition of done" table in `AGENTS.md` for files +the change affects but does not touch. diff --git a/AGENTS.md b/AGENTS.md index e6f05513..7809ee26 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ Before starting new work, review [docs/concepts.md](docs/concepts.md) for canoni - see `package.json` - Releases go through the `/release` skill. -Space names (e.g. `personal`, `politics`) are resolved via a config file - `$SCTX_CONFIG`, `$XDG_CONFIG_HOME/structured-context/config.json`, `--config ` param, or `./config.json` +Space names (e.g. `personal`, `politics`) are resolved via a config file - `$SCTX_CONFIG`, `$XDG_CONFIG_HOME/structured-context/config.json`, `--config ` param, or the nearest `.sctx.json` walking up from the working directory The lefthook pre-commit hook syncs the plugin version (below), then runs biome (`--write`, re-staged) and the typecheck. @@ -54,6 +54,7 @@ There are several places that need reviewing and updating with any new feature o - **Minimise blast radius:** Protect established boundaries and interfaces. Treat unnecessary ripple effects (such as making synchronous APIs asynchronous or adding dual APIs) as a design smell indicating the approach should be re-evaluated. - **Public API surface:** Do not add exports to `src/api.ts`, `src/types.ts` or `src/testing.ts` (the `structured-context/api`, `/types` and `/testing` entry points), or add types or hooks to the plugin interface, without the maintainer's explicit agreement on that specific surface. Exporting something to make docs complete, to tidy up, or because a feature has a public-looking class is not a reason. If a change seems to need a new export, stop and propose it, with the consumer that needs it. Internal modules can change freely. - **Where a setting lives:** Config says *what* to use, CLI flags override it for one run, and the environment holds secrets and the config location only (`apiKeyEnv` names a secret; `SCTX_CONFIG` locates the config). Do not add env vars that set config values, and never infer a choice (such as a judge provider) from a variable that happens to be set: a key present for another tool must not be spent silently. Config also never switches on costly or outward-facing behaviour (such as semantic judging): each run asks for it, through a flag or an API option. +- **Reuse types:** Derive a type from the real one (`Pick`, `Partial`) instead of restating its shape. Keep CLI wording (flags, commands) out of library errors and the public API; the CLI adds its own hint. Once a feature has many files, give it a directory. Comments explain why, never restate the code. - **Failures are visible:** A rule or expression that cannot be evaluated is reported as a violation, never skipped or treated as a pass. Likewise a misconfiguration fails before any work or spend. ## Documentation Principles @@ -62,6 +63,9 @@ There are several places that need reviewing and updating with any new feature o - **Document what it does, not what it doesn't:** Describe behaviour and purpose. State a limit only when a new user would realistically assume otherwise. Specification and decision history do not leak into docs. - **Proper name in docs:** `structured-context` is the project name for prose; `sctx` is only the CLI command in command examples. - **Approachability:** Write short, declarative sentences in active voice, one idea per sentence — about 80% of the way to ASD-STE100. Introduce a concept once, before sections that need it. Frame options by purpose (what each is for, and for whom). +- **Plain language:** Say what happens. Leave out decision history and internal jargon ("never merged by location"), error codes the output already shows, restatements of the sentence before, and "implications" the reader can work out. Label a recommendation as a recommendation. +- **README stays short:** A README section is a sentence or two that points to docs/. Setup mechanics, failure behaviour and edge cases go in docs/. +- **Skills and references:** Every line is an action or a fact the agent lacks. Cut instructions the next command makes redundant, and do not state what command output already says. Do not over-constrain capable models with rules for situations they handle. The `description` uses the words a user or agent would use, naming structured-context (sctx) and the task in plain terms. `SKILL.md` holds the common path; detail goes in `references/` or `sctx docs`. Prefer a skill to a slash command, since the two are interchangeable. - **Front-load the happy path:** Quick starts give the fewest steps that run. Tuning, alternatives and edge cases come after. ## Key Files diff --git a/README.md b/README.md index 2bf80cf3..6a1c752a 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,8 @@ claude plugin marketplace add mindsocket/structured-context claude plugin install structured-context ``` +Ask Claude to set up a space (or run `/setup-space`) in the folder that holds your notes. The plugin's hooks need Bun. + Skills can also be installed standalone without the plugin: ``` @@ -89,7 +91,7 @@ See [docs/concepts.md](docs/concepts.md) (`sctx docs concepts`) for terminology: ## Configuration -The config file maps space names to paths and schemas, with optional plugin settings. It is found from `--config`, then `$SCTX_CONFIG`, then `$XDG_CONFIG_HOME/structured-context/config.json` (default `~/.config/...`), then `./config.json`. Paths resolve relative to the config file, and `includeSpacesFrom` pulls in spaces from other config files. +The config file maps space names to paths and schemas, with optional plugin settings. It is found from `--config`, then `$SCTX_CONFIG`, then the nearest `.sctx.json` walking up from the working directory, then `$XDG_CONFIG_HOME/structured-context/config.json` (default `~/.config/...`). Paths resolve relative to the config file, and `includeSpacesFrom` pulls in spaces from other config files. See `config.example.json` and [docs/config.md](docs/config.md) (`sctx docs config`) for the full reference, including `fieldMap`, `typeInference`, templates, filter views and plugin loading. diff --git a/docs/architecture.md b/docs/architecture.md index 142cfbff..6a75aa07 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -14,7 +14,7 @@ The following diagram shows the high-level flow from configuration and source fi ```mermaid flowchart LR - config([config.json
space definition]) + config([.sctx.json or config.json
space definition]) schema[(Schema
json-schema/JSON5)] space[(Space
directory or file)] diff --git a/docs/concepts.md b/docs/concepts.md index 52060fae..6d27b349 100644 --- a/docs/concepts.md +++ b/docs/concepts.md @@ -10,7 +10,7 @@ This document is the canonical reference for concepts and terminology used in th ## Space -A **space** is a named collection of nodes organised according to a schema. Spaces are the primary unit of organisation — a space has a backing format (a `space directory` or a `space on a page` file) and may be registered in `config.json` with a name for convenient access. +A **space** is a named collection of nodes organised according to a schema. Spaces are the primary unit of organisation — a space has a backing format (a `space directory` or a `space on a page` file) and may be registered in a config file (`.sctx.json` or the global `config.json`) with a name for convenient access. ```mermaid flowchart TD diff --git a/docs/config.md b/docs/config.md index 31eabaac..762f08fa 100644 --- a/docs/config.md +++ b/docs/config.md @@ -6,13 +6,30 @@ title: "Configuration Reference" ## Config file location -structured-context looks for its config file in this order: +structured-context uses the first config file it finds, in this order: -1. `$SCTX_CONFIG` — explicit path override -2. `~/.config/structured-context/config.json` (or `$XDG_CONFIG_HOME/structured-context/config.json`) -3. `./config.json` in the current working directory +1. `--config ` +2. `$SCTX_CONFIG` +3. The nearest `.sctx.json`, looking in the working directory and then each parent folder +4. `~/.config/structured-context/config.json` (or `$XDG_CONFIG_HOME/structured-context/config.json`) -See `config.example.json` for the full structure. Paths in config files are resolved relative to the config file. +It is recommended to keep a `.sctx.json` at the base of the notes it describes (for example the root of an Obsidian vault), or to use the global config. The CLI and agent sessions look in parent folders only, so run commands from inside the folder that holds the config. To use the spaces from another config file too, list it in `includeSpacesFrom`. + +Paths in a config file are relative to the folder that holds that file. In a `.sctx.json` at a vault root, `"path": "."` is the whole vault and `"path": "notes"` is one folder. + +`sctx spaces` shows which config file is used and reports problems with it. `sctx spaces --json` returns the same information for tools and hooks. + +### Adding a space + +```bash +sctx spaces add wiki notes --schema knowledge_wiki.json +``` + +This adds the space to the config file found from the working directory, or to the one named with `--config`. When no `.sctx.json` is found, or only the global config exists, pass `--config /.sctx.json` (creates the file) or `--global`. If the config file has comments or trailing commas, the command prints the entry to add by hand. + +Custom schemas can sit anywhere. Reference them by relative path, for example `./.sctx/schemas/my_wiki.json`; `.sctx/schemas/` is the suggested folder. + +See `config.example.json` for the full structure. ## Spaces @@ -36,7 +53,7 @@ A space is a named directory or single file registered in the config. Example: - A plugin schema prefixed with the plugin name (e.g. `sctx-wardley-mapping/wardley_map.json` or `wardley-mapping/wardley_map.json`). Specifying a plugin-prefixed schema automatically loads that plugin for the space. - A simple filename (e.g. `wardley_map.json`) provided by a plugin explicitly declared under `plugins`. -**`includeSpacesFrom`** — import space definitions from other config files. Useful for aggregating spaces from multiple projects into a central config. Duplicate space names are not allowed. +**`includeSpacesFrom`** — import space definitions from other config files, for example a shared team config or your global config (`"~/.config/structured-context/config.json"`; a leading `~` is expanded). A space defined in the including file overrides an included space of the same name; between includes, later entries win. Only `spaces` are taken from an included file. A config must define at least one of `spaces` or `includeSpacesFrom`. When using `includeSpacesFrom` alone, `spaces` can be omitted entirely. diff --git a/docs/use-cases.md b/docs/use-cases.md index d342174f..30530494 100644 --- a/docs/use-cases.md +++ b/docs/use-cases.md @@ -64,6 +64,7 @@ A catalog of use cases for structured-context, covering both direct CLI usage an | Use case | Description | Status | Coverage | |---|---|---|---| +| **Set up a space** | Find structured content in a folder, choose a schema, write the config and make a first validated edit | agent | `/setup-space` skill · `sctx spaces add` · `sctx spaces` reports config problems with codes | | **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 | — | diff --git a/hook-test/unit/preflight.test.ts b/hook-test/unit/preflight.test.ts new file mode 100644 index 00000000..a272c63d --- /dev/null +++ b/hook-test/unit/preflight.test.ts @@ -0,0 +1,161 @@ +/** + * Unit tests for plugin/scripts/preflight.ts and safe.ts + * + * Tests call runPreflight() directly, with the real CLI as a subprocess. + */ + +import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { runOnPrompt } from '../../plugin/scripts/on-prompt'; +import { runPreflight } from '../../plugin/scripts/preflight'; +import { runSafely } from '../../plugin/scripts/safe'; +import { loadState, sctxCommand, 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-preflight-state-${crypto.randomUUID()}`); + sessionId = crypto.randomUUID(); +}); + +afterEach(() => { + fixtures.cleanup(); + rmSync(stateDir, { recursive: true, force: true }); +}); + +const opts = () => ({ stateDir, sctxBin: SCTX_BIN, configPath: fixtures.configPath }); + +describe('runPreflight', () => { + it('tells the agent which spaces apply when the config is healthy', async () => { + const result = await runPreflight({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + + expect(result.systemMessage).toBeUndefined(); + expect(result.additionalContext).toContain('test-space'); + }); + + it('says nothing when no space relates to the directory', async () => { + const unrelated = join(tmpdir(), `ost-preflight-unrelated-${crypto.randomUUID()}`); + + const result = await runPreflight({ session_id: sessionId, cwd: unrelated }, opts()); + + expect(result).toEqual({}); + }); + + it('says nothing when there is no config', async () => { + const dir = join(fixtures.fixtureDir, 'empty'); + mkdirSync(dir, { recursive: true }); + const noConfig = { stateDir, sctxBin: SCTX_BIN, configPath: undefined }; + const saved = { SCTX_CONFIG: process.env.SCTX_CONFIG, XDG: process.env.XDG_CONFIG_HOME }; + delete process.env.SCTX_CONFIG; + process.env.XDG_CONFIG_HOME = join(fixtures.fixtureDir, 'xdg'); + try { + const result = await runPreflight({ session_id: sessionId, cwd: dir }, noConfig); + + expect(result).toEqual({}); + } finally { + if (saved.SCTX_CONFIG !== undefined) process.env.SCTX_CONFIG = saved.SCTX_CONFIG; + if (saved.XDG !== undefined) process.env.XDG_CONFIG_HOME = saved.XDG; + else delete process.env.XDG_CONFIG_HOME; + } + }); + + it('reports a moved space path with its code and a fix', async () => { + rmSync(fixtures.vaultDir, { recursive: true, force: true }); + + const result = await runPreflight({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + + expect(result.systemMessage).toContain('E_SPACE_PATH_MISSING'); + expect(result.additionalContext).toContain('Fix:'); + expect(result.additionalContext).toContain('Troubleshooting'); + }); + + it('reports an unreadable config', async () => { + writeFileSync(fixtures.configPath, '{ not json'); + + const result = await runPreflight({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + + expect(result.systemMessage).toContain('E_CONFIG_INVALID'); + }); + + it('reports a CLI that cannot run', async () => { + const result = await runPreflight( + { session_id: sessionId, cwd: fixtures.fixtureDir }, + { ...opts(), sctxBin: join(fixtures.fixtureDir, 'does-not-exist.ts') }, + ); + + expect(result.systemMessage).toContain('E_SCTX_UNAVAILABLE'); + }); + + it('reports a CLI older than the plugin expects', async () => { + const old = join(fixtures.fixtureDir, 'old-sctx.ts'); + writeFileSync(old, 'console.log(JSON.stringify({ configFiles: [], spaces: [] }));'); + + const result = await runPreflight({ session_id: sessionId, cwd: fixtures.fixtureDir }, { ...opts(), sctxBin: old }); + + expect(result.systemMessage).toContain('E_SCTX_OUTDATED'); + }); +}); + +describe('other hooks stay quiet when setup is broken', () => { + it('on-prompt writes no state and does not throw for a broken config', async () => { + writeFileSync(fixtures.configPath, '{ not json'); + + await runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + + expect(loadState(stateFilePath(sessionId, opts())).baseline).toEqual({}); + }); + + it('on-prompt recovers once the config is fixed, without a new session', async () => { + const good = await Bun.file(fixtures.configPath).text(); + writeFileSync(fixtures.configPath, '{ not json'); + await runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + + writeFileSync(fixtures.configPath, good); + await runOnPrompt({ session_id: sessionId, cwd: fixtures.fixtureDir }, opts()); + + expect(Object.keys(loadState(stateFilePath(sessionId, opts())).baseline)).toEqual(['test-space']); + }); +}); + +describe('runSafely', () => { + it('turns an error into one message per session and does not rethrow', async () => { + const saved = process.env.SCTX_STATE_DIR; + process.env.SCTX_STATE_DIR = stateDir; + const lines: string[] = []; + const log = console.log; + console.log = (line: string) => lines.push(line); + try { + const fail = async () => { + throw new Error('boom\nstack line'); + }; + await runSafely('on-prompt', () => sessionId, fail); + await runSafely('on-prompt', () => sessionId, fail); + } finally { + console.log = log; + if (saved === undefined) delete process.env.SCTX_STATE_DIR; + else process.env.SCTX_STATE_DIR = saved; + } + + expect(lines).toHaveLength(1); + expect(JSON.parse(lines[0]!).systemMessage).toContain('E_HOOK_FAILED'); + expect(lines[0]).not.toContain('stack line'); + }); +}); + +describe('sctxCommand', () => { + const none = () => null; + + it('prefers an explicit entry point, then an installed sctx, then bunx pinned to the release line', () => { + expect(sctxCommand({ sctxBin: '/x/index.ts' }, () => '/usr/bin/sctx')).toEqual(['bun', 'run', '/x/index.ts']); + expect(sctxCommand({}, () => '/usr/bin/sctx')).toEqual(['/usr/bin/sctx']); + expect(sctxCommand({}, none)).toEqual(['bunx', expect.stringMatching(/^structured-context@\d+\.\d+$/)]); + }); +}); diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 931a766c..dc30ad1c 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "structured-context", - "version": "0.14.0", + "version": "0.14.7", "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 1ad26013..be10dffc 100644 --- a/plugin/hooks/hooks.json +++ b/plugin/hooks/hooks.json @@ -1,11 +1,22 @@ { "hooks": { + "SessionStart": [ + { + "hooks": [ + { + "type": "command", + "command": "command -v bun >/dev/null 2>&1 || { echo '{\"systemMessage\":\"structured-context: validation hooks are inactive (E_NO_BUN). Bun is not installed or not on the PATH. Install it from https://bun.sh, then start a new session.\",\"hookSpecificOutput\":{\"hookEventName\":\"SessionStart\",\"additionalContext\":\"structured-context hooks are inactive because Bun is not installed (E_NO_BUN). Fix: install Bun from https://bun.sh and start a new session. Help the user with this when they ask or when it blocks their work.\"}}'; exit 0; }; exec bun run \"${CLAUDE_PLUGIN_ROOT}/scripts/preflight.ts\"", + "timeout": 30 + } + ] + } + ], "UserPromptSubmit": [ { "hooks": [ { "type": "command", - "command": "bun run ${CLAUDE_PLUGIN_ROOT}/scripts/on-prompt.ts", + "command": "command -v bun >/dev/null 2>&1 || exit 0; exec bun run \"${CLAUDE_PLUGIN_ROOT}/scripts/on-prompt.ts\"", "timeout": 60 } ] @@ -18,13 +29,13 @@ { "if": "Write(*.md)", "type": "command", - "command": "bun run ${CLAUDE_PLUGIN_ROOT}/scripts/pre-edit.ts", + "command": "command -v bun >/dev/null 2>&1 || exit 0; exec bun run \"${CLAUDE_PLUGIN_ROOT}/scripts/pre-edit.ts\"", "timeout": 60 }, { "if": "Edit(*.md)", "type": "command", - "command": "bun run ${CLAUDE_PLUGIN_ROOT}/scripts/pre-edit.ts", + "command": "command -v bun >/dev/null 2>&1 || exit 0; exec bun run \"${CLAUDE_PLUGIN_ROOT}/scripts/pre-edit.ts\"", "timeout": 60 } ] @@ -35,7 +46,7 @@ "hooks": [ { "type": "command", - "command": "bun run ${CLAUDE_PLUGIN_ROOT}/scripts/on-stop.ts", + "command": "command -v bun >/dev/null 2>&1 || exit 0; exec bun run \"${CLAUDE_PLUGIN_ROOT}/scripts/on-stop.ts\"", "timeout": 60 } ] @@ -46,7 +57,7 @@ "hooks": [ { "type": "command", - "command": "bun run ${CLAUDE_PLUGIN_ROOT}/scripts/on-session-end.ts" + "command": "command -v bun >/dev/null 2>&1 || exit 0; exec bun run \"${CLAUDE_PLUGIN_ROOT}/scripts/on-session-end.ts\"" } ] } diff --git a/plugin/scripts/on-prompt.ts b/plugin/scripts/on-prompt.ts index be316be0..502fc222 100644 --- a/plugin/scripts/on-prompt.ts +++ b/plugin/scripts/on-prompt.ts @@ -5,6 +5,7 @@ * (e.g. the turn was interrupted), so its changes are still compared at the next Stop. */ +import { runSafely } from './safe'; import { contains, type HookOptions, listSpaces, loadState, recordBaselines, saveState, stateFilePath } from './state'; export interface OnPromptInput { @@ -16,6 +17,7 @@ export async function runOnPrompt(input: OnPromptInput, options?: HookOptions): if (!input.cwd) return; const CWD = input.cwd; + options = { ...options, cwd: 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; @@ -28,13 +30,17 @@ export async function runOnPrompt(input: OnPromptInput, options?: HookOptions): } async function main() { - const INPUT = JSON.parse(await Bun.stdin.text()) as OnPromptInput; - await runOnPrompt(INPUT); + let input: OnPromptInput = {}; + await runSafely( + 'on-prompt', + () => input.session_id, + async () => { + 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); - }); + await main(); } diff --git a/plugin/scripts/on-session-end.ts b/plugin/scripts/on-session-end.ts index 2d9c3ac5..d0fb050a 100644 --- a/plugin/scripts/on-session-end.ts +++ b/plugin/scripts/on-session-end.ts @@ -9,5 +9,9 @@ export function runOnSessionEnd(input: { session_id?: string }, options?: HookOp } if (import.meta.main) { - runOnSessionEnd(JSON.parse(await Bun.stdin.text())); + try { + runOnSessionEnd(JSON.parse(await Bun.stdin.text())); + } catch { + // Nothing to clean up that matters; never fail the session end + } } diff --git a/plugin/scripts/on-stop.ts b/plugin/scripts/on-stop.ts index aeed104a..3992a96a 100755 --- a/plugin/scripts/on-stop.ts +++ b/plugin/scripts/on-stop.ts @@ -5,6 +5,7 @@ */ import { join } from 'node:path'; +import { warnOnce } from './safe'; import { type HookOptions, hashSpace, @@ -20,6 +21,7 @@ import { export interface OnStopInput { session_id?: string; stop_hook_active?: boolean; + cwd?: string; } export interface OnStopResult { @@ -47,6 +49,7 @@ export async function runOnStop(input: OnStopInput, options?: HookOptions): Prom return { hasNewErrors: false }; } + options = { ...options, cwd: input.cwd ?? options?.cwd }; const { configFiles, spaces } = await listSpaces(options); const newErrors: string[] = []; @@ -113,9 +116,22 @@ export async function runOnStop(input: OnStopInput, options?: HookOptions): Prom } async function main() { - const INPUT_TEXT = await Bun.stdin.text(); - const INPUT = JSON.parse(INPUT_TEXT) as OnStopInput; - const result = await runOnStop(INPUT); + let input: OnStopInput = {}; + let result: OnStopResult; + try { + input = JSON.parse(await Bun.stdin.text()) as OnStopInput; + result = await runOnStop(input); + } catch (err) { + // An infrastructure failure never blocks the stop + const detail = (err as Error).message?.split('\n')[0] ?? String(err); + warnOnce( + input.session_id, + 'E_HOOK_FAILED:on-stop', + `structured-context: the on-stop hook failed (E_HOOK_FAILED): ${detail}. Validation for this turn was skipped. The structured-context skill has troubleshooting steps; set SCTX_DEBUG=1 for details.`, + ); + if (process.env.SCTX_DEBUG) console.error(err); + return; + } if (result.hasNewErrors) { // Exit 2 blocks the stop; stderr is fed back to Claude as the reason @@ -132,8 +148,5 @@ async function main() { } if (import.meta.main) { - main().catch((err) => { - console.error(err); - process.exit(1); - }); + await main(); } diff --git a/plugin/scripts/pre-edit.ts b/plugin/scripts/pre-edit.ts index 612d5953..80abd7e4 100755 --- a/plugin/scripts/pre-edit.ts +++ b/plugin/scripts/pre-edit.ts @@ -5,6 +5,7 @@ * edit to such a space this turn baselines the whole space before the change. */ +import { runSafely } from './safe'; import { contains, type HookOptions, listSpaces, loadState, recordBaselines, saveState, stateFilePath } from './state'; export interface PreEditInput { @@ -13,6 +14,7 @@ export interface PreEditInput { file_path?: string; }; session_id?: string; + cwd?: string; } export async function runPreEdit(input: PreEditInput, options?: HookOptions): Promise { @@ -23,21 +25,25 @@ export async function runPreEdit(input: PreEditInput, options?: HookOptions): Pr const state = loadState(STATE_FILE); if (Object.values(state.baseline).some((snap) => contains(snap.path, FILE_PATH))) return; - const { configFiles, spaces } = await listSpaces(options); + const { configFiles, spaces } = await listSpaces({ ...options, cwd: input.cwd ?? options?.cwd }); const containing = spaces.filter((space) => contains(space.path, FILE_PATH)); - if (await recordBaselines(state, containing, configFiles, options)) { + if (await recordBaselines(state, containing, configFiles, { ...options, cwd: input.cwd ?? options?.cwd })) { saveState(STATE_FILE, state); } } async function main() { - const INPUT = JSON.parse(await Bun.stdin.text()) as PreEditInput; - await runPreEdit(INPUT); + let input: PreEditInput = {}; + await runSafely( + 'pre-edit', + () => input.session_id, + async () => { + input = JSON.parse(await Bun.stdin.text()) as PreEditInput; + await runPreEdit(input); + }, + ); } if (import.meta.main) { - main().catch((err) => { - console.error(err); - process.exit(1); - }); + await main(); } diff --git a/plugin/scripts/preflight.ts b/plugin/scripts/preflight.ts new file mode 100644 index 00000000..c5c69c80 --- /dev/null +++ b/plugin/scripts/preflight.ts @@ -0,0 +1,108 @@ +#!/usr/bin/env bun + +/** + * SessionStart hook: check once, for the session's directory, that structured-context can run and + * that its config is usable. Reports a failure to the user and the agent here, so the other hooks + * can stay silent on the same failures. It also tells the agent which spaces apply. With no config it + * says nothing: setting up is something the user asks for. + * + * Content problems (validation errors in notes) are not checked here; the other hooks report those. + */ + +import { runSafely } from './safe'; +import { contains, type HookOptions, parseSpacesOutput, runSctx, type SpacesOutput } from './state'; + +export interface PreflightInput { + session_id?: string; + cwd?: string; +} + +export interface PreflightResult { + /** Shown to the user */ + systemMessage?: string; + /** Added to the agent's context */ + additionalContext?: string; +} + +const TROUBLESHOOTING = "The structured-context skill's Troubleshooting section explains each code."; + +function firstLine(text: string): string { + return text.trim().split('\n')[0] ?? ''; +} + +function unavailable(code: string, message: string, fix: string): PreflightResult { + return { + systemMessage: `structured-context (enabled plugin): validation hooks are inactive (${code}). ${message} ${fix} Disable the plugin to stop this check.`, + additionalContext: `structured-context hooks are inactive for this session. ${code}: ${message} Fix: ${fix} Help the user resolve this when they ask or when it blocks their work. ${TROUBLESHOOTING}`, + }; +} + +export async function runPreflight(input: PreflightInput, options?: HookOptions): Promise { + const run = await runSctx(['spaces', '--json'], { ...options, cwd: input.cwd ?? options?.cwd }); + const detail = firstLine(run.stderr) || `exit code ${run.exitCode}`; + + if (run.exitCode === null || !run.stdout.trim()) { + return unavailable( + 'E_SCTX_UNAVAILABLE', + `Could not run \`${run.command}\` (${detail}).`, + 'Check that Bun is installed and on the PATH and that the network is reachable (bunx downloads structured-context on first use), or install it with `bun install -g structured-context`. Then start a new session.', + ); + } + + const output: SpacesOutput | undefined = parseSpacesOutput(run.stdout); + if (!output?.problems || !output.config) { + return unavailable( + 'E_SCTX_OUTDATED', + 'The installed structured-context is older than this plugin expects.', + 'Update it with `bun install -g structured-context@latest`, then start a new session.', + ); + } + + const errors = output.problems.filter((p) => p.severity === 'error'); + if (errors.length > 0) { + const lines = errors.map((p) => `- ${p.code}: ${p.message}${p.fix ? ` Fix: ${p.fix}` : ''}`).join('\n'); + return { + systemMessage: `structured-context (enabled plugin): validation hooks are inactive (${errors[0]!.code}). ${errors[0]!.message} Disable the plugin to stop this check.`, + additionalContext: `structured-context hooks are inactive for this session because of its configuration (${output.config.path}):\n${lines}\nHelp the user resolve this when they ask or when it blocks their work. ${TROUBLESHOOTING}`, + }; + } + + // Not set up yet is not a failure and not worth interrupting the session for + if (!output.config.exists) return {}; + + const cwd = input.cwd ?? process.cwd(); + const related = output.spaces.filter((space) => contains(cwd, space.path) || contains(space.path, cwd)); + if (output.spaces.length === 0) return {}; + if (related.length === 0) return {}; + + const list = related.map((s) => `${s.name} (${s.path}${s.schema ? `, schema ${s.schema}` : ''})`).join('; '); + return { + additionalContext: `structured-context spaces here: ${list}. Validation runs around your edits to these files and new errors block the turn from finishing. Use the structured-context skill when working on this content.`, + }; +} + +async function main() { + let input: PreflightInput = {}; + await runSafely( + 'preflight', + () => input.session_id, + async () => { + input = JSON.parse(await Bun.stdin.text()) as PreflightInput; + const result = await runPreflight(input); + if (result.systemMessage || result.additionalContext) { + console.log( + JSON.stringify({ + ...(result.systemMessage && { systemMessage: result.systemMessage }), + ...(result.additionalContext && { + hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: result.additionalContext }, + }), + }), + ); + } + }, + ); +} + +if (import.meta.main) { + await main(); +} diff --git a/plugin/scripts/safe.ts b/plugin/scripts/safe.ts new file mode 100644 index 00000000..7a65740f --- /dev/null +++ b/plugin/scripts/safe.ts @@ -0,0 +1,46 @@ +/** + * Failure handling shared by the hooks. A hook that crashes must not break the user's turn or print a + * bare stack trace: it reports one short message per session and exits 0. Only a Stop hook that finds + * genuine new validation errors blocks, and it does that itself. + */ + +import { loadState, saveState, stateFilePath } from './state'; + +/** Print a user-visible warning for a hook (any event accepts `systemMessage`). */ +export function warn(message: string): void { + console.log(JSON.stringify({ systemMessage: message })); +} + +/** Show `message` unless this code was already shown this session. */ +export function warnOnce(sessionId: string | undefined, code: string, message: string): void { + try { + const file = stateFilePath(sessionId); + const state = loadState(file); + if (state.reported?.includes(code)) return; + state.reported = [...(state.reported ?? []), code]; + saveState(file, state); + } catch { + // If the state can't be written, show the message anyway + } + warn(message); +} + +/** Run a hook's main function so that an unexpected error becomes one message and exit code 0. */ +export async function runSafely( + name: string, + sessionId: () => string | undefined, + run: () => Promise, +): Promise { + try { + await run(); + } catch (err) { + const detail = (err as Error).message?.split('\n')[0] ?? String(err); + warnOnce( + sessionId(), + `E_HOOK_FAILED:${name}`, + `structured-context: the ${name} hook failed (E_HOOK_FAILED): ${detail}. Validation for this step was skipped. ` + + 'The structured-context skill has troubleshooting steps; set SCTX_DEBUG=1 for details.', + ); + if (process.env.SCTX_DEBUG) console.error(err); + } +} diff --git a/plugin/scripts/state.ts b/plugin/scripts/state.ts index 945f3190..f96a2ca0 100644 --- a/plugin/scripts/state.ts +++ b/plugin/scripts/state.ts @@ -17,6 +17,8 @@ export interface HookOptions { sctxBin?: string; /** Path to config file. When set, passed as SCTX_CONFIG to the CLI subprocess. */ configPath?: string; + /** Directory the CLI runs in, which is where config discovery starts. Defaults to the hook's own. */ + cwd?: string; } export interface ValidationIssue { @@ -39,6 +41,8 @@ export interface SpaceIssueKeys { } export interface SessionState { + /** Hook failure codes already shown to the user this session, so each is reported once. */ + reported?: string[]; /** 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 */ @@ -51,9 +55,20 @@ export interface SpaceInfo { schema?: string; } -interface SpacesOutput { +export interface ConfigProblem { + code: string; + severity: 'error' | 'warning' | 'info'; + message: string; + fix: string; + space?: string; +} + +export interface SpacesOutput { configFiles: string[]; spaces: SpaceInfo[]; + /** Absent from an sctx that predates config health reporting */ + config?: { path: string; source: string; exists: boolean }; + problems?: ConfigProblem[]; } interface ValidateOutput { @@ -71,7 +86,7 @@ export function stateFilePath(sessionId: string | undefined, options?: HookOptio 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 ?? {} }; + return { baseline: state.baseline ?? {}, latest: state.latest ?? {}, reported: state.reported }; } export function saveState(file: string, state: SessionState): void { @@ -83,23 +98,85 @@ 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; +export interface SctxRun { + stdout: string; + stderr: string; + /** Null when the process could not be started */ + exitCode: number | null; + /** What was run, for messages */ + command: string; +} + +/** + * The structured-context release line this plugin was built with (`major.minor`). The plugin's patch + * number is its own, so only major.minor identifies the matching CLI. + */ +function pluginReleaseLine(): string | undefined { + try { + const manifest = JSON.parse(readFileSync(join(import.meta.dir, '..', '.claude-plugin', 'plugin.json'), 'utf-8')); + const [major, minor] = String(manifest.version).split('.'); + return major && minor ? `${major}.${minor}` : undefined; + } catch { + return undefined; + } +} + +/** + * How to run sctx: an explicit entry point (`sctxBin` or SCTX_BIN), else an installed `sctx` on the + * path, else `bunx` pinned to this plugin's release line so the CLI matches the hooks. + */ +export function sctxCommand(options?: HookOptions, which: (cmd: string) => string | null = Bun.which): string[] { + const bin = options?.sctxBin ?? process.env.SCTX_BIN; + if (bin) return ['bun', 'run', bin]; + const installed = which('sctx'); + if (installed) return [installed]; + const line = pluginReleaseLine(); + return ['bunx', line ? `structured-context@${line}` : 'structured-context']; +} + +/** Run an sctx command from `cwd`. Never throws: a failure to start comes back as `exitCode: null`. */ +export async function runSctx(args: string[], options?: HookOptions): Promise { + const argv = [...sctxCommand(options), ...args]; 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(); + // A missing directory would make the spawn fail with a misleading error about the executable + const cwd = options?.cwd && existsSync(options.cwd) ? options.cwd : undefined; + try { + const proc = Bun.spawn(argv, { env, cwd, stdout: 'pipe', stderr: 'pipe', stdin: 'ignore' }); + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + proc.exited, + ]); + return { stdout, stderr, exitCode, command: argv.join(' ') }; + } catch (err) { + return { stdout: '', stderr: (err as Error).message, exitCode: null, command: argv.join(' ') }; + } +} + +async function sctx(args: string[], options?: HookOptions): Promise { + return (await runSctx(args, options)).stdout; +} + +/** Parse `sctx spaces --json` output, or undefined when it isn't usable. */ +export function parseSpacesOutput(text: string): SpacesOutput | undefined { + try { + const output = JSON.parse(text) as SpacesOutput; + return Array.isArray(output.spaces) && Array.isArray(output.configFiles) ? output : undefined; + } catch { + return undefined; + } } -/** Configured spaces whose path exists, and the config files they came from */ +/** + * Configured spaces whose path exists, and the config files they came from. Any failure to get a + * usable answer returns no spaces: the SessionStart hook is what tells the user about those. + */ 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; + const output = parseSpacesOutput((await runSctx(['spaces', '--json'], options)).stdout); + if (!output) return { configFiles: [], spaces: [] }; return { ...output, spaces: output.spaces.filter((space) => existsSync(space.path)) }; } diff --git a/plugin/skills/setup-space/SKILL.md b/plugin/skills/setup-space/SKILL.md new file mode 100644 index 00000000..e51ea2a1 --- /dev/null +++ b/plugin/skills/setup-space/SKILL.md @@ -0,0 +1,82 @@ +--- +name: setup-space +description: > + Set up structured-context (sctx) for a folder of markdown notes, such as an Obsidian vault: find what the + notes are, choose a schema, add a space to the config and make a first validated edit. Use when the user + wants schema validation or structure for a set of documents, wants to start with structured-context, or + wants to add another space. An argument names the folder or goal to start from. +--- + +# setup-space + +Leave the user with one working space and one edit that stayed valid. Most answers should come from looking +at the content, not from asking. + +## 1. Check the setup + +```bash +sctx spaces --json # config found, spaces valid, problems with codes +``` + +If `sctx` is not installed: `bun install -g structured-context` (needs Bun). For any error in `problems`, use +`../structured-context/references/troubleshooting.md` before going on. Note the existing space names so you do +not reuse one. + +Work from the folder the session opened in; config discovery only looks in parent folders. + +## 2. Get familiar with the content + +Sample rather than read everything. Skip folders that are not notes (attachments, `.obsidian`, archives). + +- Count markdown files per top-level folder, then read the first ~40 lines of about five notes from the one or + two most likely folders, spread across oldest, newest, smallest and largest. +- Look for clues to what kind of documents these are: repeated frontmatter keys (especially a type-like key), + folder and file naming, links between notes, status or provenance fields, templates, and what is in the + headings and body. +- If many folders qualify or nothing stands out, ask what the user wants to do with the content and which + folder to start with. Say what you saw. + +Compare with `sctx schemas list` and `sctx schemas show ` for the likely candidates, reading entity +types as well as names. If none fits, say so and offer the schema design process in +`../structured-context/references/schema-design.md`. + +## 3. Propose one space + +In one message give the space name (lowercase letters, digits, `-`, `_`), the folder, the schema and why, and +what you noticed. Include what configuring involves, including any edits to existing notes to add or change +frontmatter. Ask for a yes or corrections. + +## 4. Add the space + +```bash +sctx spaces add --schema .json +``` + +The first space needs a place to write. Use `--config /.sctx.json` (for an Obsidian +vault, the vault root). Use `--global` only if the user asks. If the command reports that something else needs +specifying, fix it and re-run. Settings such as type inference and field remaps go in the file afterwards (see +`sctx docs config`); edit the JSON directly, then run `sctx spaces` to confirm. + +## 5. First validation + +```bash +sctx validate +``` + +Summarise how many notes are valid and the most common problems. Existing problems do not block anything: the +plugin's hooks only report problems introduced by edits. Notes without a `type` field are noted as ignored, not +failed; adding `type` is usually the first change, before other fields and relationships. If many notes fail for +one reason, it is likely a mapping question (a field with another name) rather than many mistakes. Offer choices +rather than fixing in bulk: leave it, fix a few to see how it works, or adjust the setup. + +## 6. First edit + +Pick something small that fits the user's goal: a new note, or one change to an existing note. Check +`sctx schemas show --space ` for entity types and required fields, make the change, then +`sctx validate-file `. + +## 7. Close + +State what exists: the config path, the space, how checks behave. For an Obsidian vault, mention the optional +plugin (github.com/mindsocket/obsidian-structured-context), which shows the same checks inline. Offer one next +step, such as another space, without starting it. diff --git a/plugin/skills/structured-context/SKILL.md b/plugin/skills/structured-context/SKILL.md index 6237ce2c..eb2878ef 100644 --- a/plugin/skills/structured-context/SKILL.md +++ b/plugin/skills/structured-context/SKILL.md @@ -1,10 +1,8 @@ --- name: structured-context description: > - Use this skill when editing structured markdown content in Obsidian to ensure it conforms to a - schema, or when authoring or debugging schemas. Trigger when: (1) content needs validating after - edits, (2) schema files or rules need creating or updating, (3) configuring or designing a schema - for a space, (4) troubleshooting unexpected validation errors, (5) running structured-context CLI commands. + Use when working with structured-context (sctx): validating markdown content after edits, authoring or + debugging schemas and rules, running sctx commands, or troubleshooting validation and setup errors. --- # structured-context @@ -23,19 +21,11 @@ The plugin version is listed in `plugin/.claude-plugin/plugin.json`. A match on If not installed, run `bun install -g structured-context` -## Finding the config +## Config -structured-context looks in `$XDG_CONFIG_HOME/structured-context/config.json`, unless given an explicit config, e.g.: - -```bash -sctx validate --config path/to/config.json -# or -SCTX_CONFIG=path/to/config.json sctx validate -``` - -**Always read the config first** to understand available spaces and their schema locations before running other commands. - -Tip: To reduce the need for `--config` flags consider, with user permission, using `includeSpacesFrom` in a central config file that's loaded by default (eg `~/.config/structured-context/config.json`). +**Always read the config first** with `sctx spaces`: it shows the config in use, its spaces and any problems, each with a +code (see `references/troubleshooting.md`). `sctx docs config` covers config discovery and `sctx spaces add`. If +there is no config yet, use the setup-space skill. ## Orientation @@ -141,5 +131,6 @@ sctx docs config - **`references/schema-authoring.md`** — schema file structure, `$metadata`, rules (expression and semantic) (run `sctx docs schema` for schema dialect reference) - **`references/schema-design.md`** — process for designing a schema from existing content +- **`references/troubleshooting.md`** — error codes from `sctx spaces` and the hooks, with the fix for each For CLI and config reference, use `sctx docs ` (topics: `concepts`, `config`, `schema`, `rules`, `semantic-rules`). diff --git a/plugin/skills/structured-context/references/troubleshooting.md b/plugin/skills/structured-context/references/troubleshooting.md new file mode 100644 index 00000000..fb279362 --- /dev/null +++ b/plugin/skills/structured-context/references/troubleshooting.md @@ -0,0 +1,21 @@ +# Troubleshooting by error code + +Error output from `sctx spaces`, the session start check and the hooks already says what is wrong and a fix. +This adds only what the message does not. After fixing, re-check with `sctx spaces --json`; `problems` should be +empty or `info` only. Hooks pick up a fixed config on the next prompt. A missing tool needs a new session. + +| Code | Beyond the message | +|---|---| +| `E_NO_BUN` | `command -v bun`. Install from https://bun.sh | +| `E_SCTX_UNAVAILABLE` | Run `sctx --version` and `bunx structured-context --version` and read the error. First use of `bunx` needs the network | +| `E_SCTX_OUTDATED` | The major.minor of `sctx --version` should match the plugin's version in `plugin/.claude-plugin/plugin.json` | +| `E_CONFIG_NOT_FOUND` | At `info` level, nothing is set up: use the setup-space skill. As an error, `--config` or `$SCTX_CONFIG` points at a missing file: correct the path or unset the variable | +| `E_TARGET_REQUIRED` | Ask where the config belongs. Usually `--config /.sctx.json`; `--global` only if the user asks | +| `E_HOOK_FAILED` | A hook crashed and was skipped. Set `SCTX_DEBUG=1` for the session, or run the same `sctx` command by hand. Usually a problem with its own code above | + +Other codes (`E_CONFIG_INVALID`, `E_INCLUDE_NOT_FOUND`, `E_NO_SPACES`, `E_SPACE_PATH_MISSING`, `E_SCHEMA_*`, +`E_SPACE_EXISTS`, `E_CONFIG_NEEDS_MANUAL_EDIT`) carry their fix in the message. Do not edit the user's notes to +get around a setup problem. + +If edits are not being checked and nothing says why, run `sctx spaces --json` from the session's folder. A config +that is only in a folder below it will not be found. diff --git a/src/api.ts b/src/api.ts index 93628583..f675ea65 100644 --- a/src/api.ts +++ b/src/api.ts @@ -20,8 +20,9 @@ export type { AnySchemaObject, SchemaObject, ValidateFunction } from 'ajv'; export type { Config, SpaceConfig } from './config'; -export { loadConfig, resolveSchema, resolveSchemaPath, setConfigPath } from './config'; -export { PLUGIN_PREFIX } from './constants'; +export { loadConfig, resolveConfigPath, resolveSchema, resolveSchemaPath, setConfigPath } from './config'; +export { addSpace } from './config/write'; +export { LOCAL_CONFIG_FILE, PLUGIN_PREFIX } from './constants'; export { assembleSpaceGraph, loadSpaceGraph } from './load-space-graph'; export type { ParseHook, diff --git a/src/commands/spaces.ts b/src/commands/spaces.ts index 876b717f..362abea7 100644 --- a/src/commands/spaces.ts +++ b/src/commands/spaces.ts @@ -1,5 +1,8 @@ import { basename, resolve } from 'node:path'; -import { configPath, getConfigSourceFiles, loadConfig } from '../config'; +import { loadConfig } from '../config'; +import { checkConfig, hasBlockingProblem } from '../config/health'; +import { addSpace } from '../config/write'; +import { SctxError } from '../errors'; function renderConfigValue(v: unknown): string { if (typeof v === 'object' && v !== null) return JSON.stringify(v); @@ -7,18 +10,25 @@ function renderConfigValue(v: unknown): string { } export function listSpaces(options: { json?: boolean } = {}): void { - const path = resolve(configPath()); - const config = loadConfig(); + const health = checkConfig(); 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 })); + console.log(JSON.stringify(health)); + if (hasBlockingProblem(health)) process.exitCode = 1; return; } - console.log(`Config: ${path}\n`); + const path = resolve(health.config.path); + if (health.problems.length > 0) { + console.log(`Config: ${path} (${health.config.source}${health.config.exists ? '' : ', not found'})\n`); + for (const p of health.problems) { + console.log(`${p.severity.toUpperCase()} ${p.code}: ${p.message}`); + if (p.fix) console.log(` fix: ${p.fix}`); + } + console.log(''); + if (hasBlockingProblem(health)) process.exitCode = 1; + if (!health.config.exists) return; + } + const config = loadConfig(); + if (health.problems.length === 0) console.log(`Config: ${path} (${health.config.source})\n`); for (const space of config.spaces) { console.log(`${space.name}`); console.log(` path: ${space.path}`); @@ -42,3 +52,25 @@ export function listSpaces(options: { json?: boolean } = {}): void { console.log(''); } } + +export function addSpaceCommand( + name: string, + path: string, + options: { schema?: string; global?: boolean; json?: boolean }, +): void { + try { + const result = addSpace({ name, path, schema: options.schema, global: options.global }); + if (options.json) { + console.log(JSON.stringify(result)); + return; + } + console.log(`${result.created ? 'Created' : 'Updated'} ${result.configPath}`); + console.log(`Added space "${result.space.name}" (path: ${result.space.path})`); + } catch (err) { + if (!(err instanceof SctxError)) throw err; + const hint = err.code === 'E_TARGET_REQUIRED' ? ' Use --config /.sctx.json or --global.' : ''; + if (options.json) console.log(JSON.stringify({ error: { code: err.code, message: err.message + hint } })); + else console.error(`${err.code}: ${err.message}${hint}`); + process.exitCode = 1; + } +} diff --git a/src/config/health.ts b/src/config/health.ts new file mode 100644 index 00000000..1e683f97 --- /dev/null +++ b/src/config/health.ts @@ -0,0 +1,128 @@ +import { existsSync, readFileSync } from 'node:fs'; +import JSON5 from 'json5'; +import { LOCAL_CONFIG_FILE } from '../constants'; +import { SctxError, type SctxErrorCode } from '../errors'; +import { getConfigSourceFiles, loadConfig, type ResolvedConfigPath, resolveConfigPath, resolveSchema } from '.'; + +export type ConfigProblem = { + code: SctxErrorCode; + severity: 'error' | 'warning' | 'info'; + message: string; + fix: string; + space?: string; +}; + +export type ConfigHealth = { + config: ResolvedConfigPath & { exists: boolean }; + configFiles: string[]; + spaces: { name: string; path: string; schema?: string }[]; + problems: ConfigProblem[]; +}; + +const FIXES: Partial> = { + E_CONFIG_NOT_FOUND: `Create a config with \`sctx spaces add --schema --config /${LOCAL_CONFIG_FILE}\`, or use the setup-space skill.`, + E_CONFIG_INVALID: 'Fix the JSON in the config file named in the message; `sctx docs config` describes the shape.', + E_INCLUDE_NOT_FOUND: 'Correct or remove the missing path in `includeSpacesFrom`.', + E_NO_SPACES: 'Add a space with `sctx spaces add`.', + E_SPACE_PATH_MISSING: 'The folder or file was moved or deleted. Correct `path` in the config, or remove the space.', + E_SCHEMA_MISSING: 'Set `schema` on the space or at the top level of the config file.', + E_SCHEMA_NOT_FOUND: 'Check the schema name or path. `sctx schemas list` shows the bundled schemas.', + E_SCHEMA_INVALID: 'The schema file is not valid JSON5. Open it and fix the syntax.', +}; + +export function fixFor(code: SctxErrorCode): string { + return FIXES[code] ?? ''; +} + +function problem( + code: SctxErrorCode, + severity: ConfigProblem['severity'], + message: string, + space?: string, +): ConfigProblem { + return { code, severity, message, fix: fixFor(code), ...(space ? { space } : {}) }; +} + +/** + * Check that the config for the working directory can be found and loaded, and that each space's + * path and schema exist. Never throws: every failure becomes a problem with a stable code. + */ +export function checkConfig(options: { startDir?: string } = {}): ConfigHealth { + const resolved = resolveConfigPath(options.startDir); + const exists = existsSync(resolved.path); + const health: ConfigHealth = { config: { ...resolved, exists }, configFiles: [], spaces: [], problems: [] }; + + if (!exists) { + const detail = + resolved.source === 'none' + ? `No ${LOCAL_CONFIG_FILE} found from the working directory upward, and no global config at ${resolved.path}` + : `Config file not found: ${resolved.path}`; + health.problems.push(problem('E_CONFIG_NOT_FOUND', resolved.source === 'none' ? 'info' : 'error', detail)); + return health; + } + + let config: ReturnType; + try { + config = loadConfig({ startDir: options.startDir }); + } catch (err) { + const code = err instanceof SctxError ? err.code : 'E_CONFIG_INVALID'; + health.problems.push(problem(code, 'error', (err as Error).message)); + return health; + } + health.configFiles = [...getConfigSourceFiles()]; + health.spaces = config.spaces.map((s) => ({ name: s.name, path: s.path, schema: s.schema ?? config.schema })); + + if (config.spaces.length === 0) { + health.problems.push(problem('E_NO_SPACES', 'warning', `Config ${resolved.path} defines no spaces`)); + } + + for (const space of config.spaces) { + if (!existsSync(space.path)) { + health.problems.push( + problem( + 'E_SPACE_PATH_MISSING', + 'error', + `Space "${space.name}" path does not exist: ${space.path}`, + space.name, + ), + ); + } + const schemaRef = space.schema ?? config.schema; + if (!schemaRef) { + health.problems.push(problem('E_SCHEMA_MISSING', 'error', `Space "${space.name}" has no schema`, space.name)); + continue; + } + let schemaPath: string; + try { + schemaPath = resolveSchema(config, space); + } catch (err) { + health.problems.push(problem('E_SCHEMA_NOT_FOUND', 'error', (err as Error).message, space.name)); + continue; + } + if (/^https?:\/\//i.test(schemaPath)) continue; + if (!existsSync(schemaPath)) { + health.problems.push( + problem('E_SCHEMA_NOT_FOUND', 'error', `Space "${space.name}" schema not found: ${schemaPath}`, space.name), + ); + continue; + } + try { + JSON5.parse(readFileSync(schemaPath, 'utf-8')); + } catch (err) { + health.problems.push( + problem( + 'E_SCHEMA_INVALID', + 'error', + `Space "${space.name}" schema ${schemaPath} is not valid: ${(err as Error).message}`, + space.name, + ), + ); + } + } + return health; +} + +/** True when the health check found something that stops validation from running. */ +export function hasBlockingProblem(health: ConfigHealth): boolean { + return health.problems.some((p) => p.severity === 'error'); +} diff --git a/src/config.ts b/src/config/index.ts similarity index 74% rename from src/config.ts rename to src/config/index.ts index 315727c8..a42c98c0 100644 --- a/src/config.ts +++ b/src/config/index.ts @@ -1,17 +1,18 @@ -import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { dirname, isAbsolute, join, resolve } from 'node:path'; import Ajv2020 from 'ajv/dist/2020'; import JSON5 from 'json5'; -import { ENV_CONFIG_VAR, XDG_CONFIG_DIR } from './constants'; -import { type JudgeConfig, MODEL_PROVIDER_APIS, type ModelProviderConfig } from './judge/types'; +import { ENV_CONFIG_VAR, LOCAL_CONFIG_FILE, XDG_CONFIG_DIR } from '../constants'; +import { SctxError } from '../errors'; +import { type JudgeConfig, MODEL_PROVIDER_APIS, type ModelProviderConfig } from '../judge/types'; import { normalizePluginName, resolvePluginSchemasDir, resolveSpacePluginSchemas, shortenPluginName, -} from './plugins/util'; -import { bundledSchemasDir } from './schema/schema'; +} from '../plugins/util'; +import { bundledSchemasDir } from '../schema/schema'; const MODEL_PROVIDER_SCHEMA = { type: 'object', @@ -115,23 +116,43 @@ export function getConfigSourceFiles(): Set { return new Set(_spaceSourceFiles.values()); } -export function configPath(): string { - if (_configPathOverride) { - return _configPathOverride; - } - if (process.env[ENV_CONFIG_VAR]) { - return process.env[ENV_CONFIG_VAR]!; - } +/** How the config file was found. `none` means nothing exists and `path` is where the global file would go. */ +export type ConfigSource = 'override' | 'env' | 'local' | 'global' | 'none'; + +export type ResolvedConfigPath = { path: string; source: ConfigSource }; + +/** Path of the global config file, whether or not it exists. */ +export function globalConfigPath(): string { const xdgBase = process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'); - const xdgPath = join(xdgBase, XDG_CONFIG_DIR, 'config.json'); - if (existsSync(xdgPath)) { - return xdgPath; - } - const cwdPath = join(process.cwd(), 'config.json'); - if (existsSync(cwdPath)) { - return cwdPath; + return join(xdgBase, XDG_CONFIG_DIR, 'config.json'); +} + +function findLocalConfig(startDir: string): string | undefined { + let dir = resolve(startDir); + for (;;) { + const candidate = join(dir, LOCAL_CONFIG_FILE); + if (existsSync(candidate) && statSync(candidate).isFile()) return candidate; + const parent = dirname(dir); + if (parent === dir) return undefined; + dir = parent; } - return xdgPath; +} + +/** + * Find the config file. Precedence: explicit override (`--config`), `$SCTX_CONFIG`, the nearest + * `.sctx.json` walking up from `startDir` (default: the working directory), then the global file. + */ +export function resolveConfigPath(startDir: string = process.cwd()): ResolvedConfigPath { + if (_configPathOverride) return { path: _configPathOverride, source: 'override' }; + if (process.env[ENV_CONFIG_VAR]) return { path: process.env[ENV_CONFIG_VAR]!, source: 'env' }; + const local = findLocalConfig(startDir); + if (local) return { path: local, source: 'local' }; + const global = globalConfigPath(); + return { path: global, source: existsSync(global) ? 'global' : 'none' }; +} + +export function configPath(startDir?: string): string { + return resolveConfigPath(startDir).path; } function normalizePlugins( @@ -171,50 +192,72 @@ function resolveRelativePaths(config: Config, configDir: string): Config { function _loadConfig(path: string): Config { if (!existsSync(path)) { - throw new Error(`Config file not found: ${path}`); + throw new SctxError('E_CONFIG_NOT_FOUND', `Config file not found: ${path}`); } - const config = JSON5.parse(readFileSync(path, 'utf-8')); + let config: unknown; + try { + config = JSON5.parse(readFileSync(path, 'utf-8')); + } catch (err) { + throw new SctxError('E_CONFIG_INVALID', `Invalid config in ${path}: ${(err as Error).message}`); + } const ajv = new Ajv2020(); const validate = ajv.compile(CONFIG_SCHEMA); if (!validate(config)) { - throw new Error(`Invalid config in ${path}: ${JSON.stringify(validate.errors)}`); + throw new SctxError('E_CONFIG_INVALID', `Invalid config in ${path}: ${JSON.stringify(validate.errors)}`); } - if (!config.spaces) config.spaces = []; - return config as unknown as Config; + const parsed = config as unknown as Config; + if (!parsed.spaces) parsed.spaces = []; + return parsed; +} + +function expandHome(p: string): string { + return p === '~' || p.startsWith('~/') ? join(process.env.HOME ?? homedir(), p.slice(1)) : p; } -export function loadConfig(): Config { - const path = configPath(); +export function loadConfig(options: { startDir?: string } = {}): Config { + const { path, source } = resolveConfigPath(options.startDir); if (!existsSync(path)) { - console.warn(`Config file not found: ${path}`); + const where = + source === 'none' + ? `no ${LOCAL_CONFIG_FILE} found from ${resolve(options.startDir ?? process.cwd())} upward, and none at ${path}` + : path; + console.warn(`E_CONFIG_NOT_FOUND: Config file not found (${where})`); return { spaces: [] }; } const config = _loadConfig(path); _spaceSourceFiles.clear(); // Track which spaces come from the main config file const mainSourceDir = dirname(resolve(path)); + const ownNames = new Set(config.spaces.map((s) => s.name)); for (const space of config.spaces) { _spaceSourceFiles.set(space.name, path); space.sourceDir = mainSourceDir; } - // Load includeSpacesFrom configs and merge their spaces in, with later entries taking precedence over earlier ones + // Merge includeSpacesFrom configs. A space defined in the including file wins over an included one + // of the same name; between includes, later entries win over earlier ones. if (config.includeSpacesFrom) { for (const includePath of config.includeSpacesFrom) { // Resolve relative to the main config file - const resolvedIncludePath = isAbsolute(includePath) ? includePath : resolve(dirname(path), includePath); - const includedConfig = resolveRelativePaths(_loadConfig(resolvedIncludePath), dirname(resolvedIncludePath)); - if (includedConfig.spaces.some((s) => config.spaces.some((existing) => existing.name === s.name))) { - throw new Error(`Included config contains spaces with duplicate names: ${resolvedIncludePath}`); + const expanded = expandHome(includePath); + const resolvedIncludePath = isAbsolute(expanded) ? expanded : resolve(dirname(path), expanded); + if (!existsSync(resolvedIncludePath)) { + throw new SctxError( + 'E_INCLUDE_NOT_FOUND', + `Config ${path} includes ${resolvedIncludePath}, which does not exist`, + ); } - // Track which spaces come from this included config file + const includedConfig = resolveRelativePaths(_loadConfig(resolvedIncludePath), dirname(resolvedIncludePath)); const includeSourceDir = dirname(resolvedIncludePath); for (const space of includedConfig.spaces) { - _spaceSourceFiles.set(space.name, resolvedIncludePath); + if (ownNames.has(space.name)) continue; space.sourceDir = includeSourceDir; + _spaceSourceFiles.set(space.name, resolvedIncludePath); + const existing = config.spaces.findIndex((s) => s.name === space.name); + if (existing >= 0) config.spaces[existing] = space; + else config.spaces.push(space); } - config.spaces.push(...includedConfig.spaces); } } return resolveRelativePaths(config, dirname(resolve(path))); diff --git a/src/config/write.ts b/src/config/write.ts new file mode 100644 index 00000000..efca5e9d --- /dev/null +++ b/src/config/write.ts @@ -0,0 +1,119 @@ +import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; +import { dirname, isAbsolute, relative, resolve } from 'node:path'; +import { LOCAL_CONFIG_FILE } from '../constants'; +import { SctxError } from '../errors'; +import { globalConfigPath, resolveConfigPath, resolveSchemaPath, type SpaceConfig } from '.'; + +type AddSpaceOptions = Pick & { + /** Write to the global config file. */ + global?: boolean; + /** Write to this config file (created if missing) instead of the discovered one. */ + configFile?: string; + /** Where discovery starts when no explicit target is given. Defaults to the working directory. */ + startDir?: string; +}; + +type AddSpaceResult = { + configPath: string; + created: boolean; + space: Pick; +}; + +/** + * Decide which file to write. A config named explicitly or found by walking up from the working directory + * is used as is. If discovery would land on the global file or on nothing, the caller must say where to + * write, so a vault's space never ends up in the global file by accident. + */ +export function resolveWriteTarget(options: { global?: boolean; configFile?: string; startDir?: string }): string { + if (options.configFile) return options.configFile; + const resolved = resolveConfigPath(options.startDir); + if (options.global) { + if (resolved.source === 'override' || resolved.source === 'env') { + throw new SctxError('E_TARGET_REQUIRED', 'The global config cannot be combined with an explicitly named config'); + } + return globalConfigPath(); + } + if (resolved.source === 'override' || resolved.source === 'env' || resolved.source === 'local') { + return resolved.path; + } + const found = resolved.source === 'global' ? `only the global config (${resolved.path}) exists` : 'no config exists'; + throw new SctxError( + 'E_TARGET_REQUIRED', + `No ${LOCAL_CONFIG_FILE} found from ${resolve(options.startDir ?? process.cwd())} upward; ${found}. ` + + `Specify the config file location or global option.`, + ); +} + +function realOrSelf(p: string): string { + try { + return realpathSync(p); + } catch { + return p; + } +} + +/** The path as written in the config: relative to the config's folder when inside it, else absolute. */ +function storedPath(configFile: string, absolutePath: string): string { + // Compare real paths so a symlinked folder (such as macOS's /var -> /private/var) does not look like it escapes + const rel = relative(realOrSelf(dirname(resolve(configFile))), realOrSelf(absolutePath)); + if (rel === '') return '.'; + return rel.startsWith('..') || isAbsolute(rel) ? absolutePath : rel; +} + +/** Add a space to the chosen config file, creating the file when it does not exist. */ +export function addSpace(options: AddSpaceOptions): AddSpaceResult { + if (!/^[a-z0-9_-]+$/.test(options.name)) { + throw new SctxError( + 'E_CONFIG_INVALID', + `Space name "${options.name}" must use lowercase letters, digits, "-" and "_"`, + ); + } + const target = resolve(resolveWriteTarget(options)); + const spacePath = resolve(options.startDir ?? process.cwd(), options.path); + if (!existsSync(spacePath)) { + throw new SctxError('E_SPACE_PATH_MISSING', `Space path does not exist: ${spacePath}`); + } + + const created = !existsSync(target); + let config: { spaces?: SpaceConfig[]; schema?: string; [key: string]: unknown } = { spaces: [] }; + if (!created) { + const raw = readFileSync(target, 'utf-8'); + try { + config = JSON.parse(raw); + } catch { + const entry = { name: options.name, path: storedPath(target, spacePath), schema: options.schema }; + throw new SctxError( + 'E_CONFIG_NEEDS_MANUAL_EDIT', + `${target} is not strict JSON (comments, trailing commas or a syntax error), so it was not rewritten. ` + + `Add this entry to "spaces" by hand: ${JSON.stringify(entry)}`, + ); + } + } + if (!config.schema && !options.schema) { + throw new SctxError( + 'E_SCHEMA_MISSING', + 'Give --schema : neither the space nor the config file names a schema', + ); + } + if (options.schema && !/^https?:\/\//i.test(options.schema)) { + if (!existsSync(resolveSchemaPath(options.schema, dirname(target)))) { + const hint = options.schema.startsWith('sctx://') + ? 'Name the schema by file, such as strategy_general.json, not by sctx:// URI.' + : '`sctx schemas list` shows the bundled schemas; a file name needs its extension.'; + throw new SctxError('E_SCHEMA_NOT_FOUND', `Schema not found: ${options.schema}. ${hint}`); + } + } + config.spaces = config.spaces ?? []; + if (config.spaces.some((s) => s.name === options.name)) { + throw new SctxError('E_SPACE_EXISTS', `${target} already defines a space named "${options.name}"`); + } + const space = { + name: options.name, + path: storedPath(target, spacePath), + ...(options.schema ? { schema: options.schema } : {}), + }; + config.spaces.push(space); + mkdirSync(dirname(target), { recursive: true }); + writeFileSync(target, `${JSON.stringify(config, null, 2)}\n`); + return { configPath: target, created, space }; +} diff --git a/src/constants.ts b/src/constants.ts index efa3dc82..6f87d515 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -4,3 +4,5 @@ export const CLI_NAME = 'sctx'; export const PLUGIN_PREFIX = `${CLI_NAME}-`; export const ENV_CONFIG_VAR = 'SCTX_CONFIG'; export const SCHEMA_URI_SCHEME = CLI_NAME; +/** Name of the config file discovered by walking up from the working directory. */ +export const LOCAL_CONFIG_FILE = '.sctx.json'; diff --git a/src/errors.ts b/src/errors.ts new file mode 100644 index 00000000..9b6b27e7 --- /dev/null +++ b/src/errors.ts @@ -0,0 +1,26 @@ +/** + * Stable codes for configuration and environment problems. Hooks and agent skills map a code to a + * fix, so the message wording can change without breaking them. + */ +export type SctxErrorCode = + | 'E_CONFIG_NOT_FOUND' + | 'E_CONFIG_INVALID' + | 'E_INCLUDE_NOT_FOUND' + | 'E_NO_SPACES' + | 'E_SPACE_PATH_MISSING' + | 'E_SCHEMA_MISSING' + | 'E_SCHEMA_NOT_FOUND' + | 'E_SCHEMA_INVALID' + | 'E_SPACE_EXISTS' + | 'E_TARGET_REQUIRED' + | 'E_CONFIG_NEEDS_MANUAL_EDIT'; + +export class SctxError extends Error { + constructor( + readonly code: SctxErrorCode, + message: string, + ) { + super(message); + this.name = 'SctxError'; + } +} diff --git a/src/index.ts b/src/index.ts index 63a6a60b..251792f6 100755 --- a/src/index.ts +++ b/src/index.ts @@ -10,7 +10,7 @@ import { listPlugins } from './commands/plugins'; import { render, renderList } from './commands/render'; import { listSchemas, showSchema } from './commands/schemas'; import { show } from './commands/show'; -import { listSpaces } from './commands/spaces'; +import { addSpaceCommand, listSpaces } from './commands/spaces'; import { templateSync } from './commands/template-sync'; import { validate, watchValidate } from './commands/validate'; import { validateFileCommand } from './commands/validate-file'; @@ -58,7 +58,7 @@ program .name(CLI_NAME) .description('Structured context validation and diagram generation tool') .version(packageJson.version) - .option('--config ', 'Path to config file (overrides default config.json locations)'); + .option('--config ', 'Path to config file (overrides config discovery)'); program.hook('preAction', () => { setConfigPath(program.opts().config); @@ -185,6 +185,20 @@ spacesCmd .description('List all configured spaces and their paths') .option('--json', 'Output as JSON: config files, and each space with its path and schema') .action((options) => listSpaces(options)); +spacesCmd + .command('add') + .description('Add a space to a config file, creating the file if needed') + .argument('', 'Space name (lowercase letters, digits, - and _)') + .argument('', 'Path to the space (a folder or a file); must exist') + .option('--schema ', 'Schema name or path (required unless the config names a top-level schema)') + .option('--global', 'Write to the global config file') + .option('--json', 'Output as JSON') + .addHelpText( + 'after', + '\nWrites to the config found by walking up from the working directory, or the one named with --config.\n' + + 'If only the global config (or none) exists, name the target: --config /.sctx.json or --global.', + ) + .action((name, path, options) => addSpaceCommand(name, path, options)); program.addCommand(spacesCmd); const providersCmd = new Command('providers').description( diff --git a/tests/config/discovery.test.ts b/tests/config/discovery.test.ts new file mode 100644 index 00000000..85e37662 --- /dev/null +++ b/tests/config/discovery.test.ts @@ -0,0 +1,76 @@ +import { describe, expect, it } from 'bun:test'; +import { join } from 'node:path'; +import { loadConfig, resolveConfigPath, setConfigPath } from '../../src/config'; +import { LOCAL_CONFIG_FILE } from '../../src/constants'; +import { useConfigEnv, writeJson as write } from '../helpers/config-env'; + +const env = useConfigEnv(); + +describe('resolveConfigPath', () => { + it('finds the nearest .sctx.json walking up from a subfolder', () => { + write(join(env.vault, LOCAL_CONFIG_FILE), { spaces: [] }); + + const resolved = resolveConfigPath(join(env.vault, 'notes', 'deep')); + + expect(resolved).toEqual({ path: join(env.vault, LOCAL_CONFIG_FILE), source: 'local' }); + }); + + it('uses the nearest of two ancestor configs without merging', () => { + write(join(env.vault, LOCAL_CONFIG_FILE), { spaces: [{ name: 'outer', path: '.' }] }); + write(join(env.vault, 'notes', LOCAL_CONFIG_FILE), { spaces: [{ name: 'inner', path: '.' }] }); + + expect(resolveConfigPath(join(env.vault, 'notes', 'deep')).path).toBe(join(env.vault, 'notes', LOCAL_CONFIG_FILE)); + }); + + it('prefers a local config over the global one', () => { + write(env.globalFile, { spaces: [] }); + write(join(env.vault, LOCAL_CONFIG_FILE), { spaces: [] }); + + expect(resolveConfigPath(env.vault).source).toBe('local'); + }); + + it('falls back to the global config, then to none', () => { + expect(resolveConfigPath(env.vault)).toEqual({ path: env.globalFile, source: 'none' }); + + write(env.globalFile, { spaces: [] }); + + expect(resolveConfigPath(env.vault)).toEqual({ path: env.globalFile, source: 'global' }); + }); + + it('does not walk down into folders below the start', () => { + write(join(env.vault, 'notes', LOCAL_CONFIG_FILE), { spaces: [] }); + + expect(resolveConfigPath(env.vault).source).toBe('none'); + }); + + it('lets an explicit override and $SCTX_CONFIG beat discovery', () => { + write(join(env.vault, LOCAL_CONFIG_FILE), { spaces: [] }); + process.env.SCTX_CONFIG = join(env.root, 'env.json'); + + expect(resolveConfigPath(env.vault)).toEqual({ path: join(env.root, 'env.json'), source: 'env' }); + + setConfigPath(join(env.root, 'flag.json')); + + expect(resolveConfigPath(env.vault)).toEqual({ path: join(env.root, 'flag.json'), source: 'override' }); + }); +}); + +describe('loadConfig with discovery', () => { + it('resolves space paths against the folder holding .sctx.json, so the env.vault itself is "."', () => { + write(join(env.vault, LOCAL_CONFIG_FILE), { spaces: [{ name: 'wiki', path: '.', schema: 'knowledge_wiki.json' }] }); + + const config = loadConfig({ startDir: join(env.vault, 'notes') }); + + expect(config.spaces[0]?.path).toBe(env.vault); + }); + + it('expands ~ in includeSpacesFrom', () => { + process.env.HOME = env.root; + write(join(env.root, 'shared.json'), { spaces: [{ name: 'shared', path: '/shared' }] }); + write(join(env.vault, LOCAL_CONFIG_FILE), { includeSpacesFrom: ['~/shared.json'] }); + + const config = loadConfig({ startDir: env.vault }); + + expect(config.spaces.map((s) => s.name)).toEqual(['shared']); + }); +}); diff --git a/tests/config/health.test.ts b/tests/config/health.test.ts new file mode 100644 index 00000000..9f84b1b8 --- /dev/null +++ b/tests/config/health.test.ts @@ -0,0 +1,185 @@ +import { describe, expect, it } from 'bun:test'; +import { readFileSync, symlinkSync } from 'node:fs'; +import { join } from 'node:path'; +import { setConfigPath } from '../../src/config'; +import { checkConfig, hasBlockingProblem } from '../../src/config/health'; +import { addSpace, resolveWriteTarget } from '../../src/config/write'; +import { LOCAL_CONFIG_FILE } from '../../src/constants'; +import { SctxError } from '../../src/errors'; +import { useConfigEnv, writeJson as write } from '../helpers/config-env'; + +const env = useConfigEnv(); + +describe('checkConfig', () => { + it('reports "not set up" as info, not as a failure', () => { + const health = checkConfig({ startDir: env.vault }); + + expect(health.config.source).toBe('none'); + expect(health.problems.map((p) => [p.code, p.severity])).toEqual([['E_CONFIG_NOT_FOUND', 'info']]); + expect(hasBlockingProblem(health)).toBe(false); + }); + + it('reports a missing explicit config as an error', () => { + setConfigPath(join(env.root, 'missing.json')); + + const health = checkConfig(); + + expect(health.problems[0]).toMatchObject({ code: 'E_CONFIG_NOT_FOUND', severity: 'error' }); + expect(hasBlockingProblem(health)).toBe(true); + }); + + it('reports invalid JSON with a code and a fix', () => { + write(join(env.vault, LOCAL_CONFIG_FILE), '{ not json'); + + const health = checkConfig({ startDir: env.vault }); + + expect(health.problems[0]).toMatchObject({ code: 'E_CONFIG_INVALID', severity: 'error' }); + expect(health.problems[0]?.fix).not.toBe(''); + }); + + it('reports a moved space path and a missing schema per space', () => { + write(join(env.vault, LOCAL_CONFIG_FILE), { + spaces: [ + { name: 'gone', path: 'nope', schema: 'knowledge_wiki.json' }, + { name: 'noschema', path: '.' }, + { name: 'badschema', path: '.', schema: 'does_not_exist.json' }, + ], + }); + + const codes = checkConfig({ startDir: env.vault }).problems.map((p) => `${p.space}:${p.code}`); + + expect(codes).toEqual(['gone:E_SPACE_PATH_MISSING', 'noschema:E_SCHEMA_MISSING', 'badschema:E_SCHEMA_NOT_FOUND']); + }); + + it('is clean for a healthy space', () => { + write(join(env.vault, LOCAL_CONFIG_FILE), { spaces: [{ name: 'wiki', path: '.', schema: 'knowledge_wiki.json' }] }); + + const health = checkConfig({ startDir: env.vault }); + + expect(health.problems).toEqual([]); + expect(health.spaces[0]?.name).toBe('wiki'); + }); +}); + +describe('addSpace', () => { + function inVault(run: () => T): T { + const cwd = process.cwd(); + process.chdir(env.vault); + try { + return run(); + } finally { + process.chdir(cwd); + } + } + + it('requires an explicit target when nothing exists', () => { + const err = inVault(() => { + try { + addSpace({ name: 'wiki', path: '.', schema: 'knowledge_wiki.json' }); + } catch (e) { + return e; + } + }); + + expect(err).toBeInstanceOf(SctxError); + expect((err as SctxError).code).toBe('E_TARGET_REQUIRED'); + }); + + it('requires an explicit target when only the global config exists', () => { + write(env.globalFile, { spaces: [] }); + + expect(() => inVault(() => resolveWriteTarget({}))).toThrow('only the global config'); + }); + + it('creates the named config with a path relative to the config folder', () => { + const target = join(env.vault, LOCAL_CONFIG_FILE); + setConfigPath(target); + + const result = inVault(() => addSpace({ name: 'wiki', path: 'notes', schema: 'knowledge_wiki.json' })); + + expect(result).toMatchObject({ configPath: target, created: true, space: { name: 'wiki', path: 'notes' } }); + expect(JSON.parse(readFileSync(target, 'utf-8')).spaces).toHaveLength(1); + }); + + it('adds to the nearest existing config without a flag', () => { + write(join(env.vault, LOCAL_CONFIG_FILE), { + spaces: [{ name: 'first', path: '.', schema: 'knowledge_wiki.json' }], + }); + const cwd = process.cwd(); + process.chdir(join(env.vault, 'notes')); + try { + const result = addSpace({ name: 'second', path: 'deep', schema: 'knowledge_wiki.json' }); + + expect(result.created).toBe(false); + expect(result.space.path).toBe('notes/deep'); + } finally { + process.chdir(cwd); + } + }); + + it('stores "." for the config folder even when it is reached through a symlink', () => { + const link = join(env.root, 'link'); + symlinkSync(env.vault, link); + const target = join(link, LOCAL_CONFIG_FILE); + setConfigPath(target); + + const result = inVault(() => addSpace({ name: 'wiki', path: '.', schema: 'knowledge_wiki.json' })); + + expect(result.space.path).toBe('.'); + }); + + it('writes to an explicit configFile without consulting discovery', () => { + const target = join(env.vault, 'notes', LOCAL_CONFIG_FILE); + + const result = inVault(() => + addSpace({ name: 'wiki', path: 'notes', schema: 'knowledge_wiki.json', configFile: target }), + ); + + expect(result).toMatchObject({ configPath: target, created: true, space: { path: '.' } }); + }); + + it('writes the global file only with --global', () => { + const result = inVault(() => addSpace({ name: 'wiki', path: '.', schema: 'knowledge_wiki.json', global: true })); + + expect(result.configPath).toBe(env.globalFile); + expect(result.space.path).toBe(env.vault); + }); + + it('refuses a duplicate name, a missing path and a missing schema', () => { + write(join(env.vault, LOCAL_CONFIG_FILE), { spaces: [{ name: 'wiki', path: '.', schema: 'knowledge_wiki.json' }] }); + const code = (run: () => void) => { + try { + inVault(run); + } catch (e) { + return (e as SctxError).code; + } + }; + + expect(code(() => addSpace({ name: 'wiki', path: '.', schema: 'knowledge_wiki.json' }))).toBe('E_SPACE_EXISTS'); + expect(code(() => addSpace({ name: 'x', path: 'nope', schema: 'knowledge_wiki.json' }))).toBe( + 'E_SPACE_PATH_MISSING', + ); + write(join(env.vault, LOCAL_CONFIG_FILE), { spaces: [] }); + expect(code(() => addSpace({ name: 'x', path: '.' }))).toBe('E_SCHEMA_MISSING'); + expect(code(() => addSpace({ name: 'x', path: '.', schema: 'nope.json' }))).toBe('E_SCHEMA_NOT_FOUND'); + expect(code(() => addSpace({ name: 'x', path: '.', schema: 'knowledge_wiki' }))).toBe('E_SCHEMA_NOT_FOUND'); + expect(code(() => addSpace({ name: 'x', path: '.', schema: 'sctx://core/knowledge_wiki' }))).toBe( + 'E_SCHEMA_NOT_FOUND', + ); + expect(code(() => addSpace({ name: 'x', path: '.', schema: './missing/schema.json' }))).toBe('E_SCHEMA_NOT_FOUND'); + }); + + it('will not rewrite a file that uses JSON5 features, and says what to add', () => { + write(join(env.vault, LOCAL_CONFIG_FILE), '{ // keep me\n spaces: [] }'); + const err = inVault(() => { + try { + addSpace({ name: 'wiki', path: '.', schema: 'knowledge_wiki.json' }); + } catch (e) { + return e as SctxError; + } + }); + + expect(err?.code).toBe('E_CONFIG_NEEDS_MANUAL_EDIT'); + expect(readFileSync(join(env.vault, LOCAL_CONFIG_FILE), 'utf-8')).toContain('keep me'); + }); +}); diff --git a/tests/config.test.ts b/tests/config/index.test.ts similarity index 88% rename from tests/config.test.ts rename to tests/config/index.test.ts index 6f0f9817..20db7a8e 100644 --- a/tests/config.test.ts +++ b/tests/config/index.test.ts @@ -2,7 +2,7 @@ import { afterAll, beforeEach, describe, expect, it } from 'bun:test'; import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { JSON5 } from 'bun'; -import { type Config, loadConfig, setConfigPath, updateSpaceField } from '../src/config'; +import { type Config, loadConfig, setConfigPath, updateSpaceField } from '../../src/config'; const testDir = join(process.cwd(), 'tmp-config-test'); const mainConfigPath = join(testDir, 'main-config.json'); @@ -208,33 +208,41 @@ describe('loadConfig with includeSpacesFrom', () => { expect(() => loadConfig()).toThrow('Invalid config'); }); - it('throws error when included config has duplicate name', () => { - writeFileSync( - includedConfigPath, - JSON.stringify( - { - spaces: [{ name: 'duplicate-space', path: '/included' }], - }, - null, - 2, - ), - ); - + it('lets a space in the including file override an included space of the same name', () => { + writeFileSync(includedConfigPath, JSON.stringify({ spaces: [{ name: 'duplicate-space', path: '/included' }] })); writeFileSync( mainConfigPath, - JSON.stringify( - { - includeSpacesFrom: ['included-config.json'], - spaces: [{ name: 'duplicate-space', path: '/main' }], - }, - null, - 2, - ), + JSON.stringify({ + includeSpacesFrom: ['included-config.json'], + spaces: [{ name: 'duplicate-space', path: '/main' }], + }), ); + setConfigPath(mainConfigPath); + const config = loadConfig(); + + expect(config.spaces).toHaveLength(1); + expect(config.spaces[0]?.path).toBe('/main'); + }); + + it('lets a later include override an earlier include of the same name', () => { + writeFileSync(join(testDir, 'first.json'), JSON.stringify({ spaces: [{ name: 'shared', path: '/first' }] })); + writeFileSync(join(testDir, 'second.json'), JSON.stringify({ spaces: [{ name: 'shared', path: '/second' }] })); + writeFileSync(mainConfigPath, JSON.stringify({ includeSpacesFrom: ['first.json', 'second.json'] })); + + setConfigPath(mainConfigPath); + const config = loadConfig(); + + expect(config.spaces).toHaveLength(1); + expect(config.spaces[0]?.path).toBe('/second'); + }); + + it('reports a missing include with a stable code', () => { + writeFileSync(mainConfigPath, JSON.stringify({ includeSpacesFrom: ['nope.json'] })); + setConfigPath(mainConfigPath); - expect(() => loadConfig()).toThrow('Included config contains spaces with duplicate names'); + expect(() => loadConfig()).toThrow('does not exist'); }); it('handles included configs with their own relative paths correctly', () => { diff --git a/tests/helpers/config-env.ts b/tests/helpers/config-env.ts new file mode 100644 index 00000000..23fcb656 --- /dev/null +++ b/tests/helpers/config-env.ts @@ -0,0 +1,33 @@ +import { afterEach, beforeEach } from 'bun:test'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { setConfigPath } from '../../src/config'; + +export type ConfigEnv = { root: string; vault: string; globalFile: string }; + +export function writeJson(path: string, value: unknown): void { + mkdirSync(join(path, '..'), { recursive: true }); + writeFileSync(path, typeof value === 'string' ? value : JSON.stringify(value)); +} + +/** Isolated temp tree with a `vault/notes/deep` folder, a private XDG dir and no ambient config. */ +export function useConfigEnv(): ConfigEnv { + const env = { root: '', vault: '', globalFile: '' }; + const savedEnv = { ...process.env }; + beforeEach(() => { + env.root = realpathSync(mkdtempSync(join(tmpdir(), 'sctx-config-'))); + env.vault = join(env.root, 'vault'); + mkdirSync(join(env.vault, 'notes', 'deep'), { recursive: true }); + process.env.XDG_CONFIG_HOME = join(env.root, 'xdg'); + delete process.env.SCTX_CONFIG; + env.globalFile = join(env.root, 'xdg', 'structured-context', 'config.json'); + setConfigPath(undefined); + }); + afterEach(() => { + process.env = { ...savedEnv }; + setConfigPath(undefined); + rmSync(env.root, { recursive: true, force: true }); + }); + return env; +}