@nusoft/nuos-build-catalogue 0.11.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/cli.js +52 -39
  2. package/dist/commands/init.js +119 -42
  3. package/dist/commands/plan.d.ts +12 -0
  4. package/dist/commands/plan.js +83 -0
  5. package/dist/commands/write.js +16 -5
  6. package/dist/embedder/ollama.d.ts +14 -8
  7. package/dist/embedder/ollama.js +15 -9
  8. package/dist/path-resolution.d.ts +68 -0
  9. package/dist/path-resolution.js +147 -0
  10. package/dist/runtime/ac-parse.js +10 -6
  11. package/dist/runtime/markdown-edit.d.ts +5 -0
  12. package/dist/runtime/markdown-edit.js +13 -6
  13. package/dist/runtime/mis-adapter.js +7 -2
  14. package/package.json +2 -2
  15. package/templates/hooks/install-hooks.sh +44 -0
  16. package/templates/hooks/post-commit +96 -0
  17. package/templates/hooks/pre-commit +162 -0
  18. package/templates/protocols/end-of-session.md +101 -13
  19. package/templates/protocols/persona-new.md +64 -30
  20. package/templates/protocols/plan-orientation.md +122 -0
  21. package/templates/protocols/start-of-session.md +52 -13
  22. package/templates/protocols/wu-new.md +75 -50
  23. package/templates/starter-kit/docs/build/GLOSSARY.md +115 -0
  24. package/templates/starter-kit/docs/build/STATE.md +30 -16
  25. package/templates/starter-kit/docs/build/WELCOME.md +79 -0
  26. package/templates/starter-kit/docs/build/architecture/_index.md +39 -0
  27. package/templates/starter-kit/docs/build/architecture/module-template.md +47 -0
  28. package/templates/starter-kit/docs/build/contracts/_index.md +39 -0
  29. package/templates/starter-kit/docs/build/contracts/contract-template.md +64 -0
  30. package/templates/starter-kit/docs/build/decisions/_index.md +21 -17
  31. package/templates/starter-kit/docs/build/design-system/_index.md +57 -0
  32. package/templates/starter-kit/docs/build/design-system/accessibility.md +77 -0
  33. package/templates/starter-kit/docs/build/design-system/components/_index.md +29 -0
  34. package/templates/starter-kit/docs/build/design-system/components/_template.md +60 -0
  35. package/templates/starter-kit/docs/build/design-system/patterns/_index.md +37 -0
  36. package/templates/starter-kit/docs/build/design-system/patterns/_template.md +57 -0
  37. package/templates/starter-kit/docs/build/design-system/tokens-colour.md +52 -0
  38. package/templates/starter-kit/docs/build/design-system/tokens-motion.md +42 -0
  39. package/templates/starter-kit/docs/build/design-system/tokens-radius-elevation.md +34 -0
  40. package/templates/starter-kit/docs/build/design-system/tokens-spacing.md +48 -0
  41. package/templates/starter-kit/docs/build/design-system/tokens-typography.md +46 -0
  42. package/templates/starter-kit/docs/build/design-system/voice.md +53 -0
  43. package/templates/starter-kit/docs/build/maps/01-template.md +15 -112
  44. package/templates/starter-kit/docs/build/maps/02-template.md +52 -0
  45. package/templates/starter-kit/docs/build/maps/03-template.md +46 -0
  46. package/templates/starter-kit/docs/build/maps/99-template-power-user-operational-plan.md +126 -0
  47. package/templates/starter-kit/docs/build/maps/_index.md +17 -52
  48. package/templates/starter-kit/docs/build/open-questions/_index.md +27 -13
  49. package/templates/starter-kit/docs/build/personas/_index.md +26 -60
  50. package/templates/starter-kit/docs/build/risks/_index.md +20 -13
  51. package/templates/starter-kit/docs/build/sessions/_index.md +18 -16
  52. package/templates/starter-kit/docs/build/ui-ux/_index.md +48 -0
  53. package/templates/starter-kit/docs/build/ui-ux/surface-template.md +72 -0
  54. package/templates/starter-kit/docs/build/work-units/001-template-simple.md +43 -0
  55. package/templates/starter-kit/docs/build/work-units/_index.md +18 -20
  56. package/templates/starter-kit/methodfile.json +19 -8
  57. /package/templates/starter-kit/docs/build/work-units/{001-template.md → 001-template-full.md} +0 -0
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Default path resolution for the CLI.
3
+ *
4
+ * Defaults walk up from `process.cwd()` to find the nearest directory
5
+ * containing `docs/build/`, the same way `git` finds its repo root.
6
+ * That makes the CLI work consistently regardless of where it was
7
+ * installed from (sibling checkout, npx cache, global install) and
8
+ * regardless of which subdirectory the operator invokes it from.
9
+ *
10
+ * Resolution order, for every path-shaped flag:
11
+ * 1. Explicit `--flag=<value>` (highest precedence)
12
+ * 2. Matching `NUOS_CATALOGUE_*` env var
13
+ * 3. Walk-up discovery from cwd
14
+ * 4. Throw with a clear hint, OR fall back to cwd, depending on the
15
+ * flag's semantics (build-root throws because there's no honest
16
+ * default; storage dirs fall back to cwd because creating them
17
+ * ad-hoc is reasonable when no project root is found).
18
+ */
19
+ /**
20
+ * Walk up from `startDir` looking for a directory that contains a
21
+ * `docs/build/` subdirectory. Returns the absolute path to the
22
+ * containing directory, or null if no such directory is found before
23
+ * reaching the filesystem root.
24
+ *
25
+ * Exposed for testing; ordinary callers use `resolveBuildRoot` etc.
26
+ */
27
+ export declare function findProjectRoot(startDir: string): string | null;
28
+ export interface ResolutionContext {
29
+ /** Override for `process.cwd()` — used by tests to anchor walk-up. */
30
+ cwd?: string;
31
+ /** Override for `process.env` — used by tests to control env vars. */
32
+ env?: NodeJS.ProcessEnv;
33
+ }
34
+ /**
35
+ * Resolve the build catalogue root. Throws with a clear hint when no
36
+ * value is available — the build root is load-bearing for every write
37
+ * command, so a silent fallback would mask real errors.
38
+ */
39
+ export declare function resolveBuildRoot(flag: string | boolean | undefined, ctx?: ResolutionContext): string;
40
+ /**
41
+ * Resolve the wider documentation root for semantic-search indexing.
42
+ * Falls back to `<project-root>/docs` when no flag or env var is set,
43
+ * because semantic-search has always indexed the wider docs/ surface,
44
+ * not just docs/build/.
45
+ */
46
+ export declare function resolveCatalogueRoot(flag: string | boolean | undefined, ctx?: ResolutionContext): string;
47
+ /**
48
+ * Resolve the `.nuos-catalogue/` storage directory. Always co-located
49
+ * with the project root (the directory containing `docs/build/`).
50
+ * `NUOS_CATALOGUE_INDEX_DIR` env var wins when set.
51
+ */
52
+ export declare function resolveIndexDir(buildRoot: string, ctx?: ResolutionContext): string;
53
+ export declare function resolveWorkflowsPath(buildRoot: string, flag: string | boolean | undefined, ctx?: ResolutionContext): string;
54
+ export declare function resolveIndexPath(buildRoot: string, flag: string | boolean | undefined, ctx?: ResolutionContext): string;
55
+ export declare function resolveHashPath(buildRoot: string, flag: string | boolean | undefined, ctx?: ResolutionContext): string;
56
+ /**
57
+ * Soft warning surfaced after a `migrate` or `regenerate` run: if the
58
+ * project has a `.gitignore` at its root and that `.gitignore` does
59
+ * NOT contain a `.nuos-catalogue/` entry, the workflow store appears
60
+ * as untracked. Returns a multi-line `note:` string when a warning
61
+ * should be printed, or null when silent.
62
+ *
63
+ * Silent when:
64
+ * - the project has no `.gitignore` (it might not be a git repo)
65
+ * - the gitignore already excludes `.nuos-catalogue/`
66
+ * - the gitignore can't be read for any reason (be quiet, not noisy)
67
+ */
68
+ export declare function gitignoreCatalogueNote(buildRoot: string, ctx?: ResolutionContext): string | null;
@@ -0,0 +1,147 @@
1
+ /**
2
+ * Default path resolution for the CLI.
3
+ *
4
+ * Defaults walk up from `process.cwd()` to find the nearest directory
5
+ * containing `docs/build/`, the same way `git` finds its repo root.
6
+ * That makes the CLI work consistently regardless of where it was
7
+ * installed from (sibling checkout, npx cache, global install) and
8
+ * regardless of which subdirectory the operator invokes it from.
9
+ *
10
+ * Resolution order, for every path-shaped flag:
11
+ * 1. Explicit `--flag=<value>` (highest precedence)
12
+ * 2. Matching `NUOS_CATALOGUE_*` env var
13
+ * 3. Walk-up discovery from cwd
14
+ * 4. Throw with a clear hint, OR fall back to cwd, depending on the
15
+ * flag's semantics (build-root throws because there's no honest
16
+ * default; storage dirs fall back to cwd because creating them
17
+ * ad-hoc is reasonable when no project root is found).
18
+ */
19
+ import { existsSync, readFileSync } from 'node:fs';
20
+ import path from 'node:path';
21
+ /**
22
+ * Walk up from `startDir` looking for a directory that contains a
23
+ * `docs/build/` subdirectory. Returns the absolute path to the
24
+ * containing directory, or null if no such directory is found before
25
+ * reaching the filesystem root.
26
+ *
27
+ * Exposed for testing; ordinary callers use `resolveBuildRoot` etc.
28
+ */
29
+ export function findProjectRoot(startDir) {
30
+ let dir = path.resolve(startDir);
31
+ while (true) {
32
+ if (existsSync(path.join(dir, 'docs', 'build')))
33
+ return dir;
34
+ const parent = path.dirname(dir);
35
+ if (parent === dir)
36
+ return null;
37
+ dir = parent;
38
+ }
39
+ }
40
+ function ctxCwd(ctx) {
41
+ return ctx?.cwd ?? process.cwd();
42
+ }
43
+ function ctxEnv(ctx) {
44
+ return ctx?.env ?? process.env;
45
+ }
46
+ /**
47
+ * Resolve the build catalogue root. Throws with a clear hint when no
48
+ * value is available — the build root is load-bearing for every write
49
+ * command, so a silent fallback would mask real errors.
50
+ */
51
+ export function resolveBuildRoot(flag, ctx) {
52
+ if (typeof flag === 'string' && flag.length > 0)
53
+ return path.resolve(flag);
54
+ const env = ctxEnv(ctx);
55
+ if (env.NUOS_CATALOGUE_BUILD_ROOT)
56
+ return path.resolve(env.NUOS_CATALOGUE_BUILD_ROOT);
57
+ const root = findProjectRoot(ctxCwd(ctx));
58
+ if (root)
59
+ return path.join(root, 'docs', 'build');
60
+ throw new Error('cannot locate the build catalogue (no docs/build/ directory found from cwd or any parent).\n' +
61
+ 'Either:\n' +
62
+ ' - run from a project that has been bootstrapped via `nuos-catalogue init`,\n' +
63
+ ' - set NUOS_CATALOGUE_BUILD_ROOT in your shell profile,\n' +
64
+ ' - or pass --build-root=<dir> to this command.');
65
+ }
66
+ /**
67
+ * Resolve the wider documentation root for semantic-search indexing.
68
+ * Falls back to `<project-root>/docs` when no flag or env var is set,
69
+ * because semantic-search has always indexed the wider docs/ surface,
70
+ * not just docs/build/.
71
+ */
72
+ export function resolveCatalogueRoot(flag, ctx) {
73
+ if (typeof flag === 'string' && flag.length > 0)
74
+ return path.resolve(flag);
75
+ const env = ctxEnv(ctx);
76
+ if (env.NUOS_CATALOGUE_ROOT)
77
+ return path.resolve(env.NUOS_CATALOGUE_ROOT);
78
+ const root = findProjectRoot(ctxCwd(ctx));
79
+ if (root)
80
+ return path.join(root, 'docs');
81
+ throw new Error('cannot locate the docs/ directory (no docs/build/ found from cwd or any parent).\n' +
82
+ 'Either set NUOS_CATALOGUE_ROOT, or pass --catalogue=<dir>.');
83
+ }
84
+ /**
85
+ * Resolve the `.nuos-catalogue/` storage directory. Always co-located
86
+ * with the project root (the directory containing `docs/build/`).
87
+ * `NUOS_CATALOGUE_INDEX_DIR` env var wins when set.
88
+ */
89
+ export function resolveIndexDir(buildRoot, ctx) {
90
+ const env = ctxEnv(ctx);
91
+ if (env.NUOS_CATALOGUE_INDEX_DIR)
92
+ return path.resolve(env.NUOS_CATALOGUE_INDEX_DIR);
93
+ // buildRoot is `<project-root>/docs/build`; two dirname() calls climb
94
+ // back to the project root.
95
+ const projectRoot = path.dirname(path.dirname(buildRoot));
96
+ return path.join(projectRoot, '.nuos-catalogue');
97
+ }
98
+ export function resolveWorkflowsPath(buildRoot, flag, ctx) {
99
+ if (typeof flag === 'string' && flag.length > 0)
100
+ return path.resolve(flag);
101
+ const env = ctxEnv(ctx);
102
+ if (env.NUOS_CATALOGUE_WORKFLOWS)
103
+ return path.resolve(env.NUOS_CATALOGUE_WORKFLOWS);
104
+ return path.join(resolveIndexDir(buildRoot, ctx), 'workflows.json');
105
+ }
106
+ export function resolveIndexPath(buildRoot, flag, ctx) {
107
+ if (typeof flag === 'string' && flag.length > 0)
108
+ return path.resolve(flag);
109
+ return path.join(resolveIndexDir(buildRoot, ctx), 'index.nv');
110
+ }
111
+ export function resolveHashPath(buildRoot, flag, ctx) {
112
+ if (typeof flag === 'string' && flag.length > 0)
113
+ return path.resolve(flag);
114
+ return path.join(resolveIndexDir(buildRoot, ctx), 'hashes.json');
115
+ }
116
+ /**
117
+ * Soft warning surfaced after a `migrate` or `regenerate` run: if the
118
+ * project has a `.gitignore` at its root and that `.gitignore` does
119
+ * NOT contain a `.nuos-catalogue/` entry, the workflow store appears
120
+ * as untracked. Returns a multi-line `note:` string when a warning
121
+ * should be printed, or null when silent.
122
+ *
123
+ * Silent when:
124
+ * - the project has no `.gitignore` (it might not be a git repo)
125
+ * - the gitignore already excludes `.nuos-catalogue/`
126
+ * - the gitignore can't be read for any reason (be quiet, not noisy)
127
+ */
128
+ export function gitignoreCatalogueNote(buildRoot, ctx) {
129
+ try {
130
+ const projectRoot = path.dirname(path.dirname(buildRoot));
131
+ const gitignorePath = path.join(projectRoot, '.gitignore');
132
+ if (!existsSync(gitignorePath))
133
+ return null;
134
+ const content = readFileSync(gitignorePath, 'utf8');
135
+ if (/^\s*\.nuos-catalogue\//m.test(content))
136
+ return null;
137
+ const indexDir = resolveIndexDir(buildRoot, ctx);
138
+ return ('note: the workflow store is at ' +
139
+ path.relative(projectRoot, indexDir) +
140
+ '/, but your .gitignore does not exclude .nuos-catalogue/.\n' +
141
+ ' Add this line to .gitignore so the per-machine JSON state stays out of commits:\n' +
142
+ ' .nuos-catalogue/');
143
+ }
144
+ catch {
145
+ return null;
146
+ }
147
+ }
@@ -160,15 +160,19 @@ export function extractForCompletion(rawMarkdown) {
160
160
  */
161
161
  function parseHistoryEvidence(rawMarkdown) {
162
162
  const result = new Map();
163
- const historyHeadingIndex = rawMarkdown.indexOf('## Build catalogue history');
164
- if (historyHeadingIndex === -1)
163
+ // Anchor the heading lookup to start-of-line so prose mentions inside
164
+ // code spans or paragraphs (e.g. a WU's notes log discussing the
165
+ // section by name) don't false-match the literal string.
166
+ const HEADING_RE = /^## Build catalogue history\s*$/m;
167
+ const headingMatch = HEADING_RE.exec(rawMarkdown);
168
+ if (!headingMatch)
165
169
  return result;
170
+ const historyHeadingIndex = headingMatch.index;
171
+ const headingLength = headingMatch[0].length;
166
172
  const sectionTail = rawMarkdown.slice(historyHeadingIndex);
167
173
  // Bound the history section at the next ## heading (if any).
168
- const nextSectionMatch = /\n## \S/.exec(sectionTail.slice('## Build catalogue history'.length));
169
- const sectionEnd = nextSectionMatch
170
- ? '## Build catalogue history'.length + nextSectionMatch.index
171
- : sectionTail.length;
174
+ const nextSectionMatch = /\n## \S/.exec(sectionTail.slice(headingLength));
175
+ const sectionEnd = nextSectionMatch ? headingLength + nextSectionMatch.index : sectionTail.length;
172
176
  const section = sectionTail.slice(0, sectionEnd);
173
177
  // Split into entries on the top-level `- **<timestamp>**` bullets.
174
178
  // Each entry runs until the next top-level bullet or end-of-section.
@@ -49,5 +49,10 @@ export interface ChangeLogEntry {
49
49
  * Idempotence: each call appends; running the same workflow twice
50
50
  * appends twice. The audit chain in the workflow store is the
51
51
  * deduplicating source of truth.
52
+ *
53
+ * Heading detection is anchored to start-of-line via a regex so that
54
+ * prose mentions of the heading text inside code spans or paragraphs
55
+ * (e.g. a WU's notes log discussing the section by name) don't
56
+ * false-match and cause the entry to land in the wrong place.
52
57
  */
53
58
  export declare function appendChangeLog(rawMarkdown: string, entry: ChangeLogEntry): string;
@@ -64,10 +64,18 @@ export function insertStatusLine(rawMarkdown, newStatus) {
64
64
  * Idempotence: each call appends; running the same workflow twice
65
65
  * appends twice. The audit chain in the workflow store is the
66
66
  * deduplicating source of truth.
67
+ *
68
+ * Heading detection is anchored to start-of-line via a regex so that
69
+ * prose mentions of the heading text inside code spans or paragraphs
70
+ * (e.g. a WU's notes log discussing the section by name) don't
71
+ * false-match and cause the entry to land in the wrong place.
67
72
  */
68
73
  export function appendChangeLog(rawMarkdown, entry) {
69
74
  const heading = '## Build catalogue history';
70
- const headingIndex = rawMarkdown.indexOf(heading);
75
+ const HEADING_RE = /^## Build catalogue history\s*$/m;
76
+ const headingMatch = HEADING_RE.exec(rawMarkdown);
77
+ const headingIndex = headingMatch ? headingMatch.index : -1;
78
+ const headingLength = headingMatch ? headingMatch[0].length : 0;
71
79
  const detailLines = [];
72
80
  if (entry.details)
73
81
  detailLines.push(` - ${entry.details}`);
@@ -82,17 +90,16 @@ export function appendChangeLog(rawMarkdown, entry) {
82
90
  return `${rawMarkdown}${sep}\n${heading}\n\n${block}\n`;
83
91
  }
84
92
  // Find the end of the file (or the next section) and insert before that.
85
- // Simplest: append the block immediately after the existing section's
86
- // current content. We treat everything from `headingIndex` to the
87
- // next H1/H2 boundary (or EOF) as the section.
93
+ // We treat everything from `headingIndex` to the next H1/H2 boundary
94
+ // (or EOF) as the section's body.
88
95
  const tail = rawMarkdown.slice(headingIndex);
89
- const nextHeadingMatch = /\n##? \S/.exec(tail.slice(heading.length));
96
+ const nextHeadingMatch = /\n##? \S/.exec(tail.slice(headingLength));
90
97
  if (!nextHeadingMatch) {
91
98
  // History is the last section — append at end of file.
92
99
  const sep = rawMarkdown.endsWith('\n') ? '' : '\n';
93
100
  return `${rawMarkdown}${sep}${block}\n`;
94
101
  }
95
- const splitAt = headingIndex + heading.length + nextHeadingMatch.index;
102
+ const splitAt = headingIndex + headingLength + nextHeadingMatch.index;
96
103
  const before = rawMarkdown.slice(0, splitAt);
97
104
  const after = rawMarkdown.slice(splitAt);
98
105
  const beforeHasTrailingNewline = before.endsWith('\n');
@@ -245,9 +245,14 @@ async function commitTickAC(store, catalogueRoot, intent) {
245
245
  throw err;
246
246
  }
247
247
  }
248
+ // criterionIndex is 0-based internally; the audit log uses 1-based
249
+ // numbering consistently across both the structural-tick path and the
250
+ // audit-log-only fallback, so users never see a mix of 0-based and
251
+ // 1-based references in their catalogue history.
252
+ const oneBased = payload.criterionIndex + 1;
248
253
  const summary = acText
249
- ? `Acceptance criterion ${payload.criterionIndex + 1} ticked: "${acText}".`
250
- : `Acceptance criterion at index ${payload.criterionIndex} ticked.`;
254
+ ? `Acceptance criterion ${oneBased} ticked: "${acText}".`
255
+ : `Acceptance criterion ${oneBased} ticked.`;
251
256
  const updatedMarkdown = appendChangeLog(workingMarkdown, {
252
257
  isoTimestamp: new Date().toISOString(),
253
258
  summary: structuralTick ? summary : `${summary} (audit-log-only — AC list not recognised)`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nusoft/nuos-build-catalogue",
3
- "version": "0.11.0",
3
+ "version": "0.14.0",
4
4
  "description": "NuOS build-catalogue tooling: semantic search (WU 110) + migration runner that lifts markdown artefacts into JSON-backed workflow records (WU 111, Phase G).",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,7 +19,7 @@
19
19
  "build": "rm -rf dist && tsc && chmod +x dist/cli.js",
20
20
  "prepublishOnly": "npm run build",
21
21
  "verify-storage": "tsx scripts/verify-persistence.ts",
22
- "test": "tsx --test tests/chunk.test.ts tests/metadata.test.ts tests/crawl.test.ts tests/migrate.test.ts tests/commands-read.test.ts tests/regenerate.test.ts tests/commands-write.test.ts tests/ac-parse.test.ts tests/create.test.ts tests/init.test.ts",
22
+ "test": "tsx --test tests/chunk.test.ts tests/metadata.test.ts tests/crawl.test.ts tests/migrate.test.ts tests/commands-read.test.ts tests/regenerate.test.ts tests/commands-write.test.ts tests/ac-parse.test.ts tests/create.test.ts tests/init.test.ts tests/wu-111-soak-findings.test.ts tests/plan.test.ts",
23
23
  "typecheck": "tsc --noEmit",
24
24
  "index": "tsx src/cli.ts index",
25
25
  "search": "tsx src/cli.ts search"
@@ -0,0 +1,44 @@
1
+ #!/usr/bin/env bash
2
+ #
3
+ # Install the catalogue's git hooks into .git/hooks/.
4
+ #
5
+ # Why this script (not husky):
6
+ # The nuos repo is a markdown catalogue, not an npm package. Adding a
7
+ # package.json + node_modules just to install hooks would be infrastructure
8
+ # tax for what is otherwise a doc repo. A small bash installer copies the
9
+ # hooks from the version-controlled scripts/hooks/ into .git/hooks/.
10
+ #
11
+ # Usage:
12
+ # bash scripts/install-hooks.sh
13
+ #
14
+ # Re-run any time scripts/hooks/ changes; the installer is idempotent.
15
+
16
+ set -euo pipefail
17
+
18
+ REPO_ROOT="$(git rev-parse --show-toplevel)"
19
+ SOURCE="$REPO_ROOT/scripts/hooks"
20
+ TARGET="$REPO_ROOT/.git/hooks"
21
+
22
+ if [[ ! -d "$SOURCE" ]]; then
23
+ echo "✖ scripts/hooks/ not found; nothing to install" >&2
24
+ exit 1
25
+ fi
26
+
27
+ mkdir -p "$TARGET"
28
+
29
+ installed=0
30
+ for hook in "$SOURCE"/*; do
31
+ name="$(basename "$hook")"
32
+ cp "$hook" "$TARGET/$name"
33
+ chmod +x "$TARGET/$name"
34
+ installed=$((installed + 1))
35
+ done
36
+
37
+ echo "✓ installed $installed hook(s) into .git/hooks/"
38
+ echo
39
+ echo "Active rules (WU 111 enforcement):"
40
+ echo " • index-drift detection (work-units, decisions, open-questions, risks)"
41
+ echo " • active-decision modification BLOCK (was warning under WU 128 light-touch)"
42
+ echo
43
+ echo "To verify the install: \`git hook list\` (git ≥2.36) or \`ls .git/hooks/\`"
44
+ echo "To uninstall: \`rm .git/hooks/pre-commit\`"
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env bash
2
+ #
3
+ # NuOS catalogue post-commit hook — auto-refresh the semantic-search index
4
+ # after every commit that touched docs/build/**.
5
+ #
6
+ # Why this hook:
7
+ # `nuos-catalogue search` only finds what's in the NuVector index. The
8
+ # index is hash-based and incremental, but it doesn't update itself —
9
+ # you have to run `nuos-catalogue index` after meaningful changes for
10
+ # new content to be searchable. Running it manually is too easy to
11
+ # forget; the discipline argument that gave us the pre-commit hook
12
+ # (index-drift, accepted-decision immutability) applies equally here.
13
+ #
14
+ # Behaviour:
15
+ # - Skip if the just-landed commit did NOT touch docs/build/** (most
16
+ # code commits don't need a reindex)
17
+ # - Skip if `nuos-catalogue` isn't resolvable (the CLI may not be
18
+ # installed yet on a fresh clone; this hook should never block)
19
+ # - Otherwise: run the index in the BACKGROUND so the user's terminal
20
+ # isn't held while we embed. All output goes to .nuos-enforcement.log.
21
+ #
22
+ # The hook respects two env vars:
23
+ # NUOS_CATALOGUE_INDEX_DIR default: <repo>/.nuos-catalogue
24
+ # NUOS_CATALOGUE_OLLAMA_MODEL passed through to the CLI
25
+ #
26
+ # This hook never blocks. If indexing fails (Ollama not running, model
27
+ # not pulled, dimension mismatch with existing index), the error goes
28
+ # to the log and the user can investigate. The commit itself already
29
+ # landed by the time post-commit fires.
30
+
31
+ set -uo pipefail
32
+
33
+ REPO_ROOT="$(git rev-parse --show-toplevel)"
34
+ LOG="$REPO_ROOT/.nuos-enforcement.log"
35
+
36
+ dim() { printf '\033[2m%s\033[0m\n' "$*"; }
37
+ yellow() { printf '\033[33m%s\033[0m\n' "$*"; }
38
+
39
+ # ---- Skip-paths --------------------------------------------------------
40
+
41
+ # Skip if this project doesn't have a catalogue at all.
42
+ if [[ ! -d "$REPO_ROOT/docs/build" ]]; then
43
+ exit 0
44
+ fi
45
+
46
+ # Skip if the just-landed commit didn't touch docs/build/**.
47
+ if ! git diff-tree --no-commit-id --name-only -r HEAD 2>/dev/null | grep -q '^docs/build/'; then
48
+ exit 0
49
+ fi
50
+
51
+ # Resolve the CLI: prefer globally-installed `nuos-catalogue`; fall back
52
+ # to `npx --yes` which fetches from npm on demand.
53
+ INDEX_CMD=""
54
+ if command -v nuos-catalogue >/dev/null 2>&1; then
55
+ INDEX_CMD="nuos-catalogue"
56
+ elif command -v npx >/dev/null 2>&1; then
57
+ INDEX_CMD="npx --yes @nusoft/nuos-build-catalogue"
58
+ else
59
+ yellow "[nuos:post-commit] neither nuos-catalogue nor npx found; skipping index refresh"
60
+ printf '%s | post-commit-skip | no CLI available\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" >> "$LOG"
61
+ exit 0
62
+ fi
63
+
64
+ # ---- Background index refresh ------------------------------------------
65
+
66
+ # Default the index dir to project-local if the user hasn't set one.
67
+ : "${NUOS_CATALOGUE_INDEX_DIR:=$REPO_ROOT/.nuos-catalogue}"
68
+ export NUOS_CATALOGUE_INDEX_DIR
69
+
70
+ # Detach from the terminal so the post-commit returns immediately. All
71
+ # output (stdout + stderr) goes to the enforcement log so the user can
72
+ # tail it if they want to see progress.
73
+ (
74
+ start=$(date +%s)
75
+ printf '%s | post-commit-index | start (model=%s, dir=%s)\n' \
76
+ "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" \
77
+ "${NUOS_CATALOGUE_OLLAMA_MODEL:-default}" \
78
+ "$NUOS_CATALOGUE_INDEX_DIR" \
79
+ >> "$LOG"
80
+
81
+ if cd "$REPO_ROOT" && $INDEX_CMD index >> "$LOG" 2>&1; then
82
+ end=$(date +%s)
83
+ printf '%s | post-commit-index | done in %ss\n' \
84
+ "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" \
85
+ $((end - start)) \
86
+ >> "$LOG"
87
+ else
88
+ printf '%s | post-commit-index | FAILED (see lines above in %s)\n' \
89
+ "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" \
90
+ "$(basename "$LOG")" \
91
+ >> "$LOG"
92
+ fi
93
+ ) </dev/null >/dev/null 2>&1 &
94
+ disown 2>/dev/null || true
95
+
96
+ dim "[nuos:post-commit] index refresh started in background — see .nuos-enforcement.log"
@@ -0,0 +1,162 @@
1
+ #!/usr/bin/env bash
2
+ #
3
+ # NuOS catalogue pre-commit hook (WU 111 enforcement phase).
4
+ #
5
+ # Catches drift before commit. After WU 111's Phase J ship, the
6
+ # accepted-decision rule has flipped from warning → block (per the
7
+ # pack's narrower-than-originally-planned enforcement scope, recorded
8
+ # in WU 111's "Forward-compatibility commitments" section). Other
9
+ # rules described in WU 128's original aggressive list are NOT shipping
10
+ # — distinguishing tool-written from human-written content was deemed
11
+ # overengineering for a planning-artefact catalogue.
12
+ #
13
+ # Active rules:
14
+ # 1. index-drift detection — every WU/decision/open-question/risk file
15
+ # must have a matching row in its _index.md (and vice versa)
16
+ # 2. active-decision modification block — modifying a committed
17
+ # `accepted` decision file is BLOCKED (not just warned). The
18
+ # discipline is to write a superseding D-NNN+1 and link forward.
19
+ # To deliberately fix a typo or link in an accepted decision,
20
+ # use `git commit --no-verify` (CLAUDE.md prohibits this for
21
+ # substantive changes; reserve it for typo-only fixes).
22
+ #
23
+ # Sentinel-protected sections (e.g. STATE.md's `nuos:sentinel`) remain
24
+ # protected via the existing `.claude/hooks/check-catalogue-write.sh`
25
+ # Claude Code hook. That rule continues unchanged at WU 111 ship.
26
+ #
27
+ # Bypass: this hook respects --no-verify like any other. The CLAUDE.md
28
+ # policy explicitly prohibits --no-verify use for substantive changes;
29
+ # the technical block fires at the CI server-side check (a future WU).
30
+
31
+ set -uo pipefail
32
+
33
+ REPO_ROOT="$(git rev-parse --show-toplevel)"
34
+ ENFORCEMENT_LOG="$REPO_ROOT/.nuos-enforcement.log"
35
+ EXIT_CODE=0
36
+
37
+ red() { printf '\033[31m%s\033[0m\n' "$*"; }
38
+ yellow() { printf '\033[33m%s\033[0m\n' "$*"; }
39
+ green() { printf '\033[32m%s\033[0m\n' "$*"; }
40
+ dim() { printf '\033[2m%s\033[0m\n' "$*"; }
41
+
42
+ log_event() {
43
+ printf '%s | %s | %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$1" "$2" >> "$ENFORCEMENT_LOG"
44
+ }
45
+
46
+ # ---------- Generic index-drift checker ---------------------------------
47
+ #
48
+ # Args:
49
+ # $1 — kind label (for messages)
50
+ # $2 — directory (relative to repo root)
51
+ # $3 — _index.md path (relative to repo root)
52
+ # $4 — filename regex (matches IDs the directory contains)
53
+ # $5 — index-row ID regex (a Perl-compatible regex that anchors on the
54
+ # leftmost column of an index table row)
55
+ #
56
+ # The two regexes must extract the SAME set of IDs (e.g. "001", "030g",
57
+ # "D042") so set comparison works.
58
+
59
+ check_index_drift() {
60
+ local kind="$1" dir="$2" index="$3" file_regex="$4" row_regex="$5"
61
+
62
+ if [[ ! -d "$REPO_ROOT/$dir" ]]; then return 0; fi
63
+ if [[ ! -f "$REPO_ROOT/$index" ]]; then return 0; fi
64
+
65
+ # IDs extracted from filenames in the directory (top-level + one subdir
66
+ # like done/, resolved/, superseded/)
67
+ local ids_in_tree
68
+ ids_in_tree=$(cd "$REPO_ROOT/$dir" && {
69
+ find . -maxdepth 2 -type f -name "*.md" \
70
+ -not -name "_index.md" \
71
+ -not -name "*-template.md" 2>/dev/null \
72
+ | sed -nE "$file_regex" \
73
+ | sort -u
74
+ })
75
+
76
+ # IDs extracted from leftmost column of table rows in the index
77
+ local ids_in_index
78
+ ids_in_index=$(sed -nE "$row_regex" "$REPO_ROOT/$index" | sort -u)
79
+
80
+ local missing_from_index
81
+ missing_from_index=$(comm -23 <(printf '%s\n' "$ids_in_tree") <(printf '%s\n' "$ids_in_index"))
82
+
83
+ if [[ -n "$missing_from_index" ]]; then
84
+ red "✖ index-drift ($kind): on disk but missing from $index:"
85
+ while IFS= read -r id; do echo " — $id"; done <<< "$missing_from_index"
86
+ log_event "index-drift" "$kind missing from index: $(echo "$missing_from_index" | tr '\n' ',')"
87
+ EXIT_CODE=1
88
+ fi
89
+ }
90
+
91
+ dim "[nuos:pre-commit] index-drift check"
92
+
93
+ # Note: BSD sed (macOS default) is fussy about `|` as both delimiter and
94
+ # regex content. Using `#` as the s/// delimiter sidesteps the collision.
95
+
96
+ # Work units: filenames are NNN-slug.md or NNNa-slug.md (with optional letter).
97
+ # Index rows are `| NNN |` or `| NNNa |` in the leftmost column.
98
+ check_index_drift \
99
+ "work-units" \
100
+ "docs/build/work-units" \
101
+ "docs/build/work-units/_index.md" \
102
+ 's#^\./(done/)?([0-9]{3}[a-z]?)-[^/]*\.md$#\2#p' \
103
+ 's#^\| ([0-9]{3}[a-z]?) \|.*$#\1#p'
104
+
105
+ # Decisions: filenames are DNNN-slug.md.
106
+ # Index rows: `| DNNN |` or `| [DNNN](...) |`.
107
+ check_index_drift \
108
+ "decisions" \
109
+ "docs/build/decisions" \
110
+ "docs/build/decisions/_index.md" \
111
+ 's#^\./(done/|superseded/)?(D[0-9]{3})-[^/]*\.md$#\2#p' \
112
+ 's#^\| \[?(D[0-9]{3}).*$#\1#p'
113
+
114
+ # Open questions: filenames are QNNN-slug.md.
115
+ check_index_drift \
116
+ "open-questions" \
117
+ "docs/build/open-questions" \
118
+ "docs/build/open-questions/_index.md" \
119
+ 's#^\./(resolved/)?(Q[0-9]{3})-[^/]*\.md$#\2#p' \
120
+ 's#^\| \[?(Q[0-9]{3}).*$#\1#p'
121
+
122
+ # Risks: per current convention, individual risk files are inline in
123
+ # risks/_index.md (no per-risk .md files yet). Skip the check entirely
124
+ # until that pattern changes.
125
+ if compgen -G "$REPO_ROOT/docs/build/risks/R[0-9][0-9][0-9]-*.md" > /dev/null; then
126
+ check_index_drift \
127
+ "risks" \
128
+ "docs/build/risks" \
129
+ "docs/build/risks/_index.md" \
130
+ 's#^\./(R[0-9]{3})-[^/]*\.md$#\1#p' \
131
+ 's#^\| \[?(R[0-9]{3}).*$#\1#p'
132
+ fi
133
+
134
+ # ---------- Rule 2: active-decision modification block (WU 111 ship) ---
135
+
136
+ dim "[nuos:pre-commit] active-decision modification check"
137
+ modified_decisions=$(git diff --cached --name-only --diff-filter=M \
138
+ | grep -E '^docs/build/decisions/D[0-9]+.*\.md$' \
139
+ | grep -v '/superseded/' \
140
+ || true)
141
+
142
+ if [[ -n "$modified_decisions" ]]; then
143
+ red "✖ active-decision modification — BLOCKED (WU 111 enforcement):"
144
+ while IFS= read -r f; do echo " — $f"; done <<< "$modified_decisions"
145
+ red " Decisions are immutable once accepted. The discipline is to write a"
146
+ red " superseding D-NNN+1 and link forward. Use:"
147
+ red " nuos-catalogue decision supersede <target> --by=<new-D> --reason=\"...\""
148
+ red ""
149
+ red " If this edit is a non-substantive typo fix or link cleanup that does"
150
+ red " not change the decision's meaning, you may bypass this block with"
151
+ red " --no-verify. CLAUDE.md prohibits --no-verify for substantive changes."
152
+ log_event "active-decision-block" "$(echo "$modified_decisions" | tr '\n' ',')"
153
+ EXIT_CODE=1
154
+ fi
155
+
156
+ # ---------- Result ------------------------------------------------------
157
+
158
+ if [[ $EXIT_CODE -eq 0 ]]; then
159
+ green "[nuos:pre-commit] all rules pass (WU 111 enforcement)"
160
+ log_event "pre-commit-pass" "$(git diff --cached --name-only | wc -l | tr -d ' ') files"
161
+ fi
162
+ exit $EXIT_CODE