specdojo 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/catalog-build-references.js +144 -0
  3. package/dist/catalog-build-render.js +144 -0
  4. package/dist/catalog-build.js +13 -290
  5. package/dist/catalog-generate.js +6 -9
  6. package/dist/catalog-plan-generate.js +2 -2
  7. package/dist/catalog-plan.js +6 -6
  8. package/dist/catalog-scaffold.js +4 -4
  9. package/dist/catalog.js +2 -2
  10. package/dist/dashboard-exec-records.js +105 -0
  11. package/dist/dashboard-routines.js +255 -0
  12. package/dist/dashboard-shared.js +14 -0
  13. package/dist/dashboard-timeline.js +175 -0
  14. package/dist/dashboard.js +10 -544
  15. package/dist/deliverable-trash.js +3 -3
  16. package/dist/doc-index.js +3 -3
  17. package/dist/exec-commands.js +557 -0
  18. package/dist/exec-core.js +457 -0
  19. package/dist/exec-plans-core.js +693 -0
  20. package/dist/exec-plans-generation.js +206 -0
  21. package/dist/exec-plans-storage.js +131 -0
  22. package/dist/exec-plans.js +3 -1018
  23. package/dist/exec-repo-integration-git.js +23 -0
  24. package/dist/exec-repo-integration-sync.js +264 -0
  25. package/dist/exec-repo-integration.js +4 -281
  26. package/dist/exec-reporter-output.js +206 -0
  27. package/dist/exec-reporter.js +2 -206
  28. package/dist/exec-results.js +22 -15
  29. package/dist/exec-run-agent-pipeline.js +256 -0
  30. package/dist/exec-run-agent.js +531 -0
  31. package/dist/exec-run-in-place.js +541 -0
  32. package/dist/exec-run-job.js +717 -0
  33. package/dist/exec-run-lifecycle-commands.js +522 -0
  34. package/dist/exec-run-mode-shared.js +140 -0
  35. package/dist/exec-run-register-command.js +244 -0
  36. package/dist/exec-run-register-core.js +386 -0
  37. package/dist/exec-run-register-mode.js +206 -0
  38. package/dist/exec-run-register-resume.js +393 -0
  39. package/dist/exec-run-register-state.js +322 -0
  40. package/dist/exec-run-register-worktree.js +509 -0
  41. package/dist/exec-run-schedule-mode.js +294 -0
  42. package/dist/exec-run-schedule-prepare.js +353 -0
  43. package/dist/exec-run-schedule-task.js +572 -0
  44. package/dist/exec-run-shared.js +399 -0
  45. package/dist/exec-run.js +11 -6182
  46. package/dist/exec-shared.js +2 -2
  47. package/dist/exec-trial-commands.js +558 -0
  48. package/dist/exec-trial-core.js +371 -0
  49. package/dist/exec-trial.js +2 -921
  50. package/dist/exec-worktree-ops-commit.js +707 -0
  51. package/dist/exec-worktree-ops-lifecycle.js +292 -0
  52. package/dist/exec-worktree-ops-merge.js +303 -0
  53. package/dist/exec-worktree-ops.js +3 -1292
  54. package/dist/exec-worktree.js +32 -4
  55. package/dist/exec.js +2 -1006
  56. package/dist/frontmatter-namespace.js +2 -2
  57. package/dist/grade-apply.js +734 -0
  58. package/dist/grade-command-apply.js +250 -0
  59. package/dist/grade-command-inspect.js +138 -0
  60. package/dist/grade-command-plan.js +101 -0
  61. package/dist/grade-command-shared.js +68 -0
  62. package/dist/grade-core.js +307 -0
  63. package/dist/grade-markdown.js +274 -0
  64. package/dist/grade-pipeline-state.js +184 -0
  65. package/dist/grade-plan.js +507 -0
  66. package/dist/grade-result.js +5 -5
  67. package/dist/grade-target-discovery.js +265 -0
  68. package/dist/grade-targets.js +432 -0
  69. package/dist/grade.js +14 -3188
  70. package/dist/init-command.js +7 -7
  71. package/dist/job-definition.js +670 -0
  72. package/dist/job.js +9 -673
  73. package/dist/kata-command.js +2 -2
  74. package/dist/register-command-types.js +1 -0
  75. package/dist/register-core.js +363 -0
  76. package/dist/register-create-commands.js +245 -0
  77. package/dist/register-events.js +4 -4
  78. package/dist/register-item.js +6 -6
  79. package/dist/register-maintenance-commands.js +187 -0
  80. package/dist/register-migration.js +268 -0
  81. package/dist/register-renumber.js +314 -0
  82. package/dist/register-transition-commands.js +248 -0
  83. package/dist/register-update.js +230 -0
  84. package/dist/register-views.js +256 -0
  85. package/dist/register.js +61 -2069
  86. package/dist/review-plan.js +3 -3
  87. package/dist/routine-definition.js +401 -0
  88. package/dist/routine.js +6 -402
  89. package/dist/schedule-approach.js +2 -2
  90. package/dist/schedule-strategy-generate-document.js +273 -0
  91. package/dist/schedule-strategy-generate-scope.js +199 -0
  92. package/dist/schedule-strategy-generate.js +9 -473
  93. package/dist/schedule.js +4 -4
  94. package/dist/specdojo-config.js +3 -4
  95. package/dist/viewpoint-document-kinds-check.js +3 -3
  96. package/dist/yaml-pages.js +4 -4
  97. package/dist/yaml.js +28 -0
  98. package/docs/ja/specdojo/guides/exec-config-guide.md +6 -6
  99. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +20 -18
  100. package/docs/ja/specdojo/guides/routine-operation-guide.md +1 -1
  101. package/package.json +4 -5
  102. package/templates/antigravity/README.md +3 -3
  103. package/templates/antigravity/exec-defaults-snippet.yaml +6 -4
  104. package/templates/init-exec-defaults.yaml +3 -1
package/dist/dashboard.js CHANGED
@@ -1,17 +1,15 @@
1
1
  import { mkdirSync, existsSync, readFileSync, writeFileSync, readdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import yaml from "js-yaml";
4
- import { defaultScheduleCalendar, buildScheduleIndex } from "./exec-schedule-index.js";
5
- import { addWorkingDaysToDate } from "./exec-schedule-calendar.js";
6
- import { readJson, stripTerminalControlSequences, toArtifactPath } from "./exec-shared.js";
3
+ import { readJson, toArtifactPath } from "./exec-shared.js";
7
4
  import { readAllEventFiles } from "./exec-events.js";
8
5
  import { getProjectExecutionPath, getProjectRoutinesPath, getProjectSchedulePath, getProjectTimelinePath, loadConfig, loadEnv, specdojoRootDir, } from "./specdojo-config.js";
9
6
  import { resolveRegisterPaths, loadRegisterItems, } from "./register.js";
10
7
  import { readRegisterEventsFromContent, registerEventFilePath, } from "./register-events.js";
11
- import { buildTimelineWaves, loadTimelineIndex, } from "./timeline-build.js";
12
- // routine の due 判定は機械可読な正本(interval / trigger + last_scheduled_for / last_run)から同じ
13
- // 関数で算出する。CLI 出力の転記ではなく、routine.ts の実装へ流用して文言解析に依存しない。
14
- import { cronMatches, cronOccurrences, isRoutineDue, routineActionKindLabel, } from "./routine.js";
8
+ import { buildTimelineWaves, loadTimelineIndex } from "./timeline-build.js";
9
+ import { buildTimelineGanttSvg, computeTimelineTrackSchedules, resolveDashboardCalendar, } from "./dashboard-timeline.js";
10
+ import { aggregateRoutines, buildDailyRoutineRows, formatZonedDateTime, ROUTINE_ROW_COLLAPSE_THRESHOLD, zonedDateKey, } from "./dashboard-routines.js";
11
+ import { buildExecRecordsMarkdown, collectExecRecords, EXEC_RECORDS_FILE, } from "./dashboard-exec-records.js";
12
+ import { sanitizeDashboardCell } from "./dashboard-shared.js";
15
13
  import { gradeFindingCount, parseGradeResult } from "./grade-result.js";
16
14
  // ================================
17
15
  // Types
@@ -56,178 +54,7 @@ export function resolveDashboardPaths(opts) {
56
54
  gradeResultsPath: join(baseDir, getProjectExecutionPath(project), "grade", "results"),
57
55
  };
58
56
  }
59
- // tml-index の tracks を order → wave に集約し、planned_start_date と稼働日カレンダーで各トラックの
60
- // 予定開始日・終了日を算出する。横軸は日付であり、wave 番号ではない。
61
- export function computeTimelineTrackSchedules(index, calendar) {
62
- const waves = buildTimelineWaves(index.tracks);
63
- const waveNumberByOrder = new Map();
64
- for (const wave of waves) {
65
- for (const tk of wave.tracks)
66
- waveNumberByOrder.set(tk.order, wave.wave);
67
- }
68
- const startByTrack = new Map();
69
- const endByTrack = new Map();
70
- let cursor = index.planned_start_date;
71
- for (const wave of waves) {
72
- const waveStart = cursor;
73
- let waveEnd;
74
- for (const tk of wave.tracks) {
75
- startByTrack.set(tk.track, waveStart);
76
- if (tk.catalog_duration_estimate_days && waveStart) {
77
- const end = addWorkingDaysToDate(waveStart, tk.catalog_duration_estimate_days, calendar);
78
- endByTrack.set(tk.track, end);
79
- if (!waveEnd || end > waveEnd)
80
- waveEnd = end;
81
- }
82
- else {
83
- endByTrack.set(tk.track, undefined);
84
- }
85
- }
86
- // 次 wave の手始め。本 wave に推定日数のあるトラックがあれば最遅完了日の翌稼働日で、
87
- // 未定のトラックだけなら直前の手始め日をそのまま受け継ぐ(後続波まで日付が伝播する)。
88
- cursor = waveEnd ? addWorkingDaysToDate(waveEnd, 1, calendar) : cursor;
89
- }
90
- const schedule = index.tracks.map((tk) => ({
91
- track: tk.track,
92
- order: tk.order,
93
- domains: tk.domains,
94
- status: tk.catalog_status,
95
- estimateDays: tk.catalog_duration_estimate_days,
96
- parallel_group: tk.parallel_group,
97
- depends_on: tk.depends_on,
98
- startDate: startByTrack.get(tk.track),
99
- endDate: endByTrack.get(tk.track),
100
- wave: waveNumberByOrder.get(tk.order) ?? 0,
101
- }));
102
- return { schedule, plannedStartDate: index.planned_start_date };
103
- }
104
- // 稼働日カレンダーの機械可読正本:tml-index.planned_start_date を起点にし、Schedule 側
105
- // (sch-defaults.yaml と各 sch-*.yaml)の calendar を buildScheduleIndex から復用する。
106
- // 両方とも YAML 正本から機械的に読み取り、表示文言の解析に依存しない。
107
- export function resolveDashboardCalendar(schedulePath) {
108
- try {
109
- return buildScheduleIndex(schedulePath).calendar;
110
- }
111
- catch {
112
- return defaultScheduleCalendar();
113
- }
114
- }
115
- // ================================
116
- // Timeline Gantt SVG (x-axis = date)
117
- // ================================
118
- function xmlEscape(text) {
119
- return text
120
- .replace(/&/g, "&")
121
- .replace(/</g, "&lt;")
122
- .replace(/>/g, "&gt;")
123
- .replace(/"/g, "&quot;");
124
- }
125
- function statusColor(status) {
126
- if (status === "primary")
127
- return "#16a34a";
128
- if (status === "draft")
129
- return "#2563eb";
130
- return "#d1d5db";
131
- }
132
- // 予定日付の無いトラックはバーを持たずラベルのみ表示する(手始め日 or 推定稼働日が未設定)。
133
- export function buildTimelineGanttSvg(schedule, plannedStartDate, title = "トラック計画ガントチャート") {
134
- const dayWidth = 30;
135
- const rowHeight = 26;
136
- const leftPad = 240;
137
- const topPad = 56;
138
- const bottomPad = 20;
139
- // バーは startDate かつ endDate 両方を持つトラックへ。開始日のみのトラックは着手順の着手点として
140
- // 四角(diamond)で表示する。軸の範囲は endDate が無いトラックも startDate を含めて算出する。
141
- const fullRows = schedule.filter((row) => row.startDate);
142
- if (fullRows.length === 0 || !plannedStartDate) {
143
- return noDataTimelineSvg(title, plannedStartDate
144
- ? "トラックの予定開始日・終了日を算出できませんでした。"
145
- : "計画開始日(tml-index.yaml の planned_start_date)が未設定です。");
146
- }
147
- const parseMs = (dateOnly) => {
148
- const [year, month, day] = dateOnly.split("-").map(Number);
149
- return Date.UTC(year, month - 1, day, 0, 0, 0, 0);
150
- };
151
- const startMs = parseMs(plannedStartDate);
152
- let endMs = startMs;
153
- for (const row of fullRows) {
154
- const last = row.endDate ?? row.startDate;
155
- if (parseMs(last) > endMs)
156
- endMs = parseMs(last);
157
- }
158
- const totalDays = Math.max(1, Math.ceil((endMs - startMs) / 86_400_000) + 1);
159
- const width = leftPad + totalDays * dayWidth + 24;
160
- const height = topPad + schedule.length * rowHeight + bottomPad;
161
- const xForDate = (dateOnly) => {
162
- const daysDiff = Math.floor((parseMs(dateOnly) - startMs) / 86_400_000);
163
- return leftPad + daysDiff * dayWidth;
164
- };
165
- const parts = [];
166
- parts.push(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${xmlEscape(title)}">`);
167
- parts.push(`<style>
168
- text { font-family: ui-sans-serif, system-ui, -apple-system, sans-serif; fill: #1f2937; }
169
- .tl-title { font-size: 16px; font-weight: 700; fill: #0f172a; }
170
- .tl-caption { font-size: 11px; fill: #64748b; }
171
- .tl-label { font-size: 11px; font-weight: 600; fill: #1f2937; }
172
- .tl-axis { font-size: 10px; fill: #475569; }
173
- .tl-grid { stroke: #e2e8f0; stroke-width: 1; }
174
- .tl-month-grid { stroke: #94a3b8; stroke-width: 1.5; }
175
- .tl-note { font-size: 10px; fill: #9ca3af; }
176
- </style>`);
177
- parts.push(`<rect x="0" y="0" width="${width}" height="${height}" fill="#fffdf8" />`);
178
- parts.push(`<text class="tl-title" x="16" y="24">${xmlEscape(title)}</text>`);
179
- parts.push(`<text class="tl-caption" x="16" y="42">横軸は日付。予定開始日・予定終了日は tml-index.yaml の planned_start_date と catalog_duration_estimate_days(推定稼働日数)から算出。</text>`);
180
- for (let offset = 0; offset < totalDays; offset++) {
181
- const dayMs = startMs + offset * 86_400_000;
182
- if (new Date(dayMs).getUTCDate() !== 1)
183
- continue;
184
- const x = leftPad + offset * dayWidth;
185
- parts.push(`<line class="tl-month-grid" x1="${x}" y1="${topPad - 22}" x2="${x}" y2="${height - bottomPad}" />`);
186
- parts.push(`<text class="tl-axis" x="${x + 4}" y="${topPad - 8}">${xmlEscape(new Date(dayMs).toISOString().slice(0, 7))}</text>`);
187
- }
188
- parts.push(`<line class="tl-grid" x1="${leftPad}" y1="${topPad - 22}" x2="${leftPad}" y2="${height - bottomPad}" />`);
189
- let currentY = topPad;
190
- for (const row of schedule) {
191
- parts.push(`<text class="tl-label" x="8" y="${currentY + 14}">${xmlEscape(row.track)}</text>`);
192
- if (row.startDate && row.endDate) {
193
- const x1 = xForDate(row.startDate);
194
- const x2 = xForDate(row.endDate);
195
- const barWidth = Math.max(4, x2 - x1);
196
- parts.push(`<rect x="${x1}" y="${currentY + 6}" width="${barWidth}" height="12" rx="3" fill="${statusColor(row.status)}" opacity="0.9" />`);
197
- }
198
- else if (row.startDate) {
199
- // 開始日のみ(推定稼働日数未定): 着手点の diamond マーカーで表示。
200
- const cx = xForDate(row.startDate);
201
- parts.push(`<polygon points="${cx},${currentY + 2} ${cx + 6},${currentY + 8} ${cx},${currentY + 14} ${cx - 6},${currentY + 8}" fill="${statusColor(row.status)}" opacity="0.85" />`);
202
- parts.push(`<text class="tl-note" x="${xForDate(row.startDate) + 8}" y="${currentY + 14}">${xmlEscape(datePlanNote(row))}</text>`);
203
- }
204
- else {
205
- parts.push(`<text class="tl-note" x="${leftPad + 4}" y="${currentY + 14}">${xmlEscape(datePlanNote(row))}</text>`);
206
- }
207
- parts.push(`<line class="tl-grid" x1="0" y1="${currentY + rowHeight}" x2="${width}" y2="${currentY + rowHeight}" />`);
208
- currentY += rowHeight;
209
- }
210
- parts.push(`</svg>`);
211
- return parts.join("\n");
212
- }
213
- function datePlanNote(row) {
214
- if (!row.startDate)
215
- return "手始め日未定";
216
- if (row.endDate === undefined || !row.estimateDays)
217
- return `着手順 ${row.order}(推定稼働日数未定)`;
218
- return `${row.startDate} ~ ${row.endDate}`;
219
- }
220
- function noDataTimelineSvg(title, message) {
221
- const width = 560;
222
- const height = 120;
223
- return [
224
- `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="${xmlEscape(title)}">`,
225
- `<rect x="0" y="0" width="${width}" height="${height}" fill="#fffdf8" />`,
226
- `<text class="tl-title" x="16" y="24">${xmlEscape(title)}</text>`,
227
- `<text x="16" y="72" font-size="13" fill="#64748b">${xmlEscape(message)}</text>`,
228
- `</svg>`,
229
- ].join("\n");
230
- }
57
+ export { buildTimelineGanttSvg, computeTimelineTrackSchedules, resolveDashboardCalendar };
231
58
  function aggregateRegister(projectId) {
232
59
  const result = {
233
60
  statusCounts: {},
@@ -350,272 +177,11 @@ function aggregateAttention(paths) {
350
177
  }
351
178
  return rows;
352
179
  }
353
- // routine ファイル(rtn-*.yaml)を読み、状態ファイル generated/routine-state.json と突き合わせて
354
- // 最終実行・実行結果・due 状況を得る。CLI 出力(routine list)の転記に依存しない。
355
- function aggregateRoutines(routinesPath) {
356
- if (!routinesPath || !existsSync(routinesPath))
357
- return { rows: [], docs: [], history: [] };
358
- const result = {
359
- rows: [],
360
- docs: [],
361
- history: readRoutineRunHistory(join(routinesPath, "generated", "routine-runs.jsonl")),
362
- error: undefined,
363
- };
364
- const stateEntries = readRoutineStateEntries(join(routinesPath, "generated", "routine-state.json"));
365
- const now = new Date();
366
- const files = readdirSync(routinesPath)
367
- .filter((name) => /^rtn-.*\.(ya?ml)$/.test(name))
368
- .sort();
369
- for (const file of files) {
370
- try {
371
- const doc = parseRoutineFileSafe(join(routinesPath, file));
372
- if (!doc?.id || typeof doc.id !== "string")
373
- continue;
374
- result.docs.push(doc);
375
- buildRoutineRow(result, doc, stateEntries, now);
376
- }
377
- catch {
378
- result.error = `routine file parse failed: ${file}`;
379
- }
380
- }
381
- result.rows.sort((a, b) => a.id.localeCompare(b.id));
382
- return result;
383
- }
384
- export function readRoutineRunHistory(historyPath) {
385
- if (!existsSync(historyPath))
386
- return [];
387
- const entries = [];
388
- for (const [index, line] of readFileSync(historyPath, "utf8").split(/\r?\n/).entries()) {
389
- if (!line.trim())
390
- continue;
391
- try {
392
- const value = JSON.parse(line);
393
- if (value.version === 1 &&
394
- typeof value.routine_id === "string" &&
395
- typeof value.scheduled_for === "string" &&
396
- typeof value.started_at === "string" &&
397
- typeof value.completed_at === "string" &&
398
- ["success", "failure", "skipped"].includes(value.result) &&
399
- Array.isArray(value.job_run_ids)) {
400
- entries.push(value);
401
- }
402
- else {
403
- throw new Error("invalid routine history entry");
404
- }
405
- }
406
- catch {
407
- throw new Error(`routine history parse failed at line ${index + 1}`);
408
- }
409
- }
410
- return entries;
411
- }
412
- // 毎時の dashboard 更新のように 1 日に何度も動く routine は、日ごとに 1 行へまとめる。
413
- const ROUTINE_ROW_COLLAPSE_THRESHOLD = 3;
414
- export function formatZonedDateTime(iso, timeZone) {
415
- const date = new Date(iso);
416
- if (Number.isNaN(date.getTime()))
417
- return iso;
418
- const parts = new Intl.DateTimeFormat("en-CA", {
419
- timeZone,
420
- month: "2-digit",
421
- day: "2-digit",
422
- hour: "2-digit",
423
- minute: "2-digit",
424
- hour12: false,
425
- }).formatToParts(date);
426
- const get = (type) => parts.find((part) => part.type === type)?.value ?? "";
427
- return `${get("month")}-${get("day")} ${get("hour")}:${get("minute")}`;
428
- }
429
- function zonedDateKey(date, timeZone) {
430
- return new Intl.DateTimeFormat("en-CA", {
431
- timeZone,
432
- year: "numeric",
433
- month: "2-digit",
434
- day: "2-digit",
435
- }).format(date);
436
- }
437
- function previousDateKey(dateKey) {
438
- const [year, month, day] = dateKey.split("-").map(Number);
439
- const previous = new Date(Date.UTC(year, month - 1, day - 1));
440
- return previous.toISOString().slice(0, 10);
441
- }
442
- function scheduledToday(doc, today, now, timeZone) {
443
- if (!doc.trigger || doc.enabled === false)
444
- return [];
445
- const start = Math.floor((now.getTime() - 36 * 60 * 60 * 1000) / 60_000) * 60_000;
446
- const end = Math.floor((now.getTime() + 36 * 60 * 60 * 1000) / 60_000) * 60_000;
447
- const matches = [];
448
- for (let cursor = start; cursor <= end; cursor += 60_000) {
449
- const candidate = new Date(cursor);
450
- if (zonedDateKey(candidate, timeZone) === today &&
451
- cronMatches(doc.trigger.cron, doc.trigger.timezone, candidate)) {
452
- matches.push(candidate);
453
- }
454
- }
455
- return matches;
456
- }
457
- export function buildDailyRoutineRows(docs, history, now, timeZone = "Asia/Tokyo") {
458
- const today = zonedDateKey(now, timeZone);
459
- const yesterday = previousDateKey(today);
460
- const rows = history
461
- .filter((entry) => {
462
- const key = zonedDateKey(new Date(entry.scheduled_for), timeZone);
463
- return key === yesterday || key === today;
464
- })
465
- .map((entry) => ({
466
- day: zonedDateKey(new Date(entry.scheduled_for), timeZone) === yesterday ? "昨日" : "本日",
467
- routineId: entry.routine_id,
468
- scheduledFor: entry.scheduled_for,
469
- startedAt: entry.started_at,
470
- completedAt: entry.completed_at,
471
- result: entry.result,
472
- jobRunIds: entry.job_run_ids,
473
- runCount: 1,
474
- }));
475
- const completedKeys = new Set(history.map((entry) => `${entry.routine_id}:${new Date(entry.scheduled_for).toISOString().slice(0, 16)}`));
476
- for (const doc of docs) {
477
- for (const scheduledFor of scheduledToday(doc, today, now, timeZone)) {
478
- const key = `${doc.id}:${scheduledFor.toISOString().slice(0, 16)}`;
479
- if (completedKeys.has(key))
480
- continue;
481
- rows.push({
482
- day: "本日",
483
- routineId: doc.id,
484
- scheduledFor: scheduledFor.toISOString(),
485
- startedAt: "-",
486
- completedAt: "-",
487
- // 予定時刻を過ぎても履歴がなければ、skip や cron 停止で動かなかったことを示す。
488
- result: scheduledFor.getTime() <= now.getTime() ? "未実行" : "予定",
489
- jobRunIds: [],
490
- runCount: 1,
491
- });
492
- }
493
- }
494
- return collapseFrequentRoutineRows(rows).sort((a, b) => a.scheduledFor.localeCompare(b.scheduledFor) || a.routineId.localeCompare(b.routineId));
495
- }
496
- // 同じ routine・同じ日の行が閾値以上あれば、最新の実行 1 行に件数をまとめる。
497
- export function collapseFrequentRoutineRows(rows) {
498
- const groups = new Map();
499
- for (const row of rows) {
500
- const key = `${row.day}:${row.routineId}`;
501
- groups.set(key, [...(groups.get(key) ?? []), row]);
502
- }
503
- const collapsed = [];
504
- for (const group of groups.values()) {
505
- if (group.length < ROUTINE_ROW_COLLAPSE_THRESHOLD) {
506
- collapsed.push(...group);
507
- continue;
508
- }
509
- const executed = group.filter((row) => row.result !== "予定" && row.result !== "未実行");
510
- const latest = [...(executed.length > 0 ? executed : group)].sort((a, b) => b.scheduledFor.localeCompare(a.scheduledFor))[0];
511
- const failures = executed.filter((row) => row.result === "failure").length;
512
- collapsed.push({
513
- ...latest,
514
- runCount: executed.length > 0 ? executed.length : group.length,
515
- jobRunIds: [],
516
- result: failures > 0 ? "failure" : latest.result,
517
- });
518
- }
519
- return collapsed;
520
- }
521
- // generated/routine-state.json の routines.<id> が状態の正本。破損時は空。
522
- function readRoutineStateEntries(statePath) {
523
- const entries = {};
524
- if (!existsSync(statePath))
525
- return entries;
526
- try {
527
- const parsed = readJson(statePath);
528
- const routines = parsed?.routines;
529
- if (routines && typeof routines === "object") {
530
- for (const [id, value] of Object.entries(routines)) {
531
- if (value && typeof value === "object") {
532
- const entry = value;
533
- entries[id] = {
534
- last_run: typeof entry.last_run === "string" ? entry.last_run : undefined,
535
- last_result: typeof entry.last_result === "string" ? entry.last_result : undefined,
536
- last_scheduled_for: typeof entry.last_scheduled_for === "string" ? entry.last_scheduled_for : undefined,
537
- };
538
- }
539
- }
540
- }
541
- }
542
- catch {
543
- return {};
544
- }
545
- return entries;
546
- }
547
- function parseRoutineFileSafe(filePath) {
548
- let parsed;
549
- try {
550
- parsed = yaml.load(readFileSync(filePath, "utf8"));
551
- }
552
- catch {
553
- return undefined;
554
- }
555
- if (!parsed || typeof parsed !== "object")
556
- return undefined;
557
- return parsed;
558
- }
559
- // routine 1 行を機械可読な正本から集計し、due は now と状態から判定する。
560
- function buildRoutineRow(result, doc, stateEntries, now) {
561
- const id = String(doc.id);
562
- const enabled = doc.enabled === undefined ? true : doc.enabled;
563
- const kind = doc.action ? routineActionKindLabel(doc.action) : "-";
564
- const stateEntry = stateEntries[id];
565
- let lastRun = "-";
566
- if (stateEntry?.last_run) {
567
- lastRun = stateEntry.last_result
568
- ? `${stateEntry.last_run} (${stateEntry.last_result})`
569
- : stateEntry.last_run;
570
- }
571
- result.rows.push({
572
- id,
573
- name: typeof doc.name === "string" ? doc.name : undefined,
574
- enabled,
575
- schedule: routineScheduleLabel(doc),
576
- kind,
577
- lastRun,
578
- due: computeRoutineDue(doc, stateEntry, enabled, now),
579
- });
580
- }
581
- // interval / trigger + 現在時刻 + 状態(last_run / last_scheduled_for)から due を機械的に判定する。
582
- export function computeRoutineDue(doc, stateEntry, enabled, now) {
583
- if (!enabled)
584
- return "disabled";
585
- if (doc.trigger) {
586
- const occurrences = cronOccurrences(doc, stateEntry?.last_scheduled_for, now);
587
- return occurrences.length > 0 ? "due" : "-";
588
- }
589
- if (doc.interval) {
590
- return isRoutineDue(doc, stateEntry?.last_run, now) ? "due" : "-";
591
- }
592
- return "-";
593
- }
594
- // interval / trigger を表すラベル。interval 優先、なければ trigger.cron。
595
- function routineScheduleLabel(doc) {
596
- if (typeof doc.interval === "string")
597
- return doc.interval;
598
- const trigger = doc.trigger;
599
- if (trigger && typeof trigger.cron === "string")
600
- return `cron: ${trigger.cron}`;
601
- return "-";
602
- }
180
+ export { buildDailyRoutineRows, collapseFrequentRoutineRows, computeRoutineDue, formatZonedDateTime, readRoutineRunHistory, } from "./dashboard-routines.js";
603
181
  // ================================
604
182
  // Markdown rendering
605
183
  // ================================
606
- const MAX_DASHBOARD_CELL_LENGTH = 200;
607
- // dashboard の表へは event や subprocess 由来の文字列も入る。表へ埋める直前に
608
- // ターミナル制御シーケンスと改行類を除き、列区切りをエスケープして長さを制限する。
609
- export function sanitizeDashboardCell(text) {
610
- const singleLine = stripTerminalControlSequences(text)
611
- .replace(/[\t\r\n]+/g, " ")
612
- .replace(/ +/g, " ")
613
- .trim();
614
- const truncated = singleLine.length <= MAX_DASHBOARD_CELL_LENGTH
615
- ? singleLine
616
- : `${singleLine.slice(0, MAX_DASHBOARD_CELL_LENGTH)}…`;
617
- return truncated.replace(/\|/g, "\\|");
618
- }
184
+ export { sanitizeDashboardCell };
619
185
  const STATUS_ORDER = [
620
186
  "open",
621
187
  "in-progress",
@@ -896,107 +462,7 @@ function renderAttentionSection(paths) {
896
462
  // ================================
897
463
  // 9. Exec records (plan / result 一覧)
898
464
  // ================================
899
- export const EXEC_RECORDS_FILE = "exec-records.md";
900
- function readSpecdojoFrontmatter(filePath) {
901
- try {
902
- const content = readFileSync(filePath, "utf8");
903
- const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
904
- if (!match)
905
- return {};
906
- const parsed = yaml.load(match[1]);
907
- if (typeof parsed !== "object" || parsed === null)
908
- return {};
909
- const specdojo = parsed.specdojo;
910
- return typeof specdojo === "object" && specdojo !== null && !Array.isArray(specdojo)
911
- ? specdojo
912
- : {};
913
- }
914
- catch {
915
- // 壊れた frontmatter の記録も一覧から辿れるよう、属性なしの行として残す。
916
- return {};
917
- }
918
- }
919
- function frontmatterText(value) {
920
- if (typeof value === "string" && value.trim())
921
- return value.trim();
922
- if (value instanceof Date)
923
- return value.toISOString();
924
- return undefined;
925
- }
926
- function listMarkdownFiles(dir, suffix) {
927
- if (!existsSync(dir))
928
- return [];
929
- return readdirSync(dir)
930
- .filter((name) => name.endsWith(suffix))
931
- .sort();
932
- }
933
- // execution/exec/{plans,results} の記録を実行単位(ファイル名の stem)でまとめる。
934
- // 並びは開始日時の新しい順、開始日時が無いものは後ろに stem 順で置く。
935
- export function collectExecRecords(execPath) {
936
- const rows = new Map();
937
- const rowFor = (stem) => {
938
- const existing = rows.get(stem);
939
- if (existing)
940
- return existing;
941
- const created = { stem };
942
- rows.set(stem, created);
943
- return created;
944
- };
945
- for (const name of listMarkdownFiles(join(execPath, "plans"), "-plan.md")) {
946
- const row = rowFor(name.slice(0, -"-plan.md".length));
947
- const fm = readSpecdojoFrontmatter(join(execPath, "plans", name));
948
- row.planFile = name;
949
- row.taskId ??= frontmatterText(fm.task_id);
950
- row.mode ??= frontmatterText(fm.mode);
951
- }
952
- for (const name of listMarkdownFiles(join(execPath, "results"), "-result.md")) {
953
- const row = rowFor(name.slice(0, -"-result.md".length));
954
- const fm = readSpecdojoFrontmatter(join(execPath, "results", name));
955
- row.resultFile = name;
956
- row.taskId = frontmatterText(fm.task_id) ?? row.taskId;
957
- row.mode = frontmatterText(fm.mode) ?? row.mode;
958
- row.status = frontmatterText(fm.status);
959
- row.startedAt = frontmatterText(fm.started_at);
960
- }
961
- return [...rows.values()].sort((a, b) => {
962
- if (a.startedAt && b.startedAt && a.startedAt !== b.startedAt) {
963
- return a.startedAt < b.startedAt ? 1 : -1;
964
- }
965
- if (a.startedAt && !b.startedAt)
966
- return -1;
967
- if (!a.startedAt && b.startedAt)
968
- return 1;
969
- return a.stem.localeCompare(b.stem);
970
- });
971
- }
972
- function execRecordLink(dir, file, label) {
973
- return file ? `[${label}](../exec/${dir}/${file})` : "-";
974
- }
975
- export function buildExecRecordsMarkdown(projectId, rows) {
976
- const lines = [
977
- "# 実行記録一覧",
978
- "",
979
- `- project_id: \`${projectId}\``,
980
- `- 再生成: \`specdojo dashboard build --project ${projectId}\``,
981
- "",
982
- "> このページは `specdojo dashboard build` が生成した派生ビューです。正本は `execution/exec/` 配下の plan / result であり、このページを手編集しても次回のビルドで失われます。実行記録はサイドバーに載せないため、このページから辿ります。",
983
- "",
984
- ];
985
- if (rows.length === 0) {
986
- lines.push("- 実行記録はまだありません。");
987
- return lines.join("\n");
988
- }
989
- lines.push(`- 件数: ${rows.length}`, "");
990
- lines.push("| 開始日時 | task | mode | status | plan | result |");
991
- lines.push("| --- | --- | --- | --- | --- | --- |");
992
- for (const row of rows) {
993
- const task = row.taskId ? `\`${sanitizeDashboardCell(row.taskId)}\`` : "-";
994
- const mode = row.mode ? `\`${sanitizeDashboardCell(row.mode)}\`` : "-";
995
- const status = row.status ? `\`${sanitizeDashboardCell(row.status)}\`` : "-";
996
- lines.push(`| ${row.startedAt ? sanitizeDashboardCell(row.startedAt) : "-"} | ${task} | ${mode} | ${status} | ${execRecordLink("plans", row.planFile, "plan")} | ${execRecordLink("results", row.resultFile, "result")} |`);
997
- }
998
- return lines.join("\n");
999
- }
465
+ export { buildExecRecordsMarkdown, collectExecRecords, EXEC_RECORDS_FILE };
1000
466
  function execRecordsPath(paths) {
1001
467
  return join(paths.executionGeneratedPath, "..", "exec");
1002
468
  }
@@ -10,7 +10,7 @@
10
10
  // unrelated nested `evidence_refs[].path` field.
11
11
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
12
12
  import { basename, dirname, join, relative } from "node:path";
13
- import yaml from "js-yaml";
13
+ import { load } from "./yaml.js";
14
14
  import { isDctCatalogFileName } from "./catalog-types.js";
15
15
  import { resolveBasePath, resolveDeliverablePath } from "./catalog-paths.js";
16
16
  import { readSpecdojoNamespace } from "./frontmatter-namespace.js";
@@ -38,7 +38,7 @@ function locateDeliverable(catalogDir, localId) {
38
38
  const fullPath = join(catalogDir, file);
39
39
  let doc;
40
40
  try {
41
- doc = yaml.load(readFileSync(fullPath, "utf8"));
41
+ doc = load(readFileSync(fullPath, "utf8"));
42
42
  }
43
43
  catch {
44
44
  continue;
@@ -133,7 +133,7 @@ export function applyTrash(repoRoot, plan) {
133
133
  const rewritten = rewriteCatalogPath(rawYaml, plan.localId, plan.newDocPath);
134
134
  // Verify the rewrite parses and resolves to the expected path before touching the
135
135
  // filesystem, so a formatting assumption that doesn't hold aborts cleanly.
136
- const reparsed = yaml.load(rewritten);
136
+ const reparsed = load(rewritten);
137
137
  const resolvedAfter = reparsed?.groups
138
138
  ? findDeliverablePath(reparsed.groups, resolveBasePath("", reparsed.base_path), plan.localId)
139
139
  : null;
package/dist/doc-index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join, relative, resolve } from "node:path";
3
- import yaml from "js-yaml";
3
+ import { load } from "./yaml.js";
4
4
  import { readSpecdojoNamespace } from "./frontmatter-namespace.js";
5
5
  import { specdojoDirectoryPaths, specdojoReferencePath, } from "./template-resolution.js";
6
6
  const SKIP_DIRS = new Set(["node_modules", "dist", ".vitepress", "out"]);
@@ -176,7 +176,7 @@ function scanFile(fullPath, rootDir, repoRoot, collector, nestedMap, locales, lo
176
176
  try {
177
177
  const content = readFileSync(fullPath, "utf8");
178
178
  if (isYaml) {
179
- const parsed = yaml.load(content);
179
+ const parsed = load(content);
180
180
  const topId = extractTopLevelId(parsed);
181
181
  if (topId)
182
182
  addId(collector, topId, entryPath, locale);
@@ -290,7 +290,7 @@ function loadIndexConfig(repoRoot, configPath) {
290
290
  if (!existsSync(p))
291
291
  return {};
292
292
  try {
293
- const parsed = yaml.load(readFileSync(p, "utf8"));
293
+ const parsed = load(readFileSync(p, "utf8"));
294
294
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
295
295
  return parsed;
296
296
  }