specdojo 0.9.1 → 0.9.2

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 (62) hide show
  1. package/.github/agents/specdojo-orchestrator.md +7 -0
  2. package/CHANGELOG.md +23 -0
  3. package/README.md +4 -4
  4. package/dist/commands/agent.js +15 -24
  5. package/dist/commands/init.js +8 -5
  6. package/dist/commands/orchestrator.js +6 -11
  7. package/dist/dashboard/timeline.js +2 -2
  8. package/dist/devcontainer/command.js +1 -1
  9. package/dist/devcontainer/scaffold.js +6 -5
  10. package/dist/exec/agent-config.js +4 -0
  11. package/dist/exec/commands.js +54 -4
  12. package/dist/exec/executor-outcome-checks.js +104 -0
  13. package/dist/exec/migrate-records.js +3 -1
  14. package/dist/exec/parent-validation.js +66 -15
  15. package/dist/exec/pipeline-state.js +16 -0
  16. package/dist/exec/register.js +4 -0
  17. package/dist/exec/run/agent-pipeline.js +44 -3
  18. package/dist/exec/run/register-command.js +9 -0
  19. package/dist/exec/run/register-core.js +2 -1
  20. package/dist/exec/run/register-resume.js +19 -2
  21. package/dist/exec/run/register-worktree.js +2 -1
  22. package/dist/exec/run/resume-notes.js +50 -0
  23. package/dist/exec/run/shared.js +5 -0
  24. package/dist/exec/task-repos.js +6 -0
  25. package/dist/exec/validation-process-group.js +98 -0
  26. package/dist/grade/command-inspect.js +3 -1
  27. package/dist/grade/command-run.js +1 -0
  28. package/dist/grade/command-shared.js +10 -0
  29. package/dist/grade/run.js +58 -6
  30. package/dist/grade/targets.js +106 -0
  31. package/dist/register/create-commands.js +30 -3
  32. package/dist/register/events.js +1 -1
  33. package/dist/register/item.js +1 -0
  34. package/dist/register/maintenance-commands.js +3 -1
  35. package/dist/register/renumber.js +14 -1
  36. package/dist/register/section.js +114 -0
  37. package/dist/register/update.js +18 -0
  38. package/dist/shared/antigravity-block.js +24 -0
  39. package/dist/shared/plan-conventions.js +11 -0
  40. package/dist/shared/provider-scaffold.js +4 -0
  41. package/dist/shared/specdojo-config.js +5 -4
  42. package/dist/shared/where-alias.js +2 -2
  43. package/docs/ja/specdojo/guides/exec-config-guide.md +15 -12
  44. package/docs/ja/specdojo/guides/exec-operation-guide.md +21 -7
  45. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +5 -3
  46. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  47. package/docs/ja/specdojo/guides/register-operation-guide.md +1 -1
  48. package/docs/ja/specdojo/guides/timeline-design-guide.md +1 -1
  49. package/docs/ja/specdojo/references/command-reference.md +76 -51
  50. package/docs/ja/specdojo/rulebooks/dec-rulebook.md +10 -42
  51. package/docs/ja/specdojo/rulebooks/ntp-rulebook.md +10 -50
  52. package/docs/ja/specdojo/samples/dec-sample.md +3 -30
  53. package/docs/ja/specdojo/samples/dss-sample.md +12 -12
  54. package/docs/ja/specdojo/samples/ntp-sample.md +3 -30
  55. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +18 -0
  56. package/docs/specdojo/schemas/v1/register-events.schema.yaml +1 -0
  57. package/package.json +1 -1
  58. package/templates/antigravity/orchestrator.md +7 -0
  59. package/templates/claude/agents/specdojo-orchestrator.md +7 -0
  60. package/templates/codex/agents/specdojo-orchestrator.toml +7 -0
  61. package/templates/codex/orchestrator.md +7 -0
  62. package/templates/opencode/agents/specdojo-orchestrator.md +7 -0
package/dist/grade/run.js CHANGED
@@ -8,7 +8,7 @@ import { readGradePipelineState, recordGradePipelineStage } from "./pipeline-sta
8
8
  import { writeGradePlans } from "./plan.js";
9
9
  import { gradeContentHash, gradeFindingCount, readGradeResultForDocument } from "./result.js";
10
10
  import { discoverGradeTargets } from "./target-discovery.js";
11
- import { loadViewpoints, repoRelativePath, resolveDeliverableDoneCriteria, resolveGradeSourceHashes, resolveProject, resolveSafeMarkdownPath, resolveSafeRepositoryPath, } from "./targets.js";
11
+ import { loadViewpoints, repoRelativePath, resolveDeliverableDoneCriteria, resolveGradeSourceHashes, resolveKataBatchTargets, resolveProject, resolveSafeMarkdownPath, resolveSafeRepositoryPath, } from "./targets.js";
12
12
  /**
13
13
  * A run that stopped with documents left ungraded. Callers such as scheduled jobs tell a
14
14
  * partial run (2) from a run without any completed document (1) and from a rate limit (75),
@@ -88,6 +88,14 @@ async function runGradeUnlocked(opts, runtime) {
88
88
  throw new Error("Invalid --kind");
89
89
  if (opts.target !== "kata" && opts.kind !== undefined)
90
90
  throw new Error("--kind is only valid for kata");
91
+ if (opts.target !== "kata" && (opts.kata?.length ?? 0) > 0)
92
+ throw new Error("--kata is only valid for kata");
93
+ if (opts.paths?.length && (opts.kata?.length ?? 0) > 0)
94
+ throw new Error("Use either --path or --kata");
95
+ let documentsByKata;
96
+ if (opts.kata && opts.kata.length > 0) {
97
+ documentsByKata = resolveKataBatchTargets(opts.kata, specdojoRootDir()).documentsByKata;
98
+ }
91
99
  const maxFailures = opts.maxStageFailures ?? 3;
92
100
  if (!Number.isSafeInteger(maxFailures) || maxFailures < 1)
93
101
  throw new Error("Invalid --max-stage-failures");
@@ -136,11 +144,18 @@ async function runGradeUnlocked(opts, runtime) {
136
144
  }
137
145
  }
138
146
  else {
139
- let paths = discoverGradeTargets({ ...opts, project: projectId });
140
- if (opts.target === "kata" && kind !== "all")
141
- paths = paths.filter((path) => repoRelativePath(path).split("/").includes(`${kind}s`));
142
- if (opts.limit !== undefined)
143
- paths = paths.slice(0, opts.limit);
147
+ let paths;
148
+ if (documentsByKata) {
149
+ const flattened = Array.from(documentsByKata.values()).flat();
150
+ paths = Array.from(new Set(flattened));
151
+ }
152
+ else {
153
+ paths = discoverGradeTargets({ ...opts, project: projectId });
154
+ if (opts.target === "kata" && kind !== "all")
155
+ paths = paths.filter((path) => repoRelativePath(path).split("/").includes(`${kind}s`));
156
+ if (opts.limit !== undefined)
157
+ paths = paths.slice(0, opts.limit);
158
+ }
144
159
  state = {
145
160
  version: 1,
146
161
  request,
@@ -211,6 +226,8 @@ async function runGradeUnlocked(opts, runtime) {
211
226
  }
212
227
  writeState(statePath, state);
213
228
  const failures = [];
229
+ let rateLimited = false;
230
+ let rateLimitedActor;
214
231
  for (const [index, document] of state.documents.entries()) {
215
232
  const reference = references.get(document.path);
216
233
  if (document.status === "complete") {
@@ -282,6 +299,11 @@ async function runGradeUnlocked(opts, runtime) {
282
299
  // A rate limit is not a document failure: keep the stage retryable in this run id.
283
300
  document.status = "pending";
284
301
  writeState(statePath, state);
302
+ if (documentsByKata) {
303
+ rateLimited = true;
304
+ rateLimitedActor = actualActor;
305
+ continue;
306
+ }
285
307
  const unstarted = state.documents
286
308
  .filter((item) => item.status !== "complete")
287
309
  .map((item) => item.path);
@@ -375,6 +397,36 @@ async function runGradeUnlocked(opts, runtime) {
375
397
  failures.push(`${document.path}: ${document.error}`);
376
398
  }
377
399
  }
400
+ if (documentsByKata && documentsByKata.size > 0) {
401
+ process.stdout.write("kata results:\n");
402
+ for (const [name, docs] of documentsByKata) {
403
+ const statuses = docs.map((docPath) => {
404
+ const repoPath = repoRelativePath(docPath);
405
+ const doc = state.documents.find((item) => item.path === repoPath);
406
+ return doc?.status ?? "pending";
407
+ });
408
+ let verdictJa = "未実行";
409
+ let verdictEn = "pending";
410
+ if (statuses.every((s) => s === "complete")) {
411
+ verdictJa = "完了";
412
+ verdictEn = "complete";
413
+ }
414
+ else if (statuses.some((s) => s === "failed")) {
415
+ verdictJa = "失敗";
416
+ verdictEn = "failed";
417
+ }
418
+ process.stdout.write(` ${name}: ${verdictJa} (${verdictEn})\n`);
419
+ }
420
+ }
421
+ if (rateLimited) {
422
+ const unstarted = state.documents
423
+ .filter((item) => item.status !== "complete")
424
+ .map((item) => item.path);
425
+ throw new GradeRunIncompleteError([
426
+ `grade run stopped by rate limit: agent=${rateLimitedActor ?? actor} run_id=${opts.runId}; rerun with the same --run-id to resume`,
427
+ ...unstarted.map((path) => `grade run remaining: ${path}`),
428
+ ].join("\n"), GRADE_RUN_RATE_LIMIT_EXIT_CODE);
429
+ }
378
430
  if (failures.length) {
379
431
  const completed = state.documents.filter((document) => document.status === "complete").length;
380
432
  throw new GradeRunIncompleteError(`grade run incomplete: completed=${completed} failed=${failures.length} run_id=${opts.runId}\n${failures.join("\n")}`, completed > 0 ? GRADE_RUN_PARTIAL_EXIT_CODE : 1);
@@ -7,6 +7,8 @@ import { collectResolvedDeliverables, loadCatalogDocs } from "../catalog/build.j
7
7
  import { isTrashedPath, resolveBasePath } from "../catalog/paths.js";
8
8
  import { listFilesRecursive } from "../shared/fs.js";
9
9
  import { gradeContentHash } from "./result.js";
10
+ import { readSpecdojoNamespace } from "../docs/frontmatter-namespace.js";
11
+ import { resolveAuthoredKataPathIfExists } from "../kata/authoring.js";
10
12
  import { GRADE_TARGETS, KATA_DIRS, KATA_REFERENCE_EXTENSIONS, KATA_REFERENCE_FIELDS, gradedViewpoints, isRecord, parseGradeDocument, } from "./core.js";
11
13
  import { commonViewpointsPath, resolveViewpointsDoc } from "../review/plan.js";
12
14
  import { assertValidActor, getProjectCatalogPath, getProjectMembersPath, getProjectRolesPath, getProjectSchedulePath, getProjectViewpointsPath, loadConfig, resolveAgentMember, resolveRepoRoot, specdojoRootDir, } from "../shared/specdojo-config.js";
@@ -456,3 +458,107 @@ export function resolveGradeSourceHashes(opts, rootDir = specdojoRootDir()) {
456
458
  export function sourceHashesChanged(stored, current) {
457
459
  return Object.entries(current).some(([key, hash]) => stored?.[key] !== hash);
458
460
  }
461
+ /** Resolve rulebook and sample documents for a single kata name or prefix. */
462
+ export function resolveKataDocuments(kataName, rootDir = specdojoRootDir()) {
463
+ const normalized = kataName.trim().replace(/-rulebook(\.md)?$/, "");
464
+ if (!normalized)
465
+ return [];
466
+ const found = [];
467
+ // 1. rulebook
468
+ const rulebookCandidate = join(rootDir, `docs/ja/specdojo/rulebooks/${normalized}-rulebook.md`);
469
+ if (existsSync(rulebookCandidate)) {
470
+ found.push(repoRelativePath(rulebookCandidate));
471
+ }
472
+ else {
473
+ const authored = resolveAuthoredKataPathIfExists(`${normalized}-rulebook`, "rulebook", "md", rootDir);
474
+ if (authored && existsSync(authored.absolutePath)) {
475
+ found.push(repoRelativePath(authored.absolutePath));
476
+ }
477
+ }
478
+ // 2. sample
479
+ let foundSample = false;
480
+ if (found.length > 0) {
481
+ const rulebookPath = resolve(rootDir, found[0]);
482
+ try {
483
+ const content = readFileSync(rulebookPath, "utf8");
484
+ const fm = readSpecdojoNamespace(content);
485
+ if (fm.sample && typeof fm.sample === "string") {
486
+ if (fm.sample !== "not-needed" && fm.sample !== "none" && fm.sample !== "undecided") {
487
+ const sampleId = fm.sample;
488
+ const extensions = ["md", "yaml", "yml", "json"];
489
+ for (const ext of extensions) {
490
+ const authored = resolveAuthoredKataPathIfExists(sampleId, "sample", ext, rootDir);
491
+ if (authored && existsSync(authored.absolutePath)) {
492
+ found.push(repoRelativePath(authored.absolutePath));
493
+ foundSample = true;
494
+ break;
495
+ }
496
+ }
497
+ }
498
+ else {
499
+ // Explicitly not-needed or none
500
+ foundSample = true;
501
+ }
502
+ }
503
+ }
504
+ catch {
505
+ // Ignore rulebook read error and fall through to filename lookup
506
+ }
507
+ }
508
+ if (!foundSample) {
509
+ const sampleExtensions = ["md", "yaml", "yml", "json"];
510
+ for (const ext of sampleExtensions) {
511
+ const sampleCandidate = join(rootDir, `docs/ja/specdojo/samples/${normalized}-sample.${ext}`);
512
+ if (existsSync(sampleCandidate)) {
513
+ found.push(repoRelativePath(sampleCandidate));
514
+ break;
515
+ }
516
+ }
517
+ }
518
+ // Fallback for sample-only kata without rulebook
519
+ if (found.length === 0) {
520
+ const sampleExtensions = ["md", "yaml", "yml", "json"];
521
+ for (const ext of sampleExtensions) {
522
+ const sampleCandidate = join(rootDir, `docs/ja/specdojo/samples/${normalized}-sample.${ext}`);
523
+ if (existsSync(sampleCandidate)) {
524
+ found.push(repoRelativePath(sampleCandidate));
525
+ break;
526
+ }
527
+ }
528
+ }
529
+ return found;
530
+ }
531
+ /**
532
+ * Validate and resolve target documents for multiple kata names.
533
+ * Unknown kata names cause an error before execution.
534
+ */
535
+ export function resolveKataBatchTargets(kataNames, rootDir = specdojoRootDir()) {
536
+ const documentsByKata = new Map();
537
+ const unknown = [];
538
+ for (const rawName of kataNames) {
539
+ const name = rawName.trim();
540
+ if (!name)
541
+ continue;
542
+ if (documentsByKata.has(name))
543
+ continue;
544
+ const docs = resolveKataDocuments(name, rootDir);
545
+ if (docs.length === 0) {
546
+ unknown.push(name);
547
+ }
548
+ else {
549
+ documentsByKata.set(name, docs);
550
+ }
551
+ }
552
+ if (unknown.length > 0) {
553
+ throw new Error(`Unknown kata: ${unknown.join(", ")}`);
554
+ }
555
+ const allDocuments = [];
556
+ for (const docs of documentsByKata.values()) {
557
+ for (const doc of docs) {
558
+ if (!allDocuments.includes(doc)) {
559
+ allDocuments.push(doc);
560
+ }
561
+ }
562
+ }
563
+ return { documentsByKata, allDocuments };
564
+ }
@@ -1,4 +1,5 @@
1
1
  import { normalizeRegisterInput } from "./input.js";
2
+ import { validateSectionFile } from "./section.js";
2
3
  import { existsSync, mkdirSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { inlineCodeAnglePlaceholders } from "../shared/text.js";
@@ -287,6 +288,8 @@ export function registerUpdateCommand(reg, dependencies) {
287
288
  updateCmd.option("--commit-type <type>", `Update Conventional Commits type (${VALID_COMMIT_TYPES.join(" | ")}; use - to remove)`);
288
289
  updateCmd.option("--commit-scope <scope>", "Update Conventional Commits scope; use - to remove");
289
290
  updateCmd.option("--topic <topic>", "Update the topic slug in the ticket filename and document ID");
291
+ updateCmd.option("--section <name>", "Name of the ticket section to replace (without heading numbers, e.g., '完了条件')");
292
+ updateCmd.option("--section-file <path>", "Path to a markdown file containing the new section body");
290
293
  updateCmd.option("--by <actor>", "Actor recorded in the append-only register event");
291
294
  updateCmd.option("--reason <text>", "Reason recorded in the append-only register event");
292
295
  updateCmd.option("--dry-run", "Print change without writing", false);
@@ -320,9 +323,11 @@ export function registerUpdateCommand(reg, dependencies) {
320
323
  "commitType",
321
324
  "commitScope",
322
325
  "topic",
326
+ "section",
327
+ "sectionFile",
323
328
  ].some((key) => opts[key] !== undefined);
324
329
  if (!hasUpdates) {
325
- throw new Error("At least one field option must be specified (--track, --domain, --title, --description, --priority, --difficulty, --owner, --due, --start-on, --conclusion, --block-reason, --autopilot, --approach, --target, --source, --input, --from, --depends-on, --commit-type, --commit-scope, --topic)");
330
+ throw new Error("At least one field option must be specified (--track, --domain, --title, --description, --priority, --difficulty, --owner, --due, --start-on, --conclusion, --block-reason, --autopilot, --approach, --target, --source, --input, --from, --depends-on, --commit-type, --commit-scope, --topic, --section, --section-file)");
326
331
  }
327
332
  if (opts.priority !== undefined &&
328
333
  !VALID_PRIORITIES.includes(opts.priority)) {
@@ -349,6 +354,25 @@ export function registerUpdateCommand(reg, dependencies) {
349
354
  if (topic !== undefined && !registerTopicPattern.test(topic)) {
350
355
  throw new Error(`Invalid topic: "${topic}". Must use lowercase letters, numbers, and single hyphens`);
351
356
  }
357
+ if ((opts.section !== undefined) !== (opts.sectionFile !== undefined)) {
358
+ throw new Error("--section and --section-file must be specified together");
359
+ }
360
+ const sectionName = opts.section?.trim();
361
+ if (opts.section !== undefined && sectionName === "") {
362
+ throw new Error("Section name must not be empty");
363
+ }
364
+ const sectionFilePath = opts.sectionFile?.trim();
365
+ if (opts.sectionFile !== undefined && sectionFilePath === "") {
366
+ throw new Error("Section file path must not be empty");
367
+ }
368
+ let sectionUpdate;
369
+ if (sectionName !== undefined && sectionFilePath !== undefined) {
370
+ const sectionContent = validateSectionFile(sectionFilePath);
371
+ sectionUpdate = {
372
+ name: sectionName,
373
+ content: sectionContent,
374
+ };
375
+ }
352
376
  const blockReason = opts.blockReason?.trim();
353
377
  if (blockReason !== undefined && blockReason === "") {
354
378
  throw new Error("Block reason must not be empty; use - to remove it");
@@ -607,6 +631,7 @@ export function registerUpdateCommand(reg, dependencies) {
607
631
  : {}),
608
632
  ...(opts.title !== undefined ? { title: opts.title } : {}),
609
633
  ...(opts.description !== undefined ? { description: opts.description } : {}),
634
+ ...(sectionUpdate !== undefined ? { section: sectionUpdate } : {}),
610
635
  actor: registerEventActor(opts),
611
636
  reason: opts.reason?.trim() || "",
612
637
  });
@@ -619,9 +644,10 @@ export function registerUpdateCommand(reg, dependencies) {
619
644
  updated,
620
645
  ...(inputs !== undefined ? { inputs } : {}),
621
646
  dryRun: opts.dryRun,
622
- action: "fields updated",
647
+ action: sectionUpdate ? `section "${sectionUpdate.name}" updated` : "fields updated",
623
648
  ...(opts.title !== undefined ? { title: opts.title } : {}),
624
649
  ...(opts.description !== undefined ? { description: opts.description } : {}),
650
+ ...(sectionUpdate !== undefined ? { section: sectionUpdate } : {}),
625
651
  ...(blockReasonUpdates || autopilotUpdates || Object.keys(approachTargetUpdates).length > 0
626
652
  ? {
627
653
  fieldUpdates: {
@@ -633,7 +659,8 @@ export function registerUpdateCommand(reg, dependencies) {
633
659
  : {}),
634
660
  eventAction: "update",
635
661
  eventActor: registerEventActor(opts),
636
- eventReason: opts.reason?.trim() || "fields updated",
662
+ eventReason: opts.reason?.trim() ||
663
+ (sectionUpdate ? `section "${sectionUpdate.name}" updated` : "fields updated"),
637
664
  });
638
665
  return { id: item.id, title: updated.title };
639
666
  });
@@ -196,7 +196,7 @@ export function validateRegisterEventShape(value, source) {
196
196
  return;
197
197
  }
198
198
  if (typeof change.field !== "string" ||
199
- ![...REGISTER_EVENT_FIELDS, "id"].includes(change.field)) {
199
+ ![...REGISTER_EVENT_FIELDS, "id", "section"].includes(change.field)) {
200
200
  error(`changes[${index}].field is invalid`);
201
201
  }
202
202
  if (typeof change.from !== "string")
@@ -331,6 +331,7 @@ export function loadRegisterItemDocs(projectRegisterPath) {
331
331
  filename: entry.name,
332
332
  item: parsed.item,
333
333
  hasRegisterFields: parsed.hasRegisterFields,
334
+ blockReason: parsed.blockReason,
334
335
  });
335
336
  }
336
337
  return docs.sort((a, b) => compareRegisterItemIds(a.id, b.id));
@@ -1,3 +1,4 @@
1
+ import { warnDeprecated } from "../shared/deprecation.js";
1
2
  import { existsSync, writeFileSync } from "node:fs";
2
3
  import { collectRegisterHistoryEvents, formatRegisterHistoryEvents } from "./history.js";
3
4
  import { createGitTimestampResolver, planRegisterTimestampMigration, summarizeTimestampMigration, } from "./migrate-timestamps.js";
@@ -12,11 +13,12 @@ export function registerMaintenanceCommands(reg, dependencies) {
12
13
  // --- migrate ---
13
14
  const migrateCmd = reg
14
15
  .command("migrate")
15
- .description("Migrate legacy register data (index rows, dates, and embedded register events)");
16
+ .description("Deprecated: legacy register migration is no longer needed; individual ticket files and external events are standard (will be removed in 0.10.0)");
16
17
  addProjectOption(migrateCmd);
17
18
  migrateCmd.option("--dry-run", "Validate and print the migration summary without writing", false);
18
19
  migrateCmd.action((opts) => {
19
20
  try {
21
+ warnDeprecated("register migrate", "Legacy register migration is no longer needed as individual ticket files and external events are standard. This command will be removed in 0.10.0.");
20
22
  const paths = resolveRegisterPaths(opts);
21
23
  const plan = planRegisterMigration(paths);
22
24
  const summary = `items=${plan.sourceCount}, create=${plan.createdCount}, update=${plan.updatedCount}, ` +
@@ -8,6 +8,7 @@ import { applyRegisterItemFields, PJR_ID_RE, readRegisterItemContent, readSpecdo
8
8
  import { specdojoRootDir } from "../shared/specdojo-config.js";
9
9
  import { escapeRegExp } from "../shared/text.js";
10
10
  import { loadItemForUpdate } from "./update.js";
11
+ import { replaceTicketSection } from "./section.js";
11
12
  import { findRegisterItem, loadRegisterItems, writeDerivedViews } from "./views.js";
12
13
  // ================================
13
14
  // Renumber (duplicate ID recovery)
@@ -164,6 +165,12 @@ export function retopicPjrItem(opts) {
164
165
  const ticketWrite = plan.writes.find((write) => write.path === plan.ticketRename.to);
165
166
  if (!ticketWrite)
166
167
  throw new Error(`Retopiced ticket content not found: ${plan.ticketRename.to}`);
168
+ let sectionChanged = false;
169
+ if (opts.section !== undefined) {
170
+ const sectionResult = replaceTicketSection(ticketWrite.content, opts.section.name, opts.section.content);
171
+ ticketWrite.content = sectionResult.content;
172
+ sectionChanged = sectionResult.changed;
173
+ }
167
174
  if (opts.title !== undefined)
168
175
  ticketWrite.content = setRegisterItemTitle(ticketWrite.content, opts.title);
169
176
  if (opts.description !== undefined) {
@@ -185,6 +192,12 @@ export function retopicPjrItem(opts) {
185
192
  return;
186
193
  }
187
194
  const beforeContent = readFileSync(plan.ticketRename.from, "utf8");
195
+ const extraChanges = [
196
+ { field: "id", from: plan.fromDocId, to: plan.toDocId },
197
+ ...(opts.section !== undefined && sectionChanged
198
+ ? [{ field: "section", from: "", to: opts.section.name }]
199
+ : []),
200
+ ];
188
201
  const event = buildRegisterEvent({
189
202
  beforeContent,
190
203
  afterContent: ticketWrite.content,
@@ -193,7 +206,7 @@ export function retopicPjrItem(opts) {
193
206
  action: "update",
194
207
  actor: opts.actor?.trim() || "manual",
195
208
  reason: opts.reason?.trim() || `topic changed from ${plan.fromTopic} to ${opts.topic}`,
196
- extraChanges: [{ field: "id", from: plan.fromDocId, to: plan.toDocId }],
209
+ extraChanges,
197
210
  });
198
211
  if (!event)
199
212
  throw new Error(`Failed to build topic update event for ${opts.id}`);
@@ -0,0 +1,114 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { unified } from "unified";
3
+ import remarkParse from "remark-parse";
4
+ function isHeadingNode(node) {
5
+ return (node.type === "heading" &&
6
+ node.position?.start.offset !== undefined &&
7
+ node.position?.end.offset !== undefined);
8
+ }
9
+ function hasHeadingNode(node) {
10
+ if (node.type === "heading") {
11
+ return true;
12
+ }
13
+ if ("children" in node && Array.isArray(node.children)) {
14
+ return node.children.some(hasHeadingNode);
15
+ }
16
+ return false;
17
+ }
18
+ function headingTitle(body, node) {
19
+ return body
20
+ .slice(node.position.start.offset, node.position.end.offset)
21
+ .replace(/^#+\s+/, "")
22
+ .replace(/\s+#+\s*$/, "")
23
+ .trim();
24
+ }
25
+ /**
26
+ * 見出し文字列から先頭の章番号(例: "1. ", "3.1. ", "4 ")を除いた章名を返す。
27
+ */
28
+ export function stripSectionNumber(headingText) {
29
+ return headingText.replace(/^\d+(?:\.\d+)*\.?\s*/, "").trim();
30
+ }
31
+ /**
32
+ * 差し替え用ファイルを検証し、その本文を返す。
33
+ * ファイルが存在しない・読めない場合や、中身に Markdown 見出しが含まれる場合はエラーを投げる。
34
+ */
35
+ export function validateSectionFile(filePath) {
36
+ if (!existsSync(filePath)) {
37
+ throw new Error(`Cannot read section file: ${filePath}`);
38
+ }
39
+ let fileContent;
40
+ try {
41
+ fileContent = readFileSync(filePath, "utf8");
42
+ }
43
+ catch (error) {
44
+ throw new Error(`Cannot read section file: ${filePath}`, { cause: error });
45
+ }
46
+ const tree = unified().use(remarkParse).parse(fileContent);
47
+ if (hasHeadingNode(tree)) {
48
+ throw new Error(`Section file must not contain markdown headings: ${filePath}`);
49
+ }
50
+ return fileContent;
51
+ }
52
+ /**
53
+ * 個票 Markdown から指定された章の本文を差し替える。
54
+ * 見出し行は残し、次の同じ深さ(または浅い)見出しまでの本文だけを置き換える。
55
+ */
56
+ export function replaceTicketSection(content, sectionName, newBody) {
57
+ const prefix = content.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/)?.[0] ?? "";
58
+ const body = content.slice(prefix.length);
59
+ const targetName = sectionName.trim();
60
+ if (targetName === "") {
61
+ throw new Error("Section name must not be empty");
62
+ }
63
+ const tree = unified().use(remarkParse).parse(body);
64
+ const nodes = tree.children;
65
+ // まず H2 見出し(個票の章の標準)から探す
66
+ let headingIndex = nodes.findIndex((node) => isHeadingNode(node) &&
67
+ node.depth === 2 &&
68
+ stripSectionNumber(headingTitle(body, node)) === targetName);
69
+ // H2 にない場合は任意の見出しから探す
70
+ if (headingIndex < 0) {
71
+ headingIndex = nodes.findIndex((node) => isHeadingNode(node) && stripSectionNumber(headingTitle(body, node)) === targetName);
72
+ }
73
+ if (headingIndex < 0) {
74
+ throw new Error(`Section "${targetName}" not found in ticket`);
75
+ }
76
+ const targetHeading = nodes[headingIndex];
77
+ const targetDepth = targetHeading.depth;
78
+ // 次の同じ深さ(またはそれより浅い)見出しを探す
79
+ const nextHeadingRelativeIndex = nodes
80
+ .slice(headingIndex + 1)
81
+ .findIndex((node) => isHeadingNode(node) && node.depth <= targetDepth);
82
+ const nextHeading = nextHeadingRelativeIndex >= 0
83
+ ? nodes[headingIndex + 1 + nextHeadingRelativeIndex]
84
+ : undefined;
85
+ const bodyStartOffset = targetHeading.position.end.offset;
86
+ const bodyEndOffset = nextHeading ? nextHeading.position.start.offset : body.length;
87
+ const beforeBody = body.slice(bodyStartOffset, bodyEndOffset).trim();
88
+ const trimmedNewBody = newBody.trim();
89
+ const changed = beforeBody !== trimmedNewBody;
90
+ const head = body.slice(0, bodyStartOffset);
91
+ const tail = nextHeading ? body.slice(bodyEndOffset) : "";
92
+ let updatedBody;
93
+ if (trimmedNewBody.length > 0) {
94
+ if (tail.length > 0) {
95
+ updatedBody = `${head.trimEnd()}\n\n${trimmedNewBody}\n\n${tail.trimStart()}`;
96
+ }
97
+ else {
98
+ updatedBody = `${head.trimEnd()}\n\n${trimmedNewBody}\n`;
99
+ }
100
+ }
101
+ else {
102
+ if (tail.length > 0) {
103
+ updatedBody = `${head.trimEnd()}\n\n${tail.trimStart()}`;
104
+ }
105
+ else {
106
+ updatedBody = `${head.trimEnd()}\n`;
107
+ }
108
+ }
109
+ return {
110
+ content: `${prefix}${updatedBody}`,
111
+ changed,
112
+ beforeBody,
113
+ };
114
+ }
@@ -1,4 +1,5 @@
1
1
  import { setRegisterInput } from "./input.js";
2
+ import { replaceTicketSection } from "./section.js";
2
3
  import { existsSync, readFileSync } from "node:fs";
3
4
  import { basename, join } from "node:path";
4
5
  import { atomicWriteFile, prepareRegisterEventFile } from "./core.js";
@@ -55,6 +56,10 @@ export function applyItemUpdate(opts) {
55
56
  ...opts.fieldUpdates,
56
57
  };
57
58
  if (opts.dryRun) {
59
+ if (opts.section !== undefined) {
60
+ // 通常実行と同じく、個票に無い章の名前はエラーにする(書き込みはしない)。
61
+ replaceTicketSection(readFileSync(ticketPath, "utf8"), opts.section.name, opts.section.content);
62
+ }
58
63
  const lines = [`Would update ${ticketPath} (${opts.updated.id} ${label}):`];
59
64
  if (opts.title !== undefined)
60
65
  lines.push(` title: ${opts.title}`);
@@ -63,12 +68,21 @@ export function applyItemUpdate(opts) {
63
68
  if (opts.inputs !== undefined) {
64
69
  lines.push(` input: ${opts.inputs.length ? JSON.stringify(opts.inputs) : "-"}`);
65
70
  }
71
+ if (opts.section !== undefined) {
72
+ lines.push(` section: ${opts.section.name}`);
73
+ }
66
74
  lines.push(formatRegisterItemFields(updates));
67
75
  process.stdout.write(`${lines.join("\n")}\n`);
68
76
  return;
69
77
  }
70
78
  const beforeContent = readFileSync(ticketPath, "utf8");
71
79
  let content = beforeContent;
80
+ let sectionChanged = false;
81
+ if (opts.section !== undefined) {
82
+ const sectionResult = replaceTicketSection(content, opts.section.name, opts.section.content);
83
+ content = sectionResult.content;
84
+ sectionChanged = sectionResult.changed;
85
+ }
72
86
  if (opts.title !== undefined)
73
87
  content = setRegisterItemTitle(content, opts.title);
74
88
  if (opts.description !== undefined) {
@@ -77,6 +91,9 @@ export function applyItemUpdate(opts) {
77
91
  if (opts.inputs !== undefined)
78
92
  content = setRegisterInput(content, opts.inputs);
79
93
  content = applyRegisterItemFields(content, updates);
94
+ const extraChanges = opts.section !== undefined && sectionChanged
95
+ ? [{ field: "section", from: "", to: opts.section.name }]
96
+ : undefined;
80
97
  const event = buildRegisterEvent({
81
98
  beforeContent,
82
99
  afterContent: content,
@@ -85,6 +102,7 @@ export function applyItemUpdate(opts) {
85
102
  action: opts.eventAction,
86
103
  actor: opts.eventActor,
87
104
  reason: opts.eventReason,
105
+ ...(extraChanges ? { extraChanges } : {}),
88
106
  });
89
107
  if (!event) {
90
108
  process.stdout.write(`Unchanged: ${ticketPath} (${opts.updated.id})\n`);
@@ -0,0 +1,24 @@
1
+ // Since 0.9.2 SpecDojo never launches Antigravity (agy). On consumer plans, the Antigravity FAQ
2
+ // excludes launching agy from third-party agents or applications and the Additional Terms
3
+ // (Section 6) treat it as a breach. The block is unconditional: there is intentionally no
4
+ // setting or environment variable that lifts it (PJR-5V0T, PJR-NJE4).
5
+ export const BLOCKED_ANTIGRAVITY_PROVIDER = "antigravity";
6
+ export const ANTIGRAVITY_BLOCKED_MESSAGE = "SpecDojo 0.9.2 and later do not launch Antigravity (agy). " +
7
+ "On consumer plans, the Antigravity FAQ does not cover launching agy from third-party agents or applications, " +
8
+ "and the Antigravity Additional Terms (Section 6) treat it as a breach of contract. " +
9
+ "See https://antigravity.google/docs/faq and https://antigravity.google/terms. " +
10
+ "Set disabled: true on (or remove) the agy members in .specdojo/agent-members.yaml and use another provider.";
11
+ export class AntigravityBlockedError extends Error {
12
+ constructor(context) {
13
+ super(`${context}: ${ANTIGRAVITY_BLOCKED_MESSAGE}`);
14
+ this.name = "AntigravityBlockedError";
15
+ }
16
+ }
17
+ export function isBlockedProvider(provider) {
18
+ return provider?.trim() === BLOCKED_ANTIGRAVITY_PROVIDER;
19
+ }
20
+ /** Throws before any agent process is spawned when the provider is Antigravity. */
21
+ export function assertProviderLaunchAllowed(provider, context) {
22
+ if (isBlockedProvider(provider))
23
+ throw new AntigravityBlockedError(context);
24
+ }
@@ -117,6 +117,17 @@ export function withPlanConventionsFiles(paths) {
117
117
  ])),
118
118
  ];
119
119
  }
120
+ /**
121
+ * Insert a runner-written section before the conventions reference, which must stay the final
122
+ * paragraph for expansion and checkpointing. Plans without a reference get the section appended.
123
+ */
124
+ export function insertBeforePlanConventions(plan, section) {
125
+ const reference = conventionsReference(plan);
126
+ const offset = reference?.start ?? plan.length;
127
+ const head = plan.slice(0, offset).trimEnd();
128
+ const body = `${section.trim()}\n`;
129
+ return reference ? `${head}\n\n${body}\n${plan.slice(offset)}` : `${head}\n\n${body}`;
130
+ }
120
131
  export function rebasePlanConventions(plan, from, to) {
121
132
  const [path] = planConventionsFiles(plan, dirname(from));
122
133
  const reference = conventionsReference(plan);
@@ -2,6 +2,7 @@ import { existsSync } from "node:fs";
2
2
  import { copyFile, mkdir, readdir, readFile, writeFile } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import path from "node:path";
5
+ import { assertProviderLaunchAllowed } from "./antigravity-block.js";
5
6
  function isRecord(value) {
6
7
  return typeof value === "object" && value !== null && !Array.isArray(value);
7
8
  }
@@ -235,6 +236,9 @@ export async function applyProviderScaffoldPlan(plan, opts) {
235
236
  * 利用者向け出力だけを担う。
236
237
  */
237
238
  export async function runProviderScaffold(provider, opts) {
239
+ // The templates/antigravity/ source stays in the package until PJR-N6FQ, but it is no longer
240
+ // copied: scaffolding agy settings would only prepare a launch SpecDojo refuses.
241
+ assertProviderLaunchAllowed(provider, `Cannot scaffold provider ${provider}`);
238
242
  const plan = await buildProviderScaffoldPlan({
239
243
  packageRoot: opts.packageRoot,
240
244
  repoRoot: opts.repoRoot,
@@ -843,11 +843,12 @@ export function registerConfigCommands(program) {
843
843
  });
844
844
  cfg
845
845
  .command("migrate-members")
846
- .description("Move agent entries from project pm-members.yaml files to protected agent members")
846
+ .description("Deprecated: configure agent members directly in .specdojo/agent-members.yaml (will be removed in 0.10.0)")
847
847
  .option("--project <projectId>", "Migrate only one project (default: all configured projects)")
848
848
  .option("--dry-run", "Show planned changes without writing", false)
849
849
  .action((opts) => {
850
850
  try {
851
+ warnDeprecated("config migrate-members", "Configure agent members directly in .specdojo/agent-members.yaml instead. This command will be removed in 0.10.0.");
851
852
  migrateAgentMembers({ projectId: opts.project, dryRun: !!opts.dryRun });
852
853
  }
853
854
  catch (error) {
@@ -858,21 +859,21 @@ export function registerConfigCommands(program) {
858
859
  cfg
859
860
  .command("scaffold")
860
861
  .description("Scaffold provider settings, a VS Code multi-root workspace, Git hooks, or Slidev")
861
- .option("--provider <name>", "Provider template to copy (antigravity|claude|codex|copilot|opencode)")
862
+ .option("--provider <name>", "Provider template to copy (claude|codex|copilot|opencode)")
862
863
  .option("--workspace", "Generate VS Code multi-root workspace (<project-id>.code-workspace) from repos config", false)
863
864
  .option("--lefthook", "Generate pre-commit hooks for SpecDojo repositories", false)
864
865
  .option("--slidev", "Set up Slidev and formatting for kata", false)
865
866
  .option("--project <id>", "Target project ID for workspace scaffolding (defaults to current_project)")
866
867
  .option("--force", "Overwrite existing files", false)
867
868
  .option("--dry-run", "Show planned files without writing", false)
868
- .option("--global", "Merge provider permissions into user-level settings (currently antigravity only)", false)
869
+ .option("--global", "Merge provider permissions into user-level settings (no provider currently supports it)", false)
869
870
  .action(async (opts) => {
870
871
  try {
871
872
  if (!opts.provider && !opts.workspace && !opts.lefthook && !opts.slidev) {
872
873
  throw new Error("Specify --provider <name>, --workspace, --lefthook, or --slidev to scaffold.");
873
874
  }
874
875
  if (opts.global && !opts.provider) {
875
- throw new Error("--global requires --provider antigravity");
876
+ throw new Error("--global requires --provider <name>");
876
877
  }
877
878
  if (opts.provider) {
878
879
  await runProviderScaffold(String(opts.provider), {