specdojo 0.4.0 → 0.4.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 (77) hide show
  1. package/.github/agents/specdojo-orchestrator.md +61 -2
  2. package/CHANGELOG.md +43 -0
  3. package/README.md +8 -7
  4. package/dist/commands/init.js +72 -15
  5. package/dist/commands/night-orchestrator.js +287 -0
  6. package/dist/commands/orchestrator.js +10 -3
  7. package/dist/devcontainer/command.js +3 -1
  8. package/dist/devcontainer/scaffold.js +166 -5
  9. package/dist/exec/agent-config.js +60 -2
  10. package/dist/exec/parent-validation.js +14 -0
  11. package/dist/exec/pipeline-state.js +13 -0
  12. package/dist/exec/register.js +23 -1
  13. package/dist/exec/repo-integration.js +1 -1
  14. package/dist/exec/reporter.js +113 -13
  15. package/dist/exec/results.js +36 -14
  16. package/dist/exec/run/agent-pipeline.js +3 -0
  17. package/dist/exec/run/agent.js +40 -5
  18. package/dist/exec/run/job.js +2 -2
  19. package/dist/exec/run/lifecycle-commands.js +2 -2
  20. package/dist/exec/run/register-command.js +23 -4
  21. package/dist/exec/run/register-core.js +17 -0
  22. package/dist/exec/run/register-mode.js +39 -16
  23. package/dist/exec/run/register-post-review.js +420 -0
  24. package/dist/exec/run/register-resume.js +27 -11
  25. package/dist/exec/run/register-worktree.js +66 -2
  26. package/dist/exec/run/run.js +1 -1
  27. package/dist/exec/run/shared.js +22 -24
  28. package/dist/exec/task-repos.js +102 -15
  29. package/dist/register/core.js +14 -2
  30. package/dist/register/create-commands.js +62 -6
  31. package/dist/register/event-merge.js +13 -1
  32. package/dist/register/events.js +4 -0
  33. package/dist/register/item.js +9 -0
  34. package/dist/register/migration.js +1 -0
  35. package/dist/register/register.js +2 -2
  36. package/dist/shared/git.js +45 -15
  37. package/dist/shared/provider-scaffold.js +3 -2
  38. package/dist/shared/specdojo-config.js +69 -16
  39. package/dist/shared/text.js +4 -1
  40. package/dist/shared/workspace-scaffold.js +69 -0
  41. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +2 -1
  42. package/docs/ja/specdojo/exec-templates/xep-register-template.md +2 -0
  43. package/docs/ja/specdojo/exec-templates/xrp-register-post-run-template.md +46 -0
  44. package/docs/ja/specdojo/guides/branch-workflow-guide.md +34 -1
  45. package/docs/ja/specdojo/guides/docs-structure-guide.md +2 -0
  46. package/docs/ja/specdojo/guides/exec-config-guide.md +79 -11
  47. package/docs/ja/specdojo/guides/exec-operation-guide.md +39 -1
  48. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +9 -3
  49. package/docs/ja/specdojo/guides/quick-start-guide.md +9 -6
  50. package/docs/ja/specdojo/guides/register-operation-guide.md +42 -0
  51. package/docs/ja/specdojo/guides/remote-host-development-guide.md +52 -6
  52. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +1 -1
  53. package/docs/ja/specdojo/guides/waza-guide.md +1 -1
  54. package/docs/ja/specdojo/references/command-reference.md +101 -56
  55. package/docs/ja/specdojo/references/specdojo-config-reference.md +33 -7
  56. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +5 -2
  57. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +92 -18
  58. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +6 -1
  59. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +12 -0
  60. package/docs/specdojo/schemas/v1/register-events.schema.yaml +2 -0
  61. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +21 -0
  62. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +35 -0
  63. package/package.json +17 -17
  64. package/templates/antigravity/README.md +1 -1
  65. package/templates/antigravity/orchestrator.md +61 -2
  66. package/templates/claude/agents/specdojo-orchestrator.md +61 -2
  67. package/templates/codex/README.md +17 -0
  68. package/templates/codex/agents/specdojo-orchestrator.toml +61 -2
  69. package/templates/codex/orchestrator.md +61 -2
  70. package/templates/devcontainer/devcontainer.json +3 -0
  71. package/templates/devcontainer/post-create.sh +15 -7
  72. package/templates/devcontainer/remote-host/specdojo-tmux.sh.sample +38 -5
  73. package/templates/devcontainer/remote-host/ssh-config.sample +3 -0
  74. package/templates/devcontainer/vim/vimrc +37 -0
  75. package/templates/init-agent-members.yaml +3 -3
  76. package/templates/init-exec-defaults.yaml +20 -1
  77. package/templates/opencode/agents/specdojo-orchestrator.md +61 -2
@@ -0,0 +1,287 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdirSync, writeFileSync } from "node:fs";
3
+ import { join, relative } from "node:path";
4
+ import { resolveProjectPaths } from "../exec/project.js";
5
+ import { loadRegisterItems, resolveRegisterPaths } from "../register/register.js";
6
+ import { specdojoRootDir } from "../shared/specdojo-config.js";
7
+ export function selectApprovedNightItems(items, limit) {
8
+ return items
9
+ .filter((item) => item.autopilot === "approved" &&
10
+ (item.type === "todo" || item.type === "issue") &&
11
+ item.status === "open")
12
+ .sort((a, b) => (a.id === b.id ? 0 : a.id < b.id ? -1 : 1))
13
+ .slice(0, limit);
14
+ }
15
+ export function parseRegisterRunSummary(output) {
16
+ const results = [];
17
+ for (const line of output.split(/\r?\n/u)) {
18
+ const match = line.match(/^\s+(PJR-[0-9A-Z]{4})\s+(success|failure|skipped)\s+transition=(done|waiting|review|none)\s+commit=.*?(?:\s{2}reason=(.*))?$/u);
19
+ if (!match)
20
+ continue;
21
+ results.push({
22
+ id: match[1],
23
+ outcome: match[2],
24
+ transition: match[3],
25
+ ...(match[4]?.trim() ? { reason: match[4].trim() } : {}),
26
+ });
27
+ }
28
+ return results;
29
+ }
30
+ export function consecutiveFailureCount(previous, outcomes) {
31
+ let count = previous;
32
+ for (const outcome of outcomes) {
33
+ if (outcome.outcome === "failure")
34
+ count += 1;
35
+ else if (outcome.outcome === "success")
36
+ count = 0;
37
+ }
38
+ return count;
39
+ }
40
+ export function requiresDerivedApproval(outcome) {
41
+ if (outcome.outcome !== "failure")
42
+ return false;
43
+ return /protected|agent-config-write|git-state|\b(?:tag|push|publish)\b|CHANGELOG|scope|範囲|承認/iu.test(outcome.reason ?? "");
44
+ }
45
+ function positiveInteger(value, option) {
46
+ if (!/^[1-9]\d*$/u.test(value))
47
+ throw new Error(`${option} must be a positive integer: ${value}`);
48
+ const parsed = Number(value);
49
+ if (!Number.isSafeInteger(parsed))
50
+ throw new Error(`${option} is too large: ${value}`);
51
+ return parsed;
52
+ }
53
+ function safeCell(value) {
54
+ return (value?.trim() || "-").replaceAll("|", "\\|").replace(/\r?\n/gu, " ");
55
+ }
56
+ export function renderNightReport(options) {
57
+ const stamp = options.startedAt
58
+ .replace(/[-:.]/gu, "")
59
+ .replace(/\.\d+Z$/u, "Z")
60
+ .toLowerCase();
61
+ const byId = new Map(options.outcomes.map((outcome) => [outcome.id, outcome]));
62
+ const rows = options.selected.map((item) => {
63
+ const outcome = byId.get(item.id);
64
+ return `| ${item.id} | ${outcome?.outcome ?? "skipped"} | ${outcome?.transition ?? "none"} | ${safeCell(outcome?.reason)} |`;
65
+ });
66
+ const closed = options.outcomes
67
+ .filter((item) => item.transition === "done")
68
+ .map((item) => item.id);
69
+ const waiting = options.outcomes
70
+ .filter((item) => item.transition === "waiting")
71
+ .map((item) => item.id);
72
+ const approvals = [...options.approvalIssues].map(([source, created]) => `${created}(${source} 由来)`);
73
+ const list = (values) => (values.length > 0 ? values.join("、") : "なし");
74
+ return `---
75
+ specdojo:
76
+ id: ${options.projectId}:night-orchestrator-report-${stamp}
77
+ type: report
78
+ status: draft
79
+ ---
80
+
81
+ # 夜間 orchestrator 朝報告 ${options.startedAt.slice(0, 10)}
82
+
83
+ - 開始: \`${options.startedAt}\`
84
+ - 完了: \`${options.completedAt}\`
85
+ - 停止理由: ${safeCell(options.stopReason)}
86
+
87
+ ## 集計
88
+
89
+ - close: ${list(closed)}
90
+ - \`waiting\`: ${list(waiting)}
91
+ - 新しい承認待ち: ${list(approvals)}
92
+
93
+ ## 実行結果
94
+
95
+ | 項目 | 結果 | 遷移 | 理由 |
96
+ | ---- | ---- | ---- | ---- |
97
+ ${rows.join("\n") || "| - | skipped | none | 承認済みの open todo/issue なし |"}
98
+ `;
99
+ }
100
+ const MAX_CAPTURED_OUTPUT = 2 * 1024 * 1024;
101
+ function appendOutputTail(current, chunk) {
102
+ const combined = current + chunk;
103
+ return combined.length <= MAX_CAPTURED_OUTPUT
104
+ ? combined
105
+ : combined.slice(combined.length - MAX_CAPTURED_OUTPUT);
106
+ }
107
+ async function runCaptured(command, args) {
108
+ return await new Promise((resolveRun, reject) => {
109
+ const child = spawn(command, args, {
110
+ cwd: specdojoRootDir(),
111
+ env: process.env,
112
+ stdio: "pipe",
113
+ });
114
+ let stdout = "";
115
+ let stderr = "";
116
+ child.stdout.on("data", (chunk) => {
117
+ const text = chunk.toString();
118
+ stdout = appendOutputTail(stdout, text);
119
+ process.stdout.write(text);
120
+ });
121
+ child.stderr.on("data", (chunk) => {
122
+ const text = chunk.toString();
123
+ stderr = appendOutputTail(stderr, text);
124
+ process.stderr.write(text);
125
+ });
126
+ child.once("error", reject);
127
+ child.once("close", (code) => resolveRun({ code: code ?? 1, stdout, stderr }));
128
+ });
129
+ }
130
+ function cliInvocation(args) {
131
+ const entry = process.argv[1];
132
+ if (!entry)
133
+ throw new Error("Cannot resolve the current specdojo CLI entry point.");
134
+ return [process.execPath, [entry, ...args]];
135
+ }
136
+ async function addDerivedApprovalIssue(projectId, item, reason) {
137
+ const [command, args] = cliInvocation([
138
+ "register",
139
+ "add",
140
+ "--project",
141
+ projectId,
142
+ "--type",
143
+ "issue",
144
+ "--title",
145
+ `${item.id} 夜間実行で見つかった承認待ち`,
146
+ "--description",
147
+ `夜間 orchestrator は承認範囲外の対応が必要と判断した。元項目は ${item.id}。理由: ${reason}`,
148
+ "--priority",
149
+ item.priority,
150
+ "--owner",
151
+ item.owner,
152
+ "--from",
153
+ item.id,
154
+ "--topic",
155
+ `night-approval-${item.id.toLowerCase()}`,
156
+ "--by",
157
+ "night-orchestrator",
158
+ "--reason",
159
+ "approved night run requires human authorization",
160
+ ]);
161
+ const result = await runCaptured(command, args);
162
+ if (result.code !== 0)
163
+ throw new Error(`Failed to create derived approval for ${item.id}.`);
164
+ const created = result.stdout.match(/\(added (PJR-[0-9A-Z]{4})\)/u)?.[1];
165
+ if (!created)
166
+ throw new Error(`Could not read the derived approval ID for ${item.id}.`);
167
+ return created;
168
+ }
169
+ export function registerNightOrchestratorCommand(orchestrator) {
170
+ orchestrator
171
+ .command("night")
172
+ .description("Run only human-approved register todo/issue items and write a morning report")
173
+ .option("--project <projectId>", "Project id in specdojo.config.json")
174
+ .option("--max-items <n>", "Maximum items in one night", "10")
175
+ .option("--parallel <n>", "Maximum parallel item runs", "2")
176
+ .option("--max-consecutive-failures <n>", "Stop after this many consecutive failures", "2")
177
+ .option("--on-rate-limit <action>", "Override the difficulty route's pinned-agent action: stop|wait|fallback")
178
+ .option("--fallback-executor-by <nickname>", "Fallback executor for rate limits or configured connection errors")
179
+ .option("--scheduled-at <dateTime>", "Scheduled occurrence time used in the report")
180
+ .option("--dry-run", "Print the approved queue without executing", false)
181
+ .action(async (opts) => {
182
+ try {
183
+ const maxItems = positiveInteger(opts.maxItems, "--max-items");
184
+ const parallel = positiveInteger(opts.parallel, "--parallel");
185
+ const maxFailures = positiveInteger(opts.maxConsecutiveFailures, "--max-consecutive-failures");
186
+ if (opts.onRateLimit !== undefined &&
187
+ !["stop", "wait", "fallback"].includes(opts.onRateLimit)) {
188
+ throw new Error('--on-rate-limit must be "stop", "wait", or "fallback".');
189
+ }
190
+ const resolved = resolveProjectPaths({ project: opts.project });
191
+ const projectId = resolved.projectId ?? opts.project;
192
+ if (!projectId)
193
+ throw new Error("orchestrator night requires --project <id>.");
194
+ const items = loadRegisterItems(resolveRegisterPaths({ project: projectId })).map((view) => view.item);
195
+ const selected = selectApprovedNightItems(items, maxItems);
196
+ process.stdout.write(`[night] approved queue (${selected.length}/${maxItems}): ${selected.map((item) => item.id).join(", ") || "none"}\n`);
197
+ if (opts.dryRun)
198
+ return;
199
+ const startedAt = opts.scheduledAt
200
+ ? new Date(opts.scheduledAt).toISOString()
201
+ : new Date().toISOString();
202
+ const outcomes = [];
203
+ const approvalIssues = new Map();
204
+ let consecutiveFailures = 0;
205
+ let stopReason;
206
+ for (let offset = 0; offset < selected.length; offset += parallel) {
207
+ const wave = selected.slice(offset, offset + parallel);
208
+ const [command, args] = cliInvocation([
209
+ "exec",
210
+ "run",
211
+ "--project",
212
+ projectId,
213
+ "--register",
214
+ ...wave.map((item) => item.id),
215
+ "--worktree",
216
+ "--post-review",
217
+ "--parallel",
218
+ String(parallel),
219
+ "--on-failure",
220
+ "continue",
221
+ ...(opts.onRateLimit ? ["--on-rate-limit", opts.onRateLimit] : []),
222
+ ...(opts.fallbackExecutorBy ? ["--fallback-executor-by", opts.fallbackExecutorBy] : []),
223
+ ]);
224
+ const result = await runCaptured(command, args);
225
+ const parsed = parseRegisterRunSummary(result.stdout);
226
+ const parsedById = new Map(parsed.map((outcome) => [outcome.id, outcome]));
227
+ const waveOutcomes = wave.map((item) => parsedById.get(item.id) ?? {
228
+ id: item.id,
229
+ outcome: "failure",
230
+ transition: "waiting",
231
+ reason: `exec run ended with code ${result.code} without an item summary`,
232
+ });
233
+ outcomes.push(...waveOutcomes);
234
+ for (const outcome of waveOutcomes) {
235
+ if (!requiresDerivedApproval(outcome))
236
+ continue;
237
+ const source = wave.find((item) => item.id === outcome.id);
238
+ if (source) {
239
+ const existing = items.find((item) => item.type === "issue" &&
240
+ !["done", "decided", "rejected", "deferred"].includes(item.status) &&
241
+ item.derivedFrom?.includes(source.id) &&
242
+ item.title.startsWith(`${source.id} 夜間実行で見つかった承認待ち`));
243
+ approvalIssues.set(source.id, existing?.id ??
244
+ (await addDerivedApprovalIssue(projectId, source, outcome.reason ?? "approval required")));
245
+ }
246
+ }
247
+ consecutiveFailures = consecutiveFailureCount(consecutiveFailures, waveOutcomes);
248
+ if (consecutiveFailures >= maxFailures) {
249
+ stopReason = `連続失敗が上限 ${maxFailures} 件に達した`;
250
+ break;
251
+ }
252
+ }
253
+ const processed = new Set(outcomes.map((outcome) => outcome.id));
254
+ for (const item of selected) {
255
+ if (!processed.has(item.id)) {
256
+ outcomes.push({
257
+ id: item.id,
258
+ outcome: "skipped",
259
+ transition: "none",
260
+ reason: stopReason ?? "not started",
261
+ });
262
+ }
263
+ }
264
+ const completedAt = new Date().toISOString();
265
+ const reportsPath = join(resolved.executionPath, "reports", "night-orchestrator");
266
+ mkdirSync(reportsPath, { recursive: true });
267
+ const reportName = `night-orchestrator-${startedAt.replace(/[-:.]/gu, "").replace(/\.\d+Z$/u, "Z")}.md`;
268
+ const reportPath = join(reportsPath, reportName);
269
+ writeFileSync(reportPath, renderNightReport({
270
+ projectId,
271
+ startedAt,
272
+ completedAt,
273
+ selected,
274
+ outcomes,
275
+ approvalIssues,
276
+ ...(stopReason ? { stopReason } : {}),
277
+ }), "utf8");
278
+ process.stdout.write(`[night] morning report: ${relative(specdojoRootDir(), reportPath)}\n`);
279
+ if (outcomes.some((outcome) => outcome.outcome === "failure"))
280
+ process.exitCode = 2;
281
+ }
282
+ catch (error) {
283
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
284
+ process.exitCode = 1;
285
+ }
286
+ });
287
+ }
@@ -3,6 +3,7 @@ import { constants as osConstants } from "node:os";
3
3
  import { resolve } from "node:path";
4
4
  import { agentExtraRootArguments, resolveProductRepos } from "../exec/task-repos.js";
5
5
  import { loadConfig, specdojoRootDir, } from "../shared/specdojo-config.js";
6
+ import { registerNightOrchestratorCommand } from "./night-orchestrator.js";
6
7
  const ORCHESTRATOR_EXECUTABLES = {
7
8
  claude: "claude",
8
9
  codex: "codex",
@@ -10,6 +11,7 @@ const ORCHESTRATOR_EXECUTABLES = {
10
11
  copilot: "copilot",
11
12
  opencode: "opencode",
12
13
  };
14
+ const ORCHESTRATOR_CONFIG_ROOT_ENV = "SPECDOJO_ORCHESTRATOR_CONFIG_ROOT";
13
15
  function isRecord(value) {
14
16
  return typeof value === "object" && value !== null && !Array.isArray(value);
15
17
  }
@@ -122,18 +124,22 @@ export function buildOrchestratorLaunch(options) {
122
124
  export function resolveOrchestratorLaunch(options) {
123
125
  const env = options.env ?? process.env;
124
126
  const rootDir = specdojoRootDir();
125
- const { config, configPath } = loadConfig();
127
+ const configuredRoot = env[ORCHESTRATOR_CONFIG_ROOT_ENV]?.trim();
128
+ const configRootDir = configuredRoot ? resolve(rootDir, configuredRoot) : rootDir;
129
+ const { config, configPath } = loadConfig(configRootDir);
126
130
  if (!config)
127
131
  throw new Error(`No config found: ${configPath}`);
128
132
  const projectId = resolveOrchestratorProjectId(config, options.project, env);
129
- const repos = resolveProductRepos(rootDir, config.projects[projectId]);
130
- return buildOrchestratorLaunch({
133
+ const repos = resolveProductRepos(configRootDir, config.projects[projectId]);
134
+ const launch = buildOrchestratorLaunch({
131
135
  provider: options.provider,
132
136
  providerArgs: options.providerArgs,
133
137
  repoRoots: repos.map((repo) => repo.repoRoot),
134
138
  cwd: rootDir,
135
139
  env,
136
140
  });
141
+ delete launch.env[ORCHESTRATOR_CONFIG_ROOT_ENV];
142
+ return launch;
137
143
  }
138
144
  function parseProvider(value) {
139
145
  if (Object.hasOwn(ORCHESTRATOR_EXECUTABLES, value)) {
@@ -188,6 +194,7 @@ export function registerOrchestratorCommands(program) {
188
194
  const orchestrator = program
189
195
  .command("orchestrator")
190
196
  .description("Launch an interactive orchestrator with declared repository access");
197
+ registerNightOrchestratorCommand(orchestrator);
191
198
  orchestrator
192
199
  .command("launch")
193
200
  .description("Launch a provider CLI and allow only repositories declared by the project")
@@ -5,8 +5,9 @@ export function registerDevcontainerCommands(program) {
5
5
  const dc = program.command("devcontainer").description("Dev Container helpers");
6
6
  dc.command("scaffold")
7
7
  .description("Scaffold .devcontainer/ configuration for the repository")
8
+ .option("--preset <name>", "Apply a bundled preset (available: recommended)")
8
9
  .option("--provider <names>", "Comma-separated list of agent providers to install (e.g. claude,codex,opencode,antigravity)", "")
9
- .option("--editor <names>", "Comma-separated list of editors to install and configure (currently: emacs)", "")
10
+ .option("--editor <names>", "Comma-separated list of editors to install and configure (emacs,vim)", "")
10
11
  .option("--ollama", "Add Ollama connection settings", false)
11
12
  .option("--cron", "Add cron support", false)
12
13
  .option("--tmux", "Add tmux", false)
@@ -19,6 +20,7 @@ export function registerDevcontainerCommands(program) {
19
20
  packageRoot: specdojoPackageRootDir(),
20
21
  repoRoot: specdojoRootDir(),
21
22
  workspaceName: opts.workspaceName === undefined ? undefined : String(opts.workspaceName),
23
+ preset: opts.preset === undefined ? undefined : String(opts.preset),
22
24
  providers: opts.provider
23
25
  ? String(opts.provider)
24
26
  .split(",")
@@ -1,6 +1,70 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readFile, writeFile, mkdir } from "node:fs/promises";
3
3
  import * as path from "node:path";
4
+ const RECOMMENDED_VSCODE_EXTENSIONS = [
5
+ "mhutchie.git-graph",
6
+ "davidanson.vscode-markdownlint",
7
+ "redhat.vscode-yaml",
8
+ "esbenp.prettier-vscode",
9
+ "unifiedjs.vscode-remark",
10
+ "yzhang.markdown-all-in-one",
11
+ "streetsidesoftware.code-spell-checker",
12
+ "editorconfig.editorconfig",
13
+ "usernamehw.errorlens",
14
+ "tamasfe.even-better-toml",
15
+ ];
16
+ const PROVIDER_VSCODE_EXTENSIONS = {
17
+ claude: ["anthropic.claude-code"],
18
+ codex: ["openai.chatgpt"],
19
+ copilot: ["github.copilot", "github.copilot-chat"],
20
+ };
21
+ const RECOMMENDED_VSCODE_SETTINGS = {
22
+ "[markdown]": {
23
+ "editor.defaultFormatter": "esbenp.prettier-vscode",
24
+ "editor.formatOnSave": true,
25
+ },
26
+ "[yaml]": {
27
+ "editor.defaultFormatter": "esbenp.prettier-vscode",
28
+ "editor.formatOnSave": true,
29
+ },
30
+ "yaml.schemas": {
31
+ "./docs/specdojo/schemas/v1/agent-members.schema.yaml": ".specdojo/agent-members.yaml",
32
+ "./docs/specdojo/schemas/v1/exec-defaults.schema.yaml": ".specdojo/exec-defaults.yaml",
33
+ "./docs/specdojo/schemas/v1/job.schema.yaml": "docs/**/jobs/*.yaml",
34
+ "./docs/specdojo/schemas/v1/pm-members.schema.yaml": "docs/**/pm-members.yaml",
35
+ "./docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml": "docs/**/pm-review-viewpoints.yaml",
36
+ "./docs/specdojo/schemas/v1/pm-roles.schema.yaml": "docs/**/pm-roles.yaml",
37
+ "./docs/specdojo/schemas/v1/routine.schema.yaml": "docs/**/routines/*.yaml",
38
+ "./docs/specdojo/schemas/v1/sch-defaults.schema.yaml": "docs/**/sch-defaults.yaml",
39
+ "./docs/specdojo/schemas/v1/sch-milestones.schema.yaml": "docs/**/sch-milestones.yaml",
40
+ "./docs/specdojo/schemas/v1/sch-strategy.schema.yaml": "docs/**/sch-strategy-*.yaml",
41
+ "./docs/specdojo/schemas/v1/sch-track.schema.yaml": "docs/**/sch-track-*.yaml",
42
+ },
43
+ };
44
+ function unique(values) {
45
+ return [...new Set(values)];
46
+ }
47
+ function providerExtensions(providers) {
48
+ return unique(providers.flatMap((provider) => PROVIDER_VSCODE_EXTENSIONS[provider] ?? []));
49
+ }
50
+ function objectValue(value) {
51
+ return value && typeof value === "object" && !Array.isArray(value)
52
+ ? value
53
+ : {};
54
+ }
55
+ async function readExtensionsRecommendations(pathname) {
56
+ if (!existsSync(pathname))
57
+ return { recommendations: [] };
58
+ const parsed = JSON.parse(await readFile(pathname, "utf8"));
59
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
60
+ throw new Error(`Invalid VS Code extensions file: ${pathname}`);
61
+ }
62
+ const result = parsed;
63
+ if (result.recommendations !== undefined && !Array.isArray(result.recommendations)) {
64
+ throw new Error(`Invalid recommendations in VS Code extensions file: ${pathname}`);
65
+ }
66
+ return result;
67
+ }
4
68
  function resolveWorkspaceName(repoRoot, override) {
5
69
  const workspaceName = override ?? path.basename(path.dirname(path.resolve(repoRoot)));
6
70
  if (workspaceName === "." || workspaceName === ".." || !/^[A-Za-z0-9._-]+$/.test(workspaceName)) {
@@ -64,6 +128,9 @@ export function generateSshConfigSample(ports) {
64
128
  " User <user>",
65
129
  "",
66
130
  "# devcontainer 内の tmux セッションへ直接入る接続用",
131
+ "# RemoteCommand は非対話シェルで動くため、接続先端末の ~/.zshrc などの PATH 設定は読み込まれません。",
132
+ "# 接続元から「ssh <host> 'command -v devcontainer'」を実行して Dev Container CLI が見つかるか確認できます。",
133
+ "# 見つからない場合は、ホスト側の ~/bin/specdojo-tmux.sh の node_bin_dir を設定してください。",
67
134
  "Host <host>-tmux",
68
135
  " HostName <host>",
69
136
  " User <user>",
@@ -82,7 +149,13 @@ export function generateSshConfigSample(ports) {
82
149
  return lines.join("\n");
83
150
  }
84
151
  export async function runDevcontainerScaffold(opts) {
85
- const { packageRoot, repoRoot, workspaceName: workspaceNameOverride, providers, editors, ollama, cron, tmux, force, dryRun, } = opts;
152
+ const { packageRoot, repoRoot, workspaceName: workspaceNameOverride, preset, providers, editors, ollama, cron, tmux, force, dryRun, } = opts;
153
+ if (preset !== undefined && preset !== "recommended") {
154
+ throw new Error(`Unknown Dev Container preset: ${preset}. Available: recommended`);
155
+ }
156
+ const recommended = preset === "recommended";
157
+ const effectiveEditors = unique([...editors, ...(recommended ? ["emacs", "vim"] : [])]);
158
+ const effectiveTmux = tmux || recommended;
86
159
  const devcontainerDir = path.join(repoRoot, ".devcontainer");
87
160
  const workspaceName = resolveWorkspaceName(repoRoot, workspaceNameOverride);
88
161
  if (existsSync(devcontainerDir) && !force) {
@@ -114,15 +187,16 @@ export async function runDevcontainerScaffold(opts) {
114
187
  const aptPackages = [];
115
188
  const extraScripts = [];
116
189
  let emacsInitTemplate;
117
- if (tmux) {
190
+ let vimrcTemplate;
191
+ if (effectiveTmux) {
118
192
  aptPackages.push("tmux");
119
193
  }
120
194
  if (cron) {
121
195
  aptPackages.push("cron");
122
196
  devcontainer.postAttachCommand = "sudo service cron start";
123
197
  }
124
- const knownEditors = new Set(["emacs"]);
125
- for (const editor of editors) {
198
+ const knownEditors = new Set(["emacs", "vim"]);
199
+ for (const editor of effectiveEditors) {
126
200
  if (!knownEditors.has(editor)) {
127
201
  process.stdout.write(`Warning: unknown editor "${editor}"\n`);
128
202
  }
@@ -170,9 +244,52 @@ if [ ! -f "$HOME/.emacs" ] && \\
170
244
  mkdir -p "$(dirname "$EMACS_INIT")"
171
245
  cp .devcontainer/emacs/init.el "$EMACS_INIT"
172
246
  echo "Installed Emacs init: $EMACS_INIT"
247
+ fi`);
248
+ }
249
+ else if (editor === "vim") {
250
+ aptPackages.push("vim-nox");
251
+ vimrcTemplate = await readFile(path.join(templateDir, "vim", "vimrc"), "utf8");
252
+ extraScripts.push(`# Keep dotfiles authoritative: install the bundled defaults only when Vim has no user config.
253
+ if [ ! -f "$HOME/.vimrc" ] && [ ! -f "$HOME/.vim/vimrc" ]; then
254
+ cp .devcontainer/vim/vimrc "$HOME/.vimrc"
255
+ echo "Installed Vim config: $HOME/.vimrc"
173
256
  fi`);
174
257
  }
175
258
  }
259
+ let vscodeExtensions = [];
260
+ let extensionsFile;
261
+ if (recommended) {
262
+ vscodeExtensions = unique([...RECOMMENDED_VSCODE_EXTENSIONS, ...providerExtensions(providers)]);
263
+ const customizations = (devcontainer.customizations ??= {});
264
+ const vscode = (customizations.vscode ??= {});
265
+ const existingExtensions = Array.isArray(vscode.extensions)
266
+ ? vscode.extensions.filter((value) => typeof value === "string")
267
+ : [];
268
+ vscode.extensions = unique([...existingExtensions, ...vscodeExtensions]);
269
+ const existingSettings = objectValue(vscode.settings);
270
+ vscode.settings = {
271
+ ...existingSettings,
272
+ "[markdown]": {
273
+ ...objectValue(existingSettings["[markdown]"]),
274
+ ...RECOMMENDED_VSCODE_SETTINGS["[markdown]"],
275
+ },
276
+ "[yaml]": {
277
+ ...objectValue(existingSettings["[yaml]"]),
278
+ ...RECOMMENDED_VSCODE_SETTINGS["[yaml]"],
279
+ },
280
+ "yaml.schemas": {
281
+ ...objectValue(existingSettings["yaml.schemas"]),
282
+ ...RECOMMENDED_VSCODE_SETTINGS["yaml.schemas"],
283
+ },
284
+ };
285
+ const extensionsPath = path.join(repoRoot, ".vscode", "extensions.json");
286
+ extensionsFile = await readExtensionsRecommendations(extensionsPath);
287
+ const existingRecommendations = (extensionsFile.recommendations ?? []);
288
+ extensionsFile.recommendations = unique([
289
+ ...existingRecommendations.filter((value) => typeof value === "string"),
290
+ ...vscodeExtensions,
291
+ ]);
292
+ }
176
293
  if (aptPackages.length > 0) {
177
294
  devcontainer.features["ghcr.io/rocker-org/devcontainer-features/apt-packages:1"] = {
178
295
  packages: aptPackages.join(","),
@@ -219,7 +336,31 @@ fi`);
219
336
  postCreateScript = postCreateScript.replace("npm install", extraScripts.join("\n\n") + "\n\nnpm install");
220
337
  }
221
338
  const specdojoTmuxTemplatePath = path.join(templateDir, "remote-host", "specdojo-tmux.sh.sample");
222
- const specdojoTmuxScript = await readFile(specdojoTmuxTemplatePath, "utf8");
339
+ let specdojoTmuxScript = await readFile(specdojoTmuxTemplatePath, "utf8");
340
+ const remoteUser = typeof devcontainer.remoteUser === "string" && devcontainer.remoteUser.trim()
341
+ ? devcontainer.remoteUser.trim()
342
+ : "node";
343
+ const userLocalBin = `/home/${remoteUser}/.local/bin`;
344
+ const existingRemoteEnv = objectValue(devcontainer.remoteEnv);
345
+ const existingPath = typeof existingRemoteEnv.PATH === "string" ? existingRemoteEnv.PATH : undefined;
346
+ let remotePath;
347
+ if (existingPath) {
348
+ if (existingPath === "/home/node/.local/bin:${containerEnv:PATH}") {
349
+ remotePath = `${userLocalBin}:\${containerEnv:PATH}`;
350
+ }
351
+ else {
352
+ const parts = existingPath.split(":");
353
+ remotePath = parts.includes(userLocalBin) ? existingPath : `${userLocalBin}:${existingPath}`;
354
+ }
355
+ }
356
+ else {
357
+ remotePath = `${userLocalBin}:\${containerEnv:PATH}`;
358
+ }
359
+ devcontainer.remoteEnv = {
360
+ ...existingRemoteEnv,
361
+ PATH: remotePath,
362
+ };
363
+ specdojoTmuxScript = specdojoTmuxScript.replace('container_user="node"', `container_user="${remoteUser}"`);
223
364
  const publishedPorts = extractPublishedPorts(devcontainer);
224
365
  const sshConfigScript = generateSshConfigSample(publishedPorts);
225
366
  if (dryRun) {
@@ -228,6 +369,12 @@ fi`);
228
369
  if (emacsInitTemplate !== undefined) {
229
370
  process.stdout.write(`[dry-run] would write: .devcontainer/emacs/init.el\n`);
230
371
  }
372
+ if (vimrcTemplate !== undefined) {
373
+ process.stdout.write(`[dry-run] would write: .devcontainer/vim/vimrc\n`);
374
+ }
375
+ if (extensionsFile !== undefined) {
376
+ process.stdout.write(`[dry-run] would write: .vscode/extensions.json\n`);
377
+ }
231
378
  process.stdout.write(`[dry-run] would write: .devcontainer/remote-host/specdojo-tmux.sh.sample\n`);
232
379
  process.stdout.write(`[dry-run] would write: .devcontainer/remote-host/ssh-config.sample\n`);
233
380
  return;
@@ -239,6 +386,14 @@ fi`);
239
386
  await mkdir(path.join(devcontainerDir, "emacs"), { recursive: true });
240
387
  await writeFile(path.join(devcontainerDir, "emacs", "init.el"), emacsInitTemplate, "utf8");
241
388
  }
389
+ if (vimrcTemplate !== undefined) {
390
+ await mkdir(path.join(devcontainerDir, "vim"), { recursive: true });
391
+ await writeFile(path.join(devcontainerDir, "vim", "vimrc"), vimrcTemplate, "utf8");
392
+ }
393
+ if (extensionsFile !== undefined) {
394
+ await mkdir(path.join(repoRoot, ".vscode"), { recursive: true });
395
+ await writeFile(path.join(repoRoot, ".vscode", "extensions.json"), `${JSON.stringify(extensionsFile, null, 2)}\n`, "utf8");
396
+ }
242
397
  const remoteHostDir = path.join(devcontainerDir, "remote-host");
243
398
  await mkdir(remoteHostDir, { recursive: true });
244
399
  await writeFile(path.join(remoteHostDir, "specdojo-tmux.sh.sample"), specdojoTmuxScript, "utf8");
@@ -248,6 +403,12 @@ fi`);
248
403
  if (emacsInitTemplate !== undefined) {
249
404
  process.stdout.write(`Written: .devcontainer/emacs/init.el\n`);
250
405
  }
406
+ if (vimrcTemplate !== undefined) {
407
+ process.stdout.write(`Written: .devcontainer/vim/vimrc\n`);
408
+ }
409
+ if (extensionsFile !== undefined) {
410
+ process.stdout.write(`Written: .vscode/extensions.json\n`);
411
+ }
251
412
  process.stdout.write(`Written: .devcontainer/remote-host/specdojo-tmux.sh.sample\n`);
252
413
  process.stdout.write(`Written: .devcontainer/remote-host/ssh-config.sample\n`);
253
414
  process.stdout.write("Next steps:\n" +