specjig 0.0.0-stage → 0.2.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 (69) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/LICENSE +24 -0
  3. package/README.md +106 -2
  4. package/bin/specjig.mjs +7 -0
  5. package/harness.lock.json +61 -0
  6. package/package.json +54 -4
  7. package/src/cli.mjs +278 -0
  8. package/src/lib/install.mjs +242 -0
  9. package/src/lib/openspec.mjs +83 -0
  10. package/src/lib/util.mjs +86 -0
  11. package/templates/.claude/hooks/sdd-commit-guard.mjs +39 -0
  12. package/templates/.claude/hooks/sdd-fix-mode-guard.mjs +34 -0
  13. package/templates/.claude/hooks/sdd-lib/change-id.mjs +47 -0
  14. package/templates/.claude/hooks/sdd-lib/io.mjs +29 -0
  15. package/templates/.claude/hooks/sdd-lib/patterns.mjs +130 -0
  16. package/templates/.claude/hooks/sdd-prompt-guard.mjs +17 -0
  17. package/templates/.claude/hooks/sdd-protect-secrets.mjs +32 -0
  18. package/templates/.claude/rules/openspec.md +14 -0
  19. package/templates/.claude/rules/security.md +31 -0
  20. package/templates/.claude/rules/test-data.md +22 -0
  21. package/templates/.claude/settings.json +97 -0
  22. package/templates/.claude/skills/change-pr/SKILL.md +61 -0
  23. package/templates/.claude/skills/spec-challenge/SKILL.md +63 -0
  24. package/templates/.claude/skills/spec-compaction/SKILL.md +47 -0
  25. package/templates/.claude/skills/trace-why/SKILL.md +30 -0
  26. package/templates/.githooks/commit-msg +4 -0
  27. package/templates/.github/workflows/sdd-ci-triage.yml +61 -0
  28. package/templates/.github/workflows/sdd-confluence-sync.yml +24 -0
  29. package/templates/.github/workflows/sdd-drift-check.yml +50 -0
  30. package/templates/.github/workflows/sdd-fix-pr-guard.yml +25 -0
  31. package/templates/.github/workflows/sdd-release-notes.yml +45 -0
  32. package/templates/.github/workflows/sdd-security-review.yml +23 -0
  33. package/templates/.github/workflows/sdd-spec-gate.yml +23 -0
  34. package/templates/.github/workflows/sdd-spec-review.yml +51 -0
  35. package/templates/.mcp.json +8 -0
  36. package/templates/.sdd/harness.json +21 -0
  37. package/templates/.sdd/scripts/check-commit-msg.mjs +15 -0
  38. package/templates/.sdd/scripts/check-trailers.mjs +27 -0
  39. package/templates/.sdd/scripts/confluence-sync.mjs +110 -0
  40. package/templates/.sdd/scripts/drift-check.mjs +30 -0
  41. package/templates/.sdd/scripts/fix-pr-guard.mjs +17 -0
  42. package/templates/.sdd/scripts/lib.mjs +31 -0
  43. package/templates/.sdd/scripts/release-notes.mjs +63 -0
  44. package/templates/AGENTS.md +87 -0
  45. package/templates/CLAUDE.md +30 -0
  46. package/templates/openspec/config.yaml +38 -0
  47. package/templates/openspec/schemas/sdd/schema.yaml +379 -0
  48. package/templates/openspec/schemas/sdd/templates/design.md +29 -0
  49. package/templates/openspec/schemas/sdd/templates/impact.md +27 -0
  50. package/templates/openspec/schemas/sdd/templates/proposal.md +43 -0
  51. package/templates/openspec/schemas/sdd/templates/spec.md +13 -0
  52. package/templates/openspec/schemas/sdd/templates/tasks.md +15 -0
  53. package/templates/openspec/schemas/sdd/templates/tests.md +17 -0
  54. package/vendor/skills/grilling/.upstream.json +8 -0
  55. package/vendor/skills/grilling/SKILL.md +30 -0
  56. package/vendor/skills/receiving-code-review/.upstream.json +8 -0
  57. package/vendor/skills/receiving-code-review/SKILL.md +205 -0
  58. package/vendor/skills/systematic-debugging/.upstream.json +8 -0
  59. package/vendor/skills/systematic-debugging/SKILL.md +283 -0
  60. package/vendor/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  61. package/vendor/skills/systematic-debugging/condition-based-waiting.md +115 -0
  62. package/vendor/skills/systematic-debugging/defense-in-depth.md +122 -0
  63. package/vendor/skills/systematic-debugging/find-polluter.sh +72 -0
  64. package/vendor/skills/systematic-debugging/root-cause-tracing.md +169 -0
  65. package/vendor/skills/test-driven-development/.upstream.json +8 -0
  66. package/vendor/skills/test-driven-development/SKILL.md +330 -0
  67. package/vendor/skills/test-driven-development/writing-good-tests.md +198 -0
  68. package/vendor/skills/two-axis-review/.upstream.json +8 -0
  69. package/vendor/skills/two-axis-review/SKILL.md +89 -0
@@ -0,0 +1,242 @@
1
+ // Applies harness files to a project, tracking what it wrote in .sdd/manifest.json so updates
2
+ // never clobber local edits.
3
+ //
4
+ // Ownership modes:
5
+ // managed harness owns the file; overwritten on update unless edited locally
6
+ // (then the new version lands next to it as <file>.sdd-new)
7
+ // seed written once on init; project-owned afterwards
8
+ // block only the text between <!-- specjig:begin --> and <!-- specjig:end --> is managed
9
+ // merge JSON deep-merge: arrays are unioned, existing scalars win, harness hook entries replaced
10
+ import { existsSync } from 'node:fs';
11
+ import { chmod, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
12
+ import path from 'node:path';
13
+ import { lock, log, pkgVersion, sha256, TEMPLATES, VENDOR_SKILLS, walk } from './util.mjs';
14
+
15
+ const MANIFEST = '.sdd/manifest.json';
16
+ const BLOCK_RE = /<!-- specjig:begin[^>]*-->[\s\S]*?<!-- specjig:end -->/;
17
+
18
+ const SEED = new Set(['openspec/config.yaml', '.sdd/harness.json']);
19
+ const BLOCK = new Set(['AGENTS.md', 'CLAUDE.md']);
20
+ const MERGE = new Set(['.claude/settings.json', '.mcp.json']);
21
+
22
+ export function modeFor(rel) {
23
+ if (SEED.has(rel)) return 'seed';
24
+ if (BLOCK.has(rel)) return 'block';
25
+ if (MERGE.has(rel)) return 'merge';
26
+ return 'managed';
27
+ }
28
+
29
+ function vars(cwd, openspecVersion) {
30
+ const l = lock();
31
+ return {
32
+ PROJECT_NAME: path.basename(cwd),
33
+ HARNESS_VERSION: pkgVersion(),
34
+ OPENSPEC_VERSION: openspecVersion ?? l.openspec.version,
35
+ PLAYWRIGHT_MCP_VERSION: l.mcp['@playwright/mcp'],
36
+ CLAUDE_CODE_ACTION: l.actions['anthropics/claude-code-action'],
37
+ SECURITY_REVIEW_ACTION: l.actions['anthropics/claude-code-security-review'],
38
+ };
39
+ }
40
+
41
+ const TEXT = /\.(md|mjs|js|json|ya?ml|sh|txt)$|(^|\/)[^.]+$/;
42
+ function render(rel, buf, v) {
43
+ if (!TEXT.test(rel)) return buf;
44
+ return Buffer.from(buf.toString('utf8').replace(/\{\{([A-Z_]+)\}\}/g, (m, k) => v[k] ?? m));
45
+ }
46
+
47
+ /** All files the harness ships, as [{rel, src, content}], templates + vendored skills. */
48
+ export async function plannedFiles(cwd, openspecVersion) {
49
+ const v = vars(cwd, openspecVersion);
50
+ const files = [];
51
+ for (const rel of await walk(TEMPLATES)) {
52
+ files.push({ rel, content: render(rel, await readFile(path.join(TEMPLATES, rel)), v) });
53
+ }
54
+ for (const rel of await walk(VENDOR_SKILLS)) {
55
+ files.push({ rel: `.claude/skills/${rel}`, content: await readFile(path.join(VENDOR_SKILLS, rel)) });
56
+ }
57
+ return files;
58
+ }
59
+
60
+ async function readManifest(cwd) {
61
+ const f = path.join(cwd, MANIFEST);
62
+ return existsSync(f) ? JSON.parse(await readFile(f, 'utf8')) : { files: {} };
63
+ }
64
+
65
+ // --- merge helpers -----------------------------------------------------------------------
66
+ const isObj = (x) => x && typeof x === 'object' && !Array.isArray(x);
67
+ const isHarnessHook = (entry) => JSON.stringify(entry).includes('/.claude/hooks/sdd-');
68
+
69
+ function deepMerge(existing, incoming, keyPath = []) {
70
+ if (Array.isArray(existing) && Array.isArray(incoming)) {
71
+ // Hook event arrays: replace previous harness entries so updated commands don't duplicate.
72
+ const base = keyPath[0] === 'hooks' ? existing.filter((e) => !isHarnessHook(e)) : existing;
73
+ const seen = new Set(base.map((e) => JSON.stringify(e)));
74
+ return [...base, ...incoming.filter((e) => !seen.has(JSON.stringify(e)))];
75
+ }
76
+ if (isObj(existing) && isObj(incoming)) {
77
+ const out = { ...existing };
78
+ for (const [k, val] of Object.entries(incoming)) {
79
+ out[k] = k in existing ? deepMerge(existing[k], val, [...keyPath, k]) : val;
80
+ }
81
+ return out;
82
+ }
83
+ return existing; // scalars: the project's value wins
84
+ }
85
+
86
+ // --- apply -------------------------------------------------------------------------------
87
+ export async function applyFiles(cwd, { isUpdate = false, openspec = { mode: 'install', version: lock().openspec.version } } = {}) {
88
+ const manifest = await readManifest(cwd);
89
+ const next = { harnessVersion: pkgVersion(), openspec, files: {} };
90
+ const report = { written: [], unchanged: [], conflicts: [], skipped: [], removed: [], excluded: [] };
91
+ const planned = await plannedFiles(cwd, openspec.version);
92
+ const isExcluded = await excludeMatcher(cwd);
93
+
94
+ for (const { rel, content } of planned) {
95
+ const dest = path.join(cwd, rel);
96
+ const mode = modeFor(rel);
97
+ const exists = existsSync(dest);
98
+ const current = exists ? await readFile(dest) : null;
99
+
100
+ // Opt-outs: listed in .sdd/harness.json "exclude", or a managed file the project deleted.
101
+ if (isExcluded(rel) || (mode === 'managed' && !exists && rel in manifest.files)) {
102
+ if (rel in manifest.files) next.files[rel] = manifest.files[rel];
103
+ report.excluded.push(rel);
104
+ continue;
105
+ }
106
+ await mkdir(path.dirname(dest), { recursive: true });
107
+
108
+ if (mode === 'seed') {
109
+ if (exists && !isPristineOpenspecConfig(rel, current)) {
110
+ report.skipped.push(rel);
111
+ continue;
112
+ }
113
+ await writeFile(dest, content);
114
+ report.written.push(rel);
115
+ continue;
116
+ }
117
+
118
+ if (mode === 'block') {
119
+ const block = content.toString('utf8').match(BLOCK_RE)[0];
120
+ let text;
121
+ if (!exists) text = content.toString('utf8');
122
+ else if (BLOCK_RE.test(current.toString('utf8'))) text = current.toString('utf8').replace(BLOCK_RE, block);
123
+ else text = `${current.toString('utf8').trimEnd()}\n\n${block}\n`;
124
+ if (rel === 'CLAUDE.md' && exists && !/^@AGENTS\.md/m.test(text)) text = `@AGENTS.md\n\n${text}`;
125
+ await write(dest, text, current, report, rel);
126
+ continue;
127
+ }
128
+
129
+ if (mode === 'merge') {
130
+ const incoming = JSON.parse(content.toString('utf8'));
131
+ const merged = exists ? deepMerge(JSON.parse(current.toString('utf8')), incoming) : incoming;
132
+ await write(dest, JSON.stringify(merged, null, 2) + '\n', current, report, rel);
133
+ continue;
134
+ }
135
+
136
+ // managed
137
+ const hash = sha256(content);
138
+ next.files[rel] = hash;
139
+ if (exists) {
140
+ const curHash = sha256(current);
141
+ if (curHash === hash) {
142
+ report.unchanged.push(rel);
143
+ continue;
144
+ }
145
+ const known = manifest.files[rel];
146
+ const locallyEdited = known ? curHash !== known : true;
147
+ if (locallyEdited) {
148
+ await writeFile(`${dest}.sdd-new`, content);
149
+ next.files[rel] = known ?? curHash; // keep tracking the version the user diverged from
150
+ report.conflicts.push(rel);
151
+ continue;
152
+ }
153
+ }
154
+ await writeFile(dest, content);
155
+ if (rel.startsWith('.githooks/') || rel.endsWith('.sh')) await chmod(dest, 0o755);
156
+ report.written.push(rel);
157
+ }
158
+
159
+ // Files the previous harness version shipped but this one doesn't: remove if untouched.
160
+ if (isUpdate) {
161
+ for (const [rel, hash] of Object.entries(manifest.files)) {
162
+ if (rel in next.files) continue;
163
+ const dest = path.join(cwd, rel);
164
+ if (!existsSync(dest)) continue;
165
+ if (sha256(await readFile(dest)) === hash) {
166
+ await rm(dest);
167
+ report.removed.push(rel);
168
+ } else {
169
+ report.conflicts.push(`${rel} (removed upstream, kept because edited locally)`);
170
+ }
171
+ }
172
+ }
173
+
174
+ await ensureGitignore(cwd, report);
175
+ await mkdir(path.join(cwd, '.sdd'), { recursive: true });
176
+ await writeFile(path.join(cwd, MANIFEST), JSON.stringify(next, null, 2) + '\n');
177
+ return report;
178
+ }
179
+
180
+ async function excludeMatcher(cwd) {
181
+ const cfgFile = path.join(cwd, '.sdd', 'harness.json');
182
+ if (!existsSync(cfgFile)) return () => false;
183
+ let globs = [];
184
+ try {
185
+ globs = JSON.parse(await readFile(cfgFile, 'utf8')).exclude ?? [];
186
+ } catch {
187
+ return () => false;
188
+ }
189
+ const { globToRegExp } = await import(path.join(TEMPLATES, '.claude/hooks/sdd-lib/patterns.mjs'));
190
+ const res = globs.map((g) => globToRegExp(g.replace(/^\.?\//, '')));
191
+ // Never let a project exclude its own config or the manifest bookkeeping.
192
+ return (rel) => !SEED.has(rel) && res.some((r) => r.test(rel));
193
+ }
194
+
195
+ const GITIGNORE = ['.env', '.env.*', '!.env.example', '*.pem', '*.key', '*.dump', '*.sdd-new', 'node_modules/'];
196
+ async function ensureGitignore(cwd, report) {
197
+ const file = path.join(cwd, '.gitignore');
198
+ const current = existsSync(file) ? await readFile(file, 'utf8') : '';
199
+ const have = new Set(current.split('\n').map((l) => l.trim()));
200
+ const missing = GITIGNORE.filter((l) => !have.has(l));
201
+ if (!missing.length) return;
202
+ const sep = current && !current.endsWith('\n') ? '\n' : '';
203
+ await writeFile(file, `${current}${sep}${current ? '\n' : ''}# specjig: secrets never reach git\n${missing.join('\n')}\n`);
204
+ report.written.push('.gitignore');
205
+ }
206
+
207
+ async function write(dest, text, current, report, rel) {
208
+ if (current && current.toString('utf8') === text) {
209
+ report.unchanged.push(rel);
210
+ return;
211
+ }
212
+ await writeFile(dest, text);
213
+ report.written.push(rel);
214
+ }
215
+
216
+ // `openspec init` writes a default config.yaml (schema: spec-driven + comments). Replace that one.
217
+ function isPristineOpenspecConfig(rel, buf) {
218
+ if (rel !== 'openspec/config.yaml') return false;
219
+ const meaningful = buf
220
+ .toString('utf8')
221
+ .split('\n')
222
+ .map((l) => l.trim())
223
+ .filter((l) => l && !l.startsWith('#'));
224
+ return meaningful.length === 1 && meaningful[0] === 'schema: spec-driven';
225
+ }
226
+
227
+ export function printReport(report) {
228
+ if (report.written.length) log.ok(`${report.written.length} file(s) written`);
229
+ if (report.unchanged.length) log.ok(`${report.unchanged.length} file(s) already up to date`);
230
+ for (const f of report.skipped) log.info(` - kept project-owned ${f}`);
231
+ for (const f of report.removed) log.info(` - removed ${f} (no longer shipped)`);
232
+ if (report.excluded.length) log.info(` - ${report.excluded.length} file(s) left out (deleted locally or in .sdd/harness.json "exclude")`);
233
+ for (const f of report.conflicts) log.warn(`${f} was edited locally; new version saved as ${f.split(' ')[0]}.sdd-new; merge it by hand`);
234
+ }
235
+
236
+ export async function isDir(p) {
237
+ try {
238
+ return (await stat(p)).isDirectory();
239
+ } catch {
240
+ return false;
241
+ }
242
+ }
@@ -0,0 +1,83 @@
1
+ // OpenSpec ownership. Two modes:
2
+ // install the harness pins @fission-ai/openspec (exact devDependency), runs init/update and
3
+ // moves the pin on every `specjig update`.
4
+ // existing the project already uses OpenSpec and keeps it: the harness never installs, bumps or
5
+ // re-inits it, only adds the `sdd` schema, skills, hooks and CI next to it. CI uses the
6
+ // project's OpenSpec version.
7
+ import { existsSync } from 'node:fs';
8
+ import path from 'node:path';
9
+ import { createInterface } from 'node:readline/promises';
10
+ import { lock, log, readJson, tryRun } from './util.mjs';
11
+
12
+ export const MODES = ['install', 'existing'];
13
+ const semver = (s) => s?.match(/\d+\.\d+\.\d+(-[\w.]+)?/)?.[0] ?? null;
14
+
15
+ /** What OpenSpec the project already has, without changing anything. */
16
+ export function detectOpenspec(cwd) {
17
+ const pkg = lock().openspec.package;
18
+ const pj = path.join(cwd, 'package.json');
19
+ const json = existsSync(pj) ? readJson(pj) : {};
20
+ const declared = { ...json.dependencies, ...json.devDependencies }[pkg] ?? null;
21
+ const localBin = path.join(cwd, 'node_modules', '.bin', process.platform === 'win32' ? 'openspec.cmd' : 'openspec');
22
+ const localVersion = existsSync(localBin) ? semver(tryRun(localBin, ['--version'], { cwd })) : null;
23
+ const globalVersion = localVersion ? null : semver(tryRun('openspec', ['--version'], { cwd }));
24
+ const initialized = existsSync(path.join(cwd, 'openspec'));
25
+ const version = localVersion ?? globalVersion ?? semver(declared);
26
+ return {
27
+ initialized,
28
+ declared,
29
+ version,
30
+ bin: localVersion ? localBin : globalVersion ? 'openspec' : null,
31
+ source: localVersion ? 'node_modules' : globalVersion ? 'global' : declared ? 'package.json (not installed)' : null,
32
+ present: Boolean(initialized || declared || localVersion || globalVersion),
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Decide the mode: explicit flag > mode recorded on a previous install > ask (TTY) >
38
+ * safe default (keep the project's OpenSpec when it has one).
39
+ */
40
+ export async function chooseMode(det, { flag, previous, interactive = process.stdin.isTTY && process.stdout.isTTY } = {}) {
41
+ if (flag !== undefined && flag !== true) {
42
+ if (!MODES.includes(flag)) throw new Error(`--openspec must be one of: ${MODES.join(', ')}`);
43
+ return flag;
44
+ }
45
+ if (previous && MODES.includes(previous)) return previous;
46
+ if (!det.present) return 'install';
47
+ if (!interactive) {
48
+ log.warn(`OpenSpec already present (${describe(det)}); keeping it. Pass --openspec=install to let the harness pin and manage it.`);
49
+ return 'existing';
50
+ }
51
+ const pinned = lock().openspec.version;
52
+ console.log(`\nOpenSpec is already set up in this project (${describe(det)}).`);
53
+ console.log(` 1) Keep my OpenSpec: harness adds the sdd schema, skills, hooks and CI next to it (default)`);
54
+ console.log(` 2) Let the harness manage it: pin ${lock().openspec.package}@${pinned} and bump it on specjig update`);
55
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
56
+ const answer = (await rl.question('Choose 1 or 2 [1]: ')).trim();
57
+ rl.close();
58
+ return answer === '2' ? 'install' : 'existing';
59
+ }
60
+
61
+ export function describe(det) {
62
+ const parts = [];
63
+ if (det.version) parts.push(`v${det.version} from ${det.source}`);
64
+ else if (det.declared) parts.push(`declared ${det.declared}`);
65
+ if (det.initialized) parts.push('openspec/ initialised');
66
+ return parts.join(', ') || 'not found';
67
+ }
68
+
69
+ /** Version CI should run: the pin in install mode, the project's own in existing mode. */
70
+ export function ciVersion(mode, det) {
71
+ return mode === 'existing' && det.version ? det.version : lock().openspec.version;
72
+ }
73
+
74
+ /** Warn when the project's OpenSpec may not understand the forked schema. */
75
+ export function compatibilityWarning(det) {
76
+ const pinned = lock().openspec.version;
77
+ if (!det.version) return `could not determine the project's OpenSpec version; the sdd schema was forked from ${pinned}.`;
78
+ const major = (v) => Number(v.split('.')[0]);
79
+ if (major(det.version) < major(pinned)) {
80
+ return `project OpenSpec ${det.version} is older than ${pinned} (the sdd schema's base). Custom schemas may not load; consider --openspec=install or upgrading OpenSpec.`;
81
+ }
82
+ return null;
83
+ }
@@ -0,0 +1,86 @@
1
+ import { execFileSync, spawnSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { readdir } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ export const PKG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
9
+ export const TEMPLATES = path.join(PKG_ROOT, 'templates');
10
+ export const VENDOR_SKILLS = path.join(PKG_ROOT, 'vendor', 'skills');
11
+
12
+ export const readJson = (file) => JSON.parse(readFileSync(file, 'utf8'));
13
+ export const pkgName = () => readJson(path.join(PKG_ROOT, 'package.json')).name;
14
+ export const pkgVersion = () => readJson(path.join(PKG_ROOT, 'package.json')).version;
15
+ export const lock = () => readJson(path.join(PKG_ROOT, 'harness.lock.json'));
16
+ export const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
17
+
18
+ export const log = {
19
+ info: (m) => console.log(m),
20
+ ok: (m) => console.log(` \x1b[32m✓\x1b[0m ${m}`),
21
+ warn: (m) => console.log(` \x1b[33m!\x1b[0m ${m}`),
22
+ step: (m) => console.log(`\n\x1b[1m${m}\x1b[0m`),
23
+ };
24
+
25
+ export async function walk(dir, base = dir) {
26
+ const out = [];
27
+ if (!existsSync(dir)) return out;
28
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
29
+ const full = path.join(dir, entry.name);
30
+ if (entry.isDirectory()) out.push(...(await walk(full, base)));
31
+ else out.push(path.relative(base, full).split(path.sep).join('/'));
32
+ }
33
+ return out.sort();
34
+ }
35
+
36
+ export function run(cmd, args, { cwd, quiet = false } = {}) {
37
+ const res = spawnSync(cmd, args, { cwd, stdio: quiet ? 'pipe' : 'inherit', encoding: 'utf8', shell: process.platform === 'win32' });
38
+ if (res.status !== 0) {
39
+ const detail = quiet ? `\n${res.stderr || res.stdout}` : '';
40
+ throw new Error(`${cmd} ${args.join(' ')} failed (exit ${res.status})${detail}`);
41
+ }
42
+ return res.stdout;
43
+ }
44
+
45
+ export function tryRun(cmd, args, opts = {}) {
46
+ try {
47
+ return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], ...opts }).trim();
48
+ } catch {
49
+ return null;
50
+ }
51
+ }
52
+
53
+ export function detectPackageManager(cwd) {
54
+ if (existsSync(path.join(cwd, 'pnpm-lock.yaml'))) return 'pnpm';
55
+ if (existsSync(path.join(cwd, 'yarn.lock'))) return 'yarn';
56
+ if (existsSync(path.join(cwd, 'bun.lockb')) || existsSync(path.join(cwd, 'bun.lock'))) return 'bun';
57
+ return 'npm';
58
+ }
59
+
60
+ export function addDevDepArgs(pm, spec) {
61
+ switch (pm) {
62
+ case 'pnpm':
63
+ return ['add', '-D', '-E', spec];
64
+ case 'yarn':
65
+ return ['add', '-D', '-E', spec];
66
+ case 'bun':
67
+ return ['add', '-d', '--exact', spec];
68
+ default:
69
+ return ['install', '-D', '-E', spec];
70
+ }
71
+ }
72
+
73
+ export function parseArgs(argv) {
74
+ const flags = {};
75
+ const positional = [];
76
+ for (let i = 0; i < argv.length; i++) {
77
+ const a = argv[i];
78
+ if (a.startsWith('--')) {
79
+ const [k, v] = a.slice(2).split('=');
80
+ if (v !== undefined) flags[k] = v;
81
+ else if (argv[i + 1] && !argv[i + 1].startsWith('-') && ['dir', 'since', 'until', 'openspec'].includes(k)) flags[k] = argv[++i];
82
+ else flags[k] = true;
83
+ } else positional.push(a);
84
+ }
85
+ return { flags, positional };
86
+ }
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ // Managed by specjig. PreToolUse guard on Bash: `git commit` made by the agent must carry a
3
+ // valid `Change-Id:` trailer, so `git blame` -> commit -> openspec change always resolves.
4
+ // The .githooks/commit-msg hook enforces the same rule for humans; this hook gives the agent
5
+ // the feedback before git runs.
6
+ import { existsSync, readFileSync } from 'node:fs';
7
+ import path from 'node:path';
8
+ import { activeChanges, changeExists, NONE } from './sdd-lib/change-id.mjs';
9
+ import { block, projectDir, readHookInput } from './sdd-lib/io.mjs';
10
+
11
+ const input = await readHookInput();
12
+ const cmd = input.tool_input?.command ?? '';
13
+ if (!/\bgit\s+(-c\s+\S+\s+)*commit\b/.test(cmd)) process.exit(0);
14
+ if (/--amend\b.*--no-edit|--no-edit\b.*--amend/.test(cmd)) process.exit(0);
15
+
16
+ const cwd = projectDir(input);
17
+ let id = null;
18
+ const inline = cmd.match(/Change-Id[:=]\s*([a-z0-9][a-z0-9-]*)/i);
19
+ if (inline) id = inline[1].toLowerCase();
20
+ const fileArg = cmd.match(/(?:-F|--file)[=\s]+("[^"]+"|'[^']+'|\S+)/);
21
+ if (!id && fileArg) {
22
+ const f = path.resolve(cwd, fileArg[1].replace(/^["']|["']$/g, ''));
23
+ if (existsSync(f)) id = readFileSync(f, 'utf8').match(/^Change-Id:\s*([a-z0-9-]+)/im)?.[1] ?? null;
24
+ }
25
+
26
+ const hint = () => {
27
+ const active = activeChanges(cwd);
28
+ return active.length
29
+ ? `Active changes: ${active.join(', ')}.`
30
+ : 'No active change found; use "none" only for work without a behavior change.';
31
+ };
32
+
33
+ if (!id) {
34
+ block(`git commit without a Change-Id trailer. Add it with --trailer "Change-Id: <change-name>" (or "Change-Id: ${NONE}" for deps/format/CI-only work). ${hint()}`);
35
+ }
36
+ if (!changeExists(id, cwd)) {
37
+ block(`Change-Id "${id}" does not exist in openspec/changes/. ${hint()}`);
38
+ }
39
+ process.exit(0);
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ // Managed by specjig. PreToolUse guard active only when SDD_MODE=fix (the CI triage agent).
3
+ // In fix mode the agent repairs lint / format / types / dependencies and must not touch tests or
4
+ // specs: changing them would let it "fix" CI by weakening the contract. The fix-PR workflow
5
+ // re-checks the final diff, so this hook is the early feedback, not the only line of defence.
6
+ import { globToRegExp } from './sdd-lib/patterns.mjs';
7
+ import { block, harnessConfig, projectDir, readHookInput } from './sdd-lib/io.mjs';
8
+ import path from 'node:path';
9
+
10
+ if (process.env.SDD_MODE !== 'fix') process.exit(0);
11
+
12
+ const input = await readHookInput();
13
+ const cwd = projectDir(input);
14
+ const cfg = harnessConfig(cwd);
15
+ const DEFAULT_FROZEN = ['**/*.test.*', '**/*.spec.*', '**/__tests__/**', 'test/**', 'tests/**', 'e2e/**', '**/fixtures/**', '**/*.snap'];
16
+ const frozen = [...(cfg.fixMode?.frozenPaths ?? DEFAULT_FROZEN), 'openspec/**'].map(globToRegExp);
17
+
18
+ const rel = (p) => (path.isAbsolute(p) ? path.relative(cwd, p) : p).replace(/\\/g, '/').replace(/^\.\//, '');
19
+ const isFrozen = (p) => frozen.some((r) => r.test(rel(p)));
20
+
21
+ const t = input.tool_input ?? {};
22
+ for (const p of [t.file_path, t.notebook_path].filter(Boolean)) {
23
+ if (isFrozen(p)) block(`fix mode: "${rel(p)}" is a test or spec file. Fix PRs may not change tests or openspec/. If the failure is in the test or spec itself, stop and report it for a human.`);
24
+ }
25
+
26
+ if (input.tool_name === 'Bash') {
27
+ const cmd = t.command ?? '';
28
+ const writes = /(\bsed\s+-i|\btee\b|>|\bmv\b|\bcp\b|\brm\b|\btruncate\b|\bgit\s+(checkout|restore|rm|mv)\b|\bperl\s+-p?i)/.test(cmd);
29
+ const paths = cmd.split(/[\s;&|()<>'"]+/).filter((w) => w && !w.startsWith('-'));
30
+ if (writes && paths.some(isFrozen)) {
31
+ block('fix mode: this command would modify tests or openspec/. Fix PRs may only change source, config and lockfiles.');
32
+ }
33
+ }
34
+ process.exit(0);
@@ -0,0 +1,47 @@
1
+ // Managed by specjig. Change-Id trailer rules shared by hooks, git hooks and CI.
2
+ //
3
+ // Every commit carries `Change-Id: <openspec-change-name>` pointing at openspec/changes/<name>
4
+ // or openspec/changes/archive/<date>-<name>. `Change-Id: none` is allowed for work that has no
5
+ // behavior change (deps, formatting, CI, fix PRs from the triage bot).
6
+ import { existsSync, readdirSync } from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ export const TRAILER_RE = /^Change-Id:[ \t]*([a-z0-9][a-z0-9-]*)[ \t]*$/im;
10
+ export const NONE = 'none';
11
+
12
+ export function parseChangeId(message) {
13
+ const m = message.match(TRAILER_RE);
14
+ return m ? m[1] : null;
15
+ }
16
+
17
+ export function changeExists(id, cwd = process.cwd()) {
18
+ if (id === NONE) return true;
19
+ const changes = path.join(cwd, 'openspec', 'changes');
20
+ if (existsSync(path.join(changes, id))) return true;
21
+ const archive = path.join(changes, 'archive');
22
+ if (!existsSync(archive)) return false;
23
+ return readdirSync(archive).some((d) => d === id || d.replace(/^\d{4}-\d{2}-\d{2}-/, '') === id);
24
+ }
25
+
26
+ /** Returns an error string, or null when the message satisfies the policy. */
27
+ export function checkMessage(message, cwd = process.cwd()) {
28
+ const subject = message.split('\n')[0];
29
+ if (/^(Merge |Revert "|fixup! |squash! |amend! )/.test(subject)) return null;
30
+ const id = parseChangeId(message);
31
+ if (!id) {
32
+ return 'missing "Change-Id: <change-name>" trailer (use "Change-Id: none" for work without a behavior change)';
33
+ }
34
+ if (!changeExists(id, cwd)) {
35
+ return `Change-Id "${id}" does not match any folder in openspec/changes/ or openspec/changes/archive/`;
36
+ }
37
+ return null;
38
+ }
39
+
40
+ /** Active (non-archived) changes, newest first, to suggest an id. */
41
+ export function activeChanges(cwd = process.cwd()) {
42
+ const changes = path.join(cwd, 'openspec', 'changes');
43
+ if (!existsSync(changes)) return [];
44
+ return readdirSync(changes, { withFileTypes: true })
45
+ .filter((d) => d.isDirectory() && d.name !== 'archive')
46
+ .map((d) => d.name);
47
+ }
@@ -0,0 +1,29 @@
1
+ // Managed by specjig. Minimal helpers for Claude Code hook scripts.
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ export async function readHookInput() {
6
+ let data = '';
7
+ for await (const chunk of process.stdin) data += chunk;
8
+ return data ? JSON.parse(data) : {};
9
+ }
10
+
11
+ /** Block the tool call: exit 2 sends `reason` back to the agent as feedback. */
12
+ export function block(reason) {
13
+ process.stderr.write(`[specjig] Blocked: ${reason}\n`);
14
+ process.exit(2);
15
+ }
16
+
17
+ export function projectDir(input) {
18
+ return process.env.CLAUDE_PROJECT_DIR || input.cwd || process.cwd();
19
+ }
20
+
21
+ export function harnessConfig(cwd) {
22
+ const file = path.join(cwd, '.sdd', 'harness.json');
23
+ if (!existsSync(file)) return {};
24
+ try {
25
+ return JSON.parse(readFileSync(file, 'utf8'));
26
+ } catch {
27
+ return {};
28
+ }
29
+ }