specdojo 0.4.5 → 0.4.7

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 (101) hide show
  1. package/.github/agents/specdojo-orchestrator.md +4 -4
  2. package/CHANGELOG.md +41 -0
  3. package/dist/catalog/document-target.js +75 -0
  4. package/dist/commands/agent.js +2 -80
  5. package/dist/commands/init.js +33 -7
  6. package/dist/devcontainer/scaffold.js +5 -1
  7. package/dist/exec/agent-config.js +28 -16
  8. package/dist/exec/agent-plan.js +108 -0
  9. package/dist/exec/commands.js +3 -3
  10. package/dist/exec/evidence.js +35 -3
  11. package/dist/exec/grade-checkpoint.js +12 -0
  12. package/dist/exec/pipeline-state.js +1 -0
  13. package/dist/exec/plans-core.js +11 -67
  14. package/dist/exec/plans-generation.js +22 -5
  15. package/dist/exec/project.js +4 -1
  16. package/dist/exec/register-resume.js +8 -4
  17. package/dist/exec/register.js +66 -5
  18. package/dist/exec/reporter.js +8 -1
  19. package/dist/exec/results.js +1 -1
  20. package/dist/exec/run/agent-pipeline.js +7 -5
  21. package/dist/exec/run/agent.js +14 -1
  22. package/dist/exec/run/lifecycle-commands.js +2 -0
  23. package/dist/exec/run/register-resume.js +2 -0
  24. package/dist/exec/run/register-state.js +4 -1
  25. package/dist/exec/run/register-worktree.js +8 -1
  26. package/dist/exec/run/schedule-prepare.js +7 -1
  27. package/dist/exec/worktree-command.js +8 -1
  28. package/dist/exec/worktree-ops-lifecycle.js +4 -2
  29. package/dist/exec/worktree-ops-merge.js +40 -1
  30. package/dist/grade/apply.js +7 -5
  31. package/dist/grade/command-inspect.js +2 -1
  32. package/dist/grade/command-run.js +39 -0
  33. package/dist/grade/grade.js +3 -1
  34. package/dist/grade/markdown.js +4 -4
  35. package/dist/grade/pipeline-state.js +8 -6
  36. package/dist/grade/plan.js +8 -6
  37. package/dist/grade/run.js +307 -0
  38. package/dist/grade/target-discovery.js +1 -1
  39. package/dist/grade/targets.js +44 -22
  40. package/dist/kata/command.js +54 -9
  41. package/dist/register/approach.js +16 -0
  42. package/dist/register/core.js +2 -0
  43. package/dist/register/create-commands.js +57 -7
  44. package/dist/register/deliverable-target.js +215 -0
  45. package/dist/register/events.js +4 -0
  46. package/dist/register/external-project.js +18 -7
  47. package/dist/register/item.js +8 -0
  48. package/dist/register/views.js +3 -0
  49. package/dist/review/grade.js +19 -17
  50. package/dist/shared/agent-plan.js +1 -0
  51. package/dist/shared/git.js +3 -2
  52. package/dist/shared/lefthook-scaffold.js +5 -22
  53. package/dist/shared/markdownlint-scaffold.js +67 -0
  54. package/dist/shared/provider-scaffold.js +7 -5
  55. package/dist/shared/slidev-scaffold.js +102 -0
  56. package/dist/shared/specdojo-config.js +9 -3
  57. package/dist/specdojo.js +5 -1
  58. package/docs/ja/specdojo/exec-templates/xep-register-template.md +5 -4
  59. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +2 -2
  60. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +2 -2
  61. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +2 -2
  62. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +2 -2
  63. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +2 -2
  64. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +2 -2
  65. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +2 -2
  66. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +2 -2
  67. package/docs/ja/specdojo/exec-templates/xrp-template.md +2 -2
  68. package/docs/ja/specdojo/guides/exec-config-guide.md +81 -19
  69. package/docs/ja/specdojo/guides/exec-operation-guide.md +4 -0
  70. package/docs/ja/specdojo/guides/kata-guide.md +108 -1
  71. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +6 -6
  72. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +3 -1
  73. package/docs/ja/specdojo/guides/quick-start-guide.md +22 -2
  74. package/docs/ja/specdojo/guides/register-operation-guide.md +2 -0
  75. package/docs/ja/specdojo/guides/remote-host-development-guide.md +15 -1
  76. package/docs/ja/specdojo/guides/review-guide.md +2 -2
  77. package/docs/ja/specdojo/guides/ryu-guide.md +12 -0
  78. package/docs/ja/specdojo/references/command-reference.md +178 -62
  79. package/docs/ja/specdojo/references/specdojo-config-reference.md +31 -8
  80. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +28 -22
  81. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +17 -1
  82. package/docs/specdojo/schemas/v1/grade-pipeline-state.schema.yaml +1 -1
  83. package/docs/specdojo/schemas/v1/register-events.schema.yaml +2 -0
  84. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +33 -1
  85. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +16 -3
  86. package/package.json +5 -5
  87. package/templates/antigravity/orchestrator.md +4 -4
  88. package/templates/claude/README.md +2 -0
  89. package/templates/claude/agents/specdojo-orchestrator.md +4 -4
  90. package/templates/codex/README.md +38 -9
  91. package/templates/codex/agents/codex-executor.toml +1 -1
  92. package/templates/codex/agents/codex-expert-executor.toml +1 -1
  93. package/templates/codex/agents/codex-expert-review-executor.toml +1 -1
  94. package/templates/codex/agents/codex-review-executor.toml +1 -1
  95. package/templates/codex/agents/specdojo-orchestrator.toml +5 -5
  96. package/templates/codex/orchestrator.md +4 -4
  97. package/templates/devcontainer/devcontainer.json +1 -0
  98. package/templates/init-agent-members.yaml +131 -16
  99. package/templates/opencode/README.md +118 -14
  100. package/templates/opencode/agents/specdojo-orchestrator.md +5 -5
  101. package/templates/opencode/opencode.json +25 -0
@@ -0,0 +1,307 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { getProjectExecutionPath, specdojoRootDir } from "../shared/specdojo-config.js";
5
+ import { tryAcquireLock, releaseLock } from "../shared/cross-process-lock.js";
6
+ import { applyGradeSubmission, buildGradeSubmissionFromAnalysis } from "./apply.js";
7
+ import { readGradePipelineState, recordGradePipelineStage } from "./pipeline-state.js";
8
+ import { writeGradePlans } from "./plan.js";
9
+ import { gradeContentHash, readGradeResultForDocument } from "./result.js";
10
+ import { discoverGradeTargets } from "./target-discovery.js";
11
+ import { loadViewpoints, repoRelativePath, resolveDeliverableDoneCriteria, resolveGradeSourceHashes, resolveProject, resolveSafeMarkdownPath, resolveSafeRepositoryPath, } from "./targets.js";
12
+ const digest = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
13
+ function referenceHash(reference, project) {
14
+ return reference
15
+ ? gradeContentHash(readFileSync(resolveSafeMarkdownPath(reference, specdojoRootDir(), project), "utf8"))
16
+ : undefined;
17
+ }
18
+ function writeState(path, state) {
19
+ mkdirSync(dirname(path), { recursive: true });
20
+ const temporary = `${path}.tmp`;
21
+ writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`, "utf8");
22
+ renameSync(temporary, path);
23
+ }
24
+ /** Native single-document pipeline. A stable run id freezes selection and completed work. */
25
+ export async function runGrade(opts, runtime) {
26
+ // Serialize all runs for a project: different run ids still write the same canonical sidecars.
27
+ if (opts.dryRun)
28
+ return runGradeUnlocked(opts, runtime);
29
+ const { project } = resolveProject(opts.project);
30
+ const lockPath = resolveSafeRepositoryPath(join(getProjectExecutionPath(project), "grade", "generated", "run.lock"), "grade lock");
31
+ mkdirSync(dirname(lockPath), { recursive: true });
32
+ const lock = tryAcquireLock(lockPath, { actor: opts.by ?? "grade", label: opts.runId });
33
+ if (!lock)
34
+ throw new Error("grade run is busy for this project; retry after the active run finishes");
35
+ try {
36
+ return await runGradeUnlocked(opts, runtime);
37
+ }
38
+ finally {
39
+ releaseLock(lock);
40
+ }
41
+ }
42
+ async function runGradeUnlocked(opts, runtime) {
43
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(opts.runId))
44
+ throw new Error("Invalid --run-id");
45
+ const kind = opts.kind ?? "all";
46
+ if (!["all", "rulebook", "recipe", "sample", "template"].includes(kind))
47
+ throw new Error("Invalid --kind");
48
+ if (opts.target !== "kata" && opts.kind !== undefined)
49
+ throw new Error("--kind is only valid for kata");
50
+ const maxFailures = opts.maxStageFailures ?? 3;
51
+ if (!Number.isSafeInteger(maxFailures) || maxFailures < 1)
52
+ throw new Error("Invalid --max-stage-failures");
53
+ if (opts.limit !== undefined && (!Number.isSafeInteger(opts.limit) || opts.limit < 1))
54
+ throw new Error("Invalid --limit");
55
+ const { id: projectId, project } = resolveProject(opts.project);
56
+ const viewpoints = loadViewpoints(projectId);
57
+ const executionPath = getProjectExecutionPath(project);
58
+ const execDefaultsPath = opts.execDefaultsPath ??
59
+ (project.run?.exec_defaults
60
+ ? resolve(specdojoRootDir(), project.run.exec_defaults)
61
+ : undefined);
62
+ const directory = resolveSafeRepositoryPath(opts.workDir ?? join(executionPath, "grade", "generated", "runs", opts.runId), "--work-dir");
63
+ const statePath = join(directory, "run.json");
64
+ const requestOptions = Object.fromEntries(Object.entries(opts).filter(([key]) => key !== "dryRun"));
65
+ const request = digest({ ...requestOptions, project: projectId });
66
+ let state;
67
+ if (existsSync(statePath)) {
68
+ const stored = JSON.parse(readFileSync(statePath, "utf8"));
69
+ if (!stored ||
70
+ typeof stored !== "object" ||
71
+ !("version" in stored) ||
72
+ stored.version !== 1 ||
73
+ !("request" in stored) ||
74
+ stored.request !== request ||
75
+ !("documents" in stored) ||
76
+ !Array.isArray(stored.documents)) {
77
+ throw new Error("Run configuration changed or invalid run state; use a new --run-id / --work-dir");
78
+ }
79
+ state = stored;
80
+ for (const document of state.documents) {
81
+ if (!document ||
82
+ typeof document.path !== "string" ||
83
+ typeof document.fingerprint !== "string" ||
84
+ !["pending", "failed", "complete"].includes(document.status))
85
+ throw new Error("Invalid grade run document state");
86
+ }
87
+ }
88
+ else {
89
+ let paths = discoverGradeTargets({ ...opts, project: projectId });
90
+ if (opts.target === "kata" && kind !== "all")
91
+ paths = paths.filter((path) => repoRelativePath(path).split("/").includes(`${kind}s`));
92
+ if (opts.limit !== undefined)
93
+ paths = paths.slice(0, opts.limit);
94
+ state = {
95
+ version: 1,
96
+ request,
97
+ documents: paths.map((path) => ({
98
+ path: repoRelativePath(path),
99
+ fingerprint: "",
100
+ status: "pending",
101
+ })),
102
+ };
103
+ }
104
+ const criteria = opts.target === "deliverable"
105
+ ? resolveDeliverableDoneCriteria(state.documents.map((document) => document.path), projectId)
106
+ : undefined;
107
+ // Validate all subjects before starting any agent or writing run files.
108
+ for (const document of state.documents) {
109
+ const path = resolveSafeMarkdownPath(document.path, specdojoRootDir(), projectId);
110
+ const fingerprint = digest({
111
+ content: gradeContentHash(readFileSync(path, "utf8")),
112
+ reference: referenceHash(opts.reference, projectId),
113
+ viewpoints,
114
+ criteria: criteria?.get(document.path),
115
+ sources: resolveGradeSourceHashes({
116
+ path,
117
+ target: opts.target,
118
+ project: projectId,
119
+ viewpoints,
120
+ }),
121
+ });
122
+ if (document.fingerprint && document.fingerprint !== fingerprint)
123
+ throw new Error(`${document.path}: grading context changed; use a new --run-id`);
124
+ document.fingerprint = fingerprint;
125
+ if (document.status === "complete" || document.appliedAt) {
126
+ const result = readGradeResultForDocument({
127
+ documentPath: document.path,
128
+ project: projectId,
129
+ });
130
+ // The canonical result is written after the criteria detail. Recover the narrow
131
+ // interruption between apply and persisting completion without reapplying the stage.
132
+ if (document.status !== "complete" &&
133
+ result &&
134
+ result.graded_at === document.appliedAt &&
135
+ result.graded_by === document.actor &&
136
+ result.content_hash === gradeContentHash(readFileSync(path, "utf8")) &&
137
+ result.target === opts.target &&
138
+ result.path === document.path) {
139
+ document.status = "complete";
140
+ document.resultHash = digest(result);
141
+ }
142
+ if (document.status !== "complete")
143
+ continue;
144
+ if (!result || digest(result) !== document.resultHash)
145
+ throw new Error(`${document.path}: completed grade was replaced or removed; use a new --run-id`);
146
+ }
147
+ }
148
+ if (state.documents.length === 0)
149
+ return { documents: [] };
150
+ const actor = state.documents.some((document) => document.status !== "complete")
151
+ ? runtime.resolveActor({ ...opts, execDefaultsPath })
152
+ : undefined;
153
+ if (opts.dryRun) {
154
+ for (const document of state.documents)
155
+ process.stdout.write(`[dry-run] ${document.path} actor=${actor ?? document.actor} status=${document.status}\n`);
156
+ return { documents: state.documents };
157
+ }
158
+ writeState(statePath, state);
159
+ const failures = [];
160
+ for (const [index, document] of state.documents.entries()) {
161
+ if (document.status === "complete") {
162
+ recordGradePipelineStage({
163
+ target: opts.target,
164
+ project: projectId,
165
+ path: document.path,
166
+ runId: opts.runId,
167
+ stage: 1,
168
+ stageTotal: 1,
169
+ maxFailures,
170
+ status: "complete",
171
+ });
172
+ process.stdout.write(`resumed complete: ${document.path}\n`);
173
+ continue;
174
+ }
175
+ const prior = readGradePipelineState({
176
+ target: opts.target,
177
+ project: projectId,
178
+ path: document.path,
179
+ });
180
+ if (prior && prior.stage_total === 1 && prior.consecutive_failures >= prior.max_failures) {
181
+ failures.push(`${document.path}: stage failure limit reached`);
182
+ continue;
183
+ }
184
+ // The native runner has one stage. Old experimental three-stage retries cannot be reused.
185
+ if (prior && prior.stage_total !== 1)
186
+ recordGradePipelineStage({
187
+ target: opts.target,
188
+ project: projectId,
189
+ path: document.path,
190
+ runId: opts.runId,
191
+ stage: 1,
192
+ stageTotal: 1,
193
+ maxFailures,
194
+ status: "complete",
195
+ });
196
+ const stageDirectory = join(directory, String(index + 1), "stage-1");
197
+ try {
198
+ const [plan] = writeGradePlans({
199
+ target: opts.target,
200
+ paths: [document.path],
201
+ referenceExampleCandidates: [],
202
+ referenceExampleOverride: opts.reference,
203
+ viewpoints,
204
+ projectId,
205
+ outputDirectory: stageDirectory,
206
+ embedDocuments: opts.embedDocuments,
207
+ doneCriteriaByPath: criteria,
208
+ });
209
+ document.actor = actor;
210
+ document.status = "pending";
211
+ delete document.error;
212
+ writeState(statePath, state);
213
+ const { execution, actor: actualActor } = await runtime.executePlan({
214
+ planPath: resolve(specdojoRootDir(), plan.path),
215
+ nickname: actor,
216
+ project: projectId,
217
+ execDefaultsPath,
218
+ quiet: true,
219
+ });
220
+ document.actor = actualActor;
221
+ if (!execution)
222
+ throw new Error("Agent returned no execution result");
223
+ writeFileSync(join(stageDirectory, "executor-output.txt"), execution.stdout, "utf8");
224
+ if (execution.result !== "success")
225
+ throw new Error(`agent ${actualActor}: ${execution.result} exit=${execution.exitCode ?? "null"}`);
226
+ // Refuse output if the agent (or another process) changed the grading context while running.
227
+ const currentPath = resolveSafeMarkdownPath(document.path, specdojoRootDir(), projectId);
228
+ const currentFingerprint = digest({
229
+ content: gradeContentHash(readFileSync(currentPath, "utf8")),
230
+ reference: referenceHash(opts.reference, projectId),
231
+ viewpoints: loadViewpoints(projectId),
232
+ criteria: opts.target === "deliverable"
233
+ ? resolveDeliverableDoneCriteria([document.path], projectId).get(document.path)
234
+ : undefined,
235
+ sources: resolveGradeSourceHashes({
236
+ path: currentPath,
237
+ target: opts.target,
238
+ project: projectId,
239
+ }),
240
+ });
241
+ if (currentFingerprint !== document.fingerprint)
242
+ throw new Error("grading context changed during agent execution; use a new --run-id");
243
+ const converted = buildGradeSubmissionFromAnalysis({
244
+ executorOutput: execution.stdout,
245
+ viewpoints,
246
+ target: opts.target,
247
+ expectedPath: document.path,
248
+ doneCriteria: criteria?.get(document.path),
249
+ });
250
+ if (!converted.submission)
251
+ throw new Error(converted.issues.map((issue) => `${issue.path}: ${issue.message}`).join("\n"));
252
+ document.appliedAt = new Date().toISOString();
253
+ writeState(statePath, state);
254
+ applyGradeSubmission({
255
+ submission: converted.submission,
256
+ viewpoints,
257
+ target: opts.target,
258
+ gradedBy: actualActor,
259
+ reference: opts.reference,
260
+ doneCriteriaByPath: criteria,
261
+ criteriaDirectory: join(executionPath, "grade", "criteria"),
262
+ resultsDirectory: join(executionPath, "grade", "results"),
263
+ project: projectId,
264
+ now: new Date(document.appliedAt),
265
+ });
266
+ const result = readGradeResultForDocument({
267
+ documentPath: document.path,
268
+ project: projectId,
269
+ });
270
+ if (!result)
271
+ throw new Error("grade result missing after apply");
272
+ document.status = "complete";
273
+ document.resultHash = digest(result);
274
+ writeState(statePath, state);
275
+ recordGradePipelineStage({
276
+ target: opts.target,
277
+ project: projectId,
278
+ path: document.path,
279
+ runId: opts.runId,
280
+ stage: 1,
281
+ stageTotal: 1,
282
+ maxFailures,
283
+ status: "complete",
284
+ });
285
+ process.stdout.write(`graded: ${document.path} actor=${actualActor}\n`);
286
+ }
287
+ catch (error) {
288
+ document.status = "failed";
289
+ document.error = error instanceof Error ? error.message : String(error);
290
+ writeState(statePath, state);
291
+ recordGradePipelineStage({
292
+ target: opts.target,
293
+ project: projectId,
294
+ path: document.path,
295
+ runId: opts.runId,
296
+ stage: 1,
297
+ stageTotal: 1,
298
+ maxFailures,
299
+ status: "failed",
300
+ });
301
+ failures.push(`${document.path}: ${document.error}`);
302
+ }
303
+ }
304
+ if (failures.length)
305
+ throw new Error(`grade run incomplete:\n${failures.join("\n")}`);
306
+ return { documents: state.documents };
307
+ }
@@ -11,7 +11,7 @@ export function discoverGradeTargets(opts, rootDir = specdojoRootDir()) {
11
11
  validateGradeTargetFilters(opts);
12
12
  let candidates;
13
13
  if (opts.paths && opts.paths.length > 0) {
14
- candidates = opts.paths.map((path) => resolveSafeMarkdownPath(path, rootDir));
14
+ candidates = opts.paths.map((path) => resolveSafeMarkdownPath(path, rootDir, opts.project));
15
15
  const generated = candidates.find((path) => isGeneratedGradeTarget(path, rootDir));
16
16
  if (generated) {
17
17
  throw new Error(`${relativePathFromRoot(generated, rootDir)}: generated documents cannot be graded`);
@@ -1,14 +1,14 @@
1
1
  import { createHash } from "node:crypto";
2
- import { existsSync, readFileSync } from "node:fs";
3
- import { extname, isAbsolute, join, relative, resolve } from "node:path";
2
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
3
+ import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
4
4
  import { load } from "../shared/yaml.js";
5
5
  import { collectResolvedDeliverables, loadCatalogDocs } from "../catalog/build.js";
6
6
  import { isTrashedPath, resolveBasePath } from "../catalog/paths.js";
7
7
  import { listFilesRecursive } from "../shared/fs.js";
8
8
  import { gradeContentHash } from "./result.js";
9
9
  import { GRADE_TARGETS, KATA_DIRS, KATA_REFERENCE_EXTENSIONS, KATA_REFERENCE_FIELDS, gradedViewpoints, isRecord, parseMarkdown, } from "./core.js";
10
- import { resolveViewpointsDoc } from "../review/plan.js";
11
- import { assertValidActor, getProjectCatalogPath, getProjectMembersPath, getProjectRolesPath, getProjectSchedulePath, getProjectViewpointsPath, loadConfig, resolveAgentMember, specdojoRootDir, } from "../shared/specdojo-config.js";
10
+ import { commonViewpointsPath, resolveViewpointsDoc } from "../review/plan.js";
11
+ import { assertValidActor, getProjectCatalogPath, getProjectMembersPath, getProjectRolesPath, getProjectSchedulePath, getProjectViewpointsPath, loadConfig, resolveAgentMember, resolveRepoRoot, specdojoRootDir, } from "../shared/specdojo-config.js";
12
12
  export function resolveProject(projectOption) {
13
13
  const { config } = loadConfig();
14
14
  if (!config)
@@ -22,14 +22,14 @@ export function resolveProject(projectOption) {
22
22
  export function loadViewpoints(projectOption) {
23
23
  const { project } = resolveProject(projectOption);
24
24
  const path = getProjectViewpointsPath(project);
25
- if (!path)
26
- throw new Error("viewpoints_path is required for grade");
27
- return resolveViewpointsDoc(resolve(specdojoRootDir(), path));
25
+ return resolveViewpointsDoc(path ? resolve(specdojoRootDir(), path) : commonViewpointsPath());
28
26
  }
29
27
  // 対象探索は観点定義が無いプロジェクトでも動かす。その場合は突き合わせ先を持たない扱いにする。
30
28
  export function loadViewpointsIfConfigured(projectOption, rootDir) {
31
29
  const path = getProjectViewpointsPath(resolveProject(projectOption).project);
32
- if (!path || !existsSync(resolve(rootDir, path)))
30
+ if (!path)
31
+ return resolveViewpointsDoc(commonViewpointsPath());
32
+ if (!existsSync(resolve(rootDir, path)))
33
33
  return undefined;
34
34
  return resolveViewpointsDoc(resolve(rootDir, path));
35
35
  }
@@ -123,8 +123,8 @@ export function loadKataReferences() {
123
123
  }
124
124
  return [...references.values()];
125
125
  }
126
- export function resolveGradeReferencePathsFromCatalog(path, catalog) {
127
- const target = resolveSafeMarkdownPath(path);
126
+ export function resolveGradeReferencePathsFromCatalog(path, catalog, project) {
127
+ const target = resolveSafeMarkdownPath(path, specdojoRootDir(), project);
128
128
  const targetDocument = parseMarkdown(readFileSync(target, "utf8"), repoRelativePath(target));
129
129
  const targetMetadata = targetDocument.data.specdojo;
130
130
  const targetId = typeof targetMetadata.id === "string" ? targetMetadata.id.trim() : "";
@@ -169,9 +169,9 @@ function gradeReferenceExampleFamily(target, path, metadata) {
169
169
  const type = typeof metadata.type === "string" ? metadata.type.trim() : "";
170
170
  return type || null;
171
171
  }
172
- export function parseGradeReferenceExample(path, target) {
172
+ export function parseGradeReferenceExample(path, target, project) {
173
173
  try {
174
- const absolute = resolveSafeMarkdownPath(path);
174
+ const absolute = resolveSafeMarkdownPath(path, specdojoRootDir(), project);
175
175
  const document = parseMarkdown(readFileSync(absolute, "utf8"), repoRelativePath(absolute));
176
176
  const metadata = document.data.specdojo;
177
177
  return {
@@ -185,7 +185,7 @@ export function parseGradeReferenceExample(path, target) {
185
185
  }
186
186
  }
187
187
  export function selectGradeReferenceExampleFromCatalog(opts) {
188
- const target = resolveSafeMarkdownPath(opts.path);
188
+ const target = resolveSafeMarkdownPath(opts.path, specdojoRootDir(), opts.project);
189
189
  const targetDocument = parseMarkdown(readFileSync(target, "utf8"), repoRelativePath(target));
190
190
  const targetMetadata = targetDocument.data.specdojo;
191
191
  const family = gradeReferenceExampleFamily(opts.target, target, targetMetadata);
@@ -210,30 +210,51 @@ export function selectGradeReferenceExample(opts) {
210
210
  return selectGradeReferenceExampleFromCatalog({
211
211
  ...opts,
212
212
  candidates: opts.candidates.flatMap((candidate) => {
213
- const parsed = parseGradeReferenceExample(candidate, opts.target);
213
+ const parsed = parseGradeReferenceExample(candidate, opts.target, opts.project);
214
214
  return parsed ? [parsed] : [];
215
215
  }),
216
216
  });
217
217
  }
218
- export function resolveSafeMarkdownPath(input, root = specdojoRootDir()) {
218
+ export function resolveSafeMarkdownPath(input, root = specdojoRootDir(), projectOption) {
219
219
  const absolute = resolve(root, input);
220
- const rel = relativePathFromRoot(absolute, root);
221
- if (rel.startsWith("../") || isAbsolute(rel))
222
- throw new Error(`Path is outside repository: ${input}`);
220
+ const inside = (base, path) => {
221
+ const rel = relative(base, path);
222
+ return (rel !== ".." &&
223
+ !rel.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) &&
224
+ !isAbsolute(rel));
225
+ };
226
+ const roots = [root];
227
+ if (!inside(root, absolute)) {
228
+ const { config } = loadConfig(root);
229
+ const projectId = projectOption ?? config?.current_project ?? Object.keys(config?.projects ?? {})[0];
230
+ const project = projectId ? config?.projects[projectId] : undefined;
231
+ for (const repo of project?.repos ?? [])
232
+ roots.push(resolveRepoRoot(root, repo));
233
+ }
234
+ if (!roots.some((base) => inside(base, absolute)))
235
+ throw new Error(`Path is outside repository or declared project.repos: ${input}`);
223
236
  if (extname(absolute).toLowerCase() !== ".md") {
224
237
  throw new Error(`${input}: grade currently writes inline findings only for Markdown`);
225
238
  }
226
239
  if (!existsSync(absolute))
227
240
  throw new Error(`Document not found: ${input}`);
241
+ if (!roots.some((base) => existsSync(base) && inside(realpathSync(base), realpathSync(absolute))))
242
+ throw new Error(`Path is outside repository or declared project.repos: ${input}`);
228
243
  return absolute;
229
244
  }
230
245
  export function resolveSafeRepositoryPath(input, option) {
231
246
  const root = specdojoRootDir();
232
247
  const absolute = resolve(root, input);
233
- const rel = relative(root, absolute);
234
- if (rel.startsWith("../") || isAbsolute(rel)) {
248
+ const rel = relativePathFromRoot(absolute, root);
249
+ if (rel === ".." || rel.startsWith("../") || isAbsolute(rel)) {
235
250
  throw new Error(`${option} must be inside the repository`);
236
251
  }
252
+ let ancestor = absolute;
253
+ while (!existsSync(ancestor))
254
+ ancestor = dirname(ancestor);
255
+ const realRelative = relativePathFromRoot(realpathSync(ancestor), realpathSync(root));
256
+ if (realRelative === ".." || realRelative.startsWith("../") || isAbsolute(realRelative))
257
+ throw new Error(`${option} must be inside the repository`);
237
258
  return absolute;
238
259
  }
239
260
  export function isGeneratedGradeTarget(path, rootDir = specdojoRootDir()) {
@@ -266,6 +287,7 @@ export function loadDeliverableCatalog(projectOption, root = specdojoRootDir())
266
287
  const path = resolve(root, item.resolvedPath);
267
288
  if (!existsSync(path) || entries.has(path))
268
289
  continue;
290
+ resolveSafeMarkdownPath(path, root, projectOption);
269
291
  entries.set(path, {
270
292
  path,
271
293
  localId: item.item.local_id,
@@ -289,7 +311,7 @@ export function resolveDeliverableDoneCriteria(paths, projectOption) {
289
311
  const catalog = loadDeliverableCatalog(projectOption);
290
312
  const result = new Map();
291
313
  for (const path of paths) {
292
- const entry = catalog.get(resolveSafeMarkdownPath(path));
314
+ const entry = catalog.get(resolveSafeMarkdownPath(path, specdojoRootDir(), projectOption));
293
315
  if (entry && entry.doneCriteria.length > 0) {
294
316
  result.set(repoRelativePath(entry.path), entry.doneCriteria);
295
317
  }
@@ -424,7 +446,7 @@ export function gradeSourceHashes(documentPath, document, viewpoints, target, co
424
446
  }
425
447
  /** Current hashes of the comparison sources and dependencies that grade apply records for a document. */
426
448
  export function resolveGradeSourceHashes(opts, rootDir = specdojoRootDir()) {
427
- const absolute = resolveSafeMarkdownPath(opts.path, rootDir);
449
+ const absolute = resolveSafeMarkdownPath(opts.path, rootDir, opts.project);
428
450
  const document = parseMarkdown(readFileSync(absolute, "utf8"), relativePathFromRoot(absolute, rootDir));
429
451
  const viewpoints = opts.viewpoints ?? loadViewpointsIfConfigured(opts.project, rootDir);
430
452
  return gradeSourceHashes(absolute, document, viewpoints, opts.target, createGradeSourceContext(opts.project, rootDir));
@@ -92,11 +92,31 @@ function pathsForConfig(config, roots) {
92
92
  function relativeFiles(root) {
93
93
  return filesBelow(root).map((filePath) => normalizeRelativePath(relative(root, filePath)));
94
94
  }
95
+ const KATA_ID_EXTENSIONS = new Set([".md", ".mdx", ".yaml", ".yml", ".json"]);
96
+ function isKataIdFile(filePath) {
97
+ return KATA_ID_EXTENSIONS.has(extname(filePath).toLowerCase());
98
+ }
99
+ // ID を読める形式は独立した kata とし、付属ファイルの候補からも除く。
100
+ function companionPaths(filePath, files) {
101
+ const stem = basename(filePath, extname(filePath));
102
+ const directory = dirname(filePath);
103
+ const companionDirectory = normalizeRelativePath(join(directory, stem)) + "/";
104
+ return files.filter((candidate) => !isKataIdFile(candidate) &&
105
+ ((dirname(candidate) === directory && basename(candidate, extname(candidate)) === stem) ||
106
+ candidate.startsWith(companionDirectory)));
107
+ }
108
+ function sameCompanions(filePath, repositoryDir, bundledDir, repositoryFiles, bundledFiles) {
109
+ const repositoryCompanions = companionPaths(filePath, repositoryFiles);
110
+ const bundledCompanions = companionPaths(filePath, bundledFiles);
111
+ return (repositoryCompanions.length === bundledCompanions.length &&
112
+ repositoryCompanions.every((companion, index) => companion === bundledCompanions[index] &&
113
+ sameContents(resolve(repositoryDir, companion), resolve(bundledDir, companion))));
114
+ }
95
115
  function enumerateConfig(config, roots) {
96
116
  const { repositoryDir, bundledDir } = pathsForConfig(config, roots);
97
- const relativePaths = [
98
- ...new Set([...relativeFiles(repositoryDir), ...relativeFiles(bundledDir)]),
99
- ];
117
+ const repositoryFiles = relativeFiles(repositoryDir);
118
+ const bundledFiles = relativeFiles(bundledDir);
119
+ const relativePaths = [...new Set([...repositoryFiles, ...bundledFiles])].filter(isKataIdFile);
100
120
  return relativePaths.sort().map((filePath) => {
101
121
  const repositoryPath = resolve(repositoryDir, filePath);
102
122
  const bundledPath = resolve(bundledDir, filePath);
@@ -116,7 +136,8 @@ function enumerateConfig(config, roots) {
116
136
  state: hasRepositoryFile ? "ejected" : "referenced",
117
137
  difference: hasRepositoryFile
118
138
  ? hasBundledFile
119
- ? sameContents(repositoryPath, bundledPath)
139
+ ? sameContents(repositoryPath, bundledPath) &&
140
+ sameCompanions(filePath, repositoryDir, bundledDir, repositoryFiles, bundledFiles)
120
141
  ? "same"
121
142
  : "modified"
122
143
  : "package-missing"
@@ -132,7 +153,9 @@ function enumerateAuthoredResources(roots) {
132
153
  const legacyDir = legacyKataKindDirectory(kind);
133
154
  const resourcesFrom = (relativeDir) => {
134
155
  const absoluteDir = resolve(repositoryRoot, relativeDir);
135
- return relativeFiles(absoluteDir).flatMap((filePath) => {
156
+ return relativeFiles(absoluteDir)
157
+ .filter(isKataIdFile)
158
+ .flatMap((filePath) => {
136
159
  const resolvedPath = resolve(absoluteDir, filePath);
137
160
  const id = resourceId(resolvedPath);
138
161
  let authority;
@@ -224,7 +247,9 @@ export function findKataResource(id, options = {}) {
224
247
  function bundledResources(configs, roots) {
225
248
  return configs.flatMap((config) => {
226
249
  const { repositoryDir, bundledDir } = pathsForConfig(config, roots);
227
- return relativeFiles(bundledDir).map((filePath) => ({
250
+ return relativeFiles(bundledDir)
251
+ .filter(isKataIdFile)
252
+ .map((filePath) => ({
228
253
  id: resourceId(resolve(bundledDir, filePath)),
229
254
  config,
230
255
  relativePath: normalizeRelativePath(join(config.relativeDir, filePath)),
@@ -233,6 +258,16 @@ function bundledResources(configs, roots) {
233
258
  }));
234
259
  });
235
260
  }
261
+ function bundledCompanions(resource) {
262
+ const sourceDir = dirname(resource.sourcePath);
263
+ const filePaths = companionPaths(basename(resource.sourcePath), relativeFiles(sourceDir));
264
+ return filePaths.map((filePath) => ({
265
+ ...resource,
266
+ relativePath: normalizeRelativePath(join(dirname(resource.relativePath), filePath)),
267
+ sourcePath: resolve(sourceDir, filePath),
268
+ destinationPath: resolve(dirname(resource.destinationPath), filePath),
269
+ }));
270
+ }
236
271
  function selectBundledById(resources, id) {
237
272
  const exact = resources.filter((resource) => resource.id === id);
238
273
  const matches = exact.length > 0 ? exact : resources.filter((resource) => localId(resource.id) === id);
@@ -268,10 +303,17 @@ export function ejectKata(id, options = {}) {
268
303
  if (!resource.config.ejectable) {
269
304
  throw new Error(`Cannot eject ${resource.config.kind} '${resource.id}': ${resource.config.relativeDir} is tied to the installed SpecDojo version and must remain package-referenced.`);
270
305
  }
271
- return copyBundledResource(resource, options);
306
+ const result = copyBundledResource(resource, options);
307
+ const companions = bundledCompanions(resource).map((companion) => copyBundledResource(companion, options));
308
+ return { ...result, companions };
272
309
  }
273
310
  export function installAllKata(options = {}) {
274
- return bundledResources(EJECTABLE_KINDS, options.roots ?? {}).map((resource) => copyBundledResource(resource, options));
311
+ const resources = bundledResources(EJECTABLE_KINDS, options.roots ?? {}).flatMap((resource) => [
312
+ resource,
313
+ ...bundledCompanions(resource),
314
+ ]);
315
+ const uniqueResources = new Map(resources.map((resource) => [resource.relativePath, resource]));
316
+ return [...uniqueResources.values()].map((resource) => copyBundledResource(resource, options));
275
317
  }
276
318
  function printCommandError(error) {
277
319
  process.stdout.write(`${error instanceof Error ? error.message : String(error)}\n`);
@@ -340,7 +382,10 @@ export function registerKataCommands(program) {
340
382
  .option("--force", "Overwrite an existing repository file", false)
341
383
  .action((opts) => {
342
384
  try {
343
- printCopyResult(ejectKata(opts.id, { dryRun: opts.dryRun, force: opts.force }), opts.dryRun);
385
+ const result = ejectKata(opts.id, { dryRun: opts.dryRun, force: opts.force });
386
+ for (const file of [result, ...result.companions]) {
387
+ printCopyResult(file, opts.dryRun);
388
+ }
344
389
  }
345
390
  catch (error) {
346
391
  printCommandError(error);
@@ -8,6 +8,7 @@ import { getProjectCatalogPath, loadConfig, specdojoRootDir, } from "../shared/s
8
8
  import { APPROACHES } from "../shared/agent-types.js";
9
9
  import { load } from "../shared/yaml.js";
10
10
  import { assertAuthorableKataId, authoredKataExists, authoringKind } from "../kata/authoring.js";
11
+ import { CATALOG_LESS_APPROACHES, resolveRegisterDeliverableTarget } from "./deliverable-target.js";
11
12
  import { resolveAuthoringSources } from "./authoring-sources.js";
12
13
  const MAINTENANCE_TARGET_KIND = {
13
14
  "rulebook-maintenance": "rulebook",
@@ -86,6 +87,10 @@ export function validateRegisterApproachTargets(opts) {
86
87
  throw new Error(`Approach "${approach}" requires the new kata id as the first --target`);
87
88
  }
88
89
  }
90
+ if ((opts.targetPath !== undefined || opts.targetRulebook !== undefined) &&
91
+ (!approach || !CATALOG_LESS_APPROACHES.includes(approach))) {
92
+ throw new Error("--target-path and --target-rulebook require a supported deliverable approach");
93
+ }
89
94
  if (sources.length > 0 && !authoringKind(approach)) {
90
95
  throw new Error("--source is only valid with a *-authoring approach");
91
96
  }
@@ -132,6 +137,15 @@ export function validateRegisterApproachTargets(opts) {
132
137
  }
133
138
  return;
134
139
  }
140
+ if (CATALOG_LESS_APPROACHES.includes(approach)) {
141
+ if (opts.catalogPath &&
142
+ !catalogDeliverableDocIds(opts.catalogPath, opts.repoRoot, opts.projectId).has(targetId) &&
143
+ !(opts.targetPath && opts.targetRulebook)) {
144
+ throw new Error(`Approach "${approach}" requires a deliverable document from the project catalog, but ${targetId} is not a catalog deliverable`);
145
+ }
146
+ resolveRegisterDeliverableTarget({ ...opts, approach, targetId });
147
+ return;
148
+ }
135
149
  if (!opts.catalogPath) {
136
150
  throw new Error(`Approach "${approach}" requires a deliverable target, but catalog_path is not configured for project ${opts.projectId}`);
137
151
  }
@@ -156,6 +170,8 @@ export function validateRegisterApproachTargetsForProject(opts) {
156
170
  ...(opts.targets !== undefined ? { targets: opts.targets } : {}),
157
171
  ...(opts.sources !== undefined ? { sources: opts.sources } : {}),
158
172
  project,
173
+ ...(opts.targetPath !== undefined ? { targetPath: opts.targetPath } : {}),
174
+ ...(opts.targetRulebook !== undefined ? { targetRulebook: opts.targetRulebook } : {}),
159
175
  ...(opts.validateTargetsWithoutApproach !== undefined
160
176
  ? { validateTargetsWithoutApproach: opts.validateTargetsWithoutApproach }
161
177
  : {}),
@@ -377,6 +377,8 @@ export function buildRegisterItemContent(opts) {
377
377
  ticket: "-",
378
378
  ...(opts.fields.approach ? { approach: opts.fields.approach } : {}),
379
379
  ...(opts.fields.targets ? { targets: opts.fields.targets } : {}),
380
+ ...(opts.fields.targetPath ? { targetPath: opts.fields.targetPath } : {}),
381
+ ...(opts.fields.targetRulebook ? { targetRulebook: opts.fields.targetRulebook } : {}),
380
382
  ...(opts.fields.sources ? { sources: opts.fields.sources } : {}),
381
383
  ...(opts.fields.derivedFrom ? { derivedFrom: opts.fields.derivedFrom } : {}),
382
384
  }));