specdojo 0.1.0

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.
@@ -0,0 +1,201 @@
1
+ import { formatDateOnlyUtc } from './exec-shared.js';
2
+ import { buildWorkingTaskSegments, dateForWorkingOffset, isWorkingDateUtc, timelinePositionX, timelineStartDate, } from './exec-schedule-calendar.js';
3
+ function xmlEscape(text) {
4
+ return text
5
+ .replace(/&/g, '&')
6
+ .replace(/</g, '&lt;')
7
+ .replace(/>/g, '&gt;')
8
+ .replace(/"/g, '&quot;');
9
+ }
10
+ function dayLabelUtc(dt) {
11
+ const mm = (dt.getUTCMonth() + 1).toString().padStart(2, '0');
12
+ const dd = dt.getUTCDate().toString().padStart(2, '0');
13
+ return `${mm}/${dd}`;
14
+ }
15
+ function stateColor(state, critical) {
16
+ if (state === 'milestone')
17
+ return '#b45309';
18
+ if (state === 'done')
19
+ return '#16a34a';
20
+ if (state === 'doing')
21
+ return '#2563eb';
22
+ if (state === 'blocked')
23
+ return '#f59e0b';
24
+ if (state === 'cancelled')
25
+ return '#6b7280';
26
+ if (critical)
27
+ return '#dc2626';
28
+ return '#d1d5db';
29
+ }
30
+ export function buildTimelineSvg(cpm, schedule, stateSnapshot) {
31
+ const rows = Object.values(cpm.nodes).sort((a, b) => a.es - b.es || a.id.localeCompare(b.id));
32
+ const criticalSet = new Set(cpm.critical_path);
33
+ const leftPad = 380;
34
+ const topPad = 108;
35
+ const bottomPad = 32;
36
+ const rowHeight = 24;
37
+ const sectionHeight = 30;
38
+ const sectionGap = 8;
39
+ const dayWidth = 56;
40
+ const timelineStart = timelineStartDate(cpm.project_start_date);
41
+ const rowsByFile = new Map();
42
+ for (const row of rows) {
43
+ const group = rowsByFile.get(row.schedule_file);
44
+ if (group)
45
+ group.push(row);
46
+ else
47
+ rowsByFile.set(row.schedule_file, [row]);
48
+ }
49
+ const taskSegments = new Map();
50
+ let timelineEnd = new Date(timelineStart.getTime());
51
+ for (const row of rows) {
52
+ if (row.kind === 'task') {
53
+ const segments = cpm.project_start_date
54
+ ? buildWorkingTaskSegments(cpm.project_start_date, row.es, row.duration_days, schedule.calendar)
55
+ : [
56
+ {
57
+ start: dateForWorkingOffset(row.es, cpm.project_start_date, schedule.calendar),
58
+ end: dateForWorkingOffset(row.ef, cpm.project_start_date, schedule.calendar),
59
+ },
60
+ ];
61
+ taskSegments.set(row.id, segments);
62
+ const end = segments[segments.length - 1]?.end;
63
+ if (end && end > timelineEnd)
64
+ timelineEnd = end;
65
+ continue;
66
+ }
67
+ const milestoneAt = dateForWorkingOffset(row.es, cpm.project_start_date, schedule.calendar);
68
+ if (milestoneAt > timelineEnd)
69
+ timelineEnd = milestoneAt;
70
+ }
71
+ const totalDays = Math.max(1, Math.ceil((timelineEnd.getTime() - timelineStart.getTime()) / 86400000) + 1);
72
+ const chartWidth = totalDays * dayWidth;
73
+ const width = leftPad + chartWidth + 40;
74
+ const layoutRows = [];
75
+ for (const [scheduleFile, fileRows] of rowsByFile.entries()) {
76
+ layoutRows.push({
77
+ type: 'section',
78
+ label: schedule.section_labels[scheduleFile] ?? scheduleFile,
79
+ });
80
+ for (const row of fileRows)
81
+ layoutRows.push({ type: 'node', row });
82
+ }
83
+ const height = topPad +
84
+ layoutRows.reduce((sum, entry) => sum + (entry.type === 'section' ? sectionHeight + sectionGap : rowHeight), 0) +
85
+ bottomPad;
86
+ const parts = [];
87
+ parts.push(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img" aria-label="プロジェクトタイムライン">`);
88
+ parts.push(`<style>
89
+ text { font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; fill: #1f2937; }
90
+ .title { font-size: 18px; font-weight: 700; fill: #0f172a; }
91
+ .caption { font-size: 11px; fill: #64748b; }
92
+ .section { font-size: 13px; font-weight: 700; fill: #0f172a; }
93
+ .label { font-size: 12px; font-weight: 500; }
94
+ .axis { font-size: 11px; fill: #475569; }
95
+ .grid { stroke: #d7dee7; stroke-width: 1; }
96
+ .row-grid { stroke: #edf2f7; stroke-width: 1; }
97
+ .shade { fill: #f8fafc; }
98
+ .holiday { fill: #eff6ff; }
99
+ .legend-label { font-size: 11px; fill: #475569; }
100
+ </style>`);
101
+ parts.push(`<rect x="0" y="0" width="${width}" height="${height}" fill="#fffdf8" />`);
102
+ parts.push(`<rect x="0" y="0" width="${leftPad}" height="${height}" fill="#fffaf0" />`);
103
+ parts.push(`<rect x="${leftPad}" y="0" width="${chartWidth + 40}" height="${height}" fill="#ffffff" />`);
104
+ parts.push(`<text class="title" x="16" y="28">プロジェクトタイムライン</text>`);
105
+ parts.push(`<text class="caption" x="16" y="48">1 タスク 1 行で表示します。1 日の長さは ${schedule.calendar.work_hours_per_day} 時間で、休日と週末は空白のままとし、次の稼働日に作業を再開します。</text>`);
106
+ parts.push(`<rect x="0" y="${topPad - 36}" width="${width}" height="28" fill="#fff7ed" />`);
107
+ const legendY = 74;
108
+ const legend = [
109
+ { label: 'todo', color: '#d1d5db' },
110
+ { label: 'doing', color: '#2563eb' },
111
+ { label: 'done', color: '#16a34a' },
112
+ { label: 'blocked', color: '#f59e0b' },
113
+ { label: 'critical', color: '#dc2626' },
114
+ ];
115
+ let legendX = 16;
116
+ for (const item of legend) {
117
+ parts.push(`<rect x="${legendX}" y="${legendY - 10}" width="14" height="14" rx="3" fill="${item.color}" />`);
118
+ parts.push(`<text class="legend-label" x="${legendX + 20}" y="${legendY + 4}">${xmlEscape(item.label)}</text>`);
119
+ legendX += 76;
120
+ }
121
+ parts.push(`<rect x="${legendX}" y="${legendY - 10}" width="14" height="14" fill="#eff6ff" />`);
122
+ parts.push(`<text class="legend-label" x="${legendX + 20}" y="${legendY + 4}">holiday</text>`);
123
+ legendX += 90;
124
+ parts.push(`<rect x="${legendX}" y="${legendY - 10}" width="14" height="14" fill="#f8fafc" stroke="#d7dee7" />`);
125
+ parts.push(`<text class="legend-label" x="${legendX + 20}" y="${legendY + 4}">weekend</text>`);
126
+ for (let dayIndex = 0; dayIndex < totalDays; dayIndex += 1) {
127
+ const dayStart = new Date(timelineStart.getTime() + dayIndex * 86400000);
128
+ const x = leftPad + dayIndex * dayWidth;
129
+ const isWorking = isWorkingDateUtc(dayStart, schedule.calendar);
130
+ if (!isWorking) {
131
+ const shadeClass = schedule.calendar.holidays.has(formatDateOnlyUtc(dayStart))
132
+ ? 'holiday'
133
+ : 'shade';
134
+ parts.push(`<rect class="${shadeClass}" x="${x}" y="${topPad - 20}" width="${dayWidth}" height="${height - topPad}" />`);
135
+ }
136
+ parts.push(`<line class="grid" x1="${x}" y1="${topPad - 20}" x2="${x}" y2="${height - bottomPad}" />`);
137
+ parts.push(`<text class="axis" x="${x + 6}" y="${topPad - 18}">${xmlEscape(dayLabelUtc(dayStart))}</text>`);
138
+ }
139
+ parts.push(`<line class="grid" x1="${leftPad + chartWidth}" y1="${topPad - 20}" x2="${leftPad + chartWidth}" y2="${height - bottomPad}" />`);
140
+ let currentY = topPad;
141
+ for (const entry of layoutRows) {
142
+ if (entry.type === 'section') {
143
+ parts.push(`<rect x="0" y="${currentY - 18}" width="${width}" height="${sectionHeight}" fill="#f1f5f9" />`);
144
+ parts.push(`<text class="section" x="16" y="${currentY}">${xmlEscape(entry.label)}</text>`);
145
+ parts.push(`<line class="grid" x1="0" y1="${currentY + 8}" x2="${width}" y2="${currentY + 8}" />`);
146
+ currentY += sectionHeight + sectionGap;
147
+ continue;
148
+ }
149
+ const row = entry.row;
150
+ const rowTop = currentY - 14;
151
+ const rowMid = currentY - 2;
152
+ const taskState = row.kind === 'task' ? (stateSnapshot?.tasks[row.id]?.state ?? 'todo') : 'milestone';
153
+ const fill = stateColor(taskState, criticalSet.has(row.id));
154
+ const label = row.name ? `${row.id} ${row.name}` : row.id;
155
+ parts.push(`<text class="label" x="16" y="${currentY}">${xmlEscape(label)}</text>`);
156
+ parts.push(`<line class="row-grid" x1="0" y1="${currentY + 8}" x2="${width}" y2="${currentY + 8}" />`);
157
+ if (row.kind === 'task') {
158
+ const segments = taskSegments.get(row.id) ?? [];
159
+ for (const segment of segments) {
160
+ const startX = leftPad + timelinePositionX(segment.start, timelineStart, schedule.calendar, dayWidth);
161
+ const endX = leftPad + timelinePositionX(segment.end, timelineStart, schedule.calendar, dayWidth);
162
+ const widthPx = Math.max(2, endX - startX);
163
+ const stroke = criticalSet.has(row.id)
164
+ ? '#991b1b'
165
+ : taskState === 'todo'
166
+ ? '#9ca3af'
167
+ : taskState === 'blocked'
168
+ ? '#b45309'
169
+ : '#334155';
170
+ parts.push(`<rect x="${startX}" y="${rowTop}" width="${widthPx}" height="12" rx="4" fill="${fill}" stroke="${stroke}" stroke-width="${criticalSet.has(row.id) ? 1.25 : 0.75}" opacity="0.94" />`);
171
+ }
172
+ }
173
+ else {
174
+ const at = dateForWorkingOffset(row.es, cpm.project_start_date, schedule.calendar);
175
+ const cx = leftPad + timelinePositionX(at, timelineStart, schedule.calendar, dayWidth);
176
+ parts.push(`<polygon points="${cx},${rowMid - 7} ${cx + 7},${rowMid} ${cx},${rowMid + 7} ${cx - 7},${rowMid}" fill="${fill}" />`);
177
+ }
178
+ currentY += rowHeight;
179
+ }
180
+ parts.push(`</svg>`);
181
+ return parts.join('\n');
182
+ }
183
+ export function buildTimelineMarkdown(cpm, summary) {
184
+ const lines = [];
185
+ lines.push(`# タイムライン`);
186
+ lines.push('');
187
+ lines.push(...summary.progressSummaryLines);
188
+ lines.push(`- schedule_path: \`${cpm.schedule_path}\``);
189
+ if (cpm.project_start_date)
190
+ lines.push(`- project_start_date: \`${cpm.project_start_date}\``);
191
+ lines.push(`- project_duration_days: \`${cpm.project_duration_days}\``);
192
+ lines.push(`- scope: \`full_schedule\``);
193
+ lines.push(`- critical_path_task_count: \`${summary.criticalPathTaskCount}\``);
194
+ lines.push(`- progress_percent: \`${summary.progressPercent}%\``);
195
+ lines.push(`- done_tasks: \`${summary.doneTasks}\``);
196
+ lines.push(`- task_state_counts: \`${summary.taskStateCounts}\``);
197
+ lines.push('');
198
+ lines.push(`![プロジェクトタイムライン](./timeline.svg)`);
199
+ lines.push('');
200
+ return lines.join('\n');
201
+ }
@@ -0,0 +1,2 @@
1
+ export { buildTimelineMarkdown, buildTimelineSvg } from './exec-schedule-timeline-render.js';
2
+ export { buildProgressSummaryLines } from './exec-schedule-progress.js';
@@ -0,0 +1,195 @@
1
+ import { existsSync, writeFileSync } from 'node:fs';
2
+ import { extname, join } from 'node:path';
3
+ import { computeReadyIds, foldEventsToState, validateEventShape } from './exec-events.js';
4
+ import { ensureDir, listFilesRecursive, nowUtcIsoSeconds, readJson, toArtifactPath, toScheduleFilePath, writeJson, } from './exec-shared.js';
5
+ import { eventsDirForProject, executionRootForProject, generatedDirForProject, } from './exec-project.js';
6
+ import { buildProgressSummaryLines, buildTimelineMarkdown, buildTimelineSvg, } from './exec-schedule-timeline.js';
7
+ import { buildScheduleIndex } from './exec-schedule-index.js';
8
+ import { computeCpm, topoSort } from './exec-schedule-cpm.js';
9
+ import { buildReadySnapshot, orderReadyIds, writeReadyFiles, selectNextTask, } from './exec-schedule-ready.js';
10
+ import { writeScheduleHashAndDiff } from './exec-schedule-hash.js';
11
+ export function validateAll(projectPath) {
12
+ const errors = [];
13
+ const warnings = [];
14
+ const schedule = buildScheduleIndex(projectPath);
15
+ const scheduleIds = new Set(Array.from(schedule.nodes.keys()));
16
+ if (schedule.nodes.size === 0) {
17
+ warnings.push(`No schedule nodes loaded from sch-*.yaml under: ${projectPath}`);
18
+ }
19
+ for (const node of schedule.nodes.values()) {
20
+ for (const dep of node.depends_on) {
21
+ if (!schedule.nodes.has(dep)) {
22
+ errors.push(`${node.schedule_file}: ${node.id} depends_on missing id: ${dep}`);
23
+ }
24
+ }
25
+ }
26
+ const topo = topoSort(schedule);
27
+ if (topo.cycle && topo.cycle.length) {
28
+ errors.push(`schedule dependency cycle detected (nodes involved): ${topo.cycle.join(', ')}`);
29
+ }
30
+ const eventsDir = eventsDirForProject(projectPath);
31
+ if (!existsSync(eventsDir))
32
+ warnings.push(`No exec/events directory: ${eventsDir}`);
33
+ const files = listFilesRecursive(eventsDir).filter(p => extname(p).toLowerCase() === '.json');
34
+ let parsedEvents = 0;
35
+ for (const f of files) {
36
+ let obj;
37
+ try {
38
+ obj = readJson(f);
39
+ }
40
+ catch {
41
+ errors.push(`${f}: failed to parse JSON`);
42
+ continue;
43
+ }
44
+ const shapeErrs = validateEventShape(obj, f);
45
+ errors.push(...shapeErrs);
46
+ if (shapeErrs.length === 0) {
47
+ parsedEvents++;
48
+ const ev = obj;
49
+ if (!scheduleIds.has(ev.task_id))
50
+ errors.push(`${f}: task_id ${ev.task_id} not found in sch-*.yaml`);
51
+ }
52
+ }
53
+ return {
54
+ ok: errors.length === 0,
55
+ errors,
56
+ warnings,
57
+ stats: {
58
+ events: parsedEvents,
59
+ event_files: files.length,
60
+ schedule_ids: schedule.nodes.size,
61
+ schedule_files: schedule.files.length,
62
+ },
63
+ };
64
+ }
65
+ export function printValidateResult(res) {
66
+ process.stdout.write(res.ok ? 'OK: validation passed\n' : 'NG: validation failed\n');
67
+ process.stdout.write(`stats: events=${res.stats.events}, event_files=${res.stats.event_files}, schedule_ids=${res.stats.schedule_ids}, schedule_files=${res.stats.schedule_files}\n`);
68
+ if (res.warnings.length) {
69
+ process.stdout.write('\nWarnings:\n');
70
+ for (const w of res.warnings)
71
+ process.stdout.write(`- ${w}\n`);
72
+ }
73
+ if (res.errors.length) {
74
+ process.stdout.write('\nErrors:\n');
75
+ for (const e of res.errors)
76
+ process.stdout.write(`- ${e}\n`);
77
+ }
78
+ }
79
+ export function exitWithCode(ok) {
80
+ process.exitCode = ok ? 0 : 1;
81
+ }
82
+ export function writeCpmFiles(projectPath, cpm, stateSnapshot) {
83
+ const genDir = generatedDirForProject(projectPath);
84
+ ensureDir(genDir);
85
+ writeJson(join(genDir, 'cpm.json'), cpm);
86
+ const rows = Object.values(cpm.nodes).sort((a, b) => a.es - b.es || a.id.localeCompare(b.id));
87
+ const lines = [];
88
+ lines.push(`# CPM`);
89
+ lines.push('');
90
+ lines.push(`- project_duration_days: \`${cpm.project_duration_days}\``);
91
+ lines.push('');
92
+ lines.push(`| id | owner | kind | dur | ES | EF | LS | LF | slack | depends_on |`);
93
+ lines.push(`|---|---|---:|---:|---:|---:|---:|---:|---:|---|`);
94
+ for (const r of rows) {
95
+ lines.push(`| \`${r.id}\` | ${r.owner ?? '-'} | ${r.kind} | ${r.duration_days} | ${r.es} | ${r.ef} | ${r.ls} | ${r.lf} | ${r.slack} | ${r.depends_on.join(', ')} |`);
96
+ }
97
+ lines.push('');
98
+ writeFileSync(join(genDir, 'cpm.md'), lines.join('\n'), 'utf8');
99
+ const cp = [];
100
+ cp.push(`# Critical Path`);
101
+ cp.push('');
102
+ cp.push(`- project_duration_days: \`${cpm.project_duration_days}\``);
103
+ cp.push('');
104
+ if (!cpm.critical_path.length)
105
+ cp.push('_No critical path computed._');
106
+ else {
107
+ cp.push(`Critical path (one path, tie-broken):`);
108
+ cp.push('');
109
+ for (const id of cpm.critical_path) {
110
+ const n = cpm.nodes[id];
111
+ cp.push(`- \`${id}\`${n.name ? ` — ${n.name}` : ''} (ES=${n.es}, EF=${n.ef})`);
112
+ }
113
+ }
114
+ cp.push('');
115
+ writeFileSync(join(genDir, 'critical-path.md'), cp.join('\n'), 'utf8');
116
+ const schedule = buildScheduleIndex(projectPath);
117
+ const criticalSet = new Set(cpm.critical_path);
118
+ const taskRows = rows.filter(row => row.kind === 'task');
119
+ const stateCounts = {
120
+ todo: 0,
121
+ doing: 0,
122
+ blocked: 0,
123
+ done: 0,
124
+ cancelled: 0,
125
+ };
126
+ for (const row of taskRows) {
127
+ const state = stateSnapshot?.tasks[row.id]?.state ?? 'todo';
128
+ stateCounts[state] += 1;
129
+ }
130
+ const doneCount = stateCounts.done;
131
+ const totalTaskCount = taskRows.length;
132
+ const progressPercent = totalTaskCount > 0 ? ((doneCount / totalTaskCount) * 100).toFixed(1) : '0.0';
133
+ const ready = computeReadyIds(schedule, {
134
+ schedule_path: cpm.schedule_path,
135
+ tasks: stateSnapshot?.tasks ?? {},
136
+ });
137
+ const readyOrdered = orderReadyIds(ready, cpm, 'critical-first');
138
+ const criticalDoingCount = taskRows.filter(row => criticalSet.has(row.id) && (stateSnapshot?.tasks[row.id]?.state ?? 'todo') === 'doing').length;
139
+ const progressSummaryLines = buildProgressSummaryLines({
140
+ cpm,
141
+ schedule,
142
+ stateCounts,
143
+ totalTaskCount,
144
+ readyCount: ready.length,
145
+ nextTaskId: readyOrdered[0] ?? null,
146
+ criticalDoingCount,
147
+ });
148
+ writeFileSync(join(genDir, 'timeline.svg'), buildTimelineSvg(cpm, schedule, stateSnapshot), 'utf8');
149
+ writeFileSync(join(genDir, 'timeline.md'), buildTimelineMarkdown(cpm, {
150
+ criticalPathTaskCount: criticalSet.size,
151
+ progressPercent,
152
+ doneTasks: `${doneCount}/${totalTaskCount}`,
153
+ taskStateCounts: `todo=${stateCounts.todo}, doing=${stateCounts.doing}, blocked=${stateCounts.blocked}, done=${stateCounts.done}, cancelled=${stateCounts.cancelled}`,
154
+ progressSummaryLines,
155
+ }), 'utf8');
156
+ }
157
+ export function writeGeneratedCore(projectPath, events, schedule, cpm) {
158
+ const genDir = generatedDirForProject(projectPath);
159
+ ensureDir(genDir);
160
+ const jsonl = events.map(x => JSON.stringify(x.event)).join('\n') + (events.length ? '\n' : '');
161
+ writeFileSync(join(genDir, 'exec.jsonl'), jsonl, 'utf8');
162
+ const snapshot = foldEventsToState(events, schedule, projectPath);
163
+ writeJson(join(genDir, 'state.json'), snapshot);
164
+ const ready = computeReadyIds(schedule, snapshot);
165
+ const readySnapshot = buildReadySnapshot(projectPath, schedule, ready, cpm);
166
+ writeReadyFiles(projectPath, readySnapshot);
167
+ writeJson(join(genDir, 'metadata.json'), {
168
+ generated_at_utc: nowUtcIsoSeconds(),
169
+ schedule_path: toArtifactPath(projectPath),
170
+ execution_path: toArtifactPath(executionRootForProject(projectPath)),
171
+ generated_dir: toArtifactPath(genDir),
172
+ schedule_files: schedule.files.map(p => toScheduleFilePath(projectPath, p)).sort(),
173
+ event_files_count: events.length,
174
+ default_scheduler_strategy: 'critical-first',
175
+ derived_files: [
176
+ 'agent-briefs/index.md',
177
+ 'claim-next.json',
178
+ 'cpm.json',
179
+ 'cpm.md',
180
+ 'critical-path.md',
181
+ 'exec.jsonl',
182
+ 'metadata.json',
183
+ 'ready.json',
184
+ 'ready.md',
185
+ 'schedule-diff.md',
186
+ 'schedule-hash.json',
187
+ 'state.json',
188
+ 'task-catalog.md',
189
+ 'timeline.md',
190
+ 'timeline.svg',
191
+ ],
192
+ });
193
+ return snapshot;
194
+ }
195
+ export { buildScheduleIndex, computeCpm, selectNextTask, writeScheduleHashAndDiff };
@@ -0,0 +1,119 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
3
+ import { basename, join, relative } from 'node:path';
4
+ import yaml from 'js-yaml';
5
+ import { specdojoRootDir } from './specdojo-config.js';
6
+ export function nowUtcIsoSeconds() {
7
+ return new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
8
+ }
9
+ export function isUtcIsoSeconds(ts) {
10
+ return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(ts);
11
+ }
12
+ export function tsForFilenameUtc(ts) {
13
+ return ts.replace(/[-:]/g, '').replace('T', 'T');
14
+ }
15
+ export function safeSlug(s) {
16
+ return s
17
+ .trim()
18
+ .replace(/\s+/g, '-')
19
+ .replace(/[^A-Za-z0-9._-]/g, '_')
20
+ .slice(0, 80);
21
+ }
22
+ export function randomHex(bytes) {
23
+ return randomBytes(bytes).toString('hex');
24
+ }
25
+ export function ensureDir(path) {
26
+ if (!existsSync(path))
27
+ mkdirSync(path, { recursive: true });
28
+ }
29
+ export function requireNonEmpty(name, v) {
30
+ if (typeof v !== 'string' || v.trim().length === 0)
31
+ throw new Error(`${name} is required`);
32
+ return v.trim();
33
+ }
34
+ export function collectRepeatable(value, previous) {
35
+ return previous.concat([value]);
36
+ }
37
+ export function parseKeyValuePairs(pairs) {
38
+ if (!pairs || pairs.length === 0)
39
+ return undefined;
40
+ const out = {};
41
+ for (const p of pairs) {
42
+ const idx = p.indexOf('=');
43
+ if (idx <= 0)
44
+ throw new Error(`Invalid key=value: ${p}`);
45
+ const k = p.slice(0, idx).trim();
46
+ const v = p.slice(idx + 1).trim();
47
+ if (!k)
48
+ throw new Error(`Empty key in: ${p}`);
49
+ out[k] = v;
50
+ }
51
+ return Object.keys(out).length ? out : undefined;
52
+ }
53
+ export function listFilesRecursive(dir) {
54
+ const out = [];
55
+ if (!existsSync(dir))
56
+ return out;
57
+ for (const name of readdirSync(dir)) {
58
+ const full = join(dir, name);
59
+ const st = statSync(full);
60
+ if (st.isDirectory())
61
+ out.push(...listFilesRecursive(full));
62
+ else if (st.isFile())
63
+ out.push(full);
64
+ }
65
+ return out;
66
+ }
67
+ export function readJson(path) {
68
+ return JSON.parse(readFileSync(path, 'utf8'));
69
+ }
70
+ export function writeJson(path, data) {
71
+ writeFileSync(path, JSON.stringify(data, null, 2) + '\n', 'utf8');
72
+ }
73
+ export function readYaml(path) {
74
+ return yaml.load(readFileSync(path, 'utf8'));
75
+ }
76
+ export function isSchYamlFilename(path) {
77
+ const name = basename(path);
78
+ // Exclude defaults file
79
+ if (name === 'sch-defaults.yaml' || name === 'sch-defaults.yml')
80
+ return false;
81
+ return /^sch-.*\.(yaml|yml)$/.test(name);
82
+ }
83
+ export function sleepMs(ms) {
84
+ const sab = new SharedArrayBuffer(4);
85
+ const int32 = new Int32Array(sab);
86
+ Atomics.wait(int32, 0, 0, ms);
87
+ }
88
+ export function toPortablePath(path) {
89
+ return path.replace(/\\/g, '/');
90
+ }
91
+ export function toArtifactPath(path) {
92
+ const rel = relative(specdojoRootDir(), path);
93
+ return toPortablePath(rel || '.');
94
+ }
95
+ export function toScheduleFilePath(schedulePath, filePath) {
96
+ return toPortablePath(relative(schedulePath, filePath) || '.');
97
+ }
98
+ export function formatDateOnlyUtc(dt) {
99
+ const yyyy = dt.getUTCFullYear().toString().padStart(4, '0');
100
+ const mm = (dt.getUTCMonth() + 1).toString().padStart(2, '0');
101
+ const dd = dt.getUTCDate().toString().padStart(2, '0');
102
+ return `${yyyy}-${mm}-${dd}`;
103
+ }
104
+ export function normalizeDateOnly(value) {
105
+ if (value instanceof Date && !Number.isNaN(value.getTime()))
106
+ return formatDateOnlyUtc(value);
107
+ if (typeof value !== 'string')
108
+ return null;
109
+ const trimmed = value.trim();
110
+ if (!trimmed)
111
+ return null;
112
+ const m = trimmed.match(/^(\d{4}-\d{2}-\d{2})/);
113
+ if (m)
114
+ return m[1];
115
+ const dt = new Date(trimmed);
116
+ if (Number.isNaN(dt.getTime()))
117
+ return null;
118
+ return formatDateOnlyUtc(dt);
119
+ }
@@ -0,0 +1 @@
1
+ export {};