specjig 0.0.1-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 +107 -0
  4. package/bin/specjig.mjs +7 -0
  5. package/harness.lock.json +61 -0
  6. package/package.json +56 -1
  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,50 @@
1
+ # Managed by specjig. Warning only: domain code changed without a delta spec and without the
2
+ # low-risk label. A cheap path filter runs first; the agent runs only when the filter fires and
3
+ # judges meaning, not syntax (refactors and renames are not drift).
4
+ name: sdd / drift check
5
+ on:
6
+ pull_request:
7
+ types: [opened, synchronize, reopened, labeled, unlabeled]
8
+ permissions:
9
+ contents: read
10
+ pull-requests: write
11
+ id-token: write
12
+ concurrency:
13
+ group: sdd-drift-${{ github.event.pull_request.number }}
14
+ cancel-in-progress: true
15
+ jobs:
16
+ drift:
17
+ runs-on: ubuntu-latest
18
+ timeout-minutes: 15
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ with:
22
+ fetch-depth: 0
23
+ - id: filter
24
+ env:
25
+ PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }}
26
+ run: node .sdd/scripts/drift-check.mjs "${{ github.event.pull_request.base.sha }}" "${{ github.event.pull_request.head.sha }}"
27
+ - name: Judge behavior change
28
+ if: steps.filter.outputs.needs_review == 'true'
29
+ uses: anthropics/claude-code-action@{{CLAUDE_CODE_ACTION}}
30
+ with:
31
+ anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
32
+ prompt: |
33
+ REPO: ${{ github.repository }} PR: ${{ github.event.pull_request.number }}
34
+ This PR changes domain code but adds no OpenSpec delta spec and has no `low-risk` label.
35
+ Domain files changed:
36
+ ${{ steps.filter.outputs.domain_files }}
37
+
38
+ Decide whether OBSERVABLE BEHAVIOR changed (inputs, outputs, errors, side effects,
39
+ permissions, data stored) compared with the requirements in openspec/specs/.
40
+ Refactors, renames, moves, performance work with identical results, logging that adds
41
+ no PII, and test-only changes are NOT drift.
42
+
43
+ If behavior changed: post ONE PR comment starting with "⚠️ Spec drift" that lists each
44
+ behavior change, the requirement in openspec/specs/ it affects (path + requirement name)
45
+ or "no requirement covers this", and suggests either a change (`/openspec-propose`) or
46
+ the `low-risk` label. If behavior did not change, post nothing.
47
+ Do not modify files.
48
+ claude_args: |
49
+ --max-turns 12
50
+ --allowedTools "Read,Grep,Glob,Bash(gh pr diff:*),Bash(gh pr view:*),Bash(gh pr comment:*),Bash(git diff:*),Bash(git log:*)"
@@ -0,0 +1,25 @@
1
+ # Managed by specjig. Fix PRs from the triage agent may not touch tests, specs, harness or
2
+ # workflows. Low-risk fix PRs that pass the guard get auto-merge: they merge only after required
3
+ # CI checks are green (enable "Allow auto-merge" and branch protection in repo settings).
4
+ name: sdd / fix PR guard
5
+ on:
6
+ pull_request:
7
+ types: [opened, synchronize, labeled]
8
+ permissions:
9
+ contents: write
10
+ pull-requests: write
11
+ jobs:
12
+ guard:
13
+ if: contains(github.event.pull_request.labels.*.name, 'ai-fix')
14
+ runs-on: ubuntu-latest
15
+ timeout-minutes: 5
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ with:
19
+ fetch-depth: 0
20
+ - run: node .sdd/scripts/fix-pr-guard.mjs "${{ github.event.pull_request.base.sha }}" "${{ github.event.pull_request.head.sha }}"
21
+ - name: Auto-merge after green CI
22
+ if: contains(github.event.pull_request.labels.*.name, 'low-risk')
23
+ env:
24
+ GH_TOKEN: ${{ github.token }}
25
+ run: gh pr merge "${{ github.event.pull_request.number }}" --auto --squash
@@ -0,0 +1,45 @@
1
+ # Managed by specjig. Release notes from openspec/changes/archive/ for a period.
2
+ name: sdd / release notes
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ since:
7
+ description: "From date (YYYY-MM-DD)"
8
+ required: true
9
+ until:
10
+ description: "To date (YYYY-MM-DD), default today"
11
+ required: false
12
+ release:
13
+ types: [published]
14
+ permissions:
15
+ contents: write
16
+ jobs:
17
+ notes:
18
+ runs-on: ubuntu-latest
19
+ timeout-minutes: 5
20
+ steps:
21
+ - uses: actions/checkout@v4
22
+ with:
23
+ fetch-depth: 0
24
+ - id: period
25
+ env:
26
+ GH_TOKEN: ${{ github.token }}
27
+ run: |
28
+ if [ "${{ github.event_name }}" = "release" ]; then
29
+ prev=$(gh release list --limit 2 --json publishedAt --jq '.[1].publishedAt // ""' | cut -c1-10)
30
+ echo "since=${prev:-0000-00-00}" >> "$GITHUB_OUTPUT"
31
+ echo "until=$(date -u +%F)" >> "$GITHUB_OUTPUT"
32
+ else
33
+ echo "since=${{ inputs.since }}" >> "$GITHUB_OUTPUT"
34
+ echo "until=${{ inputs.until || '9999-99-99' }}" >> "$GITHUB_OUTPUT"
35
+ fi
36
+ - run: node .sdd/scripts/release-notes.mjs --since "${{ steps.period.outputs.since }}" --until "${{ steps.period.outputs.until }}" --out release-notes.md
37
+ - run: cat release-notes.md >> "$GITHUB_STEP_SUMMARY"
38
+ - if: github.event_name == 'release'
39
+ env:
40
+ GH_TOKEN: ${{ github.token }}
41
+ run: gh release edit "${{ github.event.release.tag_name }}" --notes-file release-notes.md
42
+ - uses: actions/upload-artifact@v4
43
+ with:
44
+ name: release-notes
45
+ path: release-notes.md
@@ -0,0 +1,23 @@
1
+ # Managed by specjig. AI security review with the project's rules on top, label-triggered.
2
+ name: sdd / security review
3
+ on:
4
+ pull_request:
5
+ types: [labeled, synchronize]
6
+ permissions:
7
+ contents: read
8
+ pull-requests: write
9
+ jobs:
10
+ security:
11
+ if: contains(github.event.pull_request.labels.*.name, 'security-review')
12
+ runs-on: ubuntu-latest
13
+ timeout-minutes: 30
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ with:
17
+ ref: ${{ github.event.pull_request.head.sha }}
18
+ fetch-depth: 2
19
+ - uses: anthropics/claude-code-security-review@{{SECURITY_REVIEW_ACTION}}
20
+ with:
21
+ claude-api-key: ${{ secrets.ANTHROPIC_API_KEY }}
22
+ comment-pr: true
23
+ custom-security-scan-instructions: .claude/rules/security.md
@@ -0,0 +1,23 @@
1
+ # Managed by specjig. Blocking: OpenSpec validates and every commit is traceable to a change.
2
+ name: sdd / spec gate
3
+ on:
4
+ pull_request:
5
+ merge_group:
6
+ permissions:
7
+ contents: read
8
+ jobs:
9
+ spec-gate:
10
+ runs-on: ubuntu-latest
11
+ timeout-minutes: 10
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ with:
15
+ fetch-depth: 0
16
+ - uses: actions/setup-node@v4
17
+ with:
18
+ node-version: 22
19
+ - name: openspec validate
20
+ run: npx -y @fission-ai/openspec@{{OPENSPEC_VERSION}} validate --all --strict --no-interactive
21
+ - name: Change-Id trailers
22
+ if: github.event_name == 'pull_request'
23
+ run: node .sdd/scripts/check-trailers.mjs "${{ github.event.pull_request.base.sha }}" "${{ github.event.pull_request.head.sha }}"
@@ -0,0 +1,51 @@
1
+ # Managed by specjig. Spec-aware review, triggered by the `ai-review` label (cost control).
2
+ # Reads the change(s) named in the Change-Id trailers and checks the code against their scenarios.
3
+ name: sdd / spec-aware review
4
+ on:
5
+ pull_request:
6
+ types: [labeled, synchronize]
7
+ permissions:
8
+ contents: read
9
+ pull-requests: write
10
+ id-token: write
11
+ concurrency:
12
+ group: sdd-review-${{ github.event.pull_request.number }}
13
+ cancel-in-progress: true
14
+ jobs:
15
+ review:
16
+ if: contains(github.event.pull_request.labels.*.name, 'ai-review')
17
+ runs-on: ubuntu-latest
18
+ timeout-minutes: 30
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ with:
22
+ fetch-depth: 0
23
+ - id: trailers
24
+ run: node .sdd/scripts/check-trailers.mjs "${{ github.event.pull_request.base.sha }}" "${{ github.event.pull_request.head.sha }}" || true
25
+ - uses: anthropics/claude-code-action@{{CLAUDE_CODE_ACTION}}
26
+ with:
27
+ anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
28
+ prompt: |
29
+ REPO: ${{ github.repository }} PR: ${{ github.event.pull_request.number }}
30
+ Changes referenced by commits: ${{ steps.trailers.outputs.change_ids || 'none found' }}
31
+
32
+ Review this PR against its OpenSpec change(s). For each change id, read
33
+ openspec/changes/<id>/ (or openspec/changes/archive/*-<id>/): proposal.md, specs/**,
34
+ tests.md, design.md, impact.md.
35
+
36
+ Check:
37
+ 1. Every scenario in the delta specs that this PR's layer covers is implemented and has
38
+ the test named in tests.md; the test asserts the scenario's THEN, not a mock.
39
+ 2. Code does not do things no requirement asked for (scope creep).
40
+ 3. Error behavior and edge cases match the scenarios.
41
+ 4. Rules in .claude/rules/security.md (PII/PHI in logs or URLs, authz, tenant isolation).
42
+ 5. tasks.md checkboxes match what was actually done.
43
+
44
+ Post inline comments with mcp__github_inline_comment__create_inline_comment (confirmed: true)
45
+ only for real problems. Each comment links the requirement:
46
+ `openspec/changes/<id>/specs/<capability>/spec.md` › "Requirement: <name>" › "Scenario: <name>".
47
+ Finish with one summary PR comment: scenarios covered / missing / wrong, as a table.
48
+ If there is no change id, say so in the summary and review against openspec/specs/ only.
49
+ claude_args: |
50
+ --max-turns 30
51
+ --allowedTools "Read,Grep,Glob,mcp__github_inline_comment__create_inline_comment,Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*),Bash(git diff:*),Bash(git log:*)"
@@ -0,0 +1,8 @@
1
+ {
2
+ "mcpServers": {
3
+ "playwright": {
4
+ "command": "npx",
5
+ "args": ["-y", "@playwright/mcp@{{PLAYWRIGHT_MCP_VERSION}}", "--isolated"]
6
+ }
7
+ }
8
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "$comment": "Created by specjig on init; project-owned. Read by hooks and CI scripts.",
3
+ "exclude": [],
4
+ "layers": {
5
+ "backend": ["src/server/**", "api/**"],
6
+ "frontend": ["src/web/**", "web/**"]
7
+ },
8
+ "domainPaths": ["src/**"],
9
+ "ignoreForDrift": ["**/*.test.*", "**/*.spec.*", "**/__tests__/**", "**/*.md", "**/*.snap"],
10
+ "fixMode": {
11
+ "frozenPaths": ["**/*.test.*", "**/*.spec.*", "**/__tests__/**", "test/**", "tests/**", "e2e/**", "**/fixtures/**", "**/*.snap"]
12
+ },
13
+ "guard": {
14
+ "extraSecretPaths": []
15
+ },
16
+ "confluence": {
17
+ "spaceKey": "",
18
+ "parentPageId": "",
19
+ "titlePrefix": "[Spec] "
20
+ }
21
+ }
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ // Managed by specjig. Used by .githooks/commit-msg: validates the Change-Id trailer.
3
+ import { readFileSync } from 'node:fs';
4
+ import { checkMessage } from '../../.claude/hooks/sdd-lib/change-id.mjs';
5
+
6
+ const message = readFileSync(process.argv[2], 'utf8')
7
+ .split('\n')
8
+ .filter((l) => !l.startsWith('#'))
9
+ .join('\n');
10
+ const error = checkMessage(message);
11
+ if (error) {
12
+ console.error(`commit-msg: ${error}`);
13
+ console.error('Add a trailer line at the end of the message, e.g.:\n\n Change-Id: add-csv-export\n');
14
+ process.exit(1);
15
+ }
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ // Managed by specjig. CI: every commit in base..head carries a valid Change-Id trailer.
3
+ // Usage: node .sdd/scripts/check-trailers.mjs <base-sha> [head-sha]
4
+ import { checkMessage } from '../../.claude/hooks/sdd-lib/change-id.mjs';
5
+ import { git, setOutput } from './lib.mjs';
6
+
7
+ const [base, head = 'HEAD'] = process.argv.slice(2);
8
+ if (!base) throw new Error('usage: check-trailers.mjs <base> [head]');
9
+
10
+ const shas = git('rev-list', '--no-merges', `${base}..${head}`).split('\n').filter(Boolean);
11
+ const failures = [];
12
+ const ids = new Set();
13
+ for (const sha of shas) {
14
+ const message = git('log', '-1', '--format=%B', sha);
15
+ const error = checkMessage(message);
16
+ if (error) failures.push(`${sha.slice(0, 8)} ${message.split('\n')[0]}\n → ${error}`);
17
+ const id = message.match(/^Change-Id:\s*([a-z0-9-]+)/im)?.[1];
18
+ if (id && id !== 'none') ids.add(id);
19
+ }
20
+
21
+ setOutput('change_ids', [...ids].join(' '));
22
+ if (failures.length) {
23
+ console.error(`::error::${failures.length} commit(s) without a valid Change-Id trailer`);
24
+ console.error(failures.join('\n'));
25
+ process.exit(1);
26
+ }
27
+ console.log(`All ${shas.length} commit(s) carry a valid Change-Id. Changes: ${[...ids].join(', ') || 'none'}`);
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env node
2
+ // Managed by specjig. Publishes a read-only, human-readable slice of openspec/specs/ to
3
+ // Confluence: one page per capability under a parent page. Pages carry a banner saying edits
4
+ // happen through an OpenSpec change; Confluence comments are input for the next change.
5
+ //
6
+ // Env: CONFLUENCE_BASE_URL (e.g. https://acme.atlassian.net/wiki or https://wiki.acme.com)
7
+ // CONFLUENCE_TOKEN API token (Cloud, with CONFLUENCE_USER) or personal access token (Server/DC)
8
+ // CONFLUENCE_USER optional; when set, basic auth user:token (Cloud)
9
+ // Config: .sdd/harness.json -> confluence.spaceKey, confluence.parentPageId, confluence.titlePrefix
10
+ // Flags: --dry-run print what would be published
11
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
12
+ import path from 'node:path';
13
+ import { config, git } from './lib.mjs';
14
+
15
+ const dryRun = process.argv.includes('--dry-run');
16
+ const cfg = config().confluence ?? {};
17
+ const { CONFLUENCE_BASE_URL: base, CONFLUENCE_TOKEN: token, CONFLUENCE_USER: user, GITHUB_SERVER_URL, GITHUB_REPOSITORY } = process.env;
18
+ if (!dryRun && (!base || !token || !cfg.spaceKey || !cfg.parentPageId)) {
19
+ console.error('Missing CONFLUENCE_BASE_URL / CONFLUENCE_TOKEN or confluence.spaceKey / parentPageId in .sdd/harness.json');
20
+ process.exit(1);
21
+ }
22
+ const auth = user ? `Basic ${Buffer.from(`${user}:${token}`).toString('base64')}` : `Bearer ${token}`;
23
+
24
+ async function api(method, p, body) {
25
+ const res = await fetch(`${base.replace(/\/$/, '')}/rest/api${p}`, {
26
+ method,
27
+ headers: { Authorization: auth, 'Content-Type': 'application/json', Accept: 'application/json' },
28
+ body: body ? JSON.stringify(body) : undefined,
29
+ });
30
+ if (!res.ok) throw new Error(`${method} ${p}: ${res.status} ${await res.text()}`);
31
+ return res.json();
32
+ }
33
+
34
+ // --- minimal Markdown → Confluence storage format -----------------------------------------
35
+ const esc = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
36
+ const inline = (s) =>
37
+ esc(s)
38
+ .replace(/`([^`]+)`/g, '<code>$1</code>')
39
+ .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
40
+ .replace(/\*([^*]+)\*/g, '<em>$1</em>')
41
+ .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
42
+
43
+ function toStorage(md) {
44
+ const out = [];
45
+ let list = false;
46
+ let code = null;
47
+ for (const line of md.replace(/<!--[\s\S]*?-->/g, '').split('\n')) {
48
+ if (code !== null) {
49
+ if (line.startsWith('```')) {
50
+ out.push(`<ac:structured-macro ac:name="code"><ac:plain-text-body><![CDATA[${code.join('\n')}]]></ac:plain-text-body></ac:structured-macro>`);
51
+ code = null;
52
+ } else code.push(line);
53
+ continue;
54
+ }
55
+ if (line.startsWith('```')) {
56
+ code = [];
57
+ continue;
58
+ }
59
+ const li = line.match(/^\s*[-*]\s+(.*)/);
60
+ if (!li && list) {
61
+ out.push('</ul>');
62
+ list = false;
63
+ }
64
+ const h = line.match(/^(#{1,6})\s+(.*)/);
65
+ if (h) out.push(`<h${h[1].length}>${inline(h[2])}</h${h[1].length}>`);
66
+ else if (li) {
67
+ if (!list) out.push('<ul>');
68
+ list = true;
69
+ out.push(`<li>${inline(li[1])}</li>`);
70
+ } else if (line.trim()) out.push(`<p>${inline(line)}</p>`);
71
+ }
72
+ if (list) out.push('</ul>');
73
+ return out.join('\n');
74
+ }
75
+
76
+ function capabilities(dir = path.join('openspec', 'specs'), baseDir = dir) {
77
+ if (!existsSync(dir)) return [];
78
+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) =>
79
+ e.isDirectory()
80
+ ? capabilities(path.join(dir, e.name), baseDir)
81
+ : e.name === 'spec.md'
82
+ ? [{ id: path.relative(baseDir, dir).split(path.sep).join('/'), file: path.join(dir, e.name) }]
83
+ : [],
84
+ );
85
+ }
86
+
87
+ const sha = git('rev-parse', '--short', 'HEAD');
88
+ const repoUrl = GITHUB_SERVER_URL && GITHUB_REPOSITORY ? `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}` : null;
89
+ const banner = (cap) =>
90
+ `<ac:structured-macro ac:name="info"><ac:rich-text-body><p>Read-only export of <code>openspec/specs/${esc(cap.id)}</code> at <code>${sha}</code>.` +
91
+ `${repoUrl ? ` <a href="${repoUrl}/blob/${sha}/${cap.file}">Source</a>.` : ''} Changes happen through an OpenSpec change; comment here and the team turns comments into the next change.</p></ac:rich-text-body></ac:structured-macro>`;
92
+
93
+ for (const cap of capabilities()) {
94
+ const title = `${cfg.titlePrefix ?? ''}${cap.id}`;
95
+ const body = banner(cap) + '\n' + toStorage(readFileSync(cap.file, 'utf8'));
96
+ if (dryRun) {
97
+ console.log(`would publish "${title}" (${body.length} chars)`);
98
+ continue;
99
+ }
100
+ const found = await api('GET', `/content?spaceKey=${encodeURIComponent(cfg.spaceKey)}&title=${encodeURIComponent(title)}&expand=version`);
101
+ const page = found.results?.[0];
102
+ const payload = { type: 'page', title, space: { key: cfg.spaceKey }, ancestors: [{ id: String(cfg.parentPageId) }], body: { storage: { value: body, representation: 'storage' } } };
103
+ if (page) {
104
+ await api('PUT', `/content/${page.id}`, { ...payload, id: page.id, version: { number: page.version.number + 1, message: `openspec ${sha}` } });
105
+ console.log(`updated ${title}`);
106
+ } else {
107
+ await api('POST', '/content', payload);
108
+ console.log(`created ${title}`);
109
+ }
110
+ }
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ // Managed by specjig. CI pre-filter for the drift check (cheap, no LLM):
3
+ // did domain code change in this PR without any delta spec and without the low-risk label?
4
+ // If yes, the workflow asks an agent whether behavior actually changed (refactors and renames
5
+ // are not drift) and posts a warning. The check never blocks the PR.
6
+ //
7
+ // Usage: node .sdd/scripts/drift-check.mjs <base-sha> [head-sha] (env PR_LABELS="a,b")
8
+ import { changedFiles, config, matcher, setOutput } from './lib.mjs';
9
+
10
+ const [base, head = 'HEAD'] = process.argv.slice(2);
11
+ const cfg = config();
12
+ const labels = (process.env.PR_LABELS ?? '').split(',').map((s) => s.trim());
13
+
14
+ const files = changedFiles(base, head);
15
+ const isDomain = matcher(cfg.domainPaths ?? ['src/**']);
16
+ const isIgnored = matcher(cfg.ignoreForDrift ?? []);
17
+ const domain = files.filter((f) => isDomain(f) && !isIgnored(f));
18
+ const deltaSpecs = files.filter((f) => /^openspec\/changes\/(?!archive\/)[^/]+\/specs\/.+\.md$/.test(f));
19
+ const skipSpecs = files.some((f) => /^openspec\/changes\/[^/]+\/\.openspec\.yaml$/.test(f));
20
+
21
+ let verdict = 'ok';
22
+ if (labels.includes('low-risk')) verdict = 'skip:low-risk';
23
+ else if (!domain.length) verdict = 'skip:no-domain-changes';
24
+ else if (deltaSpecs.length) verdict = 'ok:delta-specs-present';
25
+ else verdict = 'needs-review';
26
+
27
+ setOutput('verdict', verdict);
28
+ setOutput('needs_review', verdict === 'needs-review');
29
+ setOutput('domain_files', domain.join('\n'));
30
+ console.log(`domain files: ${domain.length}, delta specs: ${deltaSpecs.length}, change metadata touched: ${skipSpecs}`);
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ // Managed by specjig. CI: a fix PR from the triage agent may not touch tests or specs.
3
+ // Second line of defence after the SDD_MODE=fix hook (the hook can be bypassed; the diff can't).
4
+ // Usage: node .sdd/scripts/fix-pr-guard.mjs <base-sha> [head-sha]
5
+ import { changedFiles, config, matcher } from './lib.mjs';
6
+
7
+ const [base, head = 'HEAD'] = process.argv.slice(2);
8
+ const cfg = config();
9
+ const frozen = matcher([...(cfg.fixMode?.frozenPaths ?? []), 'openspec/**', '.claude/**', '.github/**', '.sdd/**']);
10
+ const violations = changedFiles(base, head).filter(frozen);
11
+
12
+ if (violations.length) {
13
+ console.error('::error::Fix PR touches frozen paths (tests, specs, harness or workflows):');
14
+ for (const f of violations) console.error(` ${f}`);
15
+ process.exit(1);
16
+ }
17
+ console.log('Fix PR touches no tests, specs or harness files.');
@@ -0,0 +1,31 @@
1
+ // Managed by specjig. Helpers shared by the CI scripts.
2
+ import { execFileSync } from 'node:child_process';
3
+ import { appendFileSync, existsSync, readFileSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { globToRegExp } from '../../.claude/hooks/sdd-lib/patterns.mjs';
6
+
7
+ export const git = (...args) => execFileSync('git', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }).trim();
8
+
9
+ export function config(cwd = process.cwd()) {
10
+ const f = path.join(cwd, '.sdd', 'harness.json');
11
+ return existsSync(f) ? JSON.parse(readFileSync(f, 'utf8')) : {};
12
+ }
13
+
14
+ export const matcher = (globs = []) => {
15
+ const res = globs.map(globToRegExp);
16
+ return (p) => res.some((r) => r.test(p));
17
+ };
18
+
19
+ export function changedFiles(base, head = 'HEAD') {
20
+ const out = git('diff', '--name-only', '--diff-filter=ACMRD', `${base}...${head}`);
21
+ return out ? out.split('\n') : [];
22
+ }
23
+
24
+ export function setOutput(name, value) {
25
+ if (process.env.GITHUB_OUTPUT) {
26
+ const v = String(value);
27
+ const delim = `EOF_${Math.random().toString(36).slice(2)}`;
28
+ appendFileSync(process.env.GITHUB_OUTPUT, `${name}<<${delim}\n${v}\n${delim}\n`);
29
+ }
30
+ console.log(`${name}=${value}`);
31
+ }
@@ -0,0 +1,63 @@
1
+ #!/usr/bin/env node
2
+ // Managed by specjig. Builds release notes from openspec/changes/archive/ for a period.
3
+ // Archive folders are named YYYY-MM-DD-<change-id>, so the period filter needs no git history.
4
+ //
5
+ // Usage: node .sdd/scripts/release-notes.mjs --since 2026-11-01 [--until 2026-11-30] [--out notes.md]
6
+ import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ const arg = (name, def) => {
10
+ const i = process.argv.indexOf(`--${name}`);
11
+ return i > -1 ? process.argv[i + 1] : def;
12
+ };
13
+ const since = arg('since', '0000-00-00');
14
+ const until = arg('until', '9999-99-99');
15
+ const out = arg('out');
16
+
17
+ const archive = path.join('openspec', 'changes', 'archive');
18
+ const dirs = existsSync(archive)
19
+ ? readdirSync(archive)
20
+ .filter((d) => /^\d{4}-\d{2}-\d{2}-/.test(d))
21
+ .filter((d) => d.slice(0, 10) >= since && d.slice(0, 10) <= until)
22
+ .sort()
23
+ : [];
24
+
25
+ function section(md, title) {
26
+ const m = md.match(new RegExp(`^##\\s+${title}\\s*\\n([\\s\\S]*?)(?=^##\\s|(?![\\s\\S]))`, 'm'));
27
+ return m ? m[1].replace(/<!--[\s\S]*?-->/g, '').trim() : '';
28
+ }
29
+
30
+ function walkSpecs(dir, base = dir) {
31
+ if (!existsSync(dir)) return [];
32
+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) =>
33
+ e.isDirectory() ? walkSpecs(path.join(dir, e.name), base) : e.name === 'spec.md' ? [path.relative(base, dir)] : [],
34
+ );
35
+ }
36
+
37
+ const groups = { high: [], low: [], unknown: [] };
38
+ for (const d of dirs) {
39
+ const proposalFile = path.join(archive, d, 'proposal.md');
40
+ const proposal = existsSync(proposalFile) ? readFileSync(proposalFile, 'utf8') : '';
41
+ const risk = section(proposal, 'Risk').match(/Level:\s*(low|high)/i)?.[1]?.toLowerCase() ?? 'unknown';
42
+ const why = section(proposal, 'Why').split('\n').join(' ');
43
+ const what = section(proposal, 'What Changes');
44
+ const caps = walkSpecs(path.join(archive, d, 'specs'));
45
+ groups[risk].push({ id: d.slice(11), date: d.slice(0, 10), dir: d, why, what, caps });
46
+ }
47
+
48
+ const lines = [`# Release notes ${since === '0000-00-00' ? '' : `${since} → `}${until === '9999-99-99' ? 'today' : until}`, ''];
49
+ const total = dirs.length;
50
+ if (!total) lines.push('_No archived changes in this period._');
51
+ for (const [risk, title] of [['high', 'Significant changes'], ['low', 'Other changes'], ['unknown', 'Unclassified']]) {
52
+ if (!groups[risk].length) continue;
53
+ lines.push(`## ${title}`, '');
54
+ for (const c of groups[risk]) {
55
+ lines.push(`### ${c.id} (${c.date})`, '');
56
+ if (c.why) lines.push(c.why, '');
57
+ if (c.what) lines.push(c.what, '');
58
+ if (c.caps.length) lines.push(`Specs: ${c.caps.map((s) => `\`${s}\``).join(', ')} · [change](openspec/changes/archive/${c.dir}/proposal.md)`, '');
59
+ }
60
+ }
61
+ const md = lines.join('\n');
62
+ if (out) writeFileSync(out, md);
63
+ else console.log(md);
@@ -0,0 +1,87 @@
1
+ # {{PROJECT_NAME}}
2
+
3
+ <!-- Project-owned: specjig never edits text outside the specjig markers below. -->
4
+
5
+ ## Project
6
+
7
+ - **What it is:** TODO one paragraph: product, users, domain.
8
+ - **Stack:** TODO (also fill `context:` in `openspec/config.yaml`).
9
+ - **Layers:** TODO e.g. `backend` (src/server), `frontend` (src/web). Keep in sync with `.sdd/harness.json`.
10
+
11
+ ## Commands
12
+
13
+ | Purpose | Command |
14
+ | --------- | ------- |
15
+ | Install | TODO |
16
+ | Unit | TODO |
17
+ | Integration | TODO |
18
+ | E2E | TODO |
19
+ | Lint | TODO |
20
+ | Types | TODO |
21
+
22
+ ## Client restrictions
23
+
24
+ TODO what the client allows and forbids (data residency, allowed models/providers, systems the
25
+ agent may not touch, approval requirements). Write "none beyond the harness defaults" if none.
26
+
27
+ <!-- specjig:begin -->
28
+ ## How we work: spec-driven development (OpenSpec)
29
+
30
+ `openspec/specs/` is how the system behaves **now**. `openspec/changes/<id>/` is how it
31
+ **will** behave after a change (delta specs) plus why and how. Both states live in the repo at
32
+ the same time; archive merges a change's deltas into `specs/`.
33
+
34
+ Every behavior change goes through a change (schema `sdd`). Pure refactors, dependency bumps
35
+ and formatting need no change and are committed with `Change-Id: none`.
36
+
37
+ | # | Step | How | Output |
38
+ |---|------|-----|--------|
39
+ | 1 | Explore (optional) | `/openspec-explore` | shared understanding, no files |
40
+ | 2 | Propose | `/openspec-propose`; set **Risk: low / high** | `proposal.md` |
41
+ | 3 | Delta specs | requirements + `#### Scenario:` WHEN/THEN | `specs/**/spec.md` |
42
+ | 4 | Spec challenge (**high risk only**) | `spec-challenge` skill, clean context | `challenge.md`, specs updated |
43
+ | 5 | Impact, tests, design | continue the change | `impact.md`, `tests.md`, `design.md` |
44
+ | 6 | Tasks | grouped by layer `[backend]` / `[frontend]` | `tasks.md` |
45
+ | 7 | Validate | `npx openspec validate <id> --strict` | green |
46
+ | 8 | Apply, one layer per run | `/openspec-apply-change <id>` + "layer: backend"; TDD always | code + tests |
47
+ | 9 | Review | `two-axis-review` (standards + spec); `/security-review` when high risk | findings fixed |
48
+ | 10 | PR | `change-pr` skill | PR with Change-Id and links |
49
+ | 11 | Review comments | `receiving-code-review` skill | every comment accepted or rejected with a reason |
50
+ | 12 | Archive (after merge) | `/openspec-archive-change <id>` | deltas merged into `specs/` |
51
+
52
+ Risk is **high** when the change touches auth, permissions, tenant isolation, PII/PHI, payments,
53
+ data migrations, public API contracts, or more than one layer at once. Otherwise **low**. When unsure, high.
54
+
55
+ Rules that always apply:
56
+
57
+ - **Tests first.** No production code without a failing test (`test-driven-development` skill).
58
+ Test levels come from `tests.md`: every scenario maps to unit, integration or e2e.
59
+ - **Bugs:** `systematic-debugging` skill: hypothesis, verification, fix, regression test.
60
+ - **Never edit `openspec/specs/` directly**; change behavior through a change and archive it.
61
+ - **Open questions** that would change specs, approach or tasks are resolved with the human
62
+ before tasks are written. Do not bake guesses into tasks.
63
+
64
+ ## Traceability: from a line of code to its meaning
65
+
66
+ Every commit carries a `Change-Id: <change-name>` trailer (`none` for non-behavioral work);
67
+ hooks reject commits without it. To understand an unclear line, follow the chain instead of
68
+ guessing (the `trace-why` skill does this):
69
+
70
+ `git blame -L <n>,<n> <file>` → commit → `Change-Id` → `openspec/changes/<id>/` or
71
+ `openspec/changes/archive/*-<id>/` → `proposal.md` (why), `design.md` (how and alternatives),
72
+ specs (the contract). Search specs and changes locally before asking or querying a tracker.
73
+
74
+ ## Governance
75
+
76
+ - **Secrets:** never read, print or request `.env*` (except `.env.example`), keys, credentials,
77
+ tokens or the process environment. Hooks and `permissions.deny` block it; do not try to work
78
+ around a block. Ask the human for variable *names*, not values.
79
+ - **Data:** only synthetic data. Fixtures are generated (seeded faker/factories), never copied
80
+ from real records. No PII/PHI in tests, fixtures, logs, URLs, commit messages or specs.
81
+ Folders `data/real`, `data/prod`, dumps and backups are off limits.
82
+ - **Fix mode** (`SDD_MODE=fix`, CI triage): only lint, format, types and dependencies; never
83
+ tests or `openspec/`. If the real fix needs a test or spec change, stop and report.
84
+ - **Pushes, merges and publishing** need explicit human approval.
85
+ - **Cost:** CI agents run only on labels, with `--max-turns`; do not loop on a failing step,
86
+ stop and report after two failed attempts at the same fix.
87
+ <!-- specjig:end -->