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,84 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, writeFileSync } from 'node:fs';
3
+ import { basename, join } from 'node:path';
4
+ import { ensureDir, readJson, toArtifactPath, toScheduleFilePath, writeJson, } from './exec-shared.js';
5
+ import { generatedDirForProject } from './exec-project.js';
6
+ function normalizeNodeForHash(n) {
7
+ return {
8
+ id: n.id,
9
+ name: n.name ?? '',
10
+ owner: n.owner ?? '',
11
+ kind: n.kind,
12
+ duration_days: n.duration_days,
13
+ depends_on: [...n.depends_on].sort(),
14
+ schedule_file: basename(n.schedule_file),
15
+ };
16
+ }
17
+ function sha256Json(obj) {
18
+ return createHash('sha256').update(JSON.stringify(obj)).digest('hex');
19
+ }
20
+ function buildScheduleHash(schedule, projectPath) {
21
+ const node_hashes = {};
22
+ for (const n of schedule.nodes.values())
23
+ node_hashes[n.id] = sha256Json(normalizeNodeForHash(n));
24
+ return {
25
+ schema_version: 1,
26
+ schedule_path: toArtifactPath(projectPath),
27
+ schedule_files: schedule.files.map(p => toScheduleFilePath(projectPath, p)).sort(),
28
+ node_hashes,
29
+ };
30
+ }
31
+ function computeScheduleDiff(prev, cur) {
32
+ const prevMap = prev?.node_hashes ?? {};
33
+ const curMap = cur.node_hashes;
34
+ const prevIds = new Set(Object.keys(prevMap));
35
+ const curIds = new Set(Object.keys(curMap));
36
+ const added = Array.from(curIds)
37
+ .filter(id => !prevIds.has(id))
38
+ .sort();
39
+ const removed = Array.from(prevIds)
40
+ .filter(id => !curIds.has(id))
41
+ .sort();
42
+ const changed = Array.from(curIds)
43
+ .filter(id => prevIds.has(id) && prevMap[id] !== curMap[id])
44
+ .sort();
45
+ return {
46
+ schedule_path: cur.schedule_path,
47
+ added,
48
+ removed,
49
+ changed,
50
+ };
51
+ }
52
+ export function writeScheduleHashAndDiff(projectPath, schedule) {
53
+ const genDir = generatedDirForProject(projectPath);
54
+ ensureDir(genDir);
55
+ const cur = buildScheduleHash(schedule, projectPath);
56
+ const hashPath = join(genDir, 'schedule-hash.json');
57
+ let prev = null;
58
+ if (existsSync(hashPath)) {
59
+ try {
60
+ prev = readJson(hashPath);
61
+ }
62
+ catch {
63
+ prev = null;
64
+ }
65
+ }
66
+ const diff = computeScheduleDiff(prev, cur);
67
+ writeJson(hashPath, cur);
68
+ const lines = [];
69
+ lines.push(`# Schedule Diff`);
70
+ lines.push('');
71
+ lines.push(`## Added`);
72
+ lines.push('');
73
+ lines.push(diff.added.length ? diff.added.map(x => `- \`${x}\``).join('\n') : '_none_');
74
+ lines.push('');
75
+ lines.push(`## Removed`);
76
+ lines.push('');
77
+ lines.push(diff.removed.length ? diff.removed.map(x => `- \`${x}\``).join('\n') : '_none_');
78
+ lines.push('');
79
+ lines.push(`## Changed`);
80
+ lines.push('');
81
+ lines.push(diff.changed.length ? diff.changed.map(x => `- \`${x}\``).join('\n') : '_none_');
82
+ lines.push('');
83
+ writeFileSync(join(genDir, 'schedule-diff.md'), lines.join('\n'), 'utf8');
84
+ }
@@ -0,0 +1,202 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { isSchYamlFilename, listFilesRecursive, normalizeDateOnly, readYaml, toScheduleFilePath, } from './exec-shared.js';
4
+ function defaultScheduleCalendar() {
5
+ return {
6
+ timezone: 'UTC',
7
+ workdays: new Set([1, 2, 3, 4, 5]),
8
+ holidays: new Set(),
9
+ work_hours_per_day: 24,
10
+ };
11
+ }
12
+ function parseWorkdayToken(value) {
13
+ const key = value.trim().slice(0, 3).toLowerCase();
14
+ const map = {
15
+ sun: 0,
16
+ mon: 1,
17
+ tue: 2,
18
+ wed: 3,
19
+ thu: 4,
20
+ fri: 5,
21
+ sat: 6,
22
+ };
23
+ return key in map ? map[key] : null;
24
+ }
25
+ function cloneScheduleCalendar(calendar) {
26
+ return {
27
+ timezone: calendar.timezone,
28
+ workdays: new Set(calendar.workdays),
29
+ holidays: new Set(calendar.holidays),
30
+ work_hours_per_day: calendar.work_hours_per_day,
31
+ };
32
+ }
33
+ function applyScheduleCalendar(base, calendar) {
34
+ if (!calendar || typeof calendar !== 'object')
35
+ return null;
36
+ const parsed = cloneScheduleCalendar(base);
37
+ if (typeof calendar.timezone === 'string' && calendar.timezone.trim()) {
38
+ parsed.timezone = calendar.timezone.trim();
39
+ }
40
+ if (Array.isArray(calendar.workdays) && calendar.workdays.length) {
41
+ const workdays = new Set();
42
+ for (const token of calendar.workdays) {
43
+ if (typeof token !== 'string')
44
+ continue;
45
+ const day = parseWorkdayToken(token);
46
+ if (day !== null)
47
+ workdays.add(day);
48
+ }
49
+ if (workdays.size)
50
+ parsed.workdays = workdays;
51
+ }
52
+ if (Array.isArray(calendar.holidays) && calendar.holidays.length) {
53
+ for (const holiday of calendar.holidays
54
+ .map((value) => normalizeDateOnly(value))
55
+ .filter(Boolean)) {
56
+ parsed.holidays.add(holiday);
57
+ }
58
+ }
59
+ if (typeof calendar.work_hours_per_day === 'number' &&
60
+ Number.isFinite(calendar.work_hours_per_day) &&
61
+ calendar.work_hours_per_day > 0 &&
62
+ calendar.work_hours_per_day <= 24) {
63
+ parsed.work_hours_per_day = calendar.work_hours_per_day;
64
+ }
65
+ return parsed;
66
+ }
67
+ function mergeScheduleCalendar(base, extra) {
68
+ const merged = cloneScheduleCalendar(base);
69
+ merged.timezone = extra.timezone;
70
+ merged.workdays = new Set(extra.workdays);
71
+ merged.work_hours_per_day = extra.work_hours_per_day;
72
+ for (const holiday of extra.holidays)
73
+ merged.holidays.add(holiday);
74
+ return merged;
75
+ }
76
+ function extractScheduleStartDate(doc) {
77
+ return normalizeDateOnly(doc?.settings?.start_date ?? doc?.start_date);
78
+ }
79
+ function minDateOnly(a, b) {
80
+ if (!a)
81
+ return b;
82
+ if (!b)
83
+ return a;
84
+ return a <= b ? a : b;
85
+ }
86
+ function nonEmptyString(value) {
87
+ if (typeof value !== 'string')
88
+ return null;
89
+ const trimmed = value.trim();
90
+ return trimmed.length > 0 ? trimmed : null;
91
+ }
92
+ function scheduleSectionLabelForDoc(doc, fallback) {
93
+ const scheduleLevel = nonEmptyString(doc?.schedule_level);
94
+ if (!scheduleLevel)
95
+ return fallback;
96
+ if (scheduleLevel === 'milestones')
97
+ return scheduleLevel;
98
+ if (scheduleLevel === 'domain') {
99
+ const domain = nonEmptyString(doc?.domain);
100
+ return domain ?? fallback;
101
+ }
102
+ if (scheduleLevel === 'container') {
103
+ const domain = nonEmptyString(doc?.domain);
104
+ const container = nonEmptyString(doc?.container);
105
+ if (domain && container)
106
+ return `${domain} / ${container}`;
107
+ return domain ?? container ?? fallback;
108
+ }
109
+ return fallback;
110
+ }
111
+ export function buildScheduleIndex(projectPath) {
112
+ const all = listFilesRecursive(projectPath);
113
+ const files = all.filter(p => isSchYamlFilename(p));
114
+ const defaultsPath = join(projectPath, 'sch-defaults.yaml');
115
+ const nodes = new Map();
116
+ const sectionLabels = {};
117
+ let startDate = null;
118
+ let calendar = defaultScheduleCalendar();
119
+ let hasCalendar = false;
120
+ if (existsSync(defaultsPath)) {
121
+ try {
122
+ const defaultsDoc = readYaml(defaultsPath);
123
+ if (defaultsDoc && typeof defaultsDoc === 'object') {
124
+ startDate = minDateOnly(startDate, extractScheduleStartDate(defaultsDoc));
125
+ const defaultCalendar = applyScheduleCalendar(defaultScheduleCalendar(), defaultsDoc.calendar);
126
+ if (defaultCalendar) {
127
+ calendar = defaultCalendar;
128
+ hasCalendar = true;
129
+ }
130
+ }
131
+ }
132
+ catch {
133
+ // Ignore malformed defaults here; schema/editor validation should catch it.
134
+ }
135
+ }
136
+ for (const f of files) {
137
+ let doc;
138
+ try {
139
+ doc = readYaml(f);
140
+ }
141
+ catch {
142
+ continue;
143
+ }
144
+ if (!doc || typeof doc !== 'object')
145
+ continue;
146
+ const docKind = nonEmptyString(doc?.kind);
147
+ if (docKind === 'defaults' || docKind === 'agent_overrides') {
148
+ continue;
149
+ }
150
+ if (docKind !== 'schedule') {
151
+ throw new Error(`${f}: kind must be 'schedule'`);
152
+ }
153
+ const scheduleFile = toScheduleFilePath(projectPath, f);
154
+ sectionLabels[scheduleFile] = scheduleSectionLabelForDoc(doc, scheduleFile);
155
+ startDate = minDateOnly(startDate, extractScheduleStartDate(doc));
156
+ const docCalendar = applyScheduleCalendar(calendar, doc.calendar);
157
+ if (docCalendar && doc.calendar && typeof doc.calendar === 'object') {
158
+ if (!hasCalendar) {
159
+ calendar = cloneScheduleCalendar(docCalendar);
160
+ hasCalendar = true;
161
+ }
162
+ else {
163
+ calendar = mergeScheduleCalendar(calendar, docCalendar);
164
+ }
165
+ }
166
+ const tasks = Array.isArray(doc.tasks) ? doc.tasks : [];
167
+ const milestones = Array.isArray(doc.milestones) ? doc.milestones : [];
168
+ for (const t of tasks) {
169
+ if (!t || typeof t !== 'object')
170
+ continue;
171
+ const id = String(t.id ?? '').trim();
172
+ if (!id)
173
+ continue;
174
+ nodes.set(id, {
175
+ id,
176
+ name: typeof t.name === 'string' ? t.name : undefined,
177
+ owner: typeof t.owner === 'string' ? t.owner : undefined,
178
+ depends_on: Array.isArray(t.depends_on) ? t.depends_on.map(String) : [],
179
+ duration_days: typeof t.duration_days === 'number' ? t.duration_days : 0,
180
+ kind: 'task',
181
+ schedule_file: f,
182
+ });
183
+ }
184
+ for (const m of milestones) {
185
+ if (!m || typeof m !== 'object')
186
+ continue;
187
+ const id = String(m.id ?? '').trim();
188
+ if (!id)
189
+ continue;
190
+ nodes.set(id, {
191
+ id,
192
+ name: typeof m.name === 'string' ? m.name : undefined,
193
+ owner: typeof m.owner === 'string' ? m.owner : undefined,
194
+ depends_on: Array.isArray(m.depends_on) ? m.depends_on.map(String) : [],
195
+ duration_days: 0,
196
+ kind: 'milestone',
197
+ schedule_file: f,
198
+ });
199
+ }
200
+ }
201
+ return { nodes, files, start_date: startDate, calendar, section_labels: sectionLabels };
202
+ }
@@ -0,0 +1,106 @@
1
+ import { formatDateOnlyUtc } from './exec-shared.js';
2
+ import { isWorkingDateUtc } from './exec-schedule-calendar.js';
3
+ function parseDateOnlyUtc(value) {
4
+ const [year, month, day] = value.split('-').map(Number);
5
+ return new Date(Date.UTC(year, month - 1, day, 0, 0, 0, 0));
6
+ }
7
+ function addUtcDays(base, days) {
8
+ return new Date(base.getTime() + days * 86400000);
9
+ }
10
+ function elapsedWorkingDaysUntil(today, startDate, calendar) {
11
+ const start = parseDateOnlyUtc(startDate);
12
+ const current = parseDateOnlyUtc(formatDateOnlyUtc(today));
13
+ if (current <= start)
14
+ return 0;
15
+ let elapsed = 0;
16
+ for (let cursor = new Date(start.getTime()); cursor < current; cursor = addUtcDays(cursor, 1)) {
17
+ if (isWorkingDateUtc(cursor, calendar))
18
+ elapsed += 1;
19
+ }
20
+ return elapsed;
21
+ }
22
+ export function buildProgressSummaryLines(input) {
23
+ const lines = [];
24
+ const today = new Date();
25
+ const todayLabel = formatDateOnlyUtc(today);
26
+ const doneEquivalent = input.stateCounts.done + input.stateCounts.doing * 0.5;
27
+ const actualPercent = input.totalTaskCount > 0 ? (doneEquivalent / input.totalTaskCount) * 100 : 0;
28
+ let status = '要確認';
29
+ let overview = '開始日または進捗比較に必要な情報が不足しています。';
30
+ let cause = '開始日未設定のため、計画との差分を自動判定できません。';
31
+ let actions = ['プロジェクト開始日を設定し、進捗判定条件を確定してください。'];
32
+ if (input.cpm.project_start_date) {
33
+ const start = parseDateOnlyUtc(input.cpm.project_start_date);
34
+ const todayDate = parseDateOnlyUtc(todayLabel);
35
+ if (todayDate < start) {
36
+ if (input.stateCounts.doing > 0 || input.stateCounts.done > 0) {
37
+ status = '前倒しで進行中';
38
+ overview = `${todayLabel} 時点では計画開始日 ${input.cpm.project_start_date} 前ですが、先行着手が進んでいます。`;
39
+ cause = `開始日前のため本来の進捗遅れはなく、doing ${input.stateCounts.doing} 件で先行準備が進んでいます。`;
40
+ actions = [
41
+ '進行中タスクを完了させ、開始日までにクリティカルパスの先頭を空けてください。',
42
+ input.nextTaskId
43
+ ? `次の着手候補 ${input.nextTaskId} の前提条件を開始日までに確認してください。`
44
+ : '開始日までに次の着手候補と担当を確定してください。',
45
+ ];
46
+ }
47
+ else {
48
+ status = '開始前';
49
+ overview = `${todayLabel} 時点では計画開始日 ${input.cpm.project_start_date} 前です。`;
50
+ cause = '未着手でも計画上の遅れではなく、まだ実行開始タイミングに入っていません。';
51
+ actions = [
52
+ '開始日に着手できるように担当者と実行順序を最終確認してください。',
53
+ input.nextTaskId
54
+ ? `最初の着手候補 ${input.nextTaskId} に必要な入力・レビュー観点を事前に揃えてください。`
55
+ : '開始時点の最初の着手候補を確定してください。',
56
+ ];
57
+ }
58
+ }
59
+ else {
60
+ const expectedPercent = Math.min(100, (elapsedWorkingDaysUntil(today, input.cpm.project_start_date, input.schedule.calendar) /
61
+ Math.max(1, input.cpm.project_duration_days)) *
62
+ 100);
63
+ if (input.stateCounts.blocked > 0 || actualPercent + 10 < expectedPercent) {
64
+ status = '遅れ気味';
65
+ overview = `${todayLabel} 時点の実績進捗は ${actualPercent.toFixed(1)}% 相当で、計画進捗 ${expectedPercent.toFixed(1)}% を下回っています。`;
66
+ cause =
67
+ input.stateCounts.blocked > 0
68
+ ? `blocked が ${input.stateCounts.blocked} 件あり、滞留が進捗を押し下げています。`
69
+ : `完了・進行中件数が計画消化ペースに対して不足しています。`;
70
+ actions = [
71
+ input.stateCounts.blocked > 0
72
+ ? 'blocked タスクの解消担当と期限を直ちに決めてください。'
73
+ : 'クリティカルパス上の進行中タスクを優先完了させてください。',
74
+ input.nextTaskId
75
+ ? `次の着手候補 ${input.nextTaskId} を前倒しで着手できるか確認してください。`
76
+ : 'Ready タスクが不足していないか依存関係と完了登録を確認してください。',
77
+ ];
78
+ }
79
+ else {
80
+ status = '順調';
81
+ overview = `${todayLabel} 時点の実績進捗は ${actualPercent.toFixed(1)}% 相当で、計画進捗 ${expectedPercent.toFixed(1)}% に対して大きな遅れはありません。`;
82
+ cause =
83
+ input.criticalDoingCount > 0
84
+ ? `クリティカルパス上のタスクが ${input.criticalDoingCount} 件進行中で、主要経路の作業が継続しています。`
85
+ : `blocked がなく、Ready タスク ${input.readyCount} 件を維持できています。`;
86
+ actions = [
87
+ '進行中タスクの完了登録を遅らせず、実績状態を最新化してください。',
88
+ input.nextTaskId
89
+ ? `次の着手候補 ${input.nextTaskId} を待たせないよう、依存完了の確認を継続してください。`
90
+ : 'Ready タスクを切らさないよう、後続依存の完了条件を継続確認してください。',
91
+ ];
92
+ }
93
+ }
94
+ }
95
+ lines.push(`## 進捗サマリー`);
96
+ lines.push('');
97
+ lines.push(`- 判定: ${status}`);
98
+ lines.push(`- 概況: ${overview}`);
99
+ lines.push(`- 主な要因: ${cause}`);
100
+ lines.push('');
101
+ lines.push(`## 今後のアクション案`);
102
+ lines.push('');
103
+ actions.forEach((action, index) => lines.push(`${index + 1}. ${action}`));
104
+ lines.push('');
105
+ return lines;
106
+ }
@@ -0,0 +1,128 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { executionRootForProject, generatedDirForProject } from './exec-project.js';
4
+ import { ensureDir, toArtifactPath, toScheduleFilePath, writeJson } from './exec-shared.js';
5
+ export function orderReadyIds(ready, cpm, strategy) {
6
+ const ordered = [...ready];
7
+ if (ordered.length === 0)
8
+ return ordered;
9
+ if (strategy === 'fifo' || !cpm) {
10
+ ordered.sort((a, b) => a.localeCompare(b));
11
+ return ordered;
12
+ }
13
+ ordered.sort((a, b) => {
14
+ const an = cpm.nodes[a];
15
+ const bn = cpm.nodes[b];
16
+ if (an && bn) {
17
+ if (an.slack !== bn.slack)
18
+ return an.slack - bn.slack;
19
+ if (an.es !== bn.es)
20
+ return an.es - bn.es;
21
+ return a.localeCompare(b);
22
+ }
23
+ if (an && !bn)
24
+ return -1;
25
+ if (!an && bn)
26
+ return 1;
27
+ return a.localeCompare(b);
28
+ });
29
+ return ordered;
30
+ }
31
+ export function buildReadySnapshot(projectPath, schedule, ready, cpm) {
32
+ const fifo = orderReadyIds(ready, cpm, 'fifo');
33
+ const criticalFirst = orderReadyIds(ready, cpm, 'critical-first');
34
+ const fifoRank = new Map(fifo.map((id, idx) => [id, idx + 1]));
35
+ const criticalRank = new Map(criticalFirst.map((id, idx) => [id, idx + 1]));
36
+ const executionPath = executionRootForProject(projectPath);
37
+ const generatedDir = generatedDirForProject(projectPath);
38
+ const tasks = criticalFirst.map(id => {
39
+ const node = schedule.nodes.get(id);
40
+ const cpmNode = cpm?.nodes[id];
41
+ return {
42
+ id,
43
+ name: node?.name,
44
+ owner: node?.owner,
45
+ schedule_file: node?.schedule_file ? toScheduleFilePath(projectPath, node.schedule_file) : '',
46
+ fifo_rank: fifoRank.get(id) ?? 0,
47
+ critical_first_rank: criticalRank.get(id) ?? 0,
48
+ cpm: cpmNode
49
+ ? {
50
+ es: cpmNode.es,
51
+ ef: cpmNode.ef,
52
+ ls: cpmNode.ls,
53
+ lf: cpmNode.lf,
54
+ slack: cpmNode.slack,
55
+ }
56
+ : undefined,
57
+ };
58
+ });
59
+ return {
60
+ schedule_path: toArtifactPath(projectPath),
61
+ execution_path: toArtifactPath(executionPath),
62
+ generated_dir: toArtifactPath(generatedDir),
63
+ ready_count: ready.length,
64
+ default_strategy: 'critical-first',
65
+ strategies: {
66
+ 'critical-first': {
67
+ next_task_id: criticalFirst[0] ?? null,
68
+ ordered_task_ids: criticalFirst,
69
+ },
70
+ fifo: {
71
+ next_task_id: fifo[0] ?? null,
72
+ ordered_task_ids: fifo,
73
+ },
74
+ },
75
+ tasks,
76
+ };
77
+ }
78
+ export function writeReadyFiles(projectPath, readySnapshot) {
79
+ const genDir = generatedDirForProject(projectPath);
80
+ ensureDir(genDir);
81
+ writeJson(join(genDir, 'ready.json'), readySnapshot);
82
+ const claimNext = {
83
+ schedule_path: readySnapshot.schedule_path,
84
+ execution_path: readySnapshot.execution_path,
85
+ generated_dir: readySnapshot.generated_dir,
86
+ default_strategy: readySnapshot.default_strategy,
87
+ strategies: readySnapshot.strategies,
88
+ };
89
+ writeJson(join(genDir, 'claim-next.json'), claimNext);
90
+ const lines = [];
91
+ lines.push(`# Ready Tasks`);
92
+ lines.push('');
93
+ lines.push(`- schedule_path: \`${readySnapshot.schedule_path}\``);
94
+ lines.push(`- execution_path: \`${readySnapshot.execution_path}\``);
95
+ lines.push(`- ready_count: \`${readySnapshot.ready_count}\``);
96
+ lines.push(`- default_strategy: \`${readySnapshot.default_strategy}\``);
97
+ lines.push('');
98
+ lines.push(`## Claim Targets`);
99
+ lines.push('');
100
+ lines.push(`| strategy | next_task_id |`);
101
+ lines.push(`|---|---|`);
102
+ lines.push(`| critical-first | ${readySnapshot.strategies['critical-first'].next_task_id ? `\`${readySnapshot.strategies['critical-first'].next_task_id}\`` : '_none_'} |`);
103
+ lines.push(`| fifo | ${readySnapshot.strategies.fifo.next_task_id ? `\`${readySnapshot.strategies.fifo.next_task_id}\`` : '_none_'} |`);
104
+ lines.push('');
105
+ if (!readySnapshot.tasks.length) {
106
+ lines.push('_No ready tasks._');
107
+ lines.push('');
108
+ }
109
+ else {
110
+ lines.push(`## Ready Order (critical-first)`);
111
+ lines.push('');
112
+ lines.push(`| rank | id | owner | slack | ES | schedule_file |`);
113
+ lines.push(`|---:|---|---|---:|---:|---|`);
114
+ for (const task of readySnapshot.tasks) {
115
+ lines.push(`| ${task.critical_first_rank} | \`${task.id}\` | ${task.owner ?? '-'} | ${task.cpm?.slack ?? '-'} | ${task.cpm?.es ?? '-'} | ${task.schedule_file || '-'} |`);
116
+ }
117
+ lines.push('');
118
+ lines.push(`## FIFO Order`);
119
+ lines.push('');
120
+ for (const id of readySnapshot.strategies.fifo.ordered_task_ids)
121
+ lines.push(`- \`${id}\``);
122
+ lines.push('');
123
+ }
124
+ writeFileSync(join(genDir, 'ready.md'), lines.join('\n'), 'utf8');
125
+ }
126
+ export function selectNextTask(ready, cpm, strategy) {
127
+ return orderReadyIds(ready, cpm, strategy)[0] ?? null;
128
+ }