specdojo 0.2.1 → 0.3.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 (242) hide show
  1. package/.github/agents/specdojo-orchestrator.md +165 -0
  2. package/CHANGELOG.md +298 -0
  3. package/README.md +92 -42
  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/catalog-build-references.js +144 -0
  8. package/dist/catalog-build-render.js +144 -0
  9. package/dist/catalog-build.js +13 -290
  10. package/dist/catalog-generate.js +6 -9
  11. package/dist/catalog-plan-generate.js +2 -2
  12. package/dist/catalog-plan.js +6 -6
  13. package/dist/catalog-scaffold.js +4 -4
  14. package/dist/catalog.js +2 -2
  15. package/dist/dashboard-exec-records.js +105 -0
  16. package/dist/dashboard-routines.js +255 -0
  17. package/dist/dashboard-shared.js +14 -0
  18. package/dist/dashboard-timeline.js +175 -0
  19. package/dist/dashboard.js +31 -444
  20. package/dist/deliverable-trash.js +3 -3
  21. package/dist/devcontainer-command.js +43 -0
  22. package/dist/devcontainer-scaffold.js +165 -0
  23. package/dist/doc-index.js +3 -3
  24. package/dist/exec-agent-config.js +107 -9
  25. package/dist/exec-agent-git-state.js +18 -0
  26. package/dist/exec-agent-protected-config.js +46 -8
  27. package/dist/exec-commands.js +557 -0
  28. package/dist/exec-core.js +457 -0
  29. package/dist/exec-evidence.js +254 -11
  30. package/dist/exec-handoff.js +336 -0
  31. package/dist/exec-parent-validation.js +317 -43
  32. package/dist/exec-pipeline-state.js +74 -9
  33. package/dist/exec-plans-core.js +693 -0
  34. package/dist/exec-plans-generation.js +206 -0
  35. package/dist/exec-plans-storage.js +131 -0
  36. package/dist/exec-plans.js +3 -1016
  37. package/dist/exec-protection-handoff.js +43 -2
  38. package/dist/exec-provider-scaffold.js +247 -15
  39. package/dist/exec-register-resume.js +65 -19
  40. package/dist/exec-register.js +9 -3
  41. package/dist/exec-repo-integration-git.js +23 -0
  42. package/dist/exec-repo-integration-sync.js +264 -0
  43. package/dist/exec-repo-integration.js +534 -0
  44. package/dist/exec-repo-trace.js +182 -0
  45. package/dist/exec-reporter-output.js +206 -0
  46. package/dist/exec-reporter.js +525 -248
  47. package/dist/exec-results.js +103 -71
  48. package/dist/exec-run-agent-pipeline.js +256 -0
  49. package/dist/exec-run-agent.js +531 -0
  50. package/dist/exec-run-in-place.js +541 -0
  51. package/dist/exec-run-job.js +717 -0
  52. package/dist/exec-run-lifecycle-commands.js +522 -0
  53. package/dist/exec-run-lock.js +110 -107
  54. package/dist/exec-run-mode-shared.js +140 -0
  55. package/dist/exec-run-register-command.js +244 -0
  56. package/dist/exec-run-register-core.js +386 -0
  57. package/dist/exec-run-register-mode.js +206 -0
  58. package/dist/exec-run-register-resume.js +393 -0
  59. package/dist/exec-run-register-state.js +322 -0
  60. package/dist/exec-run-register-worktree.js +509 -0
  61. package/dist/exec-run-schedule-mode.js +294 -0
  62. package/dist/exec-run-schedule-prepare.js +353 -0
  63. package/dist/exec-run-schedule-task.js +572 -0
  64. package/dist/exec-run-shared.js +399 -0
  65. package/dist/exec-run.js +11 -4953
  66. package/dist/exec-shared.js +9 -2
  67. package/dist/exec-slot-lock.js +242 -0
  68. package/dist/exec-task-repos.js +415 -0
  69. package/dist/exec-trial-commands.js +558 -0
  70. package/dist/exec-trial-core.js +371 -0
  71. package/dist/exec-trial.js +2 -895
  72. package/dist/exec-worktree-command.js +87 -43
  73. package/dist/exec-worktree-ops-commit.js +707 -0
  74. package/dist/exec-worktree-ops-lifecycle.js +292 -0
  75. package/dist/exec-worktree-ops-merge.js +303 -0
  76. package/dist/exec-worktree-ops.js +3 -847
  77. package/dist/exec-worktree.js +146 -31
  78. package/dist/exec.js +2 -999
  79. package/dist/frontmatter-namespace.js +2 -2
  80. package/dist/grade-apply.js +734 -0
  81. package/dist/grade-command-apply.js +250 -0
  82. package/dist/grade-command-inspect.js +138 -0
  83. package/dist/grade-command-plan.js +101 -0
  84. package/dist/grade-command-shared.js +68 -0
  85. package/dist/grade-core.js +307 -0
  86. package/dist/grade-markdown.js +274 -0
  87. package/dist/grade-pipeline-state.js +184 -0
  88. package/dist/grade-plan.js +507 -0
  89. package/dist/grade-result.js +133 -5
  90. package/dist/grade-target-discovery.js +265 -0
  91. package/dist/grade-targets.js +432 -0
  92. package/dist/grade.js +14 -2451
  93. package/dist/init-command.js +443 -0
  94. package/dist/job-definition.js +670 -0
  95. package/dist/job.js +64 -578
  96. package/dist/kata-command.js +2 -2
  97. package/dist/orchestrator.js +213 -0
  98. package/dist/register-command-types.js +1 -0
  99. package/dist/register-core.js +363 -0
  100. package/dist/register-create-commands.js +245 -0
  101. package/dist/register-event-merge.js +169 -0
  102. package/dist/register-events.js +4 -4
  103. package/dist/register-item.js +13 -7
  104. package/dist/register-maintenance-commands.js +187 -0
  105. package/dist/register-migration.js +268 -0
  106. package/dist/register-renumber.js +314 -0
  107. package/dist/register-transition-commands.js +248 -0
  108. package/dist/register-update.js +230 -0
  109. package/dist/register-views.js +256 -0
  110. package/dist/register.js +175 -1975
  111. package/dist/review-grade.js +252 -0
  112. package/dist/review-plan.js +114 -4
  113. package/dist/review-types.js +40 -1
  114. package/dist/routine-definition.js +401 -0
  115. package/dist/routine.js +73 -402
  116. package/dist/schedule-approach.js +2 -2
  117. package/dist/schedule-build.js +2 -2
  118. package/dist/schedule-strategy-generate-document.js +273 -0
  119. package/dist/schedule-strategy-generate-scope.js +199 -0
  120. package/dist/schedule-strategy-generate.js +9 -473
  121. package/dist/schedule.js +19 -6
  122. package/dist/specdojo-config.js +465 -20
  123. package/dist/specdojo-gitignore.js +135 -0
  124. package/dist/specdojo.js +6 -0
  125. package/dist/viewpoint-document-kinds-check.js +128 -0
  126. package/dist/yaml-pages.js +4 -4
  127. package/dist/yaml.js +28 -0
  128. package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
  129. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
  130. package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
  131. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
  132. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
  133. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
  134. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
  135. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
  136. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
  137. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
  138. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
  139. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
  140. package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
  141. package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
  142. package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
  143. package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
  144. package/docs/ja/specdojo/guides/exec-config-guide.md +93 -49
  145. package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
  146. package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
  147. package/docs/ja/specdojo/guides/kata-guide.md +4 -4
  148. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +45 -22
  149. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  150. package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
  151. package/docs/ja/specdojo/guides/quick-start-guide.md +260 -30
  152. package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
  153. package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
  154. package/docs/ja/specdojo/guides/remote-host-development-guide.md +22 -1
  155. package/docs/ja/specdojo/guides/review-guide.md +195 -158
  156. package/docs/ja/specdojo/guides/routine-operation-guide.md +75 -10
  157. package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
  158. package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
  159. package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
  160. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
  161. package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
  162. package/docs/ja/specdojo/guides/waza-guide.md +15 -2
  163. package/docs/ja/specdojo/index.md +2 -2
  164. package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
  165. package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
  166. package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
  167. package/docs/ja/specdojo/references/command-reference.md +335 -92
  168. package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
  169. package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
  170. package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
  171. package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
  172. package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
  173. package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
  174. package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
  175. package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
  176. package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
  177. package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
  178. package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
  179. package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
  180. package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
  181. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
  182. package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
  183. package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
  184. package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
  185. package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
  186. package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
  187. package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
  188. package/docs/ja/specdojo/samples/bps-sample.md +74 -21
  189. package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
  190. package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
  191. package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
  192. package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
  193. package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
  194. package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
  195. package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
  196. package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
  197. package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
  198. package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
  199. package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
  200. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
  201. package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
  202. package/docs/ja/specdojo/templates/bps-template.md +91 -0
  203. package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
  204. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
  205. package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
  206. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
  207. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
  208. package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
  209. package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
  210. package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
  211. package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
  212. package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
  213. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
  214. package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
  215. package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
  216. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
  217. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
  218. package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
  219. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
  220. package/package.json +17 -12
  221. package/templates/antigravity/README.md +29 -4
  222. package/templates/antigravity/{pm-members-snippet.yaml → agent-members-snippet.yaml} +8 -2
  223. package/templates/antigravity/exec-defaults-snippet.yaml +10 -7
  224. package/templates/antigravity/orchestrator.md +18 -7
  225. package/templates/antigravity/settings.global.json +55 -0
  226. package/templates/claude/agents/claude-executor.md +14 -0
  227. package/templates/claude/agents/claude-reporter.md +16 -0
  228. package/templates/claude/agents/specdojo-orchestrator.md +18 -7
  229. package/templates/claude/settings.edit.json +27 -1
  230. package/templates/codex/README.md +5 -4
  231. package/templates/codex/agents/specdojo-orchestrator.toml +18 -7
  232. package/templates/codex/orchestrator.md +18 -7
  233. package/templates/copilot/README.md +7 -5
  234. package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
  235. package/templates/devcontainer/devcontainer.json +27 -0
  236. package/templates/devcontainer/emacs/init.el +88 -0
  237. package/templates/devcontainer/post-create.sh +62 -0
  238. package/templates/init-agent-members.yaml +200 -0
  239. package/templates/init-exec-defaults.yaml +74 -0
  240. package/templates/opencode/agents/specdojo-orchestrator.md +18 -7
  241. package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
  242. package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
@@ -1,6 +1,6 @@
1
1
  import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
2
2
  import { basename, dirname, extname, join, relative, resolve } from "node:path";
3
- import yaml from "js-yaml";
3
+ import { load } from "./yaml.js";
4
4
  import { readSpecdojoNamespace } from "./frontmatter-namespace.js";
5
5
  import { specdojoResourceCandidates } from "./template-resolution.js";
6
6
  export const KATA_RESOURCE_KINDS = [
@@ -54,7 +54,7 @@ function filesBelow(root) {
54
54
  function parseDataFileId(content, extension) {
55
55
  let parsed;
56
56
  try {
57
- parsed = extension === ".json" ? JSON.parse(content) : yaml.load(content);
57
+ parsed = extension === ".json" ? JSON.parse(content) : load(content);
58
58
  }
59
59
  catch {
60
60
  return undefined;
@@ -0,0 +1,213 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants as osConstants } from "node:os";
3
+ import { resolve } from "node:path";
4
+ import { agentExtraRootArguments, resolveProductRepos } from "./exec-task-repos.js";
5
+ import { loadConfig, specdojoRootDir, } from "./specdojo-config.js";
6
+ const ORCHESTRATOR_EXECUTABLES = {
7
+ claude: "claude",
8
+ codex: "codex",
9
+ antigravity: "agy",
10
+ copilot: "copilot",
11
+ opencode: "opencode",
12
+ };
13
+ function isRecord(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15
+ }
16
+ function resolveOrchestratorProjectId(config, projectOption, env) {
17
+ const projectId = projectOption?.trim() ||
18
+ env.SPECDOJO_PROJECT?.trim() ||
19
+ config.current_project?.trim() ||
20
+ Object.keys(config.projects)[0];
21
+ if (!projectId) {
22
+ throw new Error("No project specified. Use --project <id>, SPECDOJO_PROJECT, current_project, or define a project.");
23
+ }
24
+ if (!config.projects[projectId]) {
25
+ throw new Error(`Unknown project: ${projectId}`);
26
+ }
27
+ return projectId;
28
+ }
29
+ function opencodeAgentName(args) {
30
+ let selected;
31
+ for (let index = 0; index < args.length; index += 1) {
32
+ const arg = args[index];
33
+ if (arg === "--agent") {
34
+ selected = args[index + 1];
35
+ index += 1;
36
+ }
37
+ else if (arg.startsWith("--agent=")) {
38
+ selected = arg.slice("--agent=".length);
39
+ }
40
+ }
41
+ if (!selected?.trim()) {
42
+ throw new Error("OpenCode orchestrator launch requires --agent <name> so repository permissions can be scoped to that agent.");
43
+ }
44
+ return selected.trim();
45
+ }
46
+ function inlineOpenCodeConfig(current, agentName, repoRoots) {
47
+ let config = {};
48
+ if (current?.trim()) {
49
+ let parsed;
50
+ try {
51
+ parsed = JSON.parse(current);
52
+ }
53
+ catch (error) {
54
+ const message = error instanceof Error ? error.message : String(error);
55
+ throw new Error(`Invalid OPENCODE_CONFIG_CONTENT: ${message}`);
56
+ }
57
+ if (!isRecord(parsed)) {
58
+ throw new Error("Invalid OPENCODE_CONFIG_CONTENT: top-level value must be an object");
59
+ }
60
+ config = parsed;
61
+ }
62
+ const agents = config.agent === undefined ? {} : config.agent;
63
+ if (!isRecord(agents)) {
64
+ throw new Error("Invalid OPENCODE_CONFIG_CONTENT: agent must be an object");
65
+ }
66
+ const selectedAgent = agents[agentName] === undefined ? {} : agents[agentName];
67
+ if (!isRecord(selectedAgent)) {
68
+ throw new Error(`Invalid OPENCODE_CONFIG_CONTENT: agent.${agentName} must be an object`);
69
+ }
70
+ const permission = selectedAgent.permission === undefined ? {} : selectedAgent.permission;
71
+ if (!isRecord(permission)) {
72
+ throw new Error(`Invalid OPENCODE_CONFIG_CONTENT: agent.${agentName}.permission must be an object`);
73
+ }
74
+ const externalDirectory = { "*": "deny" };
75
+ const currentEdit = permission.edit;
76
+ let edit = {};
77
+ if (isRecord(currentEdit)) {
78
+ edit = { ...currentEdit };
79
+ }
80
+ else if (typeof currentEdit === "string") {
81
+ edit = { "*": currentEdit };
82
+ }
83
+ else if (currentEdit !== undefined) {
84
+ throw new Error(`Invalid OPENCODE_CONFIG_CONTENT: agent.${agentName}.permission.edit must be a string or object`);
85
+ }
86
+ for (const repoRoot of repoRoots) {
87
+ const pattern = `${resolve(repoRoot).replaceAll("\\", "/")}/**`;
88
+ externalDirectory[pattern] = "allow";
89
+ edit[pattern] = "allow";
90
+ }
91
+ return JSON.stringify({
92
+ ...config,
93
+ agent: {
94
+ ...agents,
95
+ [agentName]: {
96
+ ...selectedAgent,
97
+ permission: {
98
+ ...permission,
99
+ external_directory: externalDirectory,
100
+ edit,
101
+ },
102
+ },
103
+ },
104
+ });
105
+ }
106
+ export function buildOrchestratorLaunch(options) {
107
+ const env = { ...(options.env ?? process.env) };
108
+ const args = [...options.providerArgs];
109
+ if (options.provider === "opencode" && options.repoRoots.length > 0) {
110
+ env.OPENCODE_CONFIG_CONTENT = inlineOpenCodeConfig(env.OPENCODE_CONFIG_CONTENT, opencodeAgentName(args), options.repoRoots);
111
+ }
112
+ else {
113
+ args.push(...agentExtraRootArguments(options.provider, options.repoRoots));
114
+ }
115
+ return {
116
+ command: ORCHESTRATOR_EXECUTABLES[options.provider],
117
+ args,
118
+ cwd: options.cwd,
119
+ env,
120
+ };
121
+ }
122
+ export function resolveOrchestratorLaunch(options) {
123
+ const env = options.env ?? process.env;
124
+ const rootDir = specdojoRootDir();
125
+ const { config, configPath } = loadConfig();
126
+ if (!config)
127
+ throw new Error(`No config found: ${configPath}`);
128
+ const projectId = resolveOrchestratorProjectId(config, options.project, env);
129
+ const repos = resolveProductRepos(rootDir, config.projects[projectId]);
130
+ return buildOrchestratorLaunch({
131
+ provider: options.provider,
132
+ providerArgs: options.providerArgs,
133
+ repoRoots: repos.map((repo) => repo.repoRoot),
134
+ cwd: rootDir,
135
+ env,
136
+ });
137
+ }
138
+ function parseProvider(value) {
139
+ if (Object.hasOwn(ORCHESTRATOR_EXECUTABLES, value)) {
140
+ return value;
141
+ }
142
+ throw new Error(`Unknown orchestrator provider: ${value}. Available: ${Object.keys(ORCHESTRATOR_EXECUTABLES).join(", ")}`);
143
+ }
144
+ export async function runOrchestratorLaunch(launch, spawnProcess = spawn, signalProcess = process) {
145
+ return await new Promise((resolveExit, reject) => {
146
+ const spawnOptions = {
147
+ cwd: launch.cwd,
148
+ env: launch.env,
149
+ stdio: "inherit",
150
+ };
151
+ const child = spawnProcess(launch.command, launch.args, spawnOptions);
152
+ const signalHandlers = [];
153
+ let settled = false;
154
+ const addSignalHandler = (signal, handler) => {
155
+ signalHandlers.push([signal, handler]);
156
+ signalProcess.on(signal, handler);
157
+ };
158
+ const cleanupSignalHandlers = () => {
159
+ for (const [signal, handler] of signalHandlers) {
160
+ signalProcess.off(signal, handler);
161
+ }
162
+ };
163
+ const settle = (callback) => {
164
+ if (settled)
165
+ return;
166
+ settled = true;
167
+ cleanupSignalHandlers();
168
+ callback();
169
+ };
170
+ addSignalHandler("SIGINT", () => undefined);
171
+ addSignalHandler("SIGQUIT", () => undefined);
172
+ for (const signal of ["SIGTERM", "SIGHUP"]) {
173
+ addSignalHandler(signal, () => {
174
+ child.kill(signal);
175
+ });
176
+ }
177
+ child.once("error", (error) => {
178
+ settle(() => reject(error));
179
+ });
180
+ child.once("exit", (code, signal) => {
181
+ settle(() => {
182
+ resolveExit(code ?? (signal ? 128 + osConstants.signals[signal] : 0));
183
+ });
184
+ });
185
+ });
186
+ }
187
+ export function registerOrchestratorCommands(program) {
188
+ const orchestrator = program
189
+ .command("orchestrator")
190
+ .description("Launch an interactive orchestrator with declared repository access");
191
+ orchestrator
192
+ .command("launch")
193
+ .description("Launch a provider CLI and allow only repositories declared by the project")
194
+ .requiredOption("--provider <name>", "Provider CLI (antigravity|claude|codex|copilot|opencode)")
195
+ .option("--project <projectId>", "Project id in specdojo.config.json")
196
+ .argument("[providerArgs...]", "Provider arguments; put them after --")
197
+ .action(async (providerArgs, opts) => {
198
+ try {
199
+ const launch = resolveOrchestratorLaunch({
200
+ provider: parseProvider(opts.provider),
201
+ providerArgs,
202
+ project: opts.project,
203
+ });
204
+ const exitCode = await runOrchestratorLaunch(launch);
205
+ if (exitCode !== 0)
206
+ process.exitCode = exitCode;
207
+ }
208
+ catch (error) {
209
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
210
+ process.exitCode = 1;
211
+ }
212
+ });
213
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,363 @@
1
+ import { randomInt, randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { inlineCodeAnglePlaceholders } from "./exec-shared.js";
5
+ import { appendRegisterEvent, registerEventFilePath, } from "./register-events.js";
6
+ import { REGISTER_TIMESTAMP_RE, resolveRegisterDateTimeZone, timestampFromDateInTimeZone, } from "./register-date.js";
7
+ import { applyRegisterItemFields, CELL_NONE, CELL_TODO, isPlaceholderCell, PJR_ID_ALPHABET, PJR_ID_RE, registerItemFieldsFromItem, setRegisterItemDescription, VALID_PRIORITIES, VALID_STATUSES, VALID_TYPES, } from "./register-item.js";
8
+ import { getProjectExecutionPath, getProjectRegisterPath, loadConfig, loadEnv, specdojoRootDir, } from "./specdojo-config.js";
9
+ import { flattenTemplateFrontmatter } from "./template-frontmatter.js";
10
+ export function registerEventActor(opts) {
11
+ return opts.by?.trim() || process.env.SPECDOJO_ACTOR?.trim() || "manual";
12
+ }
13
+ export function atomicWriteFile(path, content) {
14
+ mkdirSync(dirname(path), { recursive: true });
15
+ const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
16
+ try {
17
+ writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
18
+ renameSync(temporary, path);
19
+ }
20
+ finally {
21
+ if (existsSync(temporary))
22
+ unlinkSync(temporary);
23
+ }
24
+ }
25
+ export function findMarkdownReferenceFiles(root) {
26
+ const markdownFiles = [];
27
+ const docsJaPath = join(resolve(root), "docs", "ja");
28
+ function walk(directory) {
29
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
30
+ if (entry.name.startsWith("."))
31
+ continue;
32
+ const entryPath = join(directory, entry.name);
33
+ if (entry.isDirectory()) {
34
+ if (entry.name !== "generated")
35
+ walk(entryPath);
36
+ }
37
+ else if (entry.isFile() && entry.name.endsWith(".md")) {
38
+ markdownFiles.push(entryPath);
39
+ }
40
+ }
41
+ }
42
+ if (existsSync(docsJaPath))
43
+ walk(docsJaPath);
44
+ return markdownFiles.sort((left, right) => left.localeCompare(right));
45
+ }
46
+ export function prepareRegisterEventFile(projectRegisterPath, displayId, event) {
47
+ const eventPath = registerEventFilePath(projectRegisterPath, displayId);
48
+ const content = existsSync(eventPath) ? readFileSync(eventPath, "utf8") : undefined;
49
+ return { path: eventPath, content: appendRegisterEvent(content, event) };
50
+ }
51
+ // ================================
52
+ // Constants
53
+ // ================================
54
+ // PJR-ID の乱数部分の桁数。
55
+ const PJR_ID_LENGTH = 4;
56
+ // 個票ファイル名・文書 ID の論点部分。先頭・末尾や連続ハイフンを許さない。
57
+ export const REGISTER_TOPIC_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
58
+ // 生成した ID が偶然含みうる不適切語の簡易ブロックリスト(4 文字, 大文字, 曖昧文字除外後)。
59
+ // 一致した候補は採用せず再抽選する。曖昧文字(I/L/O/U)を含む語は生成されえないため載せない。
60
+ const PJR_ID_BLOCKLIST = new Set(["CRAP", "DAMN", "TWAT", "WANK", "SHAG", "FART"]);
61
+ // 個票 Frontmatter の文書成熟度(specdojo:pjr-rulebook「個票 status の遷移基準」)。
62
+ // pjr-index の処理状態(VALID_STATUSES)とは別の状態軸として扱う。
63
+ export const VALID_TICKET_STATUSES = ["draft", "ready", "deprecated"];
64
+ // 登録項目一覧テーブルは specdojo:pjr-rulebook「本文構成」で章 1 に固定される。
65
+ // 見出し文言(言語依存)ではなく章番号でセクションを特定し、i18n 非依存にする。
66
+ export const REGISTER_SECTION_RE = /^## 1\.\s/;
67
+ // 登録項目一覧(pjr-index)の生成 template。外枠(H1・注記・章見出し)と章 1 の
68
+ // 列見出しを所有し、生成処理は行だけを差し込む。列名を定数として持たないことで、
69
+ // 一覧の言語は template 側の差し替えだけで切り替えられる。
70
+ export const REGISTER_INDEX_TEMPLATE = "pjr-index-template.md";
71
+ // ================================
72
+ // Path Resolution
73
+ // ================================
74
+ export function resolveRegisterPaths(opts) {
75
+ loadEnv();
76
+ const { config, configPath } = loadConfig();
77
+ const baseDir = specdojoRootDir();
78
+ const projectId = opts.project?.trim() ||
79
+ process.env.SPECDOJO_PROJECT?.trim() ||
80
+ (config ? Object.keys(config.projects)[0] : "");
81
+ if (!config) {
82
+ throw new Error(`register commands require specdojo.config.json.\nRun: specdojo config init`);
83
+ }
84
+ if (!projectId) {
85
+ throw new Error(`No project specified. Use --project <id> or SPECDOJO_PROJECT.`);
86
+ }
87
+ const project = config.projects[projectId];
88
+ if (!project) {
89
+ throw new Error(`Unknown project: ${projectId} (check ${configPath})`);
90
+ }
91
+ const registerPath = getProjectRegisterPath(project);
92
+ if (!registerPath) {
93
+ throw new Error(`project_register_path not set for project '${projectId}' in ${configPath}.\n` +
94
+ `Add "project_register_path": "<path>" to the project config.`);
95
+ }
96
+ const absRegisterPath = resolve(baseDir, registerPath);
97
+ return {
98
+ projectId,
99
+ projectRegisterPath: absRegisterPath,
100
+ executionPath: resolve(baseDir, getProjectExecutionPath(project)),
101
+ pjrIndexPath: join(absRegisterPath, "pjr-index.md"),
102
+ generatedPath: join(absRegisterPath, "generated"),
103
+ controlsGeneratedPath: join(dirname(absRegisterPath), "generated"),
104
+ registerDateTimeZone: resolveRegisterDateTimeZone(config, projectId),
105
+ };
106
+ }
107
+ // ================================
108
+ // Markdown Table Parsing
109
+ // ================================
110
+ export function parseTableCells(line) {
111
+ // Replace escaped pipes with placeholder before splitting
112
+ const PIPE = "\x01";
113
+ const normalized = line.replace(/\\\|/g, PIPE);
114
+ const cells = normalized.split("|").map((c) => c.replace(new RegExp(PIPE, "g"), "\\|").trim());
115
+ // Remove first and last empty elements (line starts and ends with |)
116
+ return cells.slice(1, cells.length - 1);
117
+ }
118
+ export function isTableSeparator(line) {
119
+ return line.startsWith("|") && /\|\s*---+\s*\|/.test(line);
120
+ }
121
+ export function locateRegisterTable(lines) {
122
+ let inSection = false;
123
+ let header;
124
+ for (let index = 0; index < lines.length; index++) {
125
+ const line = lines[index];
126
+ if (REGISTER_SECTION_RE.test(line)) {
127
+ inSection = true;
128
+ continue;
129
+ }
130
+ if (inSection && /^## /.test(line))
131
+ break;
132
+ if (!inSection || !line.startsWith("|"))
133
+ continue;
134
+ if (isTableSeparator(line)) {
135
+ if (header === undefined) {
136
+ throw new Error("Register table header row not found before the separator in the register list source");
137
+ }
138
+ return {
139
+ heading: { header: header.trim(), separator: line.trim() },
140
+ separatorIndex: index,
141
+ };
142
+ }
143
+ if (header === undefined)
144
+ header = line;
145
+ }
146
+ return undefined;
147
+ }
148
+ export function extractTableHeading(content) {
149
+ const located = locateRegisterTable(content.split("\n"));
150
+ if (!located) {
151
+ throw new Error("Register table header row not found in the register list source");
152
+ }
153
+ return located.heading;
154
+ }
155
+ // 章 1 の登録項目一覧テーブルの区切り行直後へ、生成した行を差し込む。
156
+ // テーブルの列見出しは template が所有するため、生成処理は行だけを注入する。
157
+ export function injectRegisterRows(content, rows) {
158
+ const lines = content.split("\n");
159
+ const located = locateRegisterTable(lines);
160
+ if (!located) {
161
+ throw new Error(`Register table not found in template: ${REGISTER_INDEX_TEMPLATE}`);
162
+ }
163
+ lines.splice(located.separatorIndex + 1, 0, ...rows);
164
+ return lines.join("\n");
165
+ }
166
+ // 旧一覧(追跡対象だった頃の pjr-index.md)の表を読む互換経路。日付セルは暦日しか持たない
167
+ // ため、移行と同じ規則でプロジェクトタイムゾーンの 21:00 を補って日時へ変換する。
168
+ export function parsePjrIndex(content, timeZone) {
169
+ const lines = content.split("\n");
170
+ const items = [];
171
+ let inSection = false;
172
+ const toTimestamp = (cell) => isPlaceholderCell(cell) ? cell.trim() : timestampFromDateInTimeZone(cell.trim(), timeZone);
173
+ for (const line of lines) {
174
+ if (REGISTER_SECTION_RE.test(line)) {
175
+ inSection = true;
176
+ continue;
177
+ }
178
+ if (inSection && /^## /.test(line))
179
+ break;
180
+ if (!inSection)
181
+ continue;
182
+ if (!line.startsWith("|") || isTableSeparator(line))
183
+ continue;
184
+ const cells = parseTableCells(line);
185
+ if (cells.length < 12)
186
+ continue;
187
+ if (!PJR_ID_RE.test(cells[0]))
188
+ continue;
189
+ items.push({
190
+ id: cells[0],
191
+ status: cells[1],
192
+ title: cells[2],
193
+ description: cells[3],
194
+ type: cells[4],
195
+ priority: cells[5],
196
+ owner: cells[6],
197
+ registeredAt: toTimestamp(cells[7]),
198
+ due: cells[8],
199
+ completedAt: toTimestamp(cells[9]),
200
+ conclusion: cells[10],
201
+ ticket: cells[11],
202
+ });
203
+ }
204
+ return items;
205
+ }
206
+ // 32 文字セットから一様乱択した 4 文字を持つ PJR-ID 候補を 1 件生成する。
207
+ function defaultPjrCandidate() {
208
+ let suffix = "";
209
+ for (let i = 0; i < PJR_ID_LENGTH; i++) {
210
+ suffix += PJR_ID_ALPHABET[randomInt(0, PJR_ID_ALPHABET.length)];
211
+ }
212
+ return `PJR-${suffix}`;
213
+ }
214
+ // 既存 ID・不適切語ブロックリストと衝突しない PJR-ID をランダムに採番する。
215
+ // 生成候補が既存 ID かブロックリストに一致した場合は再抽選する。nextCandidate は
216
+ // テストで抽選列を差し込むための注入点で、既定は 32 文字セットからの一様乱択。
217
+ export function generatePjrId(existingIds, nextCandidate = defaultPjrCandidate, maxAttempts = 256) {
218
+ const existing = new Set(existingIds);
219
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
220
+ const id = nextCandidate();
221
+ if (!PJR_ID_RE.test(id))
222
+ continue;
223
+ if (existing.has(id))
224
+ continue;
225
+ if (PJR_ID_BLOCKLIST.has(id.slice("PJR-".length)))
226
+ continue;
227
+ return id;
228
+ }
229
+ throw new Error(`Failed to generate an unused PJR-ID after ${maxAttempts} attempts`);
230
+ }
231
+ export function formatTableRow(item) {
232
+ // frontmatter・本文由来を問わず、表へ展開する全セルを同じ規則で無害化する。
233
+ // 既存コードスパンは変換処理が保持するため、再生成しても二重に囲まれない。
234
+ const cells = [
235
+ item.id,
236
+ item.status,
237
+ item.title,
238
+ item.description,
239
+ item.type,
240
+ item.priority,
241
+ item.owner,
242
+ item.registered,
243
+ item.due,
244
+ item.completed,
245
+ item.conclusion,
246
+ item.ticket,
247
+ ].map(inlineCodeAnglePlaceholders);
248
+ return `| ${cells.join(" | ")} |`;
249
+ }
250
+ // ================================
251
+ // Validation
252
+ // ================================
253
+ export function validateFields(opts) {
254
+ const errors = [];
255
+ if (!VALID_STATUSES.includes(opts.status)) {
256
+ errors.push(`Invalid status: "${opts.status}". Must be one of: ${VALID_STATUSES.join(", ")}`);
257
+ }
258
+ if (!VALID_TYPES.includes(opts.type)) {
259
+ errors.push(`Invalid type: "${opts.type}". Must be one of: ${VALID_TYPES.join(", ")}`);
260
+ }
261
+ if (!VALID_PRIORITIES.includes(opts.priority)) {
262
+ errors.push(`Invalid priority: "${opts.priority}". Must be one of: ${VALID_PRIORITIES.join(", ")}`);
263
+ }
264
+ if (opts.id && !PJR_ID_RE.test(opts.id)) {
265
+ errors.push(`Invalid ID: "${opts.id}". Must match PJR-XXXX (e.g., PJR-0001)`);
266
+ }
267
+ if (opts.registeredAt !== CELL_TODO && !REGISTER_TIMESTAMP_RE.test(opts.registeredAt)) {
268
+ errors.push(`Invalid registered: "${opts.registeredAt}". Must be an RFC 3339 UTC date-time (YYYY-MM-DDTHH:MM:SSZ) or _TODO_`);
269
+ }
270
+ if (!/^(\d{4}-\d{2}-\d{2}|-|_TODO_)$/.test(opts.due)) {
271
+ errors.push(`Invalid due: "${opts.due}". Must be YYYY-MM-DD, -, or _TODO_`);
272
+ }
273
+ if (opts.completedAt !== CELL_NONE && !REGISTER_TIMESTAMP_RE.test(opts.completedAt)) {
274
+ errors.push(`Invalid completed: "${opts.completedAt}". Must be an RFC 3339 UTC date-time (YYYY-MM-DDTHH:MM:SSZ) or -`);
275
+ }
276
+ if (errors.length > 0) {
277
+ throw new Error(errors.join("\n"));
278
+ }
279
+ }
280
+ // ================================
281
+ // Slug
282
+ // ================================
283
+ export function slugify(text) {
284
+ return (text
285
+ .toLowerCase()
286
+ .replace(/[^a-z0-9\s-]/g, " ")
287
+ .trim()
288
+ .replace(/[\s_]+/g, "-")
289
+ .replace(/-+/g, "-")
290
+ .replace(/^-|-$/g, "") || "item");
291
+ }
292
+ // 日本語主体のタイトルから ASCII の断片だけを topic にすると、個票名から内容を
293
+ // 推測できなくなる。区切り記号は数えず、文字・数字の過半が非 ASCII で、抽出できた
294
+ // ASCII 語が 1 語だけの場合を「意味を失う可能性がある既定 topic」とみなす。
295
+ export function derivedTopicNeedsWarning(title, topic) {
296
+ const asciiWords = title.match(/[a-z0-9]+/giu) ?? [];
297
+ if (topic === "item" && asciiWords.length === 0)
298
+ return true;
299
+ if (asciiWords.length !== 1)
300
+ return false;
301
+ const lettersAndNumbers = [...title].filter((char) => /[\p{L}\p{N}]/u.test(char));
302
+ const asciiCount = lettersAndNumbers.filter((char) => /[a-z0-9]/iu.test(char)).length;
303
+ return lettersAndNumbers.length - asciiCount > asciiCount;
304
+ }
305
+ export function printDerivedTopicWarning(topic) {
306
+ process.stdout.write(`Warning: derived topic "${topic}" may not describe the title. ` +
307
+ "Specify --topic with a lowercase, hyphen-separated English slug, or change it later " +
308
+ "with register update --topic.\n");
309
+ }
310
+ // ================================
311
+ // Ticket Generation
312
+ // ================================
313
+ function getTitlePlaceholder(type) {
314
+ return `_${type.toUpperCase().replace(/-/g, "_")}_TITLE_`;
315
+ }
316
+ function generateTicket(opts) {
317
+ if (!existsSync(opts.templatePath)) {
318
+ throw new Error(`Template not found: ${opts.templatePath}`);
319
+ }
320
+ let content = readFileSync(opts.templatePath, "utf8");
321
+ content = flattenTemplateFrontmatter(content);
322
+ const pjrLower = opts.displayId.toLowerCase();
323
+ // Keep the canonical document ID aligned with the ticket filename.
324
+ content = content.replace(/_PJR_DOCUMENT_ID_/g, `${opts.projectId}:${pjrLower}-${opts.topic}`);
325
+ // Replace remaining project id placeholder
326
+ content = content.replace(/_PROJECT_ID_/g, opts.projectId);
327
+ // Replace display id placeholder with uppercase
328
+ content = content.replace(/_PJR-XXXX_/g, opts.displayId);
329
+ // Replace type-specific title placeholder
330
+ const titlePh = getTitlePlaceholder(opts.type);
331
+ const safeTitle = inlineCodeAnglePlaceholders(opts.title);
332
+ content = content.replace(new RegExp(titlePh.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), safeTitle);
333
+ return content;
334
+ }
335
+ // 個票の完成形(テンプレート展開 + 説明の反映 + 登録項目 frontmatter)を組み立てる。
336
+ // 登録項目の構造化フィールドは frontmatter、タイトルは H1、説明は概要段落が正本になる。
337
+ export function buildRegisterItemContent(opts) {
338
+ let content = generateTicket({
339
+ projectId: opts.projectId,
340
+ displayId: opts.displayId,
341
+ topic: opts.topic,
342
+ type: opts.fields.type,
343
+ title: opts.fields.title,
344
+ templatePath: opts.templatePath,
345
+ });
346
+ if (!isPlaceholderCell(opts.fields.description)) {
347
+ content = setRegisterItemDescription(content, opts.fields.description);
348
+ }
349
+ return applyRegisterItemFields(content, registerItemFieldsFromItem({
350
+ id: opts.displayId,
351
+ status: opts.fields.status,
352
+ title: opts.fields.title,
353
+ description: opts.fields.description,
354
+ type: opts.fields.type,
355
+ priority: opts.fields.priority,
356
+ owner: opts.fields.owner,
357
+ registeredAt: opts.fields.registeredAt,
358
+ due: opts.fields.due,
359
+ completedAt: opts.fields.completedAt,
360
+ conclusion: opts.fields.conclusion,
361
+ ticket: "-",
362
+ }));
363
+ }