cclaw-cli 7.7.1 → 8.1.1

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 (284) hide show
  1. package/README.md +211 -134
  2. package/dist/artifact-frontmatter.d.ts +51 -0
  3. package/dist/artifact-frontmatter.js +131 -0
  4. package/dist/artifact-paths.d.ts +7 -27
  5. package/dist/artifact-paths.js +20 -249
  6. package/dist/cancel.d.ts +16 -0
  7. package/dist/cancel.js +66 -0
  8. package/dist/cli.d.ts +2 -27
  9. package/dist/cli.js +107 -511
  10. package/dist/compound.d.ts +26 -0
  11. package/dist/compound.js +96 -0
  12. package/dist/config.d.ts +14 -51
  13. package/dist/config.js +23 -359
  14. package/dist/constants.d.ts +11 -18
  15. package/dist/constants.js +19 -106
  16. package/dist/content/antipatterns.d.ts +1 -0
  17. package/dist/content/antipatterns.js +109 -0
  18. package/dist/content/artifact-templates.d.ts +10 -0
  19. package/dist/content/artifact-templates.js +550 -0
  20. package/dist/content/cancel-command.d.ts +2 -2
  21. package/dist/content/cancel-command.js +25 -17
  22. package/dist/content/core-agents.d.ts +9 -233
  23. package/dist/content/core-agents.js +39 -768
  24. package/dist/content/decision-protocol.d.ts +1 -12
  25. package/dist/content/decision-protocol.js +27 -20
  26. package/dist/content/examples.d.ts +8 -42
  27. package/dist/content/examples.js +293 -425
  28. package/dist/content/idea-command.d.ts +2 -0
  29. package/dist/content/idea-command.js +38 -0
  30. package/dist/content/iron-laws.d.ts +4 -138
  31. package/dist/content/iron-laws.js +18 -197
  32. package/dist/content/meta-skill.d.ts +1 -3
  33. package/dist/content/meta-skill.js +57 -134
  34. package/dist/content/node-hooks.d.ts +12 -8
  35. package/dist/content/node-hooks.js +188 -838
  36. package/dist/content/recovery.d.ts +8 -0
  37. package/dist/content/recovery.js +179 -0
  38. package/dist/content/reference-patterns.d.ts +4 -13
  39. package/dist/content/reference-patterns.js +260 -389
  40. package/dist/content/research-playbooks.d.ts +8 -8
  41. package/dist/content/research-playbooks.js +108 -121
  42. package/dist/content/review-loop.d.ts +6 -192
  43. package/dist/content/review-loop.js +29 -731
  44. package/dist/content/skills.d.ts +8 -38
  45. package/dist/content/skills.js +681 -732
  46. package/dist/content/specialist-prompts/architect.d.ts +1 -0
  47. package/dist/content/specialist-prompts/architect.js +225 -0
  48. package/dist/content/specialist-prompts/brainstormer.d.ts +1 -0
  49. package/dist/content/specialist-prompts/brainstormer.js +168 -0
  50. package/dist/content/specialist-prompts/index.d.ts +2 -0
  51. package/dist/content/specialist-prompts/index.js +14 -0
  52. package/dist/content/specialist-prompts/planner.d.ts +1 -0
  53. package/dist/content/specialist-prompts/planner.js +182 -0
  54. package/dist/content/specialist-prompts/reviewer.d.ts +1 -0
  55. package/dist/content/specialist-prompts/reviewer.js +193 -0
  56. package/dist/content/specialist-prompts/security-reviewer.d.ts +1 -0
  57. package/dist/content/specialist-prompts/security-reviewer.js +133 -0
  58. package/dist/content/specialist-prompts/slice-builder.d.ts +1 -0
  59. package/dist/content/specialist-prompts/slice-builder.js +232 -0
  60. package/dist/content/stage-playbooks.d.ts +8 -0
  61. package/dist/content/stage-playbooks.js +404 -0
  62. package/dist/content/start-command.d.ts +2 -12
  63. package/dist/content/start-command.js +221 -207
  64. package/dist/flow-state.d.ts +21 -178
  65. package/dist/flow-state.js +67 -170
  66. package/dist/fs-utils.d.ts +6 -26
  67. package/dist/fs-utils.js +29 -162
  68. package/dist/gitignore.d.ts +2 -1
  69. package/dist/gitignore.js +51 -34
  70. package/dist/harness-detect.d.ts +10 -0
  71. package/dist/harness-detect.js +29 -0
  72. package/dist/harness-prompt.d.ts +26 -0
  73. package/dist/harness-prompt.js +142 -0
  74. package/dist/install.d.ts +35 -15
  75. package/dist/install.js +238 -1347
  76. package/dist/knowledge-store.d.ts +19 -163
  77. package/dist/knowledge-store.js +56 -590
  78. package/dist/logger.d.ts +8 -3
  79. package/dist/logger.js +13 -4
  80. package/dist/orchestrator-routing.d.ts +29 -0
  81. package/dist/orchestrator-routing.js +156 -0
  82. package/dist/run-persistence.d.ts +7 -118
  83. package/dist/run-persistence.js +29 -845
  84. package/dist/runtime/run-hook.entry.d.ts +1 -3
  85. package/dist/runtime/run-hook.entry.js +19 -4
  86. package/dist/runtime/run-hook.mjs +13 -1024
  87. package/dist/types.d.ts +25 -261
  88. package/dist/types.js +8 -36
  89. package/package.json +6 -3
  90. package/dist/artifact-linter/brainstorm.d.ts +0 -2
  91. package/dist/artifact-linter/brainstorm.js +0 -353
  92. package/dist/artifact-linter/design.d.ts +0 -18
  93. package/dist/artifact-linter/design.js +0 -444
  94. package/dist/artifact-linter/findings-dedup.d.ts +0 -56
  95. package/dist/artifact-linter/findings-dedup.js +0 -232
  96. package/dist/artifact-linter/plan.d.ts +0 -2
  97. package/dist/artifact-linter/plan.js +0 -826
  98. package/dist/artifact-linter/review-army.d.ts +0 -49
  99. package/dist/artifact-linter/review-army.js +0 -520
  100. package/dist/artifact-linter/review.d.ts +0 -2
  101. package/dist/artifact-linter/review.js +0 -113
  102. package/dist/artifact-linter/scope.d.ts +0 -2
  103. package/dist/artifact-linter/scope.js +0 -158
  104. package/dist/artifact-linter/shared.d.ts +0 -637
  105. package/dist/artifact-linter/shared.js +0 -2163
  106. package/dist/artifact-linter/ship.d.ts +0 -2
  107. package/dist/artifact-linter/ship.js +0 -250
  108. package/dist/artifact-linter/spec.d.ts +0 -2
  109. package/dist/artifact-linter/spec.js +0 -176
  110. package/dist/artifact-linter/tdd.d.ts +0 -118
  111. package/dist/artifact-linter/tdd.js +0 -1404
  112. package/dist/artifact-linter.d.ts +0 -15
  113. package/dist/artifact-linter.js +0 -517
  114. package/dist/codex-feature-flag.d.ts +0 -58
  115. package/dist/codex-feature-flag.js +0 -193
  116. package/dist/content/closeout-guidance.d.ts +0 -14
  117. package/dist/content/closeout-guidance.js +0 -44
  118. package/dist/content/diff-command.d.ts +0 -1
  119. package/dist/content/diff-command.js +0 -43
  120. package/dist/content/harness-doc.d.ts +0 -1
  121. package/dist/content/harness-doc.js +0 -65
  122. package/dist/content/hook-events.d.ts +0 -9
  123. package/dist/content/hook-events.js +0 -23
  124. package/dist/content/hook-manifest.d.ts +0 -81
  125. package/dist/content/hook-manifest.js +0 -156
  126. package/dist/content/hooks.d.ts +0 -11
  127. package/dist/content/hooks.js +0 -1972
  128. package/dist/content/idea.d.ts +0 -60
  129. package/dist/content/idea.js +0 -416
  130. package/dist/content/language-policy.d.ts +0 -2
  131. package/dist/content/language-policy.js +0 -13
  132. package/dist/content/learnings.d.ts +0 -6
  133. package/dist/content/learnings.js +0 -141
  134. package/dist/content/observe.d.ts +0 -19
  135. package/dist/content/observe.js +0 -86
  136. package/dist/content/opencode-plugin.d.ts +0 -1
  137. package/dist/content/opencode-plugin.js +0 -635
  138. package/dist/content/review-prompts.d.ts +0 -1
  139. package/dist/content/review-prompts.js +0 -104
  140. package/dist/content/runtime-shared-snippets.d.ts +0 -8
  141. package/dist/content/runtime-shared-snippets.js +0 -80
  142. package/dist/content/session-hooks.d.ts +0 -7
  143. package/dist/content/session-hooks.js +0 -107
  144. package/dist/content/skills-elicitation.d.ts +0 -1
  145. package/dist/content/skills-elicitation.js +0 -167
  146. package/dist/content/stage-command.d.ts +0 -2
  147. package/dist/content/stage-command.js +0 -17
  148. package/dist/content/stage-schema.d.ts +0 -117
  149. package/dist/content/stage-schema.js +0 -955
  150. package/dist/content/stages/_lint-metadata/index.d.ts +0 -2
  151. package/dist/content/stages/_lint-metadata/index.js +0 -97
  152. package/dist/content/stages/brainstorm.d.ts +0 -2
  153. package/dist/content/stages/brainstorm.js +0 -184
  154. package/dist/content/stages/design.d.ts +0 -2
  155. package/dist/content/stages/design.js +0 -288
  156. package/dist/content/stages/index.d.ts +0 -8
  157. package/dist/content/stages/index.js +0 -11
  158. package/dist/content/stages/plan.d.ts +0 -2
  159. package/dist/content/stages/plan.js +0 -191
  160. package/dist/content/stages/review.d.ts +0 -2
  161. package/dist/content/stages/review.js +0 -240
  162. package/dist/content/stages/schema-types.d.ts +0 -203
  163. package/dist/content/stages/schema-types.js +0 -1
  164. package/dist/content/stages/scope.d.ts +0 -2
  165. package/dist/content/stages/scope.js +0 -254
  166. package/dist/content/stages/ship.d.ts +0 -2
  167. package/dist/content/stages/ship.js +0 -159
  168. package/dist/content/stages/spec.d.ts +0 -2
  169. package/dist/content/stages/spec.js +0 -170
  170. package/dist/content/stages/tdd.d.ts +0 -4
  171. package/dist/content/stages/tdd.js +0 -273
  172. package/dist/content/state-contracts.d.ts +0 -1
  173. package/dist/content/state-contracts.js +0 -63
  174. package/dist/content/status-command.d.ts +0 -4
  175. package/dist/content/status-command.js +0 -109
  176. package/dist/content/subagent-context-skills.d.ts +0 -4
  177. package/dist/content/subagent-context-skills.js +0 -279
  178. package/dist/content/subagents.d.ts +0 -3
  179. package/dist/content/subagents.js +0 -997
  180. package/dist/content/templates.d.ts +0 -26
  181. package/dist/content/templates.js +0 -1692
  182. package/dist/content/track-render-context.d.ts +0 -18
  183. package/dist/content/track-render-context.js +0 -53
  184. package/dist/content/tree-command.d.ts +0 -1
  185. package/dist/content/tree-command.js +0 -64
  186. package/dist/content/utility-skills.d.ts +0 -30
  187. package/dist/content/utility-skills.js +0 -160
  188. package/dist/content/view-command.d.ts +0 -2
  189. package/dist/content/view-command.js +0 -92
  190. package/dist/delegation.d.ts +0 -649
  191. package/dist/delegation.js +0 -1539
  192. package/dist/early-loop.d.ts +0 -70
  193. package/dist/early-loop.js +0 -302
  194. package/dist/execution-topology.d.ts +0 -44
  195. package/dist/execution-topology.js +0 -95
  196. package/dist/gate-evidence.d.ts +0 -85
  197. package/dist/gate-evidence.js +0 -631
  198. package/dist/harness-adapters.d.ts +0 -151
  199. package/dist/harness-adapters.js +0 -756
  200. package/dist/harness-selection.d.ts +0 -31
  201. package/dist/harness-selection.js +0 -214
  202. package/dist/hook-schema.d.ts +0 -6
  203. package/dist/hook-schema.js +0 -114
  204. package/dist/hook-schemas/claude-hooks.v1.json +0 -10
  205. package/dist/hook-schemas/codex-hooks.v1.json +0 -10
  206. package/dist/hook-schemas/cursor-hooks.v1.json +0 -13
  207. package/dist/init-detect.d.ts +0 -2
  208. package/dist/init-detect.js +0 -50
  209. package/dist/internal/advance-stage/advance.d.ts +0 -89
  210. package/dist/internal/advance-stage/advance.js +0 -655
  211. package/dist/internal/advance-stage/cancel-run.d.ts +0 -8
  212. package/dist/internal/advance-stage/cancel-run.js +0 -19
  213. package/dist/internal/advance-stage/flow-state-coercion.d.ts +0 -3
  214. package/dist/internal/advance-stage/flow-state-coercion.js +0 -81
  215. package/dist/internal/advance-stage/helpers.d.ts +0 -14
  216. package/dist/internal/advance-stage/helpers.js +0 -145
  217. package/dist/internal/advance-stage/hook.d.ts +0 -8
  218. package/dist/internal/advance-stage/hook.js +0 -40
  219. package/dist/internal/advance-stage/parsers.d.ts +0 -72
  220. package/dist/internal/advance-stage/parsers.js +0 -357
  221. package/dist/internal/advance-stage/proactive-delegation-trace.d.ts +0 -24
  222. package/dist/internal/advance-stage/proactive-delegation-trace.js +0 -56
  223. package/dist/internal/advance-stage/review-loop.d.ts +0 -16
  224. package/dist/internal/advance-stage/review-loop.js +0 -199
  225. package/dist/internal/advance-stage/rewind.d.ts +0 -14
  226. package/dist/internal/advance-stage/rewind.js +0 -108
  227. package/dist/internal/advance-stage/start-flow.d.ts +0 -13
  228. package/dist/internal/advance-stage/start-flow.js +0 -241
  229. package/dist/internal/advance-stage/verify.d.ts +0 -21
  230. package/dist/internal/advance-stage/verify.js +0 -185
  231. package/dist/internal/advance-stage.d.ts +0 -7
  232. package/dist/internal/advance-stage.js +0 -138
  233. package/dist/internal/cohesion-contract-stub.d.ts +0 -24
  234. package/dist/internal/cohesion-contract-stub.js +0 -148
  235. package/dist/internal/compound-readiness.d.ts +0 -23
  236. package/dist/internal/compound-readiness.js +0 -102
  237. package/dist/internal/detect-public-api-changes.d.ts +0 -5
  238. package/dist/internal/detect-public-api-changes.js +0 -45
  239. package/dist/internal/detect-supply-chain-changes.d.ts +0 -6
  240. package/dist/internal/detect-supply-chain-changes.js +0 -138
  241. package/dist/internal/early-loop-status.d.ts +0 -7
  242. package/dist/internal/early-loop-status.js +0 -93
  243. package/dist/internal/envelope-validate.d.ts +0 -7
  244. package/dist/internal/envelope-validate.js +0 -66
  245. package/dist/internal/flow-state-repair.d.ts +0 -20
  246. package/dist/internal/flow-state-repair.js +0 -104
  247. package/dist/internal/plan-split-waves.d.ts +0 -190
  248. package/dist/internal/plan-split-waves.js +0 -764
  249. package/dist/internal/runtime-integrity.d.ts +0 -7
  250. package/dist/internal/runtime-integrity.js +0 -268
  251. package/dist/internal/slice-commit.d.ts +0 -7
  252. package/dist/internal/slice-commit.js +0 -619
  253. package/dist/internal/tdd-loop-status.d.ts +0 -14
  254. package/dist/internal/tdd-loop-status.js +0 -68
  255. package/dist/internal/tdd-red-evidence.d.ts +0 -7
  256. package/dist/internal/tdd-red-evidence.js +0 -153
  257. package/dist/internal/waiver-grant.d.ts +0 -62
  258. package/dist/internal/waiver-grant.js +0 -294
  259. package/dist/internal/wave-status.d.ts +0 -74
  260. package/dist/internal/wave-status.js +0 -506
  261. package/dist/managed-resources.d.ts +0 -53
  262. package/dist/managed-resources.js +0 -313
  263. package/dist/policy.d.ts +0 -10
  264. package/dist/policy.js +0 -167
  265. package/dist/retro-gate.d.ts +0 -9
  266. package/dist/retro-gate.js +0 -47
  267. package/dist/run-archive.d.ts +0 -61
  268. package/dist/run-archive.js +0 -391
  269. package/dist/runs.d.ts +0 -2
  270. package/dist/runs.js +0 -2
  271. package/dist/stack-detection.d.ts +0 -116
  272. package/dist/stack-detection.js +0 -489
  273. package/dist/streaming/event-stream.d.ts +0 -31
  274. package/dist/streaming/event-stream.js +0 -114
  275. package/dist/tdd-cycle.d.ts +0 -107
  276. package/dist/tdd-cycle.js +0 -289
  277. package/dist/tdd-verification-evidence.d.ts +0 -17
  278. package/dist/tdd-verification-evidence.js +0 -122
  279. package/dist/track-heuristics.d.ts +0 -27
  280. package/dist/track-heuristics.js +0 -154
  281. package/dist/util/slice-id.d.ts +0 -58
  282. package/dist/util/slice-id.js +0 -89
  283. package/dist/worktree-manager.d.ts +0 -20
  284. package/dist/worktree-manager.js +0 -108
package/dist/fs-utils.js CHANGED
@@ -1,161 +1,5 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { getActiveManagedResourceSession } from "./managed-resources.js";
4
- export async function ensureDir(dirPath) {
5
- await fs.mkdir(dirPath, { recursive: true });
6
- }
7
- /**
8
- * Strip a leading UTF-8 BOM (U+FEFF) if present. Many editors (VS Code on
9
- * Windows, Notepad, some CI tools) silently prepend a BOM when saving
10
- * UTF-8; when the file is then split on `\n` the first line keeps the
11
- * invisible BOM and `JSON.parse` rejects it, which caused the first
12
- * knowledge.jsonl entry to be silently dropped on load. Treat BOM as a
13
- * no-op at read time so the rest of the pipeline sees clean UTF-8.
14
- */
15
- export function stripBom(text) {
16
- return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
17
- }
18
- function sleep(ms) {
19
- return new Promise((resolve) => setTimeout(resolve, ms));
20
- }
21
- /**
22
- * Acquire a lightweight lock by creating a directory.
23
- * The lock is removed in a finally block.
24
- */
25
- export async function withDirectoryLock(lockPath, fn, options = {}) {
26
- const retries = options.retries ?? 200;
27
- const retryDelayMs = options.retryDelayMs ?? 20;
28
- const staleAfterMs = options.staleAfterMs ?? 60_000;
29
- await ensureDir(path.dirname(lockPath));
30
- let acquired = false;
31
- let lastError = null;
32
- for (let attempt = 0; attempt < retries; attempt += 1) {
33
- try {
34
- await fs.mkdir(lockPath);
35
- acquired = true;
36
- break;
37
- }
38
- catch (error) {
39
- lastError = error;
40
- const code = error?.code;
41
- if (code !== "EEXIST") {
42
- throw error;
43
- }
44
- try {
45
- const stat = await fs.stat(lockPath);
46
- if (!stat.isDirectory()) {
47
- // A non-directory lives at the lock path (e.g. a stray file).
48
- // Retrying mkdir() will keep returning EEXIST forever, and no
49
- // other cclaw process is holding the lock - the path is simply
50
- // unusable. Fail loudly rather than burning the full retry
51
- // budget, so the caller sees a deterministic error.
52
- throw new Error(`Lock path exists but is not a directory: ${lockPath}`);
53
- }
54
- if (Date.now() - stat.mtimeMs > staleAfterMs) {
55
- await fs.rm(lockPath, { recursive: true, force: true });
56
- continue;
57
- }
58
- }
59
- catch (statError) {
60
- if (statError instanceof Error &&
61
- statError.message.startsWith("Lock path exists but is not a directory")) {
62
- throw statError;
63
- }
64
- // Lock directory disappeared between retries.
65
- }
66
- await sleep(retryDelayMs);
67
- }
68
- }
69
- if (!acquired) {
70
- const details = lastError instanceof Error ? lastError.message : String(lastError);
71
- throw new Error(`Failed to acquire lock: ${lockPath} (attempts=${retries}, retryDelayMs=${retryDelayMs}, staleAfterMs=${staleAfterMs}, lastError=${details})`);
72
- }
73
- try {
74
- return await fn();
75
- }
76
- finally {
77
- await fs.rm(lockPath, { recursive: true, force: true }).catch((cleanupError) => {
78
- // Lock cleanup failure should not shadow the original operation result,
79
- // but keep a diagnostic breadcrumb for flaky FS environments.
80
- const details = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
81
- // eslint-disable-next-line no-console
82
- console.warn(`cclaw lock cleanup failed for ${lockPath}: ${details}`);
83
- });
84
- }
85
- }
86
- export async function writeFileSafe(filePath, content, options = {}) {
87
- const managedSession = getActiveManagedResourceSession();
88
- if (managedSession?.shouldManage(filePath)) {
89
- await managedSession.writeFileSafe(filePath, content, options);
90
- return;
91
- }
92
- await ensureDir(path.dirname(filePath));
93
- const tempPath = path.join(path.dirname(filePath), `.${path.basename(filePath)}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
94
- const targetMode = options.mode;
95
- await fs.writeFile(tempPath, content, { encoding: "utf8", ...(targetMode !== undefined ? { mode: targetMode } : {}) });
96
- // On Windows, `fs.rename` can fail transiently with EPERM / EBUSY / EACCES
97
- // when the target file is briefly held open by another process (antivirus,
98
- // search indexer, or a concurrent cclaw hook). Retry with small backoff
99
- // before falling back to a non-atomic copy + unlink.
100
- const renameRetryableCodes = new Set(["EPERM", "EBUSY", "EACCES"]);
101
- let attempt = 0;
102
- const maxAttempts = 6;
103
- // eslint-disable-next-line no-constant-condition
104
- while (true) {
105
- try {
106
- await fs.rename(tempPath, filePath);
107
- if (targetMode !== undefined) {
108
- await fs.chmod(filePath, targetMode).catch(() => undefined);
109
- }
110
- return;
111
- }
112
- catch (error) {
113
- const code = error?.code;
114
- // `rename` fails with EXDEV when the temp file and target live on
115
- // different filesystems (container bind mounts, tmpfs + rootfs,
116
- // cross-volume setups). Fall back to copy + unlink so atomic writes
117
- // still work — copyFile is not fully atomic but is the best we can
118
- // do across devices, and we remove the temp even if copy fails.
119
- if (code === "EXDEV") {
120
- try {
121
- await fs.copyFile(tempPath, filePath);
122
- if (targetMode !== undefined) {
123
- await fs.chmod(filePath, targetMode).catch(() => undefined);
124
- }
125
- }
126
- finally {
127
- await fs.unlink(tempPath).catch(() => undefined);
128
- }
129
- return;
130
- }
131
- if (code !== undefined && renameRetryableCodes.has(code) && attempt < maxAttempts) {
132
- attempt += 1;
133
- const waitMs = 10 * attempt + Math.floor(Math.random() * 10);
134
- await new Promise((resolve) => setTimeout(resolve, waitMs));
135
- continue;
136
- }
137
- if (code !== undefined && renameRetryableCodes.has(code)) {
138
- // Last-resort fallback on Windows: copy-then-unlink. Not atomic,
139
- // but the caller is expected to have serialized via a directory
140
- // lock so this only loses atomicity under extreme contention.
141
- try {
142
- await fs.copyFile(tempPath, filePath);
143
- if (targetMode !== undefined) {
144
- await fs.chmod(filePath, targetMode).catch(() => undefined);
145
- }
146
- return;
147
- }
148
- finally {
149
- await fs.unlink(tempPath).catch(() => undefined);
150
- }
151
- }
152
- // Other errors: try to clean up the temp to avoid littering the
153
- // directory with orphaned `.tmp-<pid>-*` files, then rethrow.
154
- await fs.unlink(tempPath).catch(() => undefined);
155
- throw error;
156
- }
157
- }
158
- }
159
3
  export async function exists(filePath) {
160
4
  try {
161
5
  await fs.access(filePath);
@@ -165,11 +9,34 @@ export async function exists(filePath) {
165
9
  return false;
166
10
  }
167
11
  }
168
- export async function removeIfExists(targetPath) {
169
- if (await exists(targetPath)) {
170
- await fs.rm(targetPath, { recursive: true, force: true });
171
- }
12
+ export async function ensureDir(dirPath) {
13
+ await fs.mkdir(dirPath, { recursive: true });
172
14
  }
173
- export function resolveProjectPath(cwd, relativePath) {
174
- return path.resolve(cwd, relativePath);
15
+ export async function writeFileSafe(filePath, content) {
16
+ await ensureDir(path.dirname(filePath));
17
+ const tempPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
18
+ await fs.writeFile(tempPath, content, "utf8");
19
+ await fs.rename(tempPath, filePath);
20
+ }
21
+ export async function readJsonIfExists(filePath) {
22
+ if (!(await exists(filePath)))
23
+ return null;
24
+ return JSON.parse(await fs.readFile(filePath, "utf8"));
25
+ }
26
+ export async function removePath(filePath) {
27
+ await fs.rm(filePath, { recursive: true, force: true });
28
+ }
29
+ export async function listMarkdownFiles(dir) {
30
+ if (!(await exists(dir)))
31
+ return [];
32
+ const entries = await fs.readdir(dir, { withFileTypes: true });
33
+ return entries
34
+ .filter((entry) => entry.isFile() && entry.name.endsWith(".md"))
35
+ .map((entry) => path.join(dir, entry.name));
36
+ }
37
+ export async function listSubdirs(dir) {
38
+ if (!(await exists(dir)))
39
+ return [];
40
+ const entries = await fs.readdir(dir, { withFileTypes: true });
41
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => path.join(dir, entry.name));
175
42
  }
@@ -1,3 +1,4 @@
1
- export declare function ensureGitignore(projectRoot: string): Promise<void>;
1
+ export declare const REQUIRED_GITIGNORE_PATTERNS: readonly ["# cclaw transient state", ".cclaw/state/", ".cclaw/worktrees/"];
2
+ export declare function ensureGitignorePatterns(projectRoot: string): Promise<void>;
2
3
  export declare function removeGitignorePatterns(projectRoot: string): Promise<void>;
3
4
  export declare function gitignoreHasRequiredPatterns(projectRoot: string): Promise<boolean>;
package/dist/gitignore.js CHANGED
@@ -1,46 +1,63 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { REQUIRED_GITIGNORE_PATTERNS } from "./constants.js";
4
3
  import { exists, writeFileSafe } from "./fs-utils.js";
5
- export async function ensureGitignore(projectRoot) {
6
- const gitignorePath = path.join(projectRoot, ".gitignore");
7
- const currentContent = (await exists(gitignorePath))
8
- ? await fs.readFile(gitignorePath, "utf8")
9
- : "";
10
- const lines = currentContent.split(/\r?\n/);
11
- const normalized = new Set(lines.map((line) => line.trim()).filter(Boolean));
12
- const missing = REQUIRED_GITIGNORE_PATTERNS.filter((pattern) => !normalized.has(pattern));
13
- if (missing.length === 0) {
4
+ /**
5
+ * cclaw .gitignore patterns.
6
+ *
7
+ * Only the *transient* parts of .cclaw/ are ignored. The artifact tree
8
+ * (`.cclaw/flows/`, `.cclaw/lib/`, `.cclaw/config.yaml`, `.cclaw/ideas.md`,
9
+ * `.cclaw/knowledge.jsonl`, hooks, etc.) is meant to be committed so the
10
+ * team and graph tools can index the work history.
11
+ *
12
+ * - `.cclaw/state/` — per-developer flow-state.json. Mutates every session.
13
+ * - `.cclaw/worktrees/` — transient git worktrees created by the
14
+ * parallel-build pattern. These already contain regular checked-out trees;
15
+ * never commit them as nested data.
16
+ */
17
+ const SECTION_HEADER = "# cclaw transient state";
18
+ export const REQUIRED_GITIGNORE_PATTERNS = [
19
+ SECTION_HEADER,
20
+ ".cclaw/state/",
21
+ ".cclaw/worktrees/"
22
+ ];
23
+ function gitignorePath(projectRoot) {
24
+ return path.join(projectRoot, ".gitignore");
25
+ }
26
+ export async function ensureGitignorePatterns(projectRoot) {
27
+ const target = gitignorePath(projectRoot);
28
+ const current = (await exists(target)) ? await fs.readFile(target, "utf8") : "";
29
+ const lines = current.split(/\r?\n/);
30
+ const present = new Set(lines.map((line) => line.trim()).filter(Boolean));
31
+ const missing = REQUIRED_GITIGNORE_PATTERNS.filter((pattern) => !present.has(pattern));
32
+ if (missing.length === 0)
14
33
  return;
15
- }
16
- const base = lines.join("\n").replace(/\s+$/u, "");
17
- const suffix = `${base.length > 0 ? "\n" : ""}${missing.join("\n")}\n`;
18
- // `writeFileSafe` performs a tmp-file + rename so a crash mid-write
19
- // cannot leave `.gitignore` in a half-written state; the previous
20
- // direct `fs.writeFile` could truncate the file on SIGKILL.
21
- await writeFileSafe(gitignorePath, `${base}${suffix}`);
34
+ const trimmedBase = current.replace(/\s+$/u, "");
35
+ const separator = trimmedBase.length > 0 ? "\n\n" : "";
36
+ const next = `${trimmedBase}${separator}${missing.join("\n")}\n`;
37
+ await writeFileSafe(target, next);
22
38
  }
23
39
  export async function removeGitignorePatterns(projectRoot) {
24
- const gitignorePath = path.join(projectRoot, ".gitignore");
25
- if (!(await exists(gitignorePath)))
40
+ const target = gitignorePath(projectRoot);
41
+ if (!(await exists(target)))
42
+ return;
43
+ const current = await fs.readFile(target, "utf8");
44
+ const drop = new Set(REQUIRED_GITIGNORE_PATTERNS);
45
+ const cleaned = current
46
+ .split(/\r?\n/)
47
+ .filter((line) => !drop.has(line.trim()))
48
+ .join("\n")
49
+ .replace(/\n{3,}/g, "\n\n")
50
+ .trim();
51
+ if (cleaned.length === 0) {
52
+ await fs.rm(target, { force: true });
26
53
  return;
27
- const content = await fs.readFile(gitignorePath, "utf8");
28
- const lines = content.split(/\r?\n/);
29
- const patternsSet = new Set(REQUIRED_GITIGNORE_PATTERNS);
30
- const cleaned = lines.filter((line) => !patternsSet.has(line.trim()));
31
- const result = cleaned.join("\n").replace(/\n{3,}/g, "\n\n").trim();
32
- if (result.length === 0) {
33
- await fs.rm(gitignorePath, { force: true });
34
- }
35
- else {
36
- await writeFileSafe(gitignorePath, `${result}\n`);
37
54
  }
55
+ await writeFileSafe(target, `${cleaned}\n`);
38
56
  }
39
57
  export async function gitignoreHasRequiredPatterns(projectRoot) {
40
- const gitignorePath = path.join(projectRoot, ".gitignore");
41
- if (!(await exists(gitignorePath))) {
58
+ const target = gitignorePath(projectRoot);
59
+ if (!(await exists(target)))
42
60
  return false;
43
- }
44
- const content = await fs.readFile(gitignorePath, "utf8");
45
- return REQUIRED_GITIGNORE_PATTERNS.every((pattern) => content.includes(pattern));
61
+ const current = await fs.readFile(target, "utf8");
62
+ return REQUIRED_GITIGNORE_PATTERNS.every((pattern) => current.includes(pattern));
46
63
  }
@@ -0,0 +1,10 @@
1
+ import { type HarnessId } from "./types.js";
2
+ /**
3
+ * Detect which harnesses are already wired up in the project root.
4
+ * Used by `cclaw init` when the operator does not pass --harness=<id>.
5
+ *
6
+ * Markers are intentionally minimal — presence of any one marker per harness
7
+ * is enough to elect it. Returns harnesses in canonical (HARNESS_IDS) order.
8
+ */
9
+ export declare function detectHarnesses(projectRoot: string): Promise<HarnessId[]>;
10
+ export declare const NO_HARNESS_DETECTED_MESSAGE: string;
@@ -0,0 +1,29 @@
1
+ import path from "node:path";
2
+ import { exists } from "./fs-utils.js";
3
+ const HARNESS_MARKERS = [
4
+ { harness: "claude", markers: [".claude", "CLAUDE.md"] },
5
+ { harness: "cursor", markers: [".cursor"] },
6
+ { harness: "opencode", markers: [".opencode", "opencode.json", "opencode.jsonc"] },
7
+ { harness: "codex", markers: [".codex", ".agents/skills"] }
8
+ ];
9
+ /**
10
+ * Detect which harnesses are already wired up in the project root.
11
+ * Used by `cclaw init` when the operator does not pass --harness=<id>.
12
+ *
13
+ * Markers are intentionally minimal — presence of any one marker per harness
14
+ * is enough to elect it. Returns harnesses in canonical (HARNESS_IDS) order.
15
+ */
16
+ export async function detectHarnesses(projectRoot) {
17
+ const detected = [];
18
+ for (const { harness, markers } of HARNESS_MARKERS) {
19
+ for (const marker of markers) {
20
+ if (await exists(path.join(projectRoot, marker))) {
21
+ detected.push(harness);
22
+ break;
23
+ }
24
+ }
25
+ }
26
+ return detected;
27
+ }
28
+ export const NO_HARNESS_DETECTED_MESSAGE = "No harness detected in project root. Pass --harness=<id>[,<id>] (claude,cursor,opencode,codex) " +
29
+ "or create a marker first (e.g. `mkdir .cursor` for Cursor, `mkdir .claude` for Claude Code).";
@@ -0,0 +1,26 @@
1
+ import { type HarnessId } from "./types.js";
2
+ export interface PickerState {
3
+ selected: ReadonlySet<HarnessId>;
4
+ cursor: number;
5
+ message?: string;
6
+ }
7
+ export type PickerOutcome = "confirm" | "cancel" | "continue";
8
+ export interface PickerUpdate {
9
+ state: PickerState;
10
+ outcome: PickerOutcome;
11
+ }
12
+ export declare function createPickerState(preselect?: readonly HarnessId[], cursor?: number): PickerState;
13
+ export declare function applyKey(state: PickerState, key: string): PickerUpdate;
14
+ export declare function selectionToList(state: PickerState): HarnessId[];
15
+ export interface IsInteractiveStreams {
16
+ stdin?: NodeJS.ReadStream;
17
+ stdout?: NodeJS.WriteStream;
18
+ }
19
+ export declare function isInteractive(streams?: IsInteractiveStreams): boolean;
20
+ export interface PromptOptions {
21
+ detected: readonly HarnessId[];
22
+ preselect?: readonly HarnessId[];
23
+ stdin?: NodeJS.ReadStream;
24
+ stdout?: NodeJS.WriteStream;
25
+ }
26
+ export declare function runPicker(options: PromptOptions): Promise<HarnessId[]>;
@@ -0,0 +1,142 @@
1
+ import process from "node:process";
2
+ import { HARNESS_IDS } from "./types.js";
3
+ const HARNESS_LABELS = {
4
+ claude: "Claude Code",
5
+ cursor: "Cursor",
6
+ opencode: "OpenCode",
7
+ codex: "Codex"
8
+ };
9
+ const HARNESS_TARGETS = {
10
+ claude: ".claude/",
11
+ cursor: ".cursor/",
12
+ opencode: ".opencode/",
13
+ codex: ".codex/"
14
+ };
15
+ export function createPickerState(preselect = [], cursor = 0) {
16
+ const valid = preselect.filter((id) => HARNESS_IDS.includes(id));
17
+ return {
18
+ selected: new Set(valid.length > 0 ? valid : ["cursor"]),
19
+ cursor: Math.max(0, Math.min(cursor, HARNESS_IDS.length - 1))
20
+ };
21
+ }
22
+ export function applyKey(state, key) {
23
+ if (key === "\u0003" || key === "\u001b") {
24
+ return { state: { ...state, message: "Cancelled." }, outcome: "cancel" };
25
+ }
26
+ if (key === "\u001b[A" || key === "k" || key === "K") {
27
+ const next = (state.cursor - 1 + HARNESS_IDS.length) % HARNESS_IDS.length;
28
+ return { state: { ...state, cursor: next, message: undefined }, outcome: "continue" };
29
+ }
30
+ if (key === "\u001b[B" || key === "j" || key === "J") {
31
+ const next = (state.cursor + 1) % HARNESS_IDS.length;
32
+ return { state: { ...state, cursor: next, message: undefined }, outcome: "continue" };
33
+ }
34
+ if (key === " ") {
35
+ const current = HARNESS_IDS[state.cursor];
36
+ if (!current)
37
+ return { state, outcome: "continue" };
38
+ const selected = new Set(state.selected);
39
+ if (selected.has(current))
40
+ selected.delete(current);
41
+ else
42
+ selected.add(current);
43
+ return { state: { ...state, selected, message: undefined }, outcome: "continue" };
44
+ }
45
+ if (key === "a" || key === "A") {
46
+ return {
47
+ state: { ...state, selected: new Set(HARNESS_IDS), message: undefined },
48
+ outcome: "continue"
49
+ };
50
+ }
51
+ if (key === "n" || key === "N") {
52
+ return {
53
+ state: { ...state, selected: new Set(), message: undefined },
54
+ outcome: "continue"
55
+ };
56
+ }
57
+ if (key === "\r" || key === "\n") {
58
+ if (state.selected.size === 0) {
59
+ return {
60
+ state: { ...state, message: "Select at least one harness." },
61
+ outcome: "continue"
62
+ };
63
+ }
64
+ return { state, outcome: "confirm" };
65
+ }
66
+ return { state, outcome: "continue" };
67
+ }
68
+ export function selectionToList(state) {
69
+ return HARNESS_IDS.filter((id) => state.selected.has(id));
70
+ }
71
+ export function isInteractive(streams = {}) {
72
+ const stdin = streams.stdin ?? process.stdin;
73
+ const stdout = streams.stdout ?? process.stdout;
74
+ return Boolean(stdin.isTTY === true &&
75
+ stdout.isTTY === true &&
76
+ typeof stdin.setRawMode === "function");
77
+ }
78
+ function renderFrame(state, detected, stdout) {
79
+ stdout.write("\u001b[2J\u001b[H");
80
+ stdout.write("cclaw — choose harness(es) to install for\n\n");
81
+ HARNESS_IDS.forEach((harness, index) => {
82
+ const pointer = index === state.cursor ? ">" : " ";
83
+ const checked = state.selected.has(harness) ? "x" : " ";
84
+ const tag = detected.has(harness) ? " (detected)" : "";
85
+ stdout.write(` ${pointer} [${checked}] ${HARNESS_LABELS[harness].padEnd(12)} ${HARNESS_TARGETS[harness]}${tag}\n`);
86
+ });
87
+ stdout.write("\nUp/Down or k/j to move · Space to toggle · a all · n none · Enter to confirm · Esc/Ctrl-C to cancel\n");
88
+ if (state.message)
89
+ stdout.write(`\n${state.message}\n`);
90
+ }
91
+ export async function runPicker(options) {
92
+ const stdin = options.stdin ?? process.stdin;
93
+ const stdout = options.stdout ?? process.stdout;
94
+ const detectedSet = new Set(options.detected);
95
+ const initial = options.preselect && options.preselect.length > 0 ? options.preselect : options.detected;
96
+ let state = createPickerState(initial);
97
+ const wasRaw = Boolean(stdin.isRaw);
98
+ return new Promise((resolve, reject) => {
99
+ let settled = false;
100
+ const cleanup = () => {
101
+ stdin.off("data", onData);
102
+ try {
103
+ stdin.setRawMode?.(wasRaw);
104
+ }
105
+ catch {
106
+ // ignore — terminal might already be torn down
107
+ }
108
+ if (!wasRaw)
109
+ stdin.pause();
110
+ stdout.write("\n");
111
+ };
112
+ const onData = (chunk) => {
113
+ if (settled)
114
+ return;
115
+ const key = chunk.toString("utf8");
116
+ const update = applyKey(state, key);
117
+ state = update.state;
118
+ renderFrame(state, detectedSet, stdout);
119
+ if (update.outcome === "confirm") {
120
+ settled = true;
121
+ cleanup();
122
+ resolve(selectionToList(state));
123
+ return;
124
+ }
125
+ if (update.outcome === "cancel") {
126
+ settled = true;
127
+ cleanup();
128
+ reject(new Error("Harness selection cancelled."));
129
+ }
130
+ };
131
+ try {
132
+ stdin.setRawMode?.(true);
133
+ stdin.resume();
134
+ stdin.on("data", onData);
135
+ renderFrame(state, detectedSet, stdout);
136
+ }
137
+ catch (err) {
138
+ cleanup();
139
+ reject(err instanceof Error ? err : new Error(String(err)));
140
+ }
141
+ });
142
+ }
package/dist/install.d.ts CHANGED
@@ -1,19 +1,39 @@
1
- import type { FlowTrack, HarnessId } from "./types.js";
2
- export interface InitOptions {
3
- projectRoot: string;
4
- harnesses?: HarnessId[];
5
- track?: FlowTrack;
1
+ import { type NodeHookSpec } from "./content/node-hooks.js";
2
+ import { type HarnessId } from "./types.js";
3
+ export interface HarnessLayout {
4
+ id: HarnessId;
5
+ commandsDir: string;
6
+ agentsDir: string;
7
+ skillsDir: string;
8
+ hooksConfig: {
9
+ dir: string;
10
+ fileName: string;
11
+ } | null;
6
12
  }
7
13
  export interface SyncOptions {
14
+ cwd: string;
8
15
  harnesses?: HarnessId[];
9
- check?: boolean;
16
+ /**
17
+ * When true (default for `init` from a real TTY), `cclaw` shows the
18
+ * interactive harness picker if no `--harness` flag and no existing
19
+ * `.cclaw/config.yaml` are available. Set to false in CI/non-TTY paths
20
+ * (smoke scripts, programmatic callers) to fall back to auto-detect or
21
+ * a hard error if nothing is found.
22
+ */
23
+ interactive?: boolean;
24
+ }
25
+ export interface SyncResult {
26
+ installedHarnesses: HarnessId[];
27
+ configPath: string;
10
28
  }
11
- export declare function initCclaw(options: InitOptions): Promise<void>;
12
- export declare function syncCclaw(projectRoot: string, options?: SyncOptions): Promise<void>;
13
- /**
14
- * Refresh generated files in `.cclaw/` without touching user-authored
15
- * artifacts or state. Config remains harness-only with managed version
16
- * stamps.
17
- */
18
- export declare function upgradeCclaw(projectRoot: string): Promise<void>;
19
- export declare function uninstallCclaw(projectRoot: string): Promise<void>;
29
+ export declare function ensureRuntimeRoot(projectRoot: string): Promise<void>;
30
+ export declare function syncCclaw(options: SyncOptions): Promise<SyncResult>;
31
+ export declare function initCclaw(options: SyncOptions): Promise<SyncResult>;
32
+ export declare function uninstallCclaw(options: {
33
+ cwd: string;
34
+ }): Promise<void>;
35
+ export declare function upgradeCclaw(options: SyncOptions): Promise<SyncResult>;
36
+ export declare function planSeedForSlug(slug: string): string;
37
+ export declare const HARNESS_LAYOUT_TABLE: Record<"claude" | "cursor" | "opencode" | "codex", HarnessLayout>;
38
+ export type { NodeHookSpec };
39
+ export declare const COMMIT_HELPER_HOOK: NodeHookSpec;