continuous-improvement 3.0.0 → 3.8.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 (126) hide show
  1. package/.claude-plugin/marketplace.json +78 -0
  2. package/CHANGELOG.md +210 -0
  3. package/LICENSE +21 -21
  4. package/QUICKSTART.md +101 -81
  5. package/README.md +224 -198
  6. package/SKILL.md +87 -9
  7. package/action.yml +33 -0
  8. package/bin/analyze.sh +161 -153
  9. package/bin/backfill.mjs +172 -0
  10. package/bin/check-docs-substrings.mjs +333 -0
  11. package/bin/check-everything-mirror.mjs +145 -0
  12. package/bin/check-routing-targets.mjs +151 -0
  13. package/bin/check-skill-law-tag.mjs +128 -0
  14. package/bin/check-skill-mirror.mjs +119 -0
  15. package/bin/check-skill-tiers.mjs +116 -0
  16. package/bin/check-third-party-shape.mjs +202 -0
  17. package/bin/generate-plugin-manifests.mjs +169 -0
  18. package/bin/harvest-friction.mjs +279 -0
  19. package/bin/hook-stats.mjs +258 -0
  20. package/bin/install.mjs +418 -456
  21. package/bin/lint-transcript.mjs +239 -0
  22. package/bin/mcp-server.mjs +842 -499
  23. package/bin/observe.mjs +148 -0
  24. package/bin/pre-commit-block-strays.sh +49 -0
  25. package/bin/refresh-third-party.mjs +416 -0
  26. package/bin/unified-cli.mjs +533 -0
  27. package/commands/continuous-improvement.md +115 -74
  28. package/commands/dashboard.md +56 -0
  29. package/commands/discipline.md +51 -0
  30. package/commands/harvest.md +76 -0
  31. package/commands/learn-eval.md +117 -0
  32. package/commands/planning-with-files.md +66 -0
  33. package/commands/proceed-with-the-recommendation.md +62 -0
  34. package/commands/ralph.md +103 -0
  35. package/commands/release-train.md +81 -0
  36. package/commands/seven-laws.md +16 -0
  37. package/commands/superpowers.md +153 -0
  38. package/commands/swarm.md +101 -0
  39. package/commands/workspace-surface-audit.md +77 -0
  40. package/hooks/observe.sh +172 -134
  41. package/hooks/session.sh +106 -106
  42. package/hooks/three-section-close.mjs +181 -0
  43. package/instinct-packs/go.json +58 -0
  44. package/instinct-packs/meta.json +16 -0
  45. package/instinct-packs/python.json +58 -0
  46. package/instinct-packs/react.json +58 -0
  47. package/lib/cli-anything.mjs +401 -0
  48. package/lib/compound-engineering.mjs +831 -0
  49. package/lib/observe-event.mjs +128 -0
  50. package/lib/plugin-metadata.mjs +432 -0
  51. package/lib/pm-marketplace.mjs +61 -0
  52. package/lib/pm-skills.mjs +1274 -0
  53. package/lib/resolve-home-dir.mjs +43 -0
  54. package/lib/skill-tiers.mjs +137 -0
  55. package/lib/unified-plugin.mjs +924 -0
  56. package/llms.txt +68 -0
  57. package/package.json +38 -15
  58. package/plugins/beginner.json +17 -6
  59. package/plugins/continuous-improvement/.claude-plugin/marketplace.json +20 -0
  60. package/plugins/continuous-improvement/.claude-plugin/plugin.json +26 -0
  61. package/plugins/continuous-improvement/LICENSE +21 -0
  62. package/plugins/continuous-improvement/README.md +56 -0
  63. package/plugins/continuous-improvement/bin/backfill.mjs +172 -0
  64. package/plugins/continuous-improvement/bin/mcp-server.mjs +886 -0
  65. package/plugins/continuous-improvement/bin/observe.mjs +148 -0
  66. package/plugins/continuous-improvement/commands/continuous-improvement.md +115 -0
  67. package/plugins/continuous-improvement/commands/dashboard.md +56 -0
  68. package/plugins/continuous-improvement/commands/discipline.md +51 -0
  69. package/plugins/continuous-improvement/commands/harvest.md +76 -0
  70. package/plugins/continuous-improvement/commands/learn-eval.md +117 -0
  71. package/plugins/continuous-improvement/commands/planning-with-files.md +66 -0
  72. package/plugins/continuous-improvement/commands/proceed-with-the-recommendation.md +62 -0
  73. package/plugins/continuous-improvement/commands/ralph.md +103 -0
  74. package/plugins/continuous-improvement/commands/release-train.md +81 -0
  75. package/plugins/continuous-improvement/commands/seven-laws.md +16 -0
  76. package/plugins/continuous-improvement/commands/superpowers.md +153 -0
  77. package/plugins/continuous-improvement/commands/swarm.md +101 -0
  78. package/plugins/continuous-improvement/commands/workspace-surface-audit.md +77 -0
  79. package/plugins/continuous-improvement/hooks/hooks.json +60 -0
  80. package/plugins/continuous-improvement/hooks/observe.sh +172 -0
  81. package/plugins/continuous-improvement/hooks/session.sh +106 -0
  82. package/plugins/continuous-improvement/hooks/three-section-close.mjs +181 -0
  83. package/plugins/continuous-improvement/instinct-packs/go.json +58 -0
  84. package/plugins/continuous-improvement/instinct-packs/meta.json +16 -0
  85. package/plugins/continuous-improvement/instinct-packs/python.json +58 -0
  86. package/plugins/continuous-improvement/instinct-packs/react.json +58 -0
  87. package/plugins/continuous-improvement/lib/observe-event.mjs +128 -0
  88. package/plugins/continuous-improvement/lib/plugin-metadata.mjs +432 -0
  89. package/plugins/continuous-improvement/lib/resolve-home-dir.mjs +43 -0
  90. package/plugins/continuous-improvement/skills/README.md +34 -0
  91. package/plugins/continuous-improvement/skills/continuous-improvement/SKILL.md +249 -0
  92. package/plugins/continuous-improvement/skills/deploy-receipt/SKILL.md +131 -0
  93. package/plugins/continuous-improvement/skills/gateguard/SKILL.md +155 -0
  94. package/plugins/continuous-improvement/skills/para-memory-files/SKILL.md +108 -0
  95. package/plugins/continuous-improvement/skills/proceed-with-the-recommendation/SKILL.md +454 -0
  96. package/plugins/continuous-improvement/skills/ralph/SKILL.md +221 -0
  97. package/plugins/continuous-improvement/skills/safety-guard/SKILL.md +76 -0
  98. package/plugins/continuous-improvement/skills/strategic-compact/SKILL.md +104 -0
  99. package/plugins/continuous-improvement/skills/superpowers/SKILL.md +212 -0
  100. package/plugins/continuous-improvement/skills/tdd-workflow/SKILL.md +411 -0
  101. package/plugins/continuous-improvement/skills/token-budget-advisor/SKILL.md +136 -0
  102. package/plugins/continuous-improvement/skills/verification-loop/SKILL.md +192 -0
  103. package/plugins/continuous-improvement/skills/wild-risa-balance/SKILL.md +191 -0
  104. package/plugins/continuous-improvement/skills/workspace-surface-audit/SKILL.md +147 -0
  105. package/plugins/continuous-improvement/templates/planning-with-files/findings.md +8 -0
  106. package/plugins/continuous-improvement/templates/planning-with-files/progress.md +7 -0
  107. package/plugins/continuous-improvement/templates/planning-with-files/task_plan.md +23 -0
  108. package/plugins/expert.json +34 -5
  109. package/skills/README.md +79 -0
  110. package/skills/deploy-receipt.md +131 -0
  111. package/skills/gateguard.md +155 -0
  112. package/skills/para-memory-files.md +108 -0
  113. package/skills/proceed-with-the-recommendation.md +454 -0
  114. package/skills/ralph.md +221 -0
  115. package/skills/safety-guard.md +76 -0
  116. package/skills/strategic-compact.md +104 -0
  117. package/skills/superpowers.md +212 -0
  118. package/skills/tdd-workflow.md +411 -0
  119. package/skills/token-budget-advisor.md +136 -0
  120. package/skills/verification-loop.md +192 -0
  121. package/skills/wild-risa-balance.md +191 -0
  122. package/skills/workspace-surface-audit.md +147 -0
  123. package/templates/planning-with-files/findings.md +8 -0
  124. package/templates/planning-with-files/progress.md +7 -0
  125. package/templates/planning-with-files/task_plan.md +23 -0
  126. package/templates/verify-ladder.example.json +47 -0
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+ // observe.mts — Mulahazah PreToolUse/PostToolUse observation hook.
3
+ //
4
+ // Reads a Claude Code hook JSON payload from stdin and appends one rich-schema
5
+ // JSONL line to ~/.claude/instincts/<project-hash>/observations.jsonl. Drop-in
6
+ // replacement for the bash observe.sh fallback path: no jq dependency, captures
7
+ // `tool_input.command` for Bash and `Edit.file_path` for Edit/Write/Read so the
8
+ // downstream analysis pass can detect user corrections, error→fix sequences,
9
+ // and tool-argument bigrams the thin schema could not represent.
10
+ //
11
+ // Contract:
12
+ // - Always exits 0. Never blocks the Claude session.
13
+ // - Catches every error to stderr; never throws.
14
+ // - Empty stdin / malformed JSON / missing tool_name → no-op exit 0.
15
+ // - Hook budget: <500ms on Windows (per CONTRIBUTING.md).
16
+ //
17
+ // See docs/plans/2026-05-05-node-observer-rich-schema.md for the full design.
18
+ import { execFileSync } from "node:child_process";
19
+ import { createHash } from "node:crypto";
20
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
21
+ import { homedir } from "node:os";
22
+ import { basename, join } from "node:path";
23
+ import { parseHookPayload, summariseInput, summariseOutput } from "../lib/observe-event.mjs";
24
+ const ROTATION_LINE_THRESHOLD = 10_000;
25
+ const ARCHIVE_RETENTION = 10;
26
+ main();
27
+ function main() {
28
+ try {
29
+ runObserver();
30
+ }
31
+ catch (error) {
32
+ // Never block the session. Failures land in stderr only.
33
+ const message = error instanceof Error ? error.message : String(error);
34
+ process.stderr.write(`[observe] ${message}\n`);
35
+ }
36
+ process.exit(0);
37
+ }
38
+ function runObserver() {
39
+ const raw = readStdin();
40
+ const payload = parseHookPayload(raw);
41
+ if (!payload)
42
+ return;
43
+ const projectRoot = resolveProjectRoot();
44
+ const projectHash = createHash("sha256").update(projectRoot).digest("hex").slice(0, 12);
45
+ const projectName = basename(projectRoot.replace(/\.git$/, ""));
46
+ const instinctsDir = join(getHomeDir(), ".claude", "instincts");
47
+ const projectDir = join(instinctsDir, projectHash);
48
+ const obsFile = join(projectDir, "observations.jsonl");
49
+ ensureDir(projectDir);
50
+ rotateIfNeeded(obsFile, projectDir);
51
+ const ts = new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
52
+ const event = payload.tool_response !== undefined ? "tool_complete" : "tool_start";
53
+ const row = {
54
+ ts,
55
+ event,
56
+ session: payload.session_id,
57
+ tool: payload.tool_name,
58
+ input_summary: summariseInput(payload.tool_name, payload.tool_input),
59
+ output_summary: summariseOutput(payload.tool_response),
60
+ project_id: projectHash,
61
+ project_name: projectName,
62
+ };
63
+ appendFileSync(obsFile, JSON.stringify(row) + "\n", "utf8");
64
+ writeProjectJsonIfNew(projectDir, projectHash, projectName, projectRoot, ts);
65
+ }
66
+ function readStdin() {
67
+ try {
68
+ return readFileSync(0, "utf8");
69
+ }
70
+ catch {
71
+ return "";
72
+ }
73
+ }
74
+ function getHomeDir() {
75
+ // CLAUDE_PROJECT_DIR is the project root, not the home dir; HOME wins for
76
+ // home-dir resolution. Fall through to USERPROFILE on Windows then os.homedir.
77
+ return process.env.HOME || process.env.USERPROFILE || homedir();
78
+ }
79
+ function resolveProjectRoot() {
80
+ const fromEnv = process.env.CLAUDE_PROJECT_DIR;
81
+ // The bash version trusts CLAUDE_PROJECT_DIR unconditionally when set;
82
+ // preserve that semantic so test fixtures with synthetic /tmp/... paths
83
+ // and operator workflows that pre-set the env var both keep working.
84
+ if (fromEnv)
85
+ return fromEnv;
86
+ try {
87
+ // execFileSync (not execSync) — no shell, fixed argv array, no injection
88
+ // surface. Inputs are all hard-coded constants.
89
+ const root = execFileSync("git", ["rev-parse", "--show-toplevel"], {
90
+ encoding: "utf8",
91
+ stdio: ["ignore", "pipe", "ignore"],
92
+ }).trim();
93
+ if (root)
94
+ return root;
95
+ }
96
+ catch {
97
+ // Not in a git repo — fall through.
98
+ }
99
+ return "global";
100
+ }
101
+ function ensureDir(dir) {
102
+ if (!existsSync(dir))
103
+ mkdirSync(dir, { recursive: true });
104
+ }
105
+ function rotateIfNeeded(obsFile, projectDir) {
106
+ if (!existsSync(obsFile))
107
+ return;
108
+ const lineCount = countLines(obsFile);
109
+ if (lineCount < ROTATION_LINE_THRESHOLD)
110
+ return;
111
+ const archiveTs = new Date().toISOString().replace(/[:.]/g, "-").replace(/Z$/, "");
112
+ renameSync(obsFile, join(projectDir, `observations.${archiveTs}.jsonl`));
113
+ pruneArchives(projectDir);
114
+ }
115
+ function countLines(file) {
116
+ const stat = statSync(file);
117
+ if (stat.size === 0)
118
+ return 0;
119
+ // For files capped at 10k lines, readFileSync is faster than streaming.
120
+ return readFileSync(file, "utf8").split("\n").length - 1;
121
+ }
122
+ function pruneArchives(projectDir) {
123
+ const archives = readdirSync(projectDir)
124
+ .filter((name) => /^observations\..+\.jsonl$/.test(name))
125
+ .sort()
126
+ .reverse()
127
+ .map((name) => join(projectDir, name));
128
+ for (const path of archives.slice(ARCHIVE_RETENTION)) {
129
+ try {
130
+ unlinkSync(path);
131
+ }
132
+ catch {
133
+ // Pruning failure is non-fatal; rotation already happened.
134
+ }
135
+ }
136
+ }
137
+ function writeProjectJsonIfNew(projectDir, projectHash, projectName, projectRoot, ts) {
138
+ const projectJson = join(projectDir, "project.json");
139
+ if (existsSync(projectJson))
140
+ return;
141
+ const body = {
142
+ id: projectHash,
143
+ name: projectName,
144
+ root: projectRoot,
145
+ created_at: ts,
146
+ };
147
+ writeFileSync(projectJson, JSON.stringify(body) + "\n", "utf8");
148
+ }
@@ -0,0 +1,49 @@
1
+ #!/usr/bin/env bash
2
+ #
3
+ # pre-commit hook: block staging of paths that were already cleaned up
4
+ # from the repo (and added to .gitignore) but could leak back in via
5
+ # `git add -f` or accidental staging. Belt-and-suspenders alongside
6
+ # .gitignore — .gitignore is silent if you bypass it; this hook is loud.
7
+ #
8
+ # Install:
9
+ # ln -s "$(pwd)/bin/pre-commit-block-strays.sh" .git/hooks/pre-commit
10
+ # # or, if you already have a pre-commit hook, source this from it.
11
+ #
12
+ # Exit codes:
13
+ # 0 — no blocked paths in the staged diff
14
+ # 1 — at least one blocked path is staged; commit is aborted
15
+
16
+ set -u
17
+
18
+ # Paths that have ever historically leaked into the repo and are now ignored.
19
+ # Add an entry here when a new transient/output directory is removed.
20
+ BLOCKED_PATTERNS=(
21
+ '^\.tmp-stop-e2e/'
22
+ '^nanobanana-output/'
23
+ )
24
+
25
+ staged_paths="$(git diff --cached --name-only --diff-filter=AM)"
26
+ if [ -z "$staged_paths" ]; then
27
+ exit 0
28
+ fi
29
+
30
+ violations=""
31
+ while IFS= read -r path; do
32
+ for pattern in "${BLOCKED_PATTERNS[@]}"; do
33
+ if printf '%s\n' "$path" | grep -qE "$pattern"; then
34
+ violations="${violations} - $path (matches /$pattern/)"$'\n'
35
+ fi
36
+ done
37
+ done <<< "$staged_paths"
38
+
39
+ if [ -n "$violations" ]; then
40
+ printf 'pre-commit: refusing to commit paths under historically-removed directories.\n\n'
41
+ printf '%s\n' "$violations"
42
+ printf 'These paths are .gitignore-blocked and have been removed from the repo;\n'
43
+ printf 'they should not re-enter via the staging area. If you really need to commit\n'
44
+ printf 'one of them, edit bin/pre-commit-block-strays.sh first to remove the pattern,\n'
45
+ printf 'document the reason, and commit that change as its own PR.\n'
46
+ exit 1
47
+ fi
48
+
49
+ exit 0
@@ -0,0 +1,416 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Refresh vendored third-party snapshots.
4
+ *
5
+ * Reads pinned SHAs from third-party/MANIFEST.md and rerunns the documented
6
+ * selective copy for each snapshot, in code, so refreshes are reproducible
7
+ * across Windows / macOS / Linux without bash.
8
+ *
9
+ * The bash recipes in MANIFEST.md remain the authoritative human-readable
10
+ * spec; this driver mirrors them. If you change the selective surface for
11
+ * a snapshot, update MANIFEST.md and the SNAPSHOTS table below together.
12
+ *
13
+ * Usage:
14
+ * node bin/refresh-third-party.mjs --list
15
+ * List configured snapshots with their pinned SHAs.
16
+ *
17
+ * node bin/refresh-third-party.mjs <name> --check
18
+ * Shallow-clone upstream, compare HEAD to the pinned SHA. No file writes.
19
+ *
20
+ * node bin/refresh-third-party.mjs <name>
21
+ * Full refresh: shallow clone, verify HEAD matches the pinned SHA,
22
+ * wipe the local path, recreate it, copy the selective surface
23
+ * verbatim, strip every CLAUDE.md inside the snapshot, print a diff
24
+ * stat. Aborts if the local snapshot path has uncommitted changes
25
+ * unless --force is passed.
26
+ *
27
+ * node bin/refresh-third-party.mjs --all
28
+ * node bin/refresh-third-party.mjs --all --check
29
+ * Same as above, applied to every configured snapshot in order.
30
+ *
31
+ * node bin/refresh-third-party.mjs --help
32
+ * Print this usage block.
33
+ *
34
+ * Exit codes:
35
+ * 0 — success (or --check found everything up-to-date)
36
+ * 1 — refresh failed, dirty working tree without --force, or --check found drift
37
+ * 2 — bad CLI usage / unknown snapshot name
38
+ */
39
+ import { spawnSync } from "node:child_process";
40
+ import { cp, mkdir, readFile, rm, stat } from "node:fs/promises";
41
+ import { tmpdir } from "node:os";
42
+ import { dirname, join, relative, resolve } from "node:path";
43
+ import { argv, cwd, exit, stderr, stdout } from "node:process";
44
+ import { fileURLToPath } from "node:url";
45
+
46
+ const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
47
+ const REPO_ROOT = resolve(SCRIPT_DIR, "..");
48
+ const MANIFEST_PATH = join(REPO_ROOT, "third-party", "MANIFEST.md");
49
+
50
+ /**
51
+ * Per-snapshot config. Mirrors the bash recipe blocks in MANIFEST.md.
52
+ * `manifestHeading` is the literal `### <heading>` text used to locate the
53
+ * pinned SHA row in MANIFEST.md.
54
+ */
55
+ const SNAPSHOTS = [
56
+ {
57
+ name: "oh-my-claudecode",
58
+ manifestHeading: "oh-my-claudecode",
59
+ upstream: "https://github.com/Yeachan-Heo/oh-my-claudecode.git",
60
+ localPath: "third-party/oh-my-claudecode",
61
+ selectiveDirs: [
62
+ "agents",
63
+ "skills",
64
+ "missions",
65
+ "templates",
66
+ "examples",
67
+ "hooks",
68
+ "docs",
69
+ ".claude-plugin",
70
+ ],
71
+ selectiveFiles: [
72
+ "LICENSE",
73
+ "README.md",
74
+ "AGENTS.md",
75
+ "CHANGELOG.md",
76
+ "SECURITY.md",
77
+ ],
78
+ },
79
+ {
80
+ name: "superpowers",
81
+ manifestHeading: "obra/superpowers",
82
+ upstream: "https://github.com/obra/superpowers.git",
83
+ localPath: "third-party/superpowers",
84
+ selectiveDirs: ["skills", "hooks", "docs", "assets", ".claude-plugin"],
85
+ selectiveFiles: [
86
+ "LICENSE",
87
+ "README.md",
88
+ "AGENTS.md",
89
+ "CODE_OF_CONDUCT.md",
90
+ "RELEASE-NOTES.md",
91
+ ],
92
+ },
93
+ ];
94
+
95
+ const SHA_RE = /^[0-9a-f]{40}$/i;
96
+
97
+ function log(msg) {
98
+ stdout.write(msg + "\n");
99
+ }
100
+ function err(msg) {
101
+ stderr.write(msg + "\n");
102
+ }
103
+
104
+ function usage() {
105
+ err(
106
+ [
107
+ "Usage:",
108
+ " node bin/refresh-third-party.mjs --list",
109
+ " node bin/refresh-third-party.mjs <name> --check",
110
+ " node bin/refresh-third-party.mjs <name> [--force]",
111
+ " node bin/refresh-third-party.mjs --all [--check] [--force]",
112
+ " node bin/refresh-third-party.mjs --help",
113
+ "",
114
+ "Configured snapshots: " + SNAPSHOTS.map((s) => s.name).join(", "),
115
+ ].join("\n"),
116
+ );
117
+ }
118
+
119
+ /**
120
+ * Parse the pinned SHA for a snapshot from MANIFEST.md.
121
+ * Strategy: locate `### <heading>`, then the first table row in that
122
+ * section beginning with `| Pinned SHA |`.
123
+ */
124
+ async function readPinnedSha(snapshot) {
125
+ const text = await readFile(MANIFEST_PATH, "utf8");
126
+ const lines = text.split(/\r?\n/);
127
+ const headingIdx = lines.findIndex(
128
+ (line) => line.trim() === `### ${snapshot.manifestHeading}`,
129
+ );
130
+ if (headingIdx === -1) {
131
+ throw new Error(
132
+ `MANIFEST.md missing heading "### ${snapshot.manifestHeading}"`,
133
+ );
134
+ }
135
+ for (let i = headingIdx + 1; i < lines.length; i++) {
136
+ const line = lines[i];
137
+ if (line.startsWith("### ")) break;
138
+ const m = line.match(/^\|\s*Pinned SHA\s*\|\s*`?([0-9a-fA-F]{7,40})`?\s*\|/);
139
+ if (m) {
140
+ const sha = m[1].toLowerCase();
141
+ if (!SHA_RE.test(sha)) {
142
+ throw new Error(
143
+ `MANIFEST.md "${snapshot.manifestHeading}": pinned SHA "${sha}" is not a 40-char hex`,
144
+ );
145
+ }
146
+ return sha;
147
+ }
148
+ }
149
+ throw new Error(
150
+ `MANIFEST.md "${snapshot.manifestHeading}": no "| Pinned SHA |" row found`,
151
+ );
152
+ }
153
+
154
+ function runGit(args, opts = {}) {
155
+ const result = spawnSync("git", args, {
156
+ encoding: "utf8",
157
+ ...opts,
158
+ });
159
+ if (result.error) {
160
+ throw new Error(`git ${args.join(" ")} failed: ${result.error.message}`);
161
+ }
162
+ return result;
163
+ }
164
+
165
+ function gitOk(args, opts = {}) {
166
+ const r = runGit(args, opts);
167
+ if (r.status !== 0) {
168
+ throw new Error(
169
+ `git ${args.join(" ")} exited ${r.status}: ${r.stderr || r.stdout}`,
170
+ );
171
+ }
172
+ return r.stdout.trim();
173
+ }
174
+
175
+ /**
176
+ * Shallow-clone upstream into a temp dir and return { dir, headSha }.
177
+ */
178
+ async function shallowClone(upstream) {
179
+ const dir = join(
180
+ tmpdir(),
181
+ `ci-refresh-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
182
+ );
183
+ gitOk(["clone", "--depth", "1", upstream, dir]);
184
+ const headSha = gitOk(["-C", dir, "rev-parse", "HEAD"]);
185
+ return { dir, headSha };
186
+ }
187
+
188
+ async function pathExists(p) {
189
+ try {
190
+ await stat(p);
191
+ return true;
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Ask git whether the local snapshot path has uncommitted changes.
199
+ * Runs from REPO_ROOT so worktrees are handled correctly.
200
+ */
201
+ function localPathDirty(relPath) {
202
+ const r = runGit(
203
+ ["status", "--porcelain", "--", relPath],
204
+ { cwd: REPO_ROOT },
205
+ );
206
+ if (r.status !== 0) {
207
+ throw new Error(
208
+ `git status failed for ${relPath}: ${r.stderr || r.stdout}`,
209
+ );
210
+ }
211
+ return r.stdout.trim().length > 0;
212
+ }
213
+
214
+ async function deleteClaudeMdRecursive(root) {
215
+ // Node-only equivalent of `find <root> -name CLAUDE.md -type f -delete`.
216
+ const { readdir } = await import("node:fs/promises");
217
+ const stack = [root];
218
+ let deleted = 0;
219
+ while (stack.length) {
220
+ const dir = stack.pop();
221
+ let entries;
222
+ try {
223
+ entries = await readdir(dir, { withFileTypes: true });
224
+ } catch {
225
+ continue;
226
+ }
227
+ for (const ent of entries) {
228
+ const full = join(dir, ent.name);
229
+ if (ent.isDirectory()) {
230
+ stack.push(full);
231
+ } else if (ent.isFile() && ent.name === "CLAUDE.md") {
232
+ await rm(full, { force: true });
233
+ deleted++;
234
+ }
235
+ }
236
+ }
237
+ return deleted;
238
+ }
239
+
240
+ async function checkOne(snapshot) {
241
+ const pinned = await readPinnedSha(snapshot);
242
+ const { dir, headSha } = await shallowClone(snapshot.upstream);
243
+ try {
244
+ const upToDate = headSha.toLowerCase() === pinned.toLowerCase();
245
+ log(`[${snapshot.name}]`);
246
+ log(` upstream : ${snapshot.upstream}`);
247
+ log(` pinned SHA : ${pinned}`);
248
+ log(` upstream HEAD: ${headSha}`);
249
+ log(` status : ${upToDate ? "up-to-date" : "would-update"}`);
250
+ return upToDate;
251
+ } finally {
252
+ await rm(dir, { recursive: true, force: true });
253
+ }
254
+ }
255
+
256
+ async function refreshOne(snapshot, { force }) {
257
+ const pinned = await readPinnedSha(snapshot);
258
+ const localAbs = join(REPO_ROOT, snapshot.localPath);
259
+
260
+ if (!force && (await pathExists(localAbs))) {
261
+ if (localPathDirty(snapshot.localPath)) {
262
+ throw new Error(
263
+ `local snapshot path "${snapshot.localPath}" has uncommitted changes; ` +
264
+ `commit/stash first, or rerun with --force`,
265
+ );
266
+ }
267
+ }
268
+
269
+ const { dir, headSha } = await shallowClone(snapshot.upstream);
270
+ try {
271
+ if (headSha.toLowerCase() !== pinned.toLowerCase()) {
272
+ throw new Error(
273
+ `[${snapshot.name}] upstream HEAD ${headSha} != pinned ${pinned}; ` +
274
+ `bump the pinned SHA in third-party/MANIFEST.md first`,
275
+ );
276
+ }
277
+
278
+ // Wipe + recreate destination.
279
+ await rm(localAbs, { recursive: true, force: true });
280
+ await mkdir(localAbs, { recursive: true });
281
+
282
+ // Copy selective directories.
283
+ let copiedDirs = 0;
284
+ for (const d of snapshot.selectiveDirs) {
285
+ const src = join(dir, d);
286
+ if (!(await pathExists(src))) {
287
+ throw new Error(
288
+ `[${snapshot.name}] expected directory "${d}" missing in upstream`,
289
+ );
290
+ }
291
+ await cp(src, join(localAbs, d), { recursive: true });
292
+ copiedDirs++;
293
+ }
294
+ // Copy selective top-level files.
295
+ let copiedFiles = 0;
296
+ for (const f of snapshot.selectiveFiles) {
297
+ const src = join(dir, f);
298
+ if (!(await pathExists(src))) {
299
+ throw new Error(
300
+ `[${snapshot.name}] expected file "${f}" missing in upstream`,
301
+ );
302
+ }
303
+ await cp(src, join(localAbs, f));
304
+ copiedFiles++;
305
+ }
306
+
307
+ // Strip every CLAUDE.md (auto-loads as session context).
308
+ const stripped = await deleteClaudeMdRecursive(localAbs);
309
+
310
+ // Print git diff stat scoped to the snapshot path.
311
+ const diffStat = runGit(
312
+ ["diff", "--stat", "--", snapshot.localPath],
313
+ { cwd: REPO_ROOT },
314
+ );
315
+ log(`[${snapshot.name}]`);
316
+ log(` upstream : ${snapshot.upstream}`);
317
+ log(` pinned SHA : ${pinned}`);
318
+ log(` upstream HEAD: ${headSha}`);
319
+ log(
320
+ ` status : updated (${copiedDirs} dirs, ${copiedFiles} files, ${stripped} CLAUDE.md stripped)`,
321
+ );
322
+ if (diffStat.stdout.trim()) {
323
+ log(" diff --stat :");
324
+ for (const line of diffStat.stdout.trimEnd().split(/\r?\n/)) {
325
+ log(` ${line}`);
326
+ }
327
+ } else {
328
+ log(" diff --stat : (no working-tree change)");
329
+ }
330
+ return true;
331
+ } finally {
332
+ await rm(dir, { recursive: true, force: true });
333
+ }
334
+ }
335
+
336
+ async function listAll() {
337
+ log("Configured third-party snapshots:");
338
+ for (const s of SNAPSHOTS) {
339
+ let pinned;
340
+ try {
341
+ pinned = await readPinnedSha(s);
342
+ } catch (e) {
343
+ pinned = `<error: ${e.message}>`;
344
+ }
345
+ log(` - ${s.name}`);
346
+ log(` upstream : ${s.upstream}`);
347
+ log(` localPath : ${s.localPath}`);
348
+ log(` pinnedSHA : ${pinned}`);
349
+ }
350
+ }
351
+
352
+ function findSnapshot(name) {
353
+ return SNAPSHOTS.find((s) => s.name === name);
354
+ }
355
+
356
+ async function main() {
357
+ const args = argv.slice(2);
358
+ if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
359
+ usage();
360
+ exit(args.length === 0 ? 2 : 0);
361
+ }
362
+
363
+ if (args.includes("--list")) {
364
+ await listAll();
365
+ exit(0);
366
+ }
367
+
368
+ const force = args.includes("--force");
369
+ const check = args.includes("--check");
370
+ const all = args.includes("--all");
371
+
372
+ const positional = args.filter((a) => !a.startsWith("--"));
373
+
374
+ let targets;
375
+ if (all) {
376
+ targets = SNAPSHOTS;
377
+ } else if (positional.length === 1) {
378
+ const snap = findSnapshot(positional[0]);
379
+ if (!snap) {
380
+ err(
381
+ `Unknown snapshot "${positional[0]}". Known: ${SNAPSHOTS.map((s) => s.name).join(", ")}`,
382
+ );
383
+ exit(2);
384
+ }
385
+ targets = [snap];
386
+ } else {
387
+ usage();
388
+ exit(2);
389
+ }
390
+
391
+ let allUpToDate = true;
392
+ let firstErr;
393
+ for (const snap of targets) {
394
+ try {
395
+ if (check) {
396
+ const ok = await checkOne(snap);
397
+ if (!ok) allUpToDate = false;
398
+ } else {
399
+ await refreshOne(snap, { force });
400
+ }
401
+ } catch (e) {
402
+ firstErr = firstErr || e;
403
+ err(`[${snap.name}] ERROR: ${e.message}`);
404
+ allUpToDate = false;
405
+ }
406
+ }
407
+
408
+ if (firstErr) exit(1);
409
+ if (check && !allUpToDate) exit(1);
410
+ exit(0);
411
+ }
412
+
413
+ main().catch((e) => {
414
+ err(`fatal: ${e.stack || e.message}`);
415
+ exit(1);
416
+ });