specdojo 0.4.6 → 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 (67) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/catalog/document-target.js +75 -0
  3. package/dist/commands/agent.js +2 -80
  4. package/dist/exec/agent-config.js +28 -16
  5. package/dist/exec/agent-plan.js +108 -0
  6. package/dist/exec/commands.js +3 -3
  7. package/dist/exec/grade-checkpoint.js +12 -0
  8. package/dist/exec/plans-core.js +4 -65
  9. package/dist/exec/plans-generation.js +22 -5
  10. package/dist/exec/project.js +4 -1
  11. package/dist/exec/register.js +66 -5
  12. package/dist/exec/run/lifecycle-commands.js +2 -0
  13. package/dist/exec/run/register-resume.js +1 -0
  14. package/dist/exec/run/register-state.js +4 -1
  15. package/dist/exec/run/register-worktree.js +5 -1
  16. package/dist/exec/run/schedule-prepare.js +7 -1
  17. package/dist/exec/worktree-command.js +8 -1
  18. package/dist/exec/worktree-ops-merge.js +40 -1
  19. package/dist/grade/apply.js +7 -5
  20. package/dist/grade/command-inspect.js +2 -1
  21. package/dist/grade/command-run.js +39 -0
  22. package/dist/grade/grade.js +3 -1
  23. package/dist/grade/markdown.js +4 -4
  24. package/dist/grade/pipeline-state.js +8 -6
  25. package/dist/grade/plan.js +8 -6
  26. package/dist/grade/run.js +307 -0
  27. package/dist/grade/target-discovery.js +1 -1
  28. package/dist/grade/targets.js +44 -22
  29. package/dist/register/approach.js +16 -0
  30. package/dist/register/core.js +2 -0
  31. package/dist/register/create-commands.js +49 -1
  32. package/dist/register/deliverable-target.js +215 -0
  33. package/dist/register/events.js +4 -0
  34. package/dist/register/item.js +8 -0
  35. package/dist/review/grade.js +19 -17
  36. package/dist/shared/agent-plan.js +1 -0
  37. package/dist/shared/provider-scaffold.js +5 -3
  38. package/dist/specdojo.js +5 -1
  39. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +2 -2
  40. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +2 -2
  41. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +2 -2
  42. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +2 -2
  43. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +2 -2
  44. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +2 -2
  45. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +2 -2
  46. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +2 -2
  47. package/docs/ja/specdojo/exec-templates/xrp-template.md +2 -2
  48. package/docs/ja/specdojo/guides/exec-config-guide.md +44 -12
  49. package/docs/ja/specdojo/guides/exec-operation-guide.md +4 -0
  50. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +3 -1
  51. package/docs/ja/specdojo/guides/quick-start-guide.md +22 -2
  52. package/docs/ja/specdojo/guides/remote-host-development-guide.md +15 -1
  53. package/docs/ja/specdojo/guides/review-guide.md +2 -2
  54. package/docs/ja/specdojo/guides/ryu-guide.md +12 -0
  55. package/docs/ja/specdojo/references/command-reference.md +52 -27
  56. package/docs/ja/specdojo/references/specdojo-config-reference.md +29 -8
  57. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +28 -22
  58. package/docs/specdojo/schemas/v1/grade-pipeline-state.schema.yaml +1 -1
  59. package/docs/specdojo/schemas/v1/register-events.schema.yaml +2 -0
  60. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +33 -1
  61. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +16 -3
  62. package/package.json +1 -1
  63. package/templates/devcontainer/devcontainer.json +1 -0
  64. package/templates/init-agent-members.yaml +46 -3
  65. package/templates/opencode/README.md +118 -14
  66. package/templates/opencode/agents/specdojo-orchestrator.md +1 -1
  67. 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));
@@ -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
  }));
@@ -82,6 +82,8 @@ export function registerCreateCommands(reg, dependencies) {
82
82
  addCmd.option("--due <date>", "Due date (YYYY-MM-DD, -, or _TODO_)", "_TODO_");
83
83
  addCmd.option("--completed <datetime>", "Completion date-time (RFC 3339 with time zone, or -)", "-");
84
84
  addCmd.option("--conclusion <text>", "Conclusion or resolution summary", "-");
85
+ addCmd.option("--target-path <path>", "Repository-relative deliverable file path");
86
+ addCmd.option("--target-rulebook <doc-id>", "Deliverable rulebook id (new id for bootstrap)");
85
87
  addCmd.option("--approach <approach>", `Execution approach: ${APPROACHES.join(" | ")}`);
86
88
  addCmd.option("--target <doc-id>", "Target document id (repeatable; authoring accepts legacy exemplar targets after the first)", collectTarget);
87
89
  addCmd.option("--source <ref>", "Read-only exemplar for *-authoring (repeatable: doc id, path, or <repo>:<path>)", collectTarget);
@@ -129,6 +131,10 @@ export function registerCreateCommands(reg, dependencies) {
129
131
  validateRegisterApproachTargetsForProject({
130
132
  projectId: paths.projectId,
131
133
  ...(opts.approach !== undefined ? { approach: opts.approach } : {}),
134
+ ...(opts.targetPath !== undefined ? { targetPath: opts.targetPath.trim() } : {}),
135
+ ...(opts.targetRulebook !== undefined
136
+ ? { targetRulebook: opts.targetRulebook.trim() }
137
+ : {}),
132
138
  ...(rawTargets !== undefined ? { targets: rawTargets } : {}),
133
139
  ...(explicitSources !== undefined ? { sources: explicitSources } : {}),
134
140
  validateTargetsWithoutApproach: opts.target !== undefined || opts.source !== undefined,
@@ -147,6 +153,10 @@ export function registerCreateCommands(reg, dependencies) {
147
153
  conclusion: opts.conclusion,
148
154
  ...(opts.approach !== undefined ? { approach: opts.approach } : {}),
149
155
  ...(targets !== undefined ? { targets } : {}),
156
+ ...(opts.targetPath !== undefined ? { targetPath: opts.targetPath.trim() } : {}),
157
+ ...(opts.targetRulebook !== undefined
158
+ ? { targetRulebook: opts.targetRulebook.trim() }
159
+ : {}),
150
160
  ...(sources !== undefined ? { sources } : {}),
151
161
  };
152
162
  const templatePath = resolveSpecdojoTemplatePath(`pjr-${opts.type}-template.md`);
@@ -229,6 +239,8 @@ export function registerUpdateCommand(reg, dependencies) {
229
239
  updateCmd.option("--conclusion <text>", "Update conclusion or use - to remove it");
230
240
  updateCmd.option("--block-reason <text>", "Update the waiting reason or use - to remove it");
231
241
  updateCmd.option("--autopilot <approval>", "Night orchestrator approval: approved, or - to revoke");
242
+ updateCmd.option("--target-path <path>", "Replace deliverable path; use - to remove");
243
+ updateCmd.option("--target-rulebook <doc-id>", "Replace deliverable rulebook id; use - to remove");
232
244
  updateCmd.option("--approach <approach>", `Update execution approach (${APPROACHES.join(" | ")}; use - to remove)`);
233
245
  updateCmd.option("--target <doc-id>", "Replace target document ids (repeatable; legacy authoring exemplars may follow; use - to remove)", collectTarget);
234
246
  updateCmd.option("--source <ref>", "Replace read-only *-authoring exemplars (repeatable; use - to remove)", collectTarget);
@@ -256,6 +268,8 @@ export function registerUpdateCommand(reg, dependencies) {
256
268
  "approach",
257
269
  "target",
258
270
  "source",
271
+ "targetPath",
272
+ "targetRulebook",
259
273
  "from",
260
274
  "topic",
261
275
  ].some((key) => opts[key] !== undefined);
@@ -303,6 +317,16 @@ export function registerUpdateCommand(reg, dependencies) {
303
317
  : {
304
318
  autopilot: opts.autopilot === "-" ? REMOVE_REGISTER_ITEM_FIELD : "approved",
305
319
  };
320
+ const nextTargetPath = opts.targetPath === undefined
321
+ ? item.targetPath
322
+ : opts.targetPath.trim() === "-"
323
+ ? undefined
324
+ : opts.targetPath.trim();
325
+ const nextTargetRulebook = opts.targetRulebook === undefined
326
+ ? item.targetRulebook
327
+ : opts.targetRulebook.trim() === "-"
328
+ ? undefined
329
+ : opts.targetRulebook.trim();
306
330
  const nextApproach = opts.approach === undefined
307
331
  ? item.approach
308
332
  : opts.approach.trim() === "-"
@@ -341,9 +365,15 @@ export function registerUpdateCommand(reg, dependencies) {
341
365
  itemId: item.id,
342
366
  derivedFrom: nextDerivedFrom,
343
367
  });
344
- if (opts.approach !== undefined || opts.target !== undefined || opts.source !== undefined) {
368
+ if (opts.approach !== undefined ||
369
+ opts.target !== undefined ||
370
+ opts.source !== undefined ||
371
+ opts.targetPath !== undefined ||
372
+ opts.targetRulebook !== undefined) {
345
373
  validateRegisterApproachTargetsForProject({
346
374
  projectId: paths.projectId,
375
+ ...(nextTargetPath !== undefined ? { targetPath: nextTargetPath } : {}),
376
+ ...(nextTargetRulebook !== undefined ? { targetRulebook: nextTargetRulebook } : {}),
347
377
  ...(nextApproach !== undefined ? { approach: nextApproach } : {}),
348
378
  ...(nextTargets !== undefined ? { targets: nextTargets } : {}),
349
379
  ...(normalizedNextSources !== undefined ? { sources: normalizedNextSources } : {}),
@@ -354,6 +384,12 @@ export function registerUpdateCommand(reg, dependencies) {
354
384
  (authoring && opts.source !== undefined && (item.targets?.length ?? 0) > 1);
355
385
  const shouldUpdateSources = opts.source !== undefined || (authoring && providedLegacySources.length > 0);
356
386
  const approachTargetUpdates = {
387
+ ...(opts.targetPath !== undefined
388
+ ? { target_path: nextTargetPath ?? REMOVE_REGISTER_ITEM_FIELD }
389
+ : {}),
390
+ ...(opts.targetRulebook !== undefined
391
+ ? { target_rulebook: nextTargetRulebook ?? REMOVE_REGISTER_ITEM_FIELD }
392
+ : {}),
357
393
  ...(opts.difficulty !== undefined
358
394
  ? {
359
395
  difficulty: opts.difficulty === "-" ? REMOVE_REGISTER_ITEM_FIELD : opts.difficulty,
@@ -400,6 +436,18 @@ export function registerUpdateCommand(reg, dependencies) {
400
436
  else
401
437
  updated.autopilot = "approved";
402
438
  }
439
+ if (opts.targetPath !== undefined) {
440
+ if (nextTargetPath === undefined)
441
+ delete updated.targetPath;
442
+ else
443
+ updated.targetPath = nextTargetPath;
444
+ }
445
+ if (opts.targetRulebook !== undefined) {
446
+ if (nextTargetRulebook === undefined)
447
+ delete updated.targetRulebook;
448
+ else
449
+ updated.targetRulebook = nextTargetRulebook;
450
+ }
403
451
  if (opts.approach !== undefined) {
404
452
  if (nextApproach === undefined)
405
453
  delete updated.approach;