specdojo 0.2.0 → 0.3.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 (170) hide show
  1. package/.github/agents/specdojo-orchestrator.md +165 -0
  2. package/CHANGELOG.md +280 -0
  3. package/README.md +143 -30
  4. package/dist/agent-response.js +20 -0
  5. package/dist/agent.js +4 -4
  6. package/dist/build-command.js +28 -8
  7. package/dist/dashboard.js +140 -9
  8. package/dist/devcontainer-command.js +43 -0
  9. package/dist/devcontainer-scaffold.js +165 -0
  10. package/dist/exec-agent-config.js +107 -9
  11. package/dist/exec-agent-git-state.js +18 -0
  12. package/dist/exec-agent-protected-config.js +46 -8
  13. package/dist/exec-evidence.js +254 -11
  14. package/dist/exec-format.js +13 -4
  15. package/dist/exec-handoff.js +336 -0
  16. package/dist/exec-parent-validation.js +317 -43
  17. package/dist/exec-pipeline-state.js +74 -9
  18. package/dist/exec-plans.js +115 -113
  19. package/dist/exec-protection-handoff.js +43 -2
  20. package/dist/exec-provider-scaffold.js +247 -15
  21. package/dist/exec-register-resume.js +65 -19
  22. package/dist/exec-register.js +9 -3
  23. package/dist/exec-repo-integration.js +811 -0
  24. package/dist/exec-repo-trace.js +182 -0
  25. package/dist/exec-reporter.js +613 -132
  26. package/dist/exec-results.js +81 -56
  27. package/dist/exec-run-lock.js +110 -107
  28. package/dist/exec-run.js +1585 -356
  29. package/dist/exec-shared.js +7 -0
  30. package/dist/exec-slot-lock.js +242 -0
  31. package/dist/exec-task-repos.js +415 -0
  32. package/dist/exec-trial.js +51 -25
  33. package/dist/exec-worktree-command.js +87 -43
  34. package/dist/exec-worktree-ops.js +502 -57
  35. package/dist/exec-worktree.js +114 -27
  36. package/dist/exec.js +13 -6
  37. package/dist/grade-result.js +128 -0
  38. package/dist/grade.js +809 -72
  39. package/dist/init-command.js +443 -0
  40. package/dist/job.js +160 -10
  41. package/dist/orchestrator.js +213 -0
  42. package/dist/package-paths.js +19 -1
  43. package/dist/register-event-merge.js +169 -0
  44. package/dist/register-item.js +7 -1
  45. package/dist/register.js +294 -86
  46. package/dist/review-grade.js +252 -0
  47. package/dist/review-plan.js +111 -1
  48. package/dist/review-types.js +40 -1
  49. package/dist/routine.js +72 -5
  50. package/dist/schedule-build.js +2 -2
  51. package/dist/schedule.js +17 -4
  52. package/dist/specdojo-config.js +466 -20
  53. package/dist/specdojo-gitignore.js +135 -0
  54. package/dist/specdojo.js +8 -1
  55. package/dist/viewpoint-document-kinds-check.js +128 -0
  56. package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
  57. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
  58. package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
  59. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
  60. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
  61. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
  62. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
  63. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
  64. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
  65. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
  66. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
  67. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
  68. package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
  69. package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
  70. package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
  71. package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
  72. package/docs/ja/specdojo/guides/exec-config-guide.md +91 -47
  73. package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
  74. package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
  75. package/docs/ja/specdojo/guides/kata-guide.md +4 -4
  76. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +25 -4
  77. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  78. package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
  79. package/docs/ja/specdojo/guides/quick-start-guide.md +261 -32
  80. package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
  81. package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
  82. package/docs/ja/specdojo/guides/remote-host-development-guide.md +184 -0
  83. package/docs/ja/specdojo/guides/review-guide.md +195 -158
  84. package/docs/ja/specdojo/guides/routine-operation-guide.md +74 -9
  85. package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
  86. package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
  87. package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
  88. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
  89. package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
  90. package/docs/ja/specdojo/guides/waza-guide.md +15 -2
  91. package/docs/ja/specdojo/index.md +2 -2
  92. package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
  93. package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
  94. package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
  95. package/docs/ja/specdojo/references/command-reference.md +336 -93
  96. package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
  97. package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
  98. package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
  99. package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
  100. package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
  101. package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
  102. package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
  103. package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
  104. package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
  105. package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
  106. package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
  107. package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
  108. package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
  109. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
  110. package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
  111. package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
  112. package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
  113. package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
  114. package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
  115. package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
  116. package/docs/ja/specdojo/samples/bps-sample.md +74 -21
  117. package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
  118. package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
  119. package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
  120. package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
  121. package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
  122. package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
  123. package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
  124. package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
  125. package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
  126. package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
  127. package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
  128. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
  129. package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
  130. package/docs/ja/specdojo/templates/bps-template.md +91 -0
  131. package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
  132. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
  133. package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
  134. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
  135. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
  136. package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
  137. package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
  138. package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
  139. package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
  140. package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
  141. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
  142. package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
  143. package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
  144. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
  145. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
  146. package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
  147. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
  148. package/package.json +16 -9
  149. package/templates/antigravity/README.md +60 -0
  150. package/templates/antigravity/agent-members-snippet.yaml +61 -0
  151. package/templates/antigravity/exec-defaults-snippet.yaml +39 -0
  152. package/templates/antigravity/orchestrator.md +157 -0
  153. package/templates/antigravity/settings.global.json +55 -0
  154. package/templates/claude/agents/claude-executor.md +14 -0
  155. package/templates/claude/agents/claude-reporter.md +16 -0
  156. package/templates/claude/agents/specdojo-orchestrator.md +164 -0
  157. package/templates/claude/settings.edit.json +27 -1
  158. package/templates/codex/README.md +5 -4
  159. package/templates/codex/agents/specdojo-orchestrator.toml +165 -0
  160. package/templates/codex/orchestrator.md +157 -0
  161. package/templates/copilot/README.md +7 -5
  162. package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
  163. package/templates/devcontainer/devcontainer.json +27 -0
  164. package/templates/devcontainer/emacs/init.el +88 -0
  165. package/templates/devcontainer/post-create.sh +62 -0
  166. package/templates/init-agent-members.yaml +200 -0
  167. package/templates/init-exec-defaults.yaml +72 -0
  168. package/templates/opencode/agents/specdojo-orchestrator.md +204 -0
  169. package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
  170. package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
@@ -152,6 +152,13 @@ const CONTROL_CHARS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
152
152
  export function stripTerminalControlSequences(text) {
153
153
  return text.replace(ANSI_ESCAPE, "").replace(CONTROL_CHARS, "");
154
154
  }
155
+ /** Redacts common credential forms before subprocess output is persisted as evidence. */
156
+ export function redactSensitiveText(value) {
157
+ return value
158
+ .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu, "Bearer [REDACTED]")
159
+ .replace(/\b(sk-(?:proj-)?[A-Za-z0-9_-]{8,}|gh[opsu]_[A-Za-z0-9_]{8,})\b/gu, "[REDACTED]")
160
+ .replace(/\b(api[_-]?key|access[_-]?token|auth(?:orization)?|password|passwd|secret)\b(\s*[:=]\s*)([^\s,;]+)/giu, "$1$2[REDACTED]");
161
+ }
155
162
  export function parseKeyValuePairs(pairs) {
156
163
  if (!pairs || pairs.length === 0)
157
164
  return undefined;
@@ -0,0 +1,242 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, } from "node:fs";
2
+ import { spawn } from "node:child_process";
3
+ import { join } from "node:path";
4
+ import { ensureDir, nowUtcIsoSeconds, randomHex, writeJson } from "./exec-shared.js";
5
+ // Cross-process locks and counting semaphores built on atomic `mkdir`. Every held lock is a
6
+ // directory with an `owner.json` and a detached heartbeat process that keeps its mtime fresh.
7
+ // A lock whose heartbeat stopped (the owner crashed) becomes stale after `staleMs` and may be
8
+ // taken over. A pool is a directory of numbered slot locks (`slot-1` … `slot-<limit>`).
9
+ export const LOCK_HEARTBEAT_MS = 5_000;
10
+ export const LOCK_STALE_MS = 30_000;
11
+ export const LOCK_POLL_MS = 200;
12
+ // The lock directory of the project whose exec-run lock this process holds. Gates that are
13
+ // reached through many call paths (parent validations) read it instead of having the directory
14
+ // threaded through every caller. One `exec run` process serves one project.
15
+ let activeExecLocksDir;
16
+ export function setActiveExecLocksDir(dir) {
17
+ activeExecLocksDir = dir;
18
+ }
19
+ export function getActiveExecLocksDir() {
20
+ return activeExecLocksDir;
21
+ }
22
+ function isRecord(value) {
23
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24
+ }
25
+ export function readLockOwner(lockDir) {
26
+ let parsed;
27
+ try {
28
+ parsed = JSON.parse(readFileSync(join(lockDir, "owner.json"), "utf8"));
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ if (!isRecord(parsed))
34
+ return null;
35
+ const { actor, pid, token, acquired_at_utc: acquiredAt, label, shareable } = parsed;
36
+ if (typeof actor !== "string" || typeof pid !== "number" || typeof token !== "string") {
37
+ return null;
38
+ }
39
+ return {
40
+ actor,
41
+ pid,
42
+ token,
43
+ acquired_at_utc: typeof acquiredAt === "string" ? acquiredAt : "",
44
+ ...(typeof label === "string" ? { label } : {}),
45
+ ...(typeof shareable === "boolean" ? { shareable } : {}),
46
+ };
47
+ }
48
+ export function formatLockOwner(lockDir) {
49
+ const owner = readLockOwner(lockDir);
50
+ return owner ? JSON.stringify(owner) : "(owner metadata unavailable)";
51
+ }
52
+ export function delay(ms) {
53
+ return new Promise((resolve) => setTimeout(resolve, ms));
54
+ }
55
+ const HEARTBEAT_SCRIPT = String.raw `
56
+ const fs = require("node:fs");
57
+ const path = require("node:path");
58
+ const [lockDir, token, intervalText, parentText] = process.argv.slice(1);
59
+ const ownerPath = path.join(lockDir, "owner.json");
60
+ const intervalMs = Number(intervalText);
61
+ const parentPid = Number(parentText);
62
+ function heartbeat() {
63
+ try {
64
+ process.kill(parentPid, 0);
65
+ const owner = JSON.parse(fs.readFileSync(ownerPath, "utf8"));
66
+ if (owner.token !== token) process.exit(0);
67
+ const now = new Date();
68
+ fs.utimesSync(lockDir, now, now);
69
+ } catch {
70
+ process.exit(0);
71
+ }
72
+ }
73
+ heartbeat();
74
+ setInterval(heartbeat, intervalMs);
75
+ `;
76
+ function startHeartbeat(lockDir, token, intervalMs) {
77
+ // A separate process keeps the heartbeat alive while the runner is inside spawnSync-based
78
+ // validate / refresh / git operations. It exits when the owner PID or token disappears.
79
+ const heartbeat = spawn(process.execPath, ["-e", HEARTBEAT_SCRIPT, lockDir, token, String(intervalMs), String(process.pid)], { detached: true, stdio: "ignore" });
80
+ heartbeat.unref();
81
+ return heartbeat;
82
+ }
83
+ function lockAgeMs(lockDir) {
84
+ try {
85
+ return Date.now() - statSync(lockDir).mtimeMs;
86
+ }
87
+ catch (error) {
88
+ if (error?.code === "ENOENT")
89
+ return null;
90
+ throw error;
91
+ }
92
+ }
93
+ /** Removes the lock when its heartbeat stopped. Returns true when the lock no longer exists. */
94
+ export function tryRemoveStaleLock(lockDir, staleMs = LOCK_STALE_MS) {
95
+ const ageMs = lockAgeMs(lockDir);
96
+ if (ageMs === null)
97
+ return true;
98
+ if (ageMs <= staleMs)
99
+ return false;
100
+ const staleDir = `${lockDir}.stale-${process.pid}-${randomHex(4)}`;
101
+ try {
102
+ // Rename first so a competing process can never make us delete its newly acquired lock.
103
+ renameSync(lockDir, staleDir);
104
+ }
105
+ catch (error) {
106
+ if (error?.code === "ENOENT")
107
+ return true;
108
+ throw error;
109
+ }
110
+ rmSync(staleDir, { recursive: true, force: true });
111
+ return true;
112
+ }
113
+ /** True when the lock exists and its heartbeat is fresh. */
114
+ export function isLiveLock(lockDir, staleMs = LOCK_STALE_MS) {
115
+ const ageMs = lockAgeMs(lockDir);
116
+ return ageMs !== null && ageMs <= staleMs;
117
+ }
118
+ /** Creates the lock directory atomically. Returns null when another holder already owns it. */
119
+ export function tryCreateLock(lockDir, owner, heartbeatMs = LOCK_HEARTBEAT_MS) {
120
+ try {
121
+ mkdirSync(lockDir);
122
+ }
123
+ catch (error) {
124
+ if (error?.code === "EEXIST")
125
+ return null;
126
+ throw error;
127
+ }
128
+ const token = `${process.pid}-${randomHex(8)}`;
129
+ writeJson(join(lockDir, "owner.json"), {
130
+ actor: owner.actor,
131
+ pid: process.pid,
132
+ token,
133
+ acquired_at_utc: nowUtcIsoSeconds(),
134
+ ...(owner.label !== undefined ? { label: owner.label } : {}),
135
+ ...(owner.shareable !== undefined ? { shareable: owner.shareable } : {}),
136
+ });
137
+ const now = new Date();
138
+ utimesSync(lockDir, now, now);
139
+ return { lockDir, token, heartbeat: startHeartbeat(lockDir, token, heartbeatMs) };
140
+ }
141
+ /** Tries once, taking over a stale lock if necessary. */
142
+ export function tryAcquireLock(lockDir, owner, timing = {}) {
143
+ const heartbeatMs = timing.heartbeatMs ?? LOCK_HEARTBEAT_MS;
144
+ const handle = tryCreateLock(lockDir, owner, heartbeatMs);
145
+ if (handle)
146
+ return handle;
147
+ if (!tryRemoveStaleLock(lockDir, timing.staleMs ?? LOCK_STALE_MS))
148
+ return null;
149
+ return tryCreateLock(lockDir, owner, heartbeatMs);
150
+ }
151
+ export function releaseLock(handle) {
152
+ handle.heartbeat.kill();
153
+ if (!existsSync(handle.lockDir))
154
+ return;
155
+ if (readLockOwner(handle.lockDir)?.token !== handle.token)
156
+ return;
157
+ rmSync(handle.lockDir, { recursive: true, force: true });
158
+ }
159
+ export function poolSlotPath(poolDir, index) {
160
+ return join(poolDir, `slot-${index}`);
161
+ }
162
+ /** Takes the first free slot among `slot-1` … `slot-<limit>`. Returns null when all are held. */
163
+ export function tryAcquirePoolSlot(poolDir, limit, owner, timing = {}) {
164
+ ensureDir(poolDir);
165
+ for (let index = 1; index <= limit; index++) {
166
+ const handle = tryAcquireLock(poolSlotPath(poolDir, index), owner, timing);
167
+ if (handle)
168
+ return handle;
169
+ }
170
+ return null;
171
+ }
172
+ /** Waits until one of the pool slots is free and takes it. */
173
+ export async function acquirePoolSlot(poolDir, limit, owner, options = {}) {
174
+ const pollMs = options.pollMs ?? LOCK_POLL_MS;
175
+ let waitingAnnounced = false;
176
+ while (true) {
177
+ const handle = tryAcquirePoolSlot(poolDir, limit, owner, options);
178
+ if (handle)
179
+ return handle;
180
+ if (!waitingAnnounced) {
181
+ options.onWait?.();
182
+ waitingAnnounced = true;
183
+ }
184
+ await delay(pollMs);
185
+ }
186
+ }
187
+ /** Lists the slot locks that currently exist in the pool, including stale ones. */
188
+ export function listPoolSlots(poolDir, staleMs = LOCK_STALE_MS) {
189
+ if (!existsSync(poolDir))
190
+ return [];
191
+ const names = readdirSync(poolDir)
192
+ .filter((name) => /^slot-\d+$/.test(name))
193
+ .sort((a, b) => Number(a.slice(5)) - Number(b.slice(5)));
194
+ const slots = [];
195
+ for (const name of names) {
196
+ const lockDir = join(poolDir, name);
197
+ const ageMs = lockAgeMs(lockDir);
198
+ if (ageMs === null)
199
+ continue;
200
+ slots.push({ name, lockDir, owner: readLockOwner(lockDir), ageMs, stale: ageMs > staleMs });
201
+ }
202
+ return slots;
203
+ }
204
+ /** Owners of the pool slots whose heartbeat is fresh. */
205
+ export function livePoolHolders(poolDir, staleMs = LOCK_STALE_MS) {
206
+ return listPoolSlots(poolDir, staleMs).filter((slot) => !slot.stale);
207
+ }
208
+ /**
209
+ * A mutex shared by every process that uses the same directory. Calls from the same process are
210
+ * queued in arrival order first, so only one of them polls the directory at a time.
211
+ */
212
+ export class CrossProcessMutex {
213
+ poolDir;
214
+ owner;
215
+ options;
216
+ tail = Promise.resolve();
217
+ constructor(poolDir, owner, options = {}) {
218
+ this.poolDir = poolDir;
219
+ this.owner = owner;
220
+ this.options = options;
221
+ }
222
+ async runExclusive(fn) {
223
+ const previous = this.tail;
224
+ let releaseLocal;
225
+ this.tail = new Promise((resolveTail) => {
226
+ releaseLocal = resolveTail;
227
+ });
228
+ await previous;
229
+ try {
230
+ const handle = await acquirePoolSlot(this.poolDir, 1, this.owner, this.options);
231
+ try {
232
+ return await fn();
233
+ }
234
+ finally {
235
+ releaseLock(handle);
236
+ }
237
+ }
238
+ finally {
239
+ releaseLocal();
240
+ }
241
+ }
242
+ }
@@ -0,0 +1,415 @@
1
+ import { existsSync, readdirSync, rmdirSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ import { getProjectRepos, getProjectSchedulePath, loadConfig, PROJECT_REPO_WORKTREE_DIRNAME, resolveRepoRoot, specdojoRootDir, } from "./specdojo-config.js";
4
+ import { ensureExecWorktree, execBranchExists, execWorktreePath, findExecWorktree, generateWorktreeArtifacts, gitOutput, gitResult, installWorktreeDependencies, listRegisteredWorktrees, worktreeNameFromTaskId, } from "./exec-worktree.js";
5
+ // PJR-98G4: 1 つのタスクがプロジェクトリポジトリと宣言済みのプロダクトリポジトリ(`repos`)を
6
+ // 変更する場合の worktree を扱う。`repos` を持たない project では、ここの関数はどれも空の結果を
7
+ // 返し、既存の 1 リポジトリ・`<worktree_base>/<task-id>/` 直下の配置を変えない。
8
+ export { PROJECT_REPO_WORKTREE_DIRNAME };
9
+ export function resolveProductRepos(rootDir, project) {
10
+ return getProjectRepos(project).map((repo) => ({
11
+ name: repo.name,
12
+ repoRoot: resolveRepoRoot(rootDir, repo),
13
+ ...(repo.integration_branch?.trim()
14
+ ? { integrationBranch: repo.integration_branch.trim() }
15
+ : {}),
16
+ install: repo.setup?.install ?? true,
17
+ build: repo.setup?.build ?? true,
18
+ }));
19
+ }
20
+ /** Product repositories of the project whose schedule path is `schedulePath` ([] when none). */
21
+ export function configuredProductRepos(schedulePath) {
22
+ const { config } = loadConfig();
23
+ if (!config)
24
+ return [];
25
+ const rootDir = specdojoRootDir();
26
+ for (const project of Object.values(config.projects)) {
27
+ if (resolve(rootDir, getProjectSchedulePath(project)) === resolve(schedulePath)) {
28
+ return resolveProductRepos(rootDir, project);
29
+ }
30
+ }
31
+ return [];
32
+ }
33
+ /** Product repositories of the project `projectId` ([] when none or unknown). */
34
+ export function configuredProductReposForProject(projectId) {
35
+ if (!projectId)
36
+ return [];
37
+ const { config } = loadConfig();
38
+ const project = config?.projects[projectId];
39
+ return project ? resolveProductRepos(specdojoRootDir(), project) : [];
40
+ }
41
+ /** Directory under `<worktree_base>/<task-name>/` used by the project worktree. */
42
+ export function projectRepoDirName(products) {
43
+ return products.length > 0 ? PROJECT_REPO_WORKTREE_DIRNAME : undefined;
44
+ }
45
+ /** Planned project worktree path (`<base>/<task>/` or `<base>/<task>/project/` with `repos`). */
46
+ export function plannedProjectWorktreePath(worktreeBase, taskId, products) {
47
+ return execWorktreePath(worktreeBase, taskId, projectRepoDirName(products));
48
+ }
49
+ function currentBranchOrNull(repoRoot) {
50
+ const result = gitResult(repoRoot, ["branch", "--show-current"]);
51
+ const branch = typeof result.stdout === "string" ? result.stdout.trim() : "";
52
+ return result.status === 0 && branch ? branch : null;
53
+ }
54
+ /** Branch the product exec branch starts from and is integrated into. */
55
+ export function productIntegrationTarget(product) {
56
+ return product.integrationBranch ?? currentBranchOrNull(product.repoRoot) ?? "HEAD";
57
+ }
58
+ const skip = () => undefined;
59
+ /**
60
+ * Create (or reuse) `<worktree_base>/<task-name>/<repo>/` for every product repository. A new
61
+ * exec branch starts from the declared `integration_branch` (or the repository's current branch)
62
+ * because the checkpoint commit belongs to the project repository only.
63
+ */
64
+ export function ensureProductWorktrees(opts) {
65
+ return opts.products.map((product) => {
66
+ if (!existsSync(product.repoRoot)) {
67
+ throw new Error(`Product repository "${product.name}" does not exist: ${product.repoRoot} (check repos[].path)`);
68
+ }
69
+ const generate = product.build ? (opts.generateArtifacts ?? generateWorktreeArtifacts) : skip;
70
+ const existing = findExecWorktree(product.repoRoot, opts.taskId);
71
+ if (existing) {
72
+ // Same as the project worktree on reuse: dependencies stay, generated files are rebuilt.
73
+ generate(existing.path);
74
+ return toProductWorktree(product, existing);
75
+ }
76
+ const worktree = ensureExecWorktree({
77
+ repoRoot: product.repoRoot,
78
+ worktreeBase: opts.worktreeBase,
79
+ taskId: opts.taskId,
80
+ repoDirName: product.name,
81
+ startPoint: productIntegrationTarget(product),
82
+ installDependencies: product.install
83
+ ? (opts.installDependencies ?? installWorktreeDependencies)
84
+ : skip,
85
+ generateArtifacts: generate,
86
+ });
87
+ return toProductWorktree(product, worktree);
88
+ });
89
+ }
90
+ function toProductWorktree(product, worktree) {
91
+ return {
92
+ name: product.name,
93
+ repoRoot: product.repoRoot,
94
+ path: worktree.path,
95
+ branch: worktree.branch,
96
+ created: worktree.created,
97
+ ...(product.integrationBranch ? { integrationBranch: product.integrationBranch } : {}),
98
+ };
99
+ }
100
+ /** Registered product worktrees of a task (repositories without one are omitted). */
101
+ export function findProductWorktrees(products, taskId) {
102
+ return products.flatMap((product) => {
103
+ if (!existsSync(product.repoRoot))
104
+ return [];
105
+ const found = findExecWorktree(product.repoRoot, taskId);
106
+ return found ? [toProductWorktree(product, found)] : [];
107
+ });
108
+ }
109
+ /** Attach the task's product worktrees to the project worktree (no-op without `repos`). */
110
+ export function withProductWorktrees(worktree, products, taskId) {
111
+ if (products.length === 0)
112
+ return worktree;
113
+ return { ...worktree, repos: findProductWorktrees(products, taskId) };
114
+ }
115
+ /** Repositories of a task that are missing a product worktree. */
116
+ export function missingProductWorktrees(products, worktree) {
117
+ const present = new Set((worktree.repos ?? []).map((repo) => repo.name));
118
+ return products.filter((product) => !present.has(product.name)).map((product) => product.name);
119
+ }
120
+ function statusPaths(worktreePath) {
121
+ return gitOutput(worktreePath, ["status", "--porcelain=v1", "-z", "--untracked-files=all"])
122
+ .split("\0")
123
+ .filter((record) => record.length >= 4)
124
+ .map((record) => record.slice(3));
125
+ }
126
+ function commitsAhead(product) {
127
+ const target = productIntegrationTarget(product);
128
+ const result = gitResult(product.repoRoot, [
129
+ "rev-list",
130
+ "--count",
131
+ `${target}..${product.branch}`,
132
+ ]);
133
+ if (result.status !== 0 || typeof result.stdout !== "string")
134
+ return 0;
135
+ return Number.parseInt(result.stdout.trim(), 10) || 0;
136
+ }
137
+ function isMergedIntoTarget(product) {
138
+ const target = productIntegrationTarget(product);
139
+ return (gitResult(product.repoRoot, ["merge-base", "--is-ancestor", product.branch, target]).status ===
140
+ 0);
141
+ }
142
+ /**
143
+ * Describe product worktrees that hold work not yet in their integration target: uncommitted
144
+ * changes or exec-branch commits. Only the exec run integrate stage (exec-repo-integration)
145
+ * commits and merges product repositories; other paths (manual `exec worktree commit`) must not
146
+ * integrate the project side and remove worktrees that still hold product work.
147
+ */
148
+ export function pendingProductWorktreeChanges(worktree) {
149
+ const pending = [];
150
+ for (const product of worktree.repos ?? []) {
151
+ if (!existsSync(product.path))
152
+ continue;
153
+ const dirty = statusPaths(product.path);
154
+ const ahead = commitsAhead(product);
155
+ if (dirty.length === 0 && ahead === 0)
156
+ continue;
157
+ const parts = [
158
+ ...(dirty.length > 0
159
+ ? [`uncommitted ${dirty.map((path) => `${product.name}:${path}`).join(", ")}`]
160
+ : []),
161
+ ...(ahead > 0 ? [`${ahead} commit(s) on ${product.branch}`] : []),
162
+ ];
163
+ pending.push(`${product.name} (${parts.join("; ")})`);
164
+ }
165
+ return pending;
166
+ }
167
+ export function assertNoPendingProductChanges(worktree) {
168
+ const pending = pendingProductWorktreeChanges(worktree);
169
+ if (pending.length === 0)
170
+ return;
171
+ throw new Error(`product repository changes are not integrated: ${pending.join(" / ")}; ` +
172
+ `product repositories are integrated only by exec run, so all task worktrees are kept`);
173
+ }
174
+ /**
175
+ * Check that every product worktree can be removed before any worktree of the task is removed,
176
+ * so a partially removed task (some repositories gone, others kept) never occurs.
177
+ */
178
+ export function productWorktreeRemovalBlockers(worktree) {
179
+ const blockers = [];
180
+ for (const product of worktree.repos ?? []) {
181
+ if (!existsSync(product.path))
182
+ continue;
183
+ const dirty = statusPaths(product.path);
184
+ if (dirty.length > 0) {
185
+ blockers.push(`${product.name} has uncommitted changes: ${dirty.map((path) => `${product.name}:${path}`).join(", ")}`);
186
+ }
187
+ if (!isMergedIntoTarget(product)) {
188
+ blockers.push(`${product.name}: exec branch ${product.branch} is not merged into ${productIntegrationTarget(product)}`);
189
+ }
190
+ }
191
+ return blockers;
192
+ }
193
+ /** Remove product worktrees (and optionally their branches). Callers check blockers first. */
194
+ export function removeProductWorktrees(params) {
195
+ for (const product of params.worktree.repos ?? []) {
196
+ if (params.dryRun) {
197
+ process.stdout.write(`[dry-run] git -C ${product.repoRoot} worktree remove --force ${product.path}\n`);
198
+ if (params.deleteBranch) {
199
+ process.stdout.write(`[dry-run] git -C ${product.repoRoot} branch -d ${product.branch}\n`);
200
+ }
201
+ continue;
202
+ }
203
+ if (existsSync(product.path)) {
204
+ // Guards (clean + merged) already ran; leftovers are ignored/regenerable files.
205
+ gitOutput(product.repoRoot, ["worktree", "remove", "--force", product.path]);
206
+ }
207
+ else {
208
+ gitResult(product.repoRoot, ["worktree", "prune"]);
209
+ }
210
+ if (params.deleteBranch) {
211
+ // `-d` compares with the main checkout's HEAD, which may differ from integration_branch.
212
+ // Use `-D` only for a branch verified to be merged into its integration target; otherwise
213
+ // keep Git's safe `-d` so unintegrated product work is never deleted.
214
+ const flag = isMergedIntoTarget(product) ? "-D" : "-d";
215
+ gitOutput(product.repoRoot, ["branch", flag, product.branch]);
216
+ }
217
+ }
218
+ }
219
+ /** Remove `<worktree_base>/<task-name>/` once every repository worktree under it is gone. */
220
+ export function removeEmptyTaskDirectory(worktree) {
221
+ if (!worktree.repos)
222
+ return;
223
+ const taskDir = dirname(worktree.path);
224
+ if (!existsSync(taskDir))
225
+ return;
226
+ try {
227
+ if (readdirSync(taskDir).length === 0)
228
+ rmdirSync(taskDir);
229
+ }
230
+ catch {
231
+ // A leftover directory is harmless; the next prepare reuses or recreates it.
232
+ }
233
+ }
234
+ /**
235
+ * Discard abandoned product worktrees and exec branches of a task (fresh claim after a blocked
236
+ * or cancelled lifecycle). Mirrors discardStaleExecWorktree for each product repository.
237
+ */
238
+ export function discardStaleProductWorktrees(products, taskId) {
239
+ const discarded = [];
240
+ for (const product of products) {
241
+ if (!existsSync(product.repoRoot))
242
+ continue;
243
+ const existing = findExecWorktree(product.repoRoot, taskId);
244
+ if (!existing && !execBranchExists(product.repoRoot, taskId))
245
+ continue;
246
+ if (existing) {
247
+ if (resolve(product.repoRoot) === resolve(existing.path)) {
248
+ throw new Error(`Refusing to discard the main checkout of ${product.name} as stale residue: ${existing.branch}`);
249
+ }
250
+ gitOutput(product.repoRoot, ["worktree", "remove", "--force", existing.path]);
251
+ }
252
+ const branch = `exec/${worktreeNameFromTaskId(taskId)}`;
253
+ if (execBranchExists(product.repoRoot, taskId)) {
254
+ gitOutput(product.repoRoot, ["branch", "-D", branch]);
255
+ }
256
+ discarded.push(`${product.name}:${branch}`);
257
+ }
258
+ return discarded;
259
+ }
260
+ /** Exec branches of the project in each product repository that no worktree checks out. */
261
+ export function listOrphanedProductExecBranches(products, projectId) {
262
+ const prefix = `exec/${worktreeNameFromTaskId(projectId)}-`;
263
+ return products.flatMap((product) => {
264
+ if (!existsSync(product.repoRoot))
265
+ return [];
266
+ const checkedOut = new Set(listRegisteredWorktrees(product.repoRoot)
267
+ .map((worktree) => worktree.branch)
268
+ .filter((branch) => !!branch));
269
+ const target = productIntegrationTarget(product);
270
+ return gitOutput(product.repoRoot, [
271
+ "for-each-ref",
272
+ "--format=%(refname:short)",
273
+ "refs/heads/exec/",
274
+ ])
275
+ .split(/\r?\n/)
276
+ .map((branch) => branch.trim())
277
+ .filter((branch) => branch.startsWith(prefix) && !checkedOut.has(branch))
278
+ .sort()
279
+ .map((branch) => ({
280
+ repo: product.name,
281
+ branch,
282
+ mergedIntoTarget: gitResult(product.repoRoot, ["merge-base", "--is-ancestor", branch, target]).status === 0,
283
+ }));
284
+ });
285
+ }
286
+ /** Delete merged orphan exec branches of product repositories with Git's safe `-d`. */
287
+ export function pruneOrphanedProductExecBranches(params) {
288
+ const orphaned = listOrphanedProductExecBranches(params.products, params.projectId);
289
+ for (const item of orphaned) {
290
+ if (!item.mergedIntoTarget || params.dryRun)
291
+ continue;
292
+ const product = params.products.find((candidate) => candidate.name === item.repo);
293
+ if (!product)
294
+ continue;
295
+ try {
296
+ gitOutput(product.repoRoot, ["branch", "-d", item.branch]);
297
+ }
298
+ catch (error) {
299
+ throw new Error(`Failed to delete merged orphaned exec branch ${item.repo}:${item.branch}; ` +
300
+ `cause=${error instanceof Error ? error.message : String(error)}`);
301
+ }
302
+ }
303
+ return orphaned;
304
+ }
305
+ // ── Agent environment and provider arguments ───────────────────────────────
306
+ export const REPO_NAMES_ENV = "SPECDOJO_REPO_NAMES";
307
+ /** `SPECDOJO_REPO_<NAME>` with `-` mapped to `_` (names are `[a-z0-9-]`, so this is injective). */
308
+ export function repoEnvironmentVariableName(name) {
309
+ return `SPECDOJO_REPO_${name.toUpperCase().replaceAll("-", "_")}`;
310
+ }
311
+ /**
312
+ * Environment that tells the agent where each repository of the task is checked out.
313
+ * `SPECDOJO_REPO_PROJECT` is the project worktree (the agent's cwd), `SPECDOJO_REPO_<NAME>`
314
+ * each product worktree, and `SPECDOJO_REPO_NAMES` the comma-separated product names in
315
+ * declaration order. Empty for tasks without product worktrees.
316
+ */
317
+ export function productRepoEnvironment(projectWorktreePath, products) {
318
+ if (!products || products.length === 0)
319
+ return {};
320
+ const env = {
321
+ [repoEnvironmentVariableName(PROJECT_REPO_WORKTREE_DIRNAME)]: resolve(projectWorktreePath),
322
+ [REPO_NAMES_ENV]: products.map((product) => product.name).join(","),
323
+ };
324
+ for (const product of products) {
325
+ env[repoEnvironmentVariableName(product.name)] = resolve(product.path);
326
+ }
327
+ return env;
328
+ }
329
+ /**
330
+ * Drop `SPECDOJO_REPO_*` inherited from the parent process (e.g. a runner started inside another
331
+ * task's agent), so only the current task's repositories reach the agent and its sandbox flags.
332
+ */
333
+ export function withoutInheritedRepoEnvironment(env) {
334
+ return Object.fromEntries(Object.entries(env).filter(([key]) => !key.startsWith("SPECDOJO_REPO_")));
335
+ }
336
+ /** Product worktrees announced by productRepoEnvironment, in declaration order. */
337
+ export function productRootsFromEnvironment(env) {
338
+ const names = (env[REPO_NAMES_ENV] ?? "")
339
+ .split(",")
340
+ .map((name) => name.trim())
341
+ .filter(Boolean);
342
+ return names.flatMap((name) => {
343
+ const path = env[repoEnvironmentVariableName(name)];
344
+ return path ? [{ name, path }] : [];
345
+ });
346
+ }
347
+ /**
348
+ * Prompt section that tells the agent where the product worktrees are and how to name their
349
+ * files. Empty without product worktrees, so single-repository prompts are unchanged.
350
+ */
351
+ export function productRepoPromptSection(products) {
352
+ if (!products || products.length === 0)
353
+ return "";
354
+ const rows = products.map((product) => `- \`${product.name}\`: ${resolve(product.path)} (environment variable ` +
355
+ `\`${repoEnvironmentVariableName(product.name)}\`)`);
356
+ return [
357
+ "",
358
+ "# Task repositories",
359
+ "",
360
+ "This task spans several repositories. The working directory is the project repository " +
361
+ "worktree. The product repositories are checked out as separate worktrees of the same task:",
362
+ "",
363
+ ...rows,
364
+ "",
365
+ "Edit product files under those absolute paths (or via the environment variables); paths " +
366
+ "relative to the working directory refer to the project repository only. When reporting " +
367
+ "a product file (for example in target_coverage), write it as `<repo>:<path>` relative to " +
368
+ "that repository root, e.g. `" +
369
+ `${products[0].name}:src/index.ts` +
370
+ "`. Do not commit or change Git configuration in any repository.",
371
+ "",
372
+ ].join("\n");
373
+ }
374
+ /** Append productRepoPromptSection to a prompt (unchanged without product worktrees). */
375
+ export function withProductRepoPrompt(prompt, products) {
376
+ const section = productRepoPromptSection(products);
377
+ return section ? `${prompt.trimEnd()}\n${section}` : prompt;
378
+ }
379
+ function shellQuote(value) {
380
+ return `'${value.replaceAll("'", `'\\''`)}'`;
381
+ }
382
+ /**
383
+ * Provider arguments that add the product worktrees as extra roots with write access. The agent
384
+ * keeps the project worktree as cwd. Returns [] for providers without a launch flag. OpenCode's
385
+ * orchestrator entry injects `permission.external_directory` through its runtime config instead.
386
+ */
387
+ export function agentExtraRootArguments(provider, dirs) {
388
+ if (dirs.length === 0)
389
+ return [];
390
+ const absolute = dirs.map((dir) => resolve(dir));
391
+ switch (provider) {
392
+ case "claude":
393
+ // `--add-dir` makes the directory a working directory; `Edit(//<abs>/**)` is required because
394
+ // the mode settings only allow edits under project-relative paths.
395
+ return [
396
+ "--add-dir",
397
+ ...absolute,
398
+ "--allowedTools",
399
+ ...absolute.map((dir) => `Edit(/${dir}/**)`),
400
+ ];
401
+ case "codex":
402
+ case "antigravity":
403
+ case "copilot":
404
+ return absolute.flatMap((dir) => ["--add-dir", dir]);
405
+ default:
406
+ return [];
407
+ }
408
+ }
409
+ /** Append the extra-root arguments to a resolved shell command (unchanged when there are none). */
410
+ export function withAgentExtraRoots(command, provider, dirs) {
411
+ const args = agentExtraRootArguments(provider, dirs);
412
+ if (args.length === 0)
413
+ return command;
414
+ return `${command} ${args.map(shellQuote).join(" ")}`;
415
+ }