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.
package/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # specdojo
2
+
3
+ CLI for SpecDojo specification-driven execution workflows.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g specdojo
9
+ ```
10
+
11
+ Or run via `npx`:
12
+
13
+ ```bash
14
+ npx specdojo --help
15
+ ```
16
+
17
+ ## Quick start
18
+
19
+ Initialize config:
20
+
21
+ ```bash
22
+ specdojo config init
23
+ ```
24
+
25
+ List projects:
26
+
27
+ ```bash
28
+ specdojo project list
29
+ ```
30
+
31
+ Validate and build execution artifacts:
32
+
33
+ ```bash
34
+ specdojo exec validate --project shj-0001
35
+ specdojo exec build --project shj-0001
36
+ ```
37
+
38
+ Claim the next task:
39
+
40
+ ```bash
41
+ specdojo exec scheduler --project shj-0001 --by copilot --owner ARC
42
+ ```
43
+
44
+ ## Config file
45
+
46
+ Create `specdojo.config.json` in the repository root.
47
+
48
+ ```json
49
+ {
50
+ "version": 1,
51
+ "projects": {
52
+ "shj-0001": {
53
+ "schedule_path": "docs/ja/sdh-ja-projects/prj-0001/060-schedule",
54
+ "execution_path": "docs/ja/sdh-ja-projects/prj-0001/070-execution",
55
+ "members_path": "docs/ja/sdh-ja-projects/prj-0001/040-project-management/010-management-plan/members.yaml"
56
+ }
57
+ }
58
+ }
59
+ ```
@@ -0,0 +1,342 @@
1
+ import { extname, join, resolve } from 'node:path';
2
+ import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import { collectRepeatable, ensureDir, isUtcIsoSeconds, listFilesRecursive, nowUtcIsoSeconds, parseKeyValuePairs, randomHex, readJson, requireNonEmpty, safeSlug, sleepMs, toArtifactPath, tsForFilenameUtc, writeJson, } from './exec-shared.js';
4
+ import { eventsDirForProject, executionRootForProject } from './exec-project.js';
5
+ export { collectRepeatable };
6
+ export function validateEventShape(obj, source) {
7
+ const errs = [];
8
+ function err(msg) {
9
+ errs.push(`${source}: ${msg}`);
10
+ }
11
+ if (!obj || typeof obj !== 'object') {
12
+ err('not a JSON object');
13
+ return errs;
14
+ }
15
+ if (obj.v !== 1)
16
+ err('v must be 1');
17
+ if (typeof obj.ts !== 'string' || !isUtcIsoSeconds(obj.ts)) {
18
+ err('ts must be UTC ISO seconds like 2026-03-05T03:10:00Z');
19
+ }
20
+ const allowed = new Set([
21
+ 'claim',
22
+ 'note',
23
+ 'block',
24
+ 'unblock',
25
+ 'complete',
26
+ 'cancel',
27
+ 'link',
28
+ 'estimate',
29
+ ]);
30
+ if (typeof obj.type !== 'string' || !allowed.has(obj.type)) {
31
+ err(`type must be one of ${Array.from(allowed).join(', ')}`);
32
+ }
33
+ if (typeof obj.task_id !== 'string' || obj.task_id.trim() === '') {
34
+ err('task_id must be non-empty string');
35
+ }
36
+ if (typeof obj.by !== 'string' || obj.by.trim() === '')
37
+ err('by must be non-empty string');
38
+ if (typeof obj.msg !== 'string')
39
+ err('msg must be string');
40
+ if (obj.refs !== undefined &&
41
+ (typeof obj.refs !== 'object' || obj.refs === null || Array.isArray(obj.refs))) {
42
+ err('refs must be object if provided');
43
+ }
44
+ if (obj.meta !== undefined &&
45
+ (typeof obj.meta !== 'object' || obj.meta === null || Array.isArray(obj.meta))) {
46
+ err('meta must be object if provided');
47
+ }
48
+ return errs;
49
+ }
50
+ export function readAllEventFiles(projectPath) {
51
+ const dir = eventsDirForProject(projectPath);
52
+ const files = listFilesRecursive(dir).filter(p => extname(p).toLowerCase() === '.json');
53
+ const items = [];
54
+ for (const f of files)
55
+ items.push({ path: f, event: readJson(f) });
56
+ items.sort((a, b) => {
57
+ if (a.event.ts < b.event.ts)
58
+ return -1;
59
+ if (a.event.ts > b.event.ts)
60
+ return 1;
61
+ return a.path.localeCompare(b.path);
62
+ });
63
+ return items;
64
+ }
65
+ export function buildEvent(type, o) {
66
+ const task_id = requireNonEmpty('task', o.task);
67
+ const by = requireNonEmpty('by', o.by);
68
+ const msg = requireNonEmpty('msg', o.msg);
69
+ const refs = parseKeyValuePairs(o.ref);
70
+ const metaPairs = parseKeyValuePairs(o.meta);
71
+ const meta = metaPairs
72
+ ? Object.fromEntries(Object.entries(metaPairs))
73
+ : undefined;
74
+ const e = { v: 1, ts: nowUtcIsoSeconds(), type, task_id, by, msg };
75
+ if (o.runId)
76
+ e.run_id = String(o.runId);
77
+ if (refs)
78
+ e.refs = refs;
79
+ if (meta)
80
+ e.meta = meta;
81
+ return e;
82
+ }
83
+ export function writeEventFile(projectPath, event) {
84
+ const execDir = eventsDirForProject(projectPath);
85
+ ensureDir(execDir);
86
+ const tsPart = tsForFilenameUtc(event.ts);
87
+ const byPart = safeSlug(event.by);
88
+ const idPart = safeSlug(event.task_id);
89
+ const rand = randomHex(2);
90
+ const filename = `${tsPart}_${byPart}_${idPart}_${event.type}_${rand}.json`;
91
+ const fullpath = join(execDir, filename);
92
+ writeFileSync(fullpath, JSON.stringify(event, null, 2) + '\n', 'utf8');
93
+ return fullpath;
94
+ }
95
+ export function foldEventsToState(events, schedule, projectPath) {
96
+ const tasks = {};
97
+ function ensure(id) {
98
+ if (!tasks[id])
99
+ tasks[id] = { state: 'todo' };
100
+ return tasks[id];
101
+ }
102
+ for (const { event } of events) {
103
+ const cur = ensure(event.task_id);
104
+ cur.last_ts = event.ts;
105
+ cur.last_by = event.by;
106
+ cur.last_type = event.type;
107
+ cur.last_msg = event.msg;
108
+ if (event.refs)
109
+ cur.refs = event.refs;
110
+ if (event.meta)
111
+ cur.meta = event.meta;
112
+ if (event.type === 'claim')
113
+ cur.state = 'doing';
114
+ else if (event.type === 'block')
115
+ cur.state = 'blocked';
116
+ else if (event.type === 'unblock')
117
+ cur.state = 'todo';
118
+ else if (event.type === 'complete')
119
+ cur.state = 'done';
120
+ else if (event.type === 'cancel')
121
+ cur.state = 'cancelled';
122
+ }
123
+ for (const id of schedule.nodes.keys())
124
+ ensure(id);
125
+ return {
126
+ schedule_path: toArtifactPath(projectPath),
127
+ tasks,
128
+ };
129
+ }
130
+ export function isDependencySatisfied(schedule, snapshot, nodeId, visiting = new Set()) {
131
+ const node = schedule.nodes.get(nodeId);
132
+ if (!node)
133
+ return false;
134
+ if (node.kind === 'task') {
135
+ return (snapshot.tasks[nodeId]?.state ?? 'todo') === 'done';
136
+ }
137
+ if (visiting.has(nodeId))
138
+ return false;
139
+ visiting.add(nodeId);
140
+ const ok = node.depends_on.every(dep => isDependencySatisfied(schedule, snapshot, dep, visiting));
141
+ visiting.delete(nodeId);
142
+ return ok;
143
+ }
144
+ export function computeReadyIds(schedule, snapshot) {
145
+ function stateOf(id) {
146
+ return snapshot.tasks[id]?.state ?? 'todo';
147
+ }
148
+ const ready = [];
149
+ for (const n of schedule.nodes.values()) {
150
+ if (n.kind !== 'task')
151
+ continue;
152
+ const st = stateOf(n.id);
153
+ if (st === 'done' || st === 'cancelled' || st === 'doing' || st === 'blocked')
154
+ continue;
155
+ if (n.depends_on.every(d => isDependencySatisfied(schedule, snapshot, d)))
156
+ ready.push(n.id);
157
+ }
158
+ ready.sort();
159
+ return ready;
160
+ }
161
+ export function findDoingTasksForActor(snapshot, actor) {
162
+ return Object.entries(snapshot.tasks)
163
+ .filter(([, st]) => st.state === 'doing' && st.last_by === actor)
164
+ .map(([taskId]) => taskId)
165
+ .sort();
166
+ }
167
+ export function canClaimTask(schedule, snapshot, taskId, actorOwner, allowOwnerMismatch = false) {
168
+ const node = schedule.nodes.get(taskId);
169
+ if (!node)
170
+ return { ok: false, reason: `task not found in schedule: ${taskId}` };
171
+ if (node.kind !== 'task')
172
+ return { ok: false, reason: `cannot claim non-task node: ${taskId}` };
173
+ if (node.owner && !allowOwnerMismatch && actorOwner !== node.owner) {
174
+ return {
175
+ ok: false,
176
+ reason: `task assigned to owner ${node.owner}; acting owner is ${actorOwner ?? '(unspecified)'}. ` +
177
+ `Use --owner ${node.owner}, SPECDOJO_OWNER=${node.owner}, or --allow-owner-mismatch.`,
178
+ };
179
+ }
180
+ const cur = snapshot.tasks[taskId];
181
+ const state = cur?.state ?? 'todo';
182
+ if (state === 'doing')
183
+ return { ok: false, reason: `task already doing: ${taskId}` };
184
+ if (state === 'done')
185
+ return { ok: false, reason: `task already done: ${taskId}` };
186
+ if (state === 'cancelled')
187
+ return { ok: false, reason: `task cancelled: ${taskId}` };
188
+ if (state === 'blocked')
189
+ return { ok: false, reason: `task blocked: ${taskId}` };
190
+ for (const dep of node.depends_on) {
191
+ if (!isDependencySatisfied(schedule, snapshot, dep)) {
192
+ return { ok: false, reason: `dependency not satisfied: ${dep}` };
193
+ }
194
+ }
195
+ return { ok: true };
196
+ }
197
+ export function canCompleteTask(schedule, snapshot, taskId, actor) {
198
+ const node = schedule.nodes.get(taskId);
199
+ if (!node)
200
+ return { ok: false, reason: `task not found in schedule: ${taskId}` };
201
+ if (node.kind !== 'task')
202
+ return { ok: false, reason: `cannot complete non-task node: ${taskId}` };
203
+ const cur = snapshot.tasks[taskId];
204
+ const state = cur?.state ?? 'todo';
205
+ if (state === 'todo')
206
+ return { ok: false, reason: `task not started: ${taskId}` };
207
+ if (state === 'blocked')
208
+ return { ok: false, reason: `task is blocked: ${taskId}` };
209
+ if (state === 'done')
210
+ return { ok: false, reason: `task already done: ${taskId}` };
211
+ if (state === 'cancelled')
212
+ return { ok: false, reason: `task cancelled: ${taskId}` };
213
+ if (state !== 'doing')
214
+ return { ok: false, reason: `task is not doing: ${taskId}` };
215
+ if (cur?.last_by !== actor) {
216
+ return {
217
+ ok: false,
218
+ reason: `task is being worked on by another actor: ${cur?.last_by ?? '(unknown)'}`,
219
+ };
220
+ }
221
+ return { ok: true };
222
+ }
223
+ export function canBlockTask(schedule, snapshot, taskId, actor) {
224
+ const node = schedule.nodes.get(taskId);
225
+ if (!node)
226
+ return { ok: false, reason: `task not found in schedule: ${taskId}` };
227
+ if (node.kind !== 'task')
228
+ return { ok: false, reason: `cannot block non-task node: ${taskId}` };
229
+ const cur = snapshot.tasks[taskId];
230
+ const state = cur?.state ?? 'todo';
231
+ if (state === 'todo')
232
+ return { ok: false, reason: `task not started: ${taskId}` };
233
+ if (state === 'blocked')
234
+ return { ok: false, reason: `task already blocked: ${taskId}` };
235
+ if (state === 'done')
236
+ return { ok: false, reason: `task already done: ${taskId}` };
237
+ if (state === 'cancelled')
238
+ return { ok: false, reason: `task cancelled: ${taskId}` };
239
+ if (state !== 'doing')
240
+ return { ok: false, reason: `task is not doing: ${taskId}` };
241
+ if (cur?.last_by !== actor) {
242
+ return {
243
+ ok: false,
244
+ reason: `task is being worked on by another actor: ${cur?.last_by ?? '(unknown)'}`,
245
+ };
246
+ }
247
+ return { ok: true };
248
+ }
249
+ export function canUnblockTask(schedule, snapshot, taskId) {
250
+ const node = schedule.nodes.get(taskId);
251
+ if (!node)
252
+ return { ok: false, reason: `task not found in schedule: ${taskId}` };
253
+ if (node.kind !== 'task')
254
+ return { ok: false, reason: `cannot unblock non-task node: ${taskId}` };
255
+ const cur = snapshot.tasks[taskId];
256
+ const state = cur?.state ?? 'todo';
257
+ if (state === 'todo')
258
+ return { ok: false, reason: `task is not blocked: ${taskId}` };
259
+ if (state === 'doing')
260
+ return { ok: false, reason: `task is not blocked: ${taskId}` };
261
+ if (state === 'done')
262
+ return { ok: false, reason: `task already done: ${taskId}` };
263
+ if (state === 'cancelled')
264
+ return { ok: false, reason: `task cancelled: ${taskId}` };
265
+ if (state !== 'blocked')
266
+ return { ok: false, reason: `task is not blocked: ${taskId}` };
267
+ return { ok: true };
268
+ }
269
+ export function canCancelTask(schedule, snapshot, taskId, actor) {
270
+ const node = schedule.nodes.get(taskId);
271
+ if (!node)
272
+ return { ok: false, reason: `task not found in schedule: ${taskId}` };
273
+ if (node.kind !== 'task')
274
+ return { ok: false, reason: `cannot cancel non-task node: ${taskId}` };
275
+ const cur = snapshot.tasks[taskId];
276
+ const state = cur?.state ?? 'todo';
277
+ if (state === 'done')
278
+ return { ok: false, reason: `task already done: ${taskId}` };
279
+ if (state === 'cancelled')
280
+ return { ok: false, reason: `task already cancelled: ${taskId}` };
281
+ if (state === 'doing' && cur?.last_by !== actor) {
282
+ return {
283
+ ok: false,
284
+ reason: `task is being worked on by another actor: ${cur?.last_by ?? '(unknown)'}`,
285
+ };
286
+ }
287
+ return { ok: true };
288
+ }
289
+ function schedulerLockDir(projectPath) {
290
+ return join(executionRootForProject(projectPath), 'exec', '.locks', 'scheduler.lock');
291
+ }
292
+ export function acquireSchedulerLock(projectPath, opts) {
293
+ const lockDir = schedulerLockDir(projectPath);
294
+ const lockParent = resolve(lockDir, '..');
295
+ ensureDir(lockParent);
296
+ const start = Date.now();
297
+ while (true) {
298
+ try {
299
+ mkdirSync(lockDir);
300
+ writeJson(join(lockDir, 'owner.json'), {
301
+ actor: opts.actor,
302
+ pid: process.pid,
303
+ acquired_at_utc: nowUtcIsoSeconds(),
304
+ });
305
+ return lockDir;
306
+ }
307
+ catch (e) {
308
+ if (e?.code !== 'EEXIST')
309
+ throw e;
310
+ try {
311
+ const st = statSync(lockDir);
312
+ const ageMs = Date.now() - st.mtimeMs;
313
+ if (ageMs > opts.lockStaleMs) {
314
+ rmSync(lockDir, { recursive: true, force: true });
315
+ continue;
316
+ }
317
+ }
318
+ catch {
319
+ continue;
320
+ }
321
+ if (Date.now() - start > opts.lockTimeoutMs) {
322
+ let ownerInfo = '';
323
+ try {
324
+ ownerInfo = readFileSync(join(lockDir, 'owner.json'), 'utf8');
325
+ }
326
+ catch {
327
+ ownerInfo = '(owner metadata unavailable)';
328
+ }
329
+ throw new Error(`Failed to acquire scheduler lock within ${opts.lockTimeoutMs} ms.\n` +
330
+ `Lock: ${lockDir}\n` +
331
+ `Owner: ${ownerInfo}`);
332
+ }
333
+ sleepMs(200);
334
+ }
335
+ }
336
+ }
337
+ export function releaseSchedulerLock(lockDir) {
338
+ rmSync(lockDir, { recursive: true, force: true });
339
+ }
340
+ export function schedulerLockPath(projectPath) {
341
+ return schedulerLockDir(projectPath);
342
+ }
@@ -0,0 +1,87 @@
1
+ import { dirname, join, resolve } from 'node:path';
2
+ import { defaultConfigPath, getProjectExecutionPath, getProjectSchedulePath, loadConfig, loadEnv, } from './specdojo-config.js';
3
+ function projectBaseDir() {
4
+ const { configPath } = loadConfig();
5
+ return dirname(configPath || defaultConfigPath());
6
+ }
7
+ function resolveProjectRelative(baseDir, pathValue) {
8
+ return resolve(baseDir, pathValue.trim());
9
+ }
10
+ export function activateResolvedProjectPaths(paths) {
11
+ process.env.SPECDOJO_SCHEDULE_PATH = paths.schedulePath;
12
+ process.env.SPECDOJO_EXECUTION_PATH = paths.executionPath;
13
+ }
14
+ export function executionRootForProject(projectPath) {
15
+ loadEnv();
16
+ const baseDir = projectBaseDir();
17
+ const envSchedulePath = process.env.SPECDOJO_SCHEDULE_PATH;
18
+ const envExecutionPath = process.env.SPECDOJO_EXECUTION_PATH;
19
+ if (envSchedulePath &&
20
+ envSchedulePath.trim() &&
21
+ envExecutionPath &&
22
+ envExecutionPath.trim() &&
23
+ resolveProjectRelative(baseDir, envSchedulePath) === projectPath) {
24
+ return resolveProjectRelative(baseDir, envExecutionPath);
25
+ }
26
+ const { config } = loadConfig();
27
+ if (config) {
28
+ for (const project of Object.values(config.projects)) {
29
+ const schedulePath = resolveProjectRelative(baseDir, getProjectSchedulePath(project));
30
+ if (schedulePath !== projectPath)
31
+ continue;
32
+ return resolveProjectRelative(baseDir, getProjectExecutionPath(project));
33
+ }
34
+ }
35
+ throw new Error(`Execution path not specified for schedule path: ${projectPath}\n` +
36
+ `Provide --project <id>, or SPECDOJO_PROJECT, or SPECDOJO_SCHEDULE_PATH together with SPECDOJO_EXECUTION_PATH.`);
37
+ }
38
+ export function generatedDirForProject(projectPath) {
39
+ return join(executionRootForProject(projectPath), 'generated');
40
+ }
41
+ export function eventsDirForProject(projectPath) {
42
+ return join(executionRootForProject(projectPath), 'exec', 'events');
43
+ }
44
+ export function resolveProjectPaths(opts) {
45
+ loadEnv();
46
+ const { config, configPath } = loadConfig();
47
+ const baseDir = dirname(configPath);
48
+ const envSchedulePath = process.env.SPECDOJO_SCHEDULE_PATH;
49
+ const envExecutionPath = process.env.SPECDOJO_EXECUTION_PATH;
50
+ const envProject = process.env.SPECDOJO_PROJECT;
51
+ function fromProjectId(projectId, source) {
52
+ if (!config) {
53
+ throw new Error(`${source} requires specdojo.config.json: ${configPath}\n` +
54
+ `Define the project id there, or use SPECDOJO_SCHEDULE_PATH/SPECDOJO_EXECUTION_PATH.`);
55
+ }
56
+ const project = config.projects[projectId];
57
+ if (!project) {
58
+ throw new Error(`Unknown ${source} value: ${projectId} (check ${configPath})`);
59
+ }
60
+ return {
61
+ schedulePath: resolveProjectRelative(baseDir, getProjectSchedulePath(project)),
62
+ executionPath: resolveProjectRelative(baseDir, getProjectExecutionPath(project)),
63
+ };
64
+ }
65
+ if (opts.project && opts.project.trim()) {
66
+ return fromProjectId(opts.project.trim(), '--project');
67
+ }
68
+ if ((envSchedulePath && envSchedulePath.trim()) ||
69
+ (envExecutionPath && envExecutionPath.trim())) {
70
+ if (!envSchedulePath ||
71
+ !envSchedulePath.trim() ||
72
+ !envExecutionPath ||
73
+ !envExecutionPath.trim()) {
74
+ throw new Error(`SPECDOJO_SCHEDULE_PATH and SPECDOJO_EXECUTION_PATH must be specified together when using direct environment path overrides.`);
75
+ }
76
+ return {
77
+ schedulePath: resolveProjectRelative(baseDir, envSchedulePath),
78
+ executionPath: resolveProjectRelative(baseDir, envExecutionPath),
79
+ };
80
+ }
81
+ if (envProject && envProject.trim()) {
82
+ return fromProjectId(envProject.trim(), 'SPECDOJO_PROJECT');
83
+ }
84
+ throw new Error(`Project path not specified.\n` +
85
+ `Provide --project <id>, or SPECDOJO_PROJECT, or SPECDOJO_SCHEDULE_PATH together with SPECDOJO_EXECUTION_PATH.\n` +
86
+ `SPECDOJO_PROJECT must match a project id in ${configPath}.`);
87
+ }
@@ -0,0 +1,93 @@
1
+ import { formatDateOnlyUtc } from './exec-shared.js';
2
+ function scheduleAnchorDateUtc() {
3
+ return Date.UTC(2000, 0, 1, 0, 0, 0, 0);
4
+ }
5
+ export function workingMinutesPerDay(calendar) {
6
+ return Math.max(1, Math.round(calendar.work_hours_per_day * 60));
7
+ }
8
+ function endOfWorkingDayUtc(dt, calendar) {
9
+ const end = new Date(dt.getTime());
10
+ end.setUTCHours(0, 0, 0, 0);
11
+ end.setUTCMinutes(workingMinutesPerDay(calendar));
12
+ return end;
13
+ }
14
+ export function isWorkingDateUtc(dt, calendar) {
15
+ const dateOnly = formatDateOnlyUtc(dt);
16
+ return calendar.workdays.has(dt.getUTCDay()) && !calendar.holidays.has(dateOnly);
17
+ }
18
+ function advanceToNextWorkingInstantUtc(dt, calendar) {
19
+ while (true) {
20
+ if (!isWorkingDateUtc(dt, calendar)) {
21
+ dt.setUTCDate(dt.getUTCDate() + 1);
22
+ dt.setUTCHours(0, 0, 0, 0);
23
+ continue;
24
+ }
25
+ const minutesFromStart = dt.getUTCHours() * 60 + dt.getUTCMinutes();
26
+ if (minutesFromStart >= workingMinutesPerDay(calendar)) {
27
+ dt.setUTCDate(dt.getUTCDate() + 1);
28
+ dt.setUTCHours(0, 0, 0, 0);
29
+ continue;
30
+ }
31
+ return;
32
+ }
33
+ }
34
+ export function addWorkingDayOffset(startDate, dayOffset, calendar) {
35
+ const [year, month, day] = startDate.split('-').map(Number);
36
+ const dt = new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));
37
+ advanceToNextWorkingInstantUtc(dt, calendar);
38
+ let remainingMinutes = Math.round(dayOffset * workingMinutesPerDay(calendar));
39
+ while (remainingMinutes > 0) {
40
+ advanceToNextWorkingInstantUtc(dt, calendar);
41
+ const workingDayEnd = endOfWorkingDayUtc(dt, calendar);
42
+ const usableMinutes = Math.round((workingDayEnd.getTime() - dt.getTime()) / (60 * 1000));
43
+ if (remainingMinutes < usableMinutes) {
44
+ dt.setUTCMinutes(dt.getUTCMinutes() + remainingMinutes);
45
+ remainingMinutes = 0;
46
+ break;
47
+ }
48
+ dt.setTime(workingDayEnd.getTime());
49
+ remainingMinutes -= usableMinutes;
50
+ }
51
+ advanceToNextWorkingInstantUtc(dt, calendar);
52
+ return dt;
53
+ }
54
+ export function buildWorkingTaskSegments(startDate, startOffset, durationDays, calendar) {
55
+ const cursor = addWorkingDayOffset(startDate, startOffset, calendar);
56
+ let remainingMinutes = Math.round(durationDays * workingMinutesPerDay(calendar));
57
+ const segments = [];
58
+ while (remainingMinutes > 0) {
59
+ advanceToNextWorkingInstantUtc(cursor, calendar);
60
+ const workingDayEnd = endOfWorkingDayUtc(cursor, calendar);
61
+ const usableMinutes = Math.round((workingDayEnd.getTime() - cursor.getTime()) / (60 * 1000));
62
+ const segmentMinutes = Math.min(remainingMinutes, usableMinutes);
63
+ const segmentStart = new Date(cursor.getTime());
64
+ const segmentEnd = new Date(cursor.getTime());
65
+ segmentEnd.setUTCMinutes(segmentEnd.getUTCMinutes() + segmentMinutes);
66
+ segments.push({ start: segmentStart, end: segmentEnd });
67
+ cursor.setTime(segmentEnd.getTime());
68
+ remainingMinutes -= segmentMinutes;
69
+ }
70
+ return segments;
71
+ }
72
+ function timelineAnchorDate(startDate) {
73
+ if (!startDate)
74
+ return new Date(scheduleAnchorDateUtc());
75
+ const [year, month, day] = startDate.split('-').map(Number);
76
+ return new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));
77
+ }
78
+ export function dateForWorkingOffset(dayOffset, startDate, calendar) {
79
+ return startDate
80
+ ? addWorkingDayOffset(startDate, dayOffset, calendar)
81
+ : new Date(scheduleAnchorDateUtc() + Math.round(dayOffset * workingMinutesPerDay(calendar)) * 60 * 1000);
82
+ }
83
+ export function timelinePositionX(dt, timelineStart, calendar, dayWidth) {
84
+ const midnight = new Date(dt.getTime());
85
+ midnight.setUTCHours(0, 0, 0, 0);
86
+ const dayIndex = Math.floor((midnight.getTime() - timelineStart.getTime()) / 86400000);
87
+ const minutesFromMidnight = dt.getUTCHours() * 60 + dt.getUTCMinutes();
88
+ const relative = Math.max(0, Math.min(1, minutesFromMidnight / workingMinutesPerDay(calendar)));
89
+ return (dayIndex + relative) * dayWidth;
90
+ }
91
+ export function timelineStartDate(startDate) {
92
+ return timelineAnchorDate(startDate);
93
+ }
@@ -0,0 +1,109 @@
1
+ import { toArtifactPath, toScheduleFilePath } from './exec-shared.js';
2
+ export function topoSort(schedule) {
3
+ const indeg = new Map();
4
+ const out = new Map();
5
+ for (const id of schedule.nodes.keys()) {
6
+ indeg.set(id, 0);
7
+ out.set(id, []);
8
+ }
9
+ for (const node of schedule.nodes.values()) {
10
+ for (const dep of node.depends_on) {
11
+ out.get(dep).push(node.id);
12
+ indeg.set(node.id, (indeg.get(node.id) ?? 0) + 1);
13
+ }
14
+ }
15
+ const q = [];
16
+ for (const [id, d] of indeg.entries())
17
+ if (d === 0)
18
+ q.push(id);
19
+ q.sort();
20
+ const order = [];
21
+ while (q.length) {
22
+ const id = q.shift();
23
+ order.push(id);
24
+ for (const nxt of out.get(id)) {
25
+ indeg.set(nxt, (indeg.get(nxt) ?? 0) - 1);
26
+ if ((indeg.get(nxt) ?? 0) === 0) {
27
+ q.push(nxt);
28
+ q.sort();
29
+ }
30
+ }
31
+ }
32
+ if (order.length !== schedule.nodes.size) {
33
+ const rem = Array.from(indeg.entries())
34
+ .filter(([, d]) => d > 0)
35
+ .map(([id]) => id);
36
+ return { order, cycle: rem };
37
+ }
38
+ return { order };
39
+ }
40
+ export function computeCpm(schedule, projectPath) {
41
+ const { order, cycle } = topoSort(schedule);
42
+ if (cycle && cycle.length)
43
+ throw new Error(`schedule dependency cycle detected: ${cycle.join(', ')}`);
44
+ const nodes = {};
45
+ for (const id of order) {
46
+ const n = schedule.nodes.get(id);
47
+ const es = n.depends_on.length === 0 ? 0 : Math.max(...n.depends_on.map(d => nodes[d].ef));
48
+ const ef = es + n.duration_days;
49
+ nodes[id] = {
50
+ id,
51
+ name: n.name,
52
+ owner: n.owner,
53
+ kind: n.kind,
54
+ duration_days: n.duration_days,
55
+ es,
56
+ ef,
57
+ ls: 0,
58
+ lf: 0,
59
+ slack: 0,
60
+ depends_on: n.depends_on,
61
+ schedule_file: toScheduleFilePath(projectPath, n.schedule_file),
62
+ };
63
+ }
64
+ const projectDuration = Math.max(...Object.values(nodes).map(n => n.ef), 0);
65
+ const succ = new Map();
66
+ for (const id of schedule.nodes.keys())
67
+ succ.set(id, []);
68
+ for (const n of schedule.nodes.values()) {
69
+ for (const dep of n.depends_on)
70
+ succ.get(dep).push(n.id);
71
+ }
72
+ const rev = [...order].reverse();
73
+ for (const id of rev) {
74
+ const s = succ.get(id);
75
+ const lf = s.length === 0 ? projectDuration : Math.min(...s.map(child => nodes[child].ls));
76
+ const ls = lf - nodes[id].duration_days;
77
+ nodes[id].lf = lf;
78
+ nodes[id].ls = ls;
79
+ nodes[id].slack = ls - nodes[id].es;
80
+ }
81
+ const critical = new Set(Object.values(nodes)
82
+ .filter(n => n.slack === 0)
83
+ .map(n => n.id));
84
+ const starts = Object.values(nodes)
85
+ .filter(n => critical.has(n.id) && n.es === 0)
86
+ .sort((a, b) => a.id.localeCompare(b.id));
87
+ const path = [];
88
+ if (starts.length) {
89
+ let cur = starts[0].id;
90
+ path.push(cur);
91
+ while (true) {
92
+ const nexts = (succ.get(cur) ?? [])
93
+ .filter(x => critical.has(x))
94
+ .filter(x => nodes[x].es === nodes[cur].ef)
95
+ .sort((a, b) => a.localeCompare(b));
96
+ if (!nexts.length)
97
+ break;
98
+ cur = nexts[0];
99
+ path.push(cur);
100
+ }
101
+ }
102
+ return {
103
+ schedule_path: toArtifactPath(projectPath),
104
+ project_start_date: schedule.start_date,
105
+ project_duration_days: projectDuration,
106
+ nodes,
107
+ critical_path: path,
108
+ };
109
+ }