@infodb/p3 0.9.0 → 0.11.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.
Files changed (65) hide show
  1. package/README.md +5 -2
  2. package/dist/web/assets/{Outputs-CQi0oba1.js → Outputs-ddwte0jj.js} +1 -1
  3. package/dist/web/assets/{RequestStatus-grC0F_SQ.js → RequestStatus-Bg1OLbRc.js} +1 -1
  4. package/dist/web/assets/{Tabs-BJRGzidj.js → Tabs-DTmggzgg.js} +1 -1
  5. package/dist/web/assets/{TagInput-cIIwXAHA.js → TagInput-BHAgjLP7.js} +1 -1
  6. package/dist/web/assets/{TaskDrawer-CSZ7Z0JC.js → TaskDrawer-Dz_5c2NH.js} +1 -1
  7. package/dist/web/assets/{_requestId-Z3CBhTIL.js → _requestId-D9-gtIcG.js} +1 -1
  8. package/dist/web/assets/_requestId-DzCNYvqf.js +30 -0
  9. package/dist/web/assets/{appCtx-DCiGJFAe.js → appCtx-Cm24VpAf.js} +1 -1
  10. package/dist/web/assets/{board-DyfGX5h0.js → board-MCHcZ-PU.js} +1 -1
  11. package/dist/web/assets/{directTask-Dk3H5Q2B.js → directTask-C1NWDkZp.js} +1 -1
  12. package/dist/web/assets/{done-Bhxqy7bH.js → done-zq10Bt08.js} +1 -1
  13. package/dist/web/assets/{index-Bt13tvIX.js → index-Ce0ndpne.js} +3 -3
  14. package/dist/web/assets/index-D68mkSnw.css +2 -0
  15. package/dist/web/assets/{new-BRsIUNIb.js → new-9TKiNT4O.js} +1 -1
  16. package/dist/web/assets/{preload-helper-B40dBmwL.js → preload-helper-FBLw7u7x.js} +1 -1
  17. package/dist/web/assets/release-notes-hK5XezLW.js +5 -0
  18. package/dist/web/assets/{requestData-w6fhCYmh.js → requestData-BnN7mctX.js} +1 -1
  19. package/dist/web/assets/{routes-QNgQHe48.js → routes-usHwrrA0.js} +1 -1
  20. package/dist/web/assets/{settings-CoKJahEe.js → settings-BVZDnL6O.js} +1 -1
  21. package/dist/web/index.html +4 -4
  22. package/docs/architecture.md +151 -8
  23. package/docs/development.md +19 -9
  24. package/docs/how-to-use.md +128 -7
  25. package/docs/installation.md +26 -10
  26. package/docs/publishing.md +5 -1
  27. package/lib/cli/args.js +2 -0
  28. package/lib/cli/help.js +14 -2
  29. package/lib/cli/main.js +28 -5
  30. package/lib/cli/preflightCommands.js +30 -7
  31. package/lib/cli/project.js +31 -9
  32. package/lib/cli/requestCommands.js +207 -14
  33. package/lib/core/context.js +4 -1
  34. package/lib/core/milestoneReview/code.js +129 -0
  35. package/lib/core/milestoneReview/material.js +138 -0
  36. package/lib/core/milestoneReview/mockReviewer.js +27 -0
  37. package/lib/core/milestoneReview/review.js +261 -0
  38. package/lib/core/milestoneReview/service.js +278 -0
  39. package/lib/core/milestoneReview/store.js +226 -0
  40. package/lib/core/preflight/codexEngine.js +75 -17
  41. package/lib/core/preflight/codexImage.js +49 -19
  42. package/lib/core/preflight/docker.js +149 -0
  43. package/lib/core/preflight/owner.js +118 -0
  44. package/lib/core/preflight/render-image/Dockerfile +1 -1
  45. package/lib/core/preflight/service.js +235 -16
  46. package/lib/core/projectRegistry.js +5 -4
  47. package/lib/core/requestOps.js +4 -0
  48. package/lib/core/store/dataWatcher.js +122 -0
  49. package/lib/core/store/normalize.js +36 -2
  50. package/lib/core/store/preflightStore.js +20 -2
  51. package/lib/core/store/projectFile.js +14 -2
  52. package/lib/core/store/workspace.js +102 -41
  53. package/lib/server/api/manifest.js +29 -2
  54. package/lib/server/api/milestoneReviewRoutes.js +69 -0
  55. package/lib/server/api/routes.js +37 -8
  56. package/lib/server/server.js +5 -3
  57. package/lib/shared/directTask.js +2 -2
  58. package/lib/shared/milestoneGoals.js +57 -0
  59. package/lib/shared/milestoneReview.js +26 -0
  60. package/lib/shared/preflightRunner.js +18 -0
  61. package/package.json +2 -2
  62. package/skills/p3/SKILL.md +29 -17
  63. package/dist/web/assets/_requestId-C8WYk2kC.js +0 -30
  64. package/dist/web/assets/index-BF1xMdJo.css +0 -2
  65. package/dist/web/assets/release-notes-C3FdiM36.js +0 -3
@@ -1,4 +1,5 @@
1
1
  import { repoNameProblem } from "../../shared/repos.js";
2
+ import { isPreflightRunner } from "../../shared/preflightRunner.js";
2
3
  import { isTaskStatus, RELATION_TYPES, REQUEST_STATUSES } from "../../shared/types.js";
3
4
  const str = (v) => (v === undefined || v === null || v === "" ? undefined : String(v));
4
5
  const num = (v) => (v === undefined || v === null || v === "" ? undefined : Number(v));
@@ -76,6 +77,33 @@ export const REQUEST_KEY_ORDER = [
76
77
  "id", "title", "status", "parent", "childOrder", "splitFrom", "due", "milestone", "tags", "areas", "workstreams", "lastPreflight",
77
78
  "rev", "createdAt", "updatedAt", "updatedBy",
78
79
  ];
80
+ /** preflight.runner(未設定は書かない。読めない値は invalidRunner に残し、担当を推測しない) */
81
+ function runnerOf(v) {
82
+ const raw = str(v)?.trim();
83
+ if (raw === undefined || raw === "")
84
+ return {};
85
+ return isPreflightRunner(raw) ? { runner: raw } : { invalidRunner: raw };
86
+ }
87
+ /**
88
+ * マイルストーンの目的と予定機能(無い古いファイルは空として読む)。予定機能は id と text のある項目だけを読み、重複した id は
89
+ * 最初のものを残す(読めない項目は画面・CLI に出ず、次の保存で消える)
90
+ */
91
+ function milestoneGoalsOf(m) {
92
+ const purpose = typeof m.purpose === "string" && m.purpose.trim() ? m.purpose.replace(/\s+$/, "") : undefined;
93
+ const goals = [];
94
+ if (Array.isArray(m.goals)) {
95
+ for (const g of m.goals) {
96
+ if (!g || typeof g !== "object")
97
+ continue;
98
+ const { id, text } = g;
99
+ const gid = typeof id === "string" || typeof id === "number" ? String(id).trim() : "";
100
+ if (!gid || typeof text !== "string" || !text.trim() || goals.some((x) => x.id === gid))
101
+ continue;
102
+ goals.push({ id: gid, text: text.trim() });
103
+ }
104
+ }
105
+ return { ...(purpose ? { purpose } : {}), ...(goals.length ? { goals } : {}) };
106
+ }
79
107
  export function normalizeProject(d) {
80
108
  const preflight = (d.preflight ?? {});
81
109
  return {
@@ -85,10 +113,16 @@ export function normalizeProject(d) {
85
113
  milestones: Array.isArray(d.milestones)
86
114
  ? d.milestones
87
115
  .filter((m) => !!m && typeof m === "object" && !!m.id)
88
- .map((m) => ({ id: String(m.id), title: str(m.title) ?? String(m.id), due: date(m.due), done: m.done === true ? true : undefined }))
116
+ .map((m) => ({
117
+ id: String(m.id),
118
+ title: str(m.title) ?? String(m.id),
119
+ due: date(m.due),
120
+ done: m.done === true ? true : undefined,
121
+ ...milestoneGoalsOf(m),
122
+ }))
89
123
  : [],
90
124
  branchPattern: str(d.branchPattern) ?? "req/{id}-{slug}",
91
- preflight: { instructions: str(preflight.instructions) ?? "" },
125
+ preflight: { instructions: str(preflight.instructions) ?? "", ...runnerOf(preflight.runner) },
92
126
  };
93
127
  }
94
128
  /**
@@ -8,6 +8,8 @@ import { writeFileAtomic } from "./fsutil.js";
8
8
  * drafts/D1.md ... 細分化されたタスク案(1案 = 1ファイル。人や AI が直接編集できる)
9
9
  * children/C1.md ... 子の要望の案(分割の run。タスク案とは一緒に置かない)
10
10
  */
11
+ /** 中断の依頼のファイル(run のフォルダの中) */
12
+ export const CANCEL_REQUEST_FILE = "cancel-request.json";
11
13
  export class PreflightStore {
12
14
  requestsDir;
13
15
  /** requestsDir: .p3/requests */
@@ -18,7 +20,8 @@ export class PreflightStore {
18
20
  return join(this.requestsDir, requestId, "preflight", runId);
19
21
  }
20
22
  async save(run) {
21
- const { drafts, children, ...meta } = run;
23
+ // 中断の依頼は別のファイル(cancel-request.json。頼む側と実行する側が同じファイルを書き合わないように)
24
+ const { drafts, children, cancelRequested, ...meta } = run;
22
25
  await writeFileAtomic(join(this.runDir(run.requestId, run.id), "run.json"), JSON.stringify(meta, null, 2) + "\n");
23
26
  }
24
27
  async saveDrafts(requestId, runId, drafts) {
@@ -81,7 +84,8 @@ export class PreflightStore {
81
84
  try {
82
85
  const meta = JSON.parse(await readFile(join(this.runDir(requestId, runId), "run.json"), "utf8"));
83
86
  const children = await this.loadChildren(requestId, runId);
84
- return { ...meta, drafts: await this.loadDrafts(requestId, runId), ...(children ? { children } : {}) };
87
+ const cancelRequested = meta.status === "running" ? await this.cancelRequest(requestId, runId) : undefined;
88
+ return { ...meta, drafts: await this.loadDrafts(requestId, runId), ...(children ? { children } : {}), ...(cancelRequested ? { cancelRequested } : {}) };
85
89
  }
86
90
  catch {
87
91
  return undefined;
@@ -114,6 +118,20 @@ export class PreflightStore {
114
118
  return { id: runId, state: "broken" };
115
119
  }
116
120
  }
121
+ /** 中断の依頼(無ければ undefined) */
122
+ async cancelRequest(requestId, runId) {
123
+ try {
124
+ const v = JSON.parse(await readFile(join(this.runDir(requestId, runId), CANCEL_REQUEST_FILE), "utf8"));
125
+ return { at: String(v.at ?? ""), ...(typeof v.by === "string" ? { by: v.by } : {}) };
126
+ }
127
+ catch {
128
+ return undefined;
129
+ }
130
+ }
131
+ /** 中断を頼む(実行しているプロセスが見て止める) */
132
+ async requestCancel(requestId, runId, by) {
133
+ await writeFileAtomic(join(this.runDir(requestId, runId), CANCEL_REQUEST_FILE), JSON.stringify({ at: new Date().toISOString(), ...(by ? { by } : {}) }) + "\n");
134
+ }
117
135
  async list(requestId) {
118
136
  const ids = await readdir(join(this.requestsDir, requestId, "preflight")).catch(() => []);
119
137
  const runs = await Promise.all(ids.filter((i) => i.startsWith("PF-")).map((i) => this.get(requestId, i)));
@@ -11,12 +11,24 @@ function toPlain(cfg) {
11
11
  name: cfg.name,
12
12
  description: cfg.description || undefined,
13
13
  milestones: cfg.milestones.length
14
- ? cfg.milestones.map((m) => Object.fromEntries(Object.entries({ id: m.id, title: m.title, due: m.due, done: m.done || undefined }).filter(([, v]) => v !== undefined)))
14
+ ? cfg.milestones.map((m) => Object.fromEntries(Object.entries({
15
+ id: m.id,
16
+ title: m.title,
17
+ due: m.due,
18
+ done: m.done || undefined,
19
+ purpose: m.purpose || undefined,
20
+ goals: m.goals?.length ? m.goals.map((g) => ({ id: g.id, text: g.text })) : undefined,
21
+ }).filter(([, v]) => v !== undefined)))
15
22
  : undefined,
16
23
  branchPattern: cfg.branchPattern,
17
- preflight: cfg.preflight.instructions ? { instructions: cfg.preflight.instructions } : undefined,
24
+ preflight: preflightPlain(cfg.preflight),
18
25
  };
19
26
  }
27
+ /** preflight の項目(空の観点は省く。担当は設定したときだけ書き、読めない値もそのまま残す) */
28
+ function preflightPlain(p) {
29
+ const out = Object.fromEntries(Object.entries({ instructions: p.instructions || undefined, runner: p.runner ?? p.invalidRunner }).filter(([, v]) => v !== undefined));
30
+ return Object.keys(out).length ? out : undefined;
31
+ }
20
32
  /**
21
33
  * project.yaml を書く。既存のファイルがあれば YAML の文書として更新し、人が書いたコメントを残す。
22
34
  */
@@ -1,16 +1,29 @@
1
- import { readdir, readFile, watch } from "node:fs/promises";
1
+ import { createHash } from "node:crypto";
2
+ import { readdir, readFile } from "node:fs/promises";
2
3
  import { join } from "node:path";
3
4
  import YAML from "yaml";
4
5
  import { parseRef, REQUEST_ID, TASK_ID, taskId } from "../../shared/refs.js";
6
+ import { milestoneGoalProblems, tidyMilestoneGoals } from "../../shared/milestoneGoals.js";
5
7
  import { fileLayout, folderLayout, MarkdownCollection, NotFoundError } from "./collection.js";
6
- import { newRequestId } from "./fsutil.js";
8
+ import { newRequestId, withFileLock } from "./fsutil.js";
7
9
  import { normalizeProject, normalizeRequest, normalizeTaskIn, REQUEST_KEY_ORDER, TASK_KEY_ORDER } from "./normalize.js";
8
10
  import { AttachmentStore } from "./attachments.js";
11
+ import { DataWatcher } from "./dataWatcher.js";
9
12
  import { NoteStore } from "./noteStore.js";
10
13
  import { PreflightStore } from "./preflightStore.js";
11
14
  import { writeProjectFile } from "./projectFile.js";
12
15
  import { resolveRefs } from "../repoRefs.js";
13
16
  import { RELEASE_NOTES_DIR, ReleaseNoteStore } from "../releaseNotes/store.js";
17
+ import { MILESTONE_REVIEWS_DIR, MilestoneReviewStore } from "../milestoneReview/store.js";
18
+ /** 保存する並びの各項目で、purpose / goals のキーが無ければ同じ ID の今の値を残す */
19
+ function keepGoals(next, cur) {
20
+ return next.map((m) => {
21
+ const was = cur.find((c) => c.id === m.id);
22
+ if (!was)
23
+ return m;
24
+ return { ...m, ...(!("purpose" in m) ? { purpose: was.purpose } : {}), ...(!("goals" in m) ? { goals: was.goals } : {}) };
25
+ });
26
+ }
14
27
  /** 全件の読み直しができなかった(project.yaml やデータのフォルダが読めない)。メモリ上の状態は変えていない */
15
28
  export class ReloadError extends Error {
16
29
  }
@@ -32,19 +45,28 @@ export function stampStatus(prev, next) {
32
45
  checkedAt: done ? next.checkedAt : undefined,
33
46
  };
34
47
  }
48
+ /** 編集を始めた後に、マイルストーンが他(CLI・ほかの画面・エディタ)で変わった。何も書いていない */
49
+ export class MilestonesConflictError extends Error {
50
+ expected;
51
+ current;
52
+ code = "milestones_conflict";
53
+ constructor(expected, current) {
54
+ super(`マイルストーンが他で変わりました(版 ${expected} → ${current})。最新を読み直してからやり直してください`);
55
+ this.expected = expected;
56
+ this.current = current;
57
+ }
58
+ }
59
+ /** プロジェクトの設定として保存できない値(何も書いていない) */
60
+ export class ProjectInputError extends Error {
61
+ }
35
62
  /**
36
- * 1リポジトリ = 1プロジェクト。データディレクトリ配下がすべての状態で、要望ごとにフォルダを分ける。
37
- *
38
- * <data>/project.yaml
39
- * <data>/requests/<要望ID>/request.md
40
- * <data>/requests/<要望ID>/tasks/T001.md
41
- * <data>/requests/<要望ID>/preflight/PF-.../{run.json, assessment.json, carryover.md, drafts/D1.md}
42
- * <data>/requests/<要望ID>/notes/N-....md Preflight へのメモ
43
- * <data>/requests/<要望ID>/attachments/A-.../{meta.json, file.*} 添付(画像・xlsx)
44
- * <data>/release-notes/<マイルストーンID>.md リリースノート(マイルストーンごとに1件。releaseNotes/store.ts)
45
- *
46
- * 共有(git / ファイル共有)も要望のフォルダ単位で行える。
63
+ * マイルストーンの版: 中身(ID・名前・期限・リリース済み・目的・予定機能と並び)のハッシュ。ファイルの書き方(コメント・空白)
64
+ * やほかの設定の項目は含めない
47
65
  */
66
+ export function milestonesVersion(ms) {
67
+ const plain = ms.map((m) => [m.id, m.title, m.due ?? null, !!m.done, m.purpose ?? null, (m.goals ?? []).map((g) => [g.id, g.text])]);
68
+ return createHash("sha256").update(JSON.stringify(plain)).digest("hex").slice(0, 16);
69
+ }
48
70
  export class Workspace {
49
71
  dataDir;
50
72
  localRepos;
@@ -54,9 +76,12 @@ export class Workspace {
54
76
  notes;
55
77
  attachments;
56
78
  releaseNotes;
79
+ /** マイルストーンレビューの履歴(milestoneReview/store.ts) */
80
+ milestoneReviews;
57
81
  taskCollections = new Map();
58
82
  listeners = new Set();
59
- abort = new AbortController();
83
+ watcher;
84
+ closed = false;
60
85
  /** localRepos: 個人設定の参照先の名前 → このマシンのパス(repoRefs.ts) */
61
86
  constructor(dataDir, localRepos = {}) {
62
87
  this.dataDir = dataDir;
@@ -70,6 +95,7 @@ export class Workspace {
70
95
  this.notes = new NoteStore(this.requestsDir);
71
96
  this.attachments = new AttachmentStore(this.requestsDir);
72
97
  this.releaseNotes = new ReleaseNoteStore(dataDir);
98
+ this.milestoneReviews = new MilestoneReviewStore(dataDir);
73
99
  }
74
100
  get requestsDir() {
75
101
  return join(this.dataDir, "requests");
@@ -217,12 +243,51 @@ export class Workspace {
217
243
  out[`requests/${rid}/tasks/${id}.md`] = e;
218
244
  return out;
219
245
  }
220
- /** プロジェクト設定を更新して project.yaml に書く(コメントは残す) */
221
- async saveProject(patch) {
222
- await this.loadProject();
223
- const next = { ...this.project, ...patch };
224
- await writeProjectFile(join(this.dataDir, "project.yaml"), next);
225
- await this.loadProject();
246
+ /** 今のマイルストーンの版(milestonesVersion) */
247
+ get milestonesVersion() {
248
+ return milestonesVersion(this.project.milestones);
249
+ }
250
+ /**
251
+ * プロジェクト設定を更新して project.yaml に書く(コメントは残す)。別のプロセス(CLI・serve)の保存とはロックで1つずつにし、
252
+ * ロックの中で最新のファイルを読んでから、patch の項目だけを重ねる。
253
+ *
254
+ * - preflight は項目ごとに重ねる
255
+ * - milestones の各項目で purpose / goals のキーが無ければ、同じ ID の今の値を残す(目的を知らない古い画面・API の保存で落とさない)。
256
+ * 消すなら空(purpose: "" / goals: [])を渡す
257
+ * - opts.milestonesVersion を渡すと、最新の版と照らして違えば MilestonesConflictError(何も書かない)
258
+ */
259
+ async saveProject(patch, opts = {}) {
260
+ return this.writeProject((cur) => {
261
+ // preflight は項目ごとに重ねる(観点だけ・担当だけの更新で、もう片方を消さない。以前の API の形 { instructions } も同じ)。
262
+ // 担当を設定したら、読めなかった値は消す
263
+ const pf = patch.preflight;
264
+ const preflight = pf ? { ...cur.preflight, ...pf, ...(pf.runner ? { invalidRunner: undefined } : {}) } : cur.preflight;
265
+ const milestones = patch.milestones ? keepGoals(patch.milestones, cur.milestones) : cur.milestones;
266
+ return { ...cur, ...patch, milestones, preflight };
267
+ }, opts);
268
+ }
269
+ /**
270
+ * マイルストーンを、ロックの中で読んだ最新の並びから作り直して書く(CLI の milestone の操作。指定した項目のほかを巻き戻さない)。
271
+ * fn が投げたら何も書かない
272
+ */
273
+ async updateMilestones(fn, opts = {}) {
274
+ return this.writeProject((cur) => ({ ...cur, milestones: fn(cur.milestones) }), opts);
275
+ }
276
+ async writeProject(make, opts) {
277
+ const path = join(this.dataDir, "project.yaml");
278
+ await withFileLock(join(this.dataDir, ".project.yaml.lock"), async () => {
279
+ await this.loadProject();
280
+ const now = milestonesVersion(this.project.milestones);
281
+ if (opts.milestonesVersion !== undefined && opts.milestonesVersion !== now)
282
+ throw new MilestonesConflictError(opts.milestonesVersion, now);
283
+ const next = make(this.project);
284
+ next.milestones = next.milestones.map((m) => tidyMilestoneGoals(m));
285
+ const problems = next.milestones.flatMap((m) => milestoneGoalProblems(m));
286
+ if (problems.length)
287
+ throw new ProjectInputError(problems.join(" / "));
288
+ await writeProjectFile(path, next);
289
+ await this.loadProject();
290
+ }, { busyMessage: "project.yaml を保存できませんでした(別のプロセスが保存中です。少し待ってやり直してください)" });
226
291
  this.emit({ type: "changed", kind: "project" });
227
292
  return this.project;
228
293
  }
@@ -251,31 +316,26 @@ export class Workspace {
251
316
  l(e);
252
317
  }
253
318
  /**
254
- * データディレクトリを監視し、外部からのファイル編集(エディタ・AI・Codex・git pull)を取り込む(補助)。
319
+ * データディレクトリを監視し、外部からのファイル編集(エディタ・AI・Codex・git pull)を取り込む(補助。dataWatcher.ts)。
255
320
  * NFS などでは通知が届かず、Node の再帰的な監視は置き換えて保存したファイルの2回目以降の変更を通知しないことがある。
256
- * 正しさはこれに頼らず、画面の「再読み込み」(reloadAll)で保証する。
321
+ * 正しさはこれに頼らず、画面の「再読み込み」(reloadAll)で保証する。監視が壊れても serve は止めない(ログに残し、立て直す)。
322
+ * 既に監視していれば何もしない。close の後は始めない
257
323
  */
258
- async watch() {
259
- const pending = new Map();
260
- try {
261
- for await (const ev of watch(this.dataDir, { recursive: true, signal: this.abort.signal })) {
262
- const f = ev.filename;
263
- if (!f || f.endsWith(".tmp") || f.includes(".archive"))
264
- continue;
265
- clearTimeout(pending.get(f));
266
- pending.set(f, setTimeout(() => {
267
- pending.delete(f);
268
- void this.onFileChanged(f);
269
- }, 80));
270
- }
271
- }
272
- catch (e) {
273
- if (e.name !== "AbortError")
274
- console.error("[watch]", e);
275
- }
324
+ watch(options) {
325
+ if (this.closed)
326
+ return undefined;
327
+ this.watcher ??= new DataWatcher(this.dataDir, (rel) => this.onFileChanged(rel), options);
328
+ this.watcher.start();
329
+ return this.watcher;
276
330
  }
277
331
  async onFileChanged(rel) {
278
332
  const [top, rid, kind, file] = rel.split(/[\\/]/);
333
+ if (top === MILESTONE_REVIEWS_DIR) {
334
+ // レビューの履歴(ほかのプロセスの実行・取消)。ロックのフォルダ .locks は除く
335
+ if (rid && !rid.startsWith("."))
336
+ this.emit({ type: "milestone-review", milestone: rid });
337
+ return;
338
+ }
279
339
  if (top === RELEASE_NOTES_DIR) {
280
340
  // リリースノートの作成・更新・削除(ロックのファイル .<ID>.lock は除く)
281
341
  if (rid?.endsWith(".md") && !rid.startsWith(".") && kind === undefined)
@@ -315,6 +375,7 @@ export class Workspace {
315
375
  }
316
376
  }
317
377
  close() {
318
- this.abort.abort();
378
+ this.closed = true;
379
+ this.watcher?.close();
319
380
  }
320
381
  }
@@ -22,7 +22,13 @@ export const AI_MANIFEST = {
22
22
  "ここに無い API は /api/projects/:project/... の下に置く(通常の serve の /api/... と同じ)。変える操作には x-p3-project-generation が要る(無ければ 428、違えば 409 code: changed)。" +
23
23
  "プロジェクトを書かないデータの API は 404 code: project_required。/api/chatgpt(engine は null)・/api/user-theme・/api/events(一覧・テーマ・接続の変更)はプロジェクトを選ばずに使える",
24
24
  },
25
- { method: "GET", path: "/api/project", desc: "プロジェクト設定" },
25
+ { method: "GET", path: "/api/project", desc: "プロジェクト設定と milestonesVersion(マイルストーンの版)" },
26
+ {
27
+ method: "PUT",
28
+ path: "/api/project",
29
+ desc: "プロジェクト設定を項目ごとに保存する。milestones の各項目は purpose(目的)・goals(予定機能 {id, text})を持てる(キーを省くと今の値を残す。null・空で消す)。" +
30
+ "milestonesVersion を付けると最新の版と照らし、違えば 409 code: milestones_conflict で何も書かない",
31
+ },
26
32
  {
27
33
  method: "POST",
28
34
  path: "/api/reload",
@@ -83,7 +89,16 @@ export const AI_MANIFEST = {
83
89
  {
84
90
  method: "GET",
85
91
  path: "/api/requests/:rid/preflight[/:run]",
86
- desc: "Preflight の run。各 run に inputMatch {status: same|changed|unknown, changed?: [title|body], reason?}(評価対象と今の要望が同じか。タグ・期限・ステータスは比べない)",
92
+ desc: "Preflight の run。各 run に inputMatch {status: same|changed|unknown, changed?: [title|body], reason?}(評価対象と今の要望が同じか。タグ・期限・ステータスは比べない)。" +
93
+ "running の run には liveness {state: alive|waiting|dead|unknown, reason?}(実行しているプロセスの今の状態)と、頼まれていれば cancelRequested {at, by?}。" +
94
+ "中断した run には interrupted {reason, at, acknowledgedBy?}",
95
+ },
96
+ {
97
+ method: "POST",
98
+ path: "/api/requests/:rid/preflight/:run/cancel",
99
+ desc: "run を中断する {acknowledgeStopped?: boolean}(最新でなくてもよい)→ {state: cancelled|requested|already, message, run, acknowledgeable?}。" +
100
+ "requested は中断を頼んだ(まだ running。実行しているプロセスが止める)。acknowledgeable は動いているか確かめられない run で、" +
101
+ "止まっていることを人が確かめたら acknowledgeStopped: true で中断にできる。無い run は 404、完了した run・動いている run への確認は 409(code: completed|alive)",
87
102
  },
88
103
  {
89
104
  method: "PATCH",
@@ -138,6 +153,18 @@ export const AI_MANIFEST = {
138
153
  path: "/api/release-generations/:id[/cancel]",
139
154
  desc: "生成1件 {status: running|completed|failed|cancelled, failure?, items(文と出典), markdown(本文の案), warnings, materialChanged, log} / 取り消し",
140
155
  },
156
+ { method: "GET", path: "/api/milestone-reviews", desc: "レビューの履歴のあるマイルストーン {milestones}(project.yaml に無い孤立も。履歴のあるマイルストーンは消せず ID も変えられない)" },
157
+ { method: "GET", path: "/api/milestones/:mid/review-preview", desc: "マイルストーンレビューの今の材料(比較単位・目的・要望の件数と状態・参照先のコード・範囲・警告・hash)。何も書かない" },
158
+ {
159
+ method: "GET|POST",
160
+ path: "/api/milestones/:mid/reviews",
161
+ desc: "レビューの履歴 {items}(新しい順。読めない記録は state: broken)/ 実行を始める {engine?: codex|mock}(202。目的も予定機能も無ければ 400 no_goals、実行中は 409 running)",
162
+ },
163
+ {
164
+ method: "GET|POST",
165
+ path: "/api/milestones/:mid/reviews/:run[/cancel]",
166
+ desc: "1回分 {run, input, result, owner?} / 取消 {acknowledgeStopped?}(ほかのプロセスの run は要求を残す。終わっている・所有者が動いていれば 409)。結果は参考で、要望・ノート・リリース済みを変えない",
167
+ },
141
168
  { method: "GET", path: "/api/resolve?q=&request=", desc: "参照・タイトルから対象を特定" },
142
169
  { method: "GET", path: "/api/chatgpt", desc: "ChatGPT プランの接続の状態(トークンは返さない)。このマシンからだけ" },
143
170
  { method: "POST", path: "/api/chatgpt/login|cancel|paste|logout", desc: "サインインの開始・取消・コールバックの URL の貼り付け・解除。このマシンのローカルの画面(Origin)からだけ" },
@@ -0,0 +1,69 @@
1
+ import { Hono } from "hono";
2
+ import { z } from "zod";
3
+ import { extractReviewInput } from "../../core/milestoneReview/material.js";
4
+ import { ReviewCancelRefused, ReviewRejected } from "../../core/milestoneReview/service.js";
5
+ import { checkReviewMilestoneId, ReviewStoreError } from "../../core/milestoneReview/store.js";
6
+ /**
7
+ * マイルストーンレビュー(画面のため)。規則と保存は core/milestoneReview(CLI の p3 milestone review と同じ)。
8
+ *
9
+ * GET /milestone-reviews 履歴のあるマイルストーン(project.yaml に無い孤立も)
10
+ * GET /milestones/:mid/review-preview 今の材料(比較単位・目的・要望の件数と状態・参照先のコード・範囲・警告・hash)。何も書かない
11
+ * GET /milestones/:mid/reviews 履歴(新しい順。読めない記録も broken で出す)
12
+ * POST /milestones/:mid/reviews 実行を始める(202。目的も予定機能も無ければ 400 no_goals、実行中なら 409 running)
13
+ * GET /milestones/:mid/reviews/:run 1回分(固定した材料・結果。実行中は所有者の状態 owner)
14
+ * POST /milestones/:mid/reviews/:run/cancel 取り消す(ほかのプロセスの run は要求を残す)。{ acknowledgeStopped: true } は
15
+ * 所有者の分からない run を人が明示して中断する(ほかの環境のプロセスを止めたとは限らない)
16
+ */
17
+ const actorOf = (c) => c.req.header("x-p3-actor") ?? "human:web";
18
+ export function milestoneReviewRoutes(ctx) {
19
+ const app = new Hono();
20
+ const svc = () => ctx.milestoneReview;
21
+ app.onError((err, c) => {
22
+ if (err instanceof ReviewStoreError) {
23
+ const status = err.code === "not_found" ? 404 : err.code === "bad_id" ? 400 : err.code === "broken" ? 422 : 409;
24
+ return c.json({ error: err.message, code: err.code }, status);
25
+ }
26
+ if (err instanceof ReviewRejected) {
27
+ const status = err.code === "running" ? 409 : err.code === "unknown_milestone" ? 404 : 400;
28
+ return c.json({ error: err.message, code: err.code, ...(err.running ? { run: err.running } : {}) }, status);
29
+ }
30
+ if (err instanceof ReviewCancelRefused)
31
+ return c.json({ error: err.message, code: err.code }, 409);
32
+ if (err instanceof z.ZodError)
33
+ return c.json({ error: "invalid input", issues: err.issues }, 400);
34
+ console.error(err);
35
+ return c.json({ error: err.message }, 400);
36
+ });
37
+ app.get("/milestone-reviews", async (c) => c.json({ milestones: await ctx.ws.milestoneReviews.milestones() }));
38
+ app.get("/milestones/:mid/review-preview", async (c) => {
39
+ const mid = c.req.param("mid");
40
+ checkReviewMilestoneId(mid);
41
+ const i = await extractReviewInput(ctx.ws.dataDir, mid, ctx.ws.refs());
42
+ const statuses = {};
43
+ for (const r of i.requests)
44
+ statuses[r.status] = (statuses[r.status] ?? 0) + 1;
45
+ return c.json({
46
+ milestone: i.milestone,
47
+ units: i.units,
48
+ requests: i.requests.length,
49
+ statuses,
50
+ context: i.context.length,
51
+ code: i.code ?? [],
52
+ warnings: i.warnings,
53
+ scope: i.scope,
54
+ hash: i.hash,
55
+ extractedAt: i.extractedAt,
56
+ });
57
+ });
58
+ app.get("/milestones/:mid/reviews", async (c) => c.json({ items: await svc().list(c.req.param("mid")) }));
59
+ app.post("/milestones/:mid/reviews", async (c) => {
60
+ const { engine } = z.object({ engine: z.enum(["codex", "mock"]).optional() }).parse(await c.req.json().catch(() => ({})));
61
+ return c.json(await svc().start(c.req.param("mid"), actorOf(c), engine), 202);
62
+ });
63
+ app.get("/milestones/:mid/reviews/:run", async (c) => c.json(await svc().get(c.req.param("mid"), c.req.param("run"))));
64
+ app.post("/milestones/:mid/reviews/:run/cancel", async (c) => {
65
+ const { acknowledgeStopped } = z.object({ acknowledgeStopped: z.boolean().optional() }).parse(await c.req.json().catch(() => ({})));
66
+ return c.json(await svc().cancel(c.req.param("mid"), c.req.param("run"), actorOf(c), { acknowledgeStopped }));
67
+ });
68
+ return app;
69
+ }
@@ -7,7 +7,7 @@ import { listTasks, progress, resolve } from "../../core/ops.js";
7
7
  import { ConflictError, NotFoundError } from "../../core/store/collection.js";
8
8
  import { ATTACHMENT_LIMITS, ATTACHMENT_TYPES, AttachmentError, safeFileName } from "../../core/store/attachments.js";
9
9
  import { bodyLimit } from "hono/body-limit";
10
- import { ReloadError } from "../../core/store/workspace.js";
10
+ import { MilestonesConflictError, ReloadError } from "../../core/store/workspace.js";
11
11
  import { completionCheckOf, hierarchyNow, resolvedIssue } from "../../core/requestStatus.js";
12
12
  import { HierarchyError, hierarchyView } from "../../core/hierarchy.js";
13
13
  import { supersededMarks } from "../../core/supersede.js";
@@ -17,9 +17,11 @@ import { UserConfigError } from "../../core/userConfig.js";
17
17
  import { AI_MANIFEST } from "./manifest.js";
18
18
  import { repoRoutes } from "./repoRoutes.js";
19
19
  import { releaseNoteRoutes } from "./releaseNoteRoutes.js";
20
+ import { milestoneReviewRoutes } from "./milestoneReviewRoutes.js";
20
21
  import { archiveTask, checkMilestoneRemoval, createRequest, createTask, orderChildren, updateRequest, updateTask } from "../../core/requestOps.js";
22
+ import { PREFLIGHT_RUNNERS } from "../../shared/preflightRunner.js";
21
23
  import { StaleInputError } from "../../core/preflight/input.js";
22
- import { ChildConflictError, ChildDraftsChangedError, DraftConflictError, PulseInputError } from "../../core/preflight/service.js";
24
+ import { CancelRefusedError, ChildConflictError, ChildDraftsChangedError, DraftConflictError, PulseInputError } from "../../core/preflight/service.js";
23
25
  /**
24
26
  * ブラウザ用のローカル API。AI や人の操作は CLI(ファイルを直接読み書き)が主で、ここは画面のため。
25
27
  *
@@ -29,6 +31,7 @@ import { ChildConflictError, ChildDraftsChangedError, DraftConflictError, PulseI
29
31
  * /requests/:rid/preflight[/:run] Preflight
30
32
  * /requests/:rid/notes Preflight へのメモ
31
33
  * /release-notes[/:mid] マイルストーンのリリースノート(releaseNoteRoutes.ts)
34
+ * /milestones/:mid/review[s...] マイルストーンレビュー(milestoneReviewRoutes.ts)
32
35
  */
33
36
  const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
34
37
  const taskInput = z.object({
@@ -70,9 +73,18 @@ const projectPatch = z
70
73
  title: z.string().min(1),
71
74
  due: date.optional(),
72
75
  done: z.boolean().optional(),
76
+ // 目的・予定機能(キーを省くと今の値を残す。null・空で消す)。件数・文字数・空・重複の規則は保存の側(shared/milestoneGoals.ts)
77
+ purpose: z.string().nullish().transform((v) => (v === null ? "" : v)),
78
+ goals: z
79
+ .array(z.object({ id: z.string(), text: z.string() }))
80
+ .nullish()
81
+ .transform((v) => (v === null ? [] : v)),
73
82
  })),
74
83
  branchPattern: z.string().includes("{id}"),
75
- preflight: z.object({ instructions: z.string() }),
84
+ // 担当(runner)は省ける(以前の形 { instructions } の更新でも、保存は項目ごとに重ねるので担当は残る)
85
+ preflight: z.object({ instructions: z.string().optional(), runner: z.enum(PREFLIGHT_RUNNERS).optional() }),
86
+ /** 編集を始めたときのマイルストーンの版(GET /api/project の milestonesVersion)。違えば 409 milestones_conflict */
87
+ milestonesVersion: z.string(),
76
88
  })
77
89
  .partial()
78
90
  .superRefine((p, ctx) => {
@@ -124,6 +136,9 @@ export function apiRoutes(ctx, opts = {}) {
124
136
  // 要望の親子(code: hierarchy_invalid・hierarchy_busy・has_children・has_parent。何も書いていない)
125
137
  if (err instanceof HierarchyError)
126
138
  return c.json({ error: err.message, code: err.code, ...err.detail }, 409);
139
+ // マイルストーンの版が違う(編集を始めた後に他で変わった。何も書いていない)
140
+ if (err instanceof MilestonesConflictError)
141
+ return c.json({ error: err.message, code: err.code, milestonesVersion: err.current }, 409);
127
142
  if (err instanceof z.ZodError)
128
143
  return c.json({ error: "invalid input", issues: err.issues }, 400);
129
144
  // 個人設定のファイルが読めない・壊れている(ファイルは変えていない)
@@ -142,17 +157,19 @@ export function apiRoutes(ctx, opts = {}) {
142
157
  // --- meta ---------------------------------------------------------------
143
158
  app.get("/project", (c) => c.json({
144
159
  project: ws.project,
160
+ milestonesVersion: ws.milestonesVersion,
145
161
  dataDir: ws.dataDir,
146
162
  engines: preflight.availableEngines(),
147
163
  defaultEngine: preflight.defaultEngine,
148
164
  errors: ws.errors(),
149
165
  }));
150
166
  app.put("/project", async (c) => {
151
- const patch = projectPatch.parse(await c.req.json());
167
+ const { milestonesVersion, ...patch } = projectPatch.parse(await c.req.json());
152
168
  // 使っている要望・リリースノートのあるマイルストーンは消さない(CLI の milestone rm と同じ規則)
153
169
  if (patch.milestones)
154
170
  await checkMilestoneRemoval(ctx, patch.milestones.map((m) => m.id));
155
- return c.json(await ws.saveProject(patch));
171
+ const milestones = patch.milestones?.map((m) => Object.fromEntries(Object.entries(m).filter(([, v]) => v !== undefined)));
172
+ return c.json(await ws.saveProject({ ...patch, ...(milestones ? { milestones } : {}) }, { milestonesVersion }));
156
173
  });
157
174
  app.get("/ai/manifest", (c) => c.json(AI_MANIFEST));
158
175
  /** 参照先(設定画面。このマシンのパスはローカルの画面からだけ) */
@@ -169,6 +186,7 @@ export function apiRoutes(ctx, opts = {}) {
169
186
  app.route("/user-theme.js", userThemeScriptRoute());
170
187
  /** マイルストーンのリリースノート(材料・保存・出力・要約の生成) */
171
188
  app.route("/", releaseNoteRoutes(ctx));
189
+ app.route("/", milestoneReviewRoutes(ctx));
172
190
  // --- requests -------------------------------------------------------------
173
191
  app.get("/requests", (c) => {
174
192
  // ?parent=<ID>: 直下の子だけを、親の表示順(子の一覧・詳細と同じ)で。省くと更新の新しい順
@@ -345,9 +363,20 @@ export function apiRoutes(ctx, opts = {}) {
345
363
  const text = await preflight.fixedExtract(rid(c), c.req.param("run"), c.req.param("aid"));
346
364
  return c.body(text, 200, { "Content-Type": "text/plain; charset=utf-8", "X-Content-Type-Options": "nosniff", "Content-Security-Policy": "default-src 'none'" });
347
365
  });
348
- app.post("/requests/:rid/preflight/:run/cancel", (c) => {
349
- preflight.cancel(c.req.param("run"));
350
- return c.json({ ok: true });
366
+ // 中断(最新でなくてもよい)。state: cancelled(中断した)/ requested(中断を頼んだ。まだ running)/ already(既に終わっている)。
367
+ // acknowledgeStopped: 動いているか確かめられない run を、人が止まっていることを確かめて中断にする。完了した run・動いている run への
368
+ // 確認は 409(code)。無い run は 404
369
+ app.post("/requests/:rid/preflight/:run/cancel", async (c) => {
370
+ const body = z.object({ acknowledgeStopped: z.boolean().optional() }).parse(await c.req.json().catch(() => ({})));
371
+ try {
372
+ const r = await preflight.cancelRun(rid(c), c.req.param("run"), { acknowledgeStopped: body.acknowledgeStopped, actor: actorOf(c) });
373
+ return c.json({ state: r.state, message: r.message, run: r.run, ...(r.acknowledgeable ? { acknowledgeable: true } : {}) });
374
+ }
375
+ catch (e) {
376
+ if (e instanceof CancelRefusedError)
377
+ return c.json({ error: e.message, code: e.code }, 409);
378
+ throw e;
379
+ }
351
380
  });
352
381
  app.patch("/requests/:rid/preflight/:run/drafts/:key", async (c) => {
353
382
  // expectedTitle: 編集を始めたときの題(制御用。案には書かない)。今の題と違えば 409 で書かない
@@ -33,7 +33,9 @@ export async function startServer(opts) {
33
33
  if (!opts.dataDir)
34
34
  throw new Error("serve: データのフォルダが決まっていません");
35
35
  ctx = await openProject(opts.dataDir, { repos: opts.repos, settings: opts.settings, projectName: opts.projectName });
36
- void ctx.ws.watch();
36
+ ctx.ws.watch();
37
+ // 落ちたプロセスが残した run(実行していたプロセスが終わっていると確かめられるもの)を中断にする。失敗しても serve は続ける
38
+ void ctx.preflight.recover().catch((e) => console.error(`[preflight] 残った run を確かめられません: ${e.message}`));
37
39
  app.route("/api", singleProjectApp(ctx));
38
40
  }
39
41
  if (opts.static) {
@@ -73,10 +75,10 @@ export async function startServer(opts) {
73
75
  pending = (await registry.close({ timeoutMs })).pending;
74
76
  else if (ctx) {
75
77
  const c = ctx;
76
- const settle = Promise.all([c.preflight.settle({ cancel: true }), c.releaseGenerator.settle({ cancel: true })]).then(() => false);
78
+ const settle = Promise.all([c.preflight.settle({ cancel: true }), c.releaseGenerator.settle({ cancel: true }), c.milestoneReview.settle({ cancel: true })]).then(() => false);
77
79
  const timedOut = await Promise.race([settle, new Promise((r) => setTimeout(() => r(true), timeoutMs).unref())]);
78
80
  c.ws.close();
79
- pending = timedOut ? c.preflight.running() + c.releaseGenerator.running() : 0;
81
+ pending = timedOut ? c.preflight.running() + c.releaseGenerator.running() + c.milestoneReview.running() : 0;
80
82
  }
81
83
  await Promise.race([closed, new Promise((r) => setTimeout(r, 1000).unref())]);
82
84
  return { pending };
@@ -8,5 +8,5 @@ export const DIRECT_TASK_NOTE = "Preflight の評価・細分化・根拠の調
8
8
  export const LATER_PREFLIGHT_NOTE = "後から Preflight を使えるようになったら、この要望に実行できます。実行しても既にあるタスクは変わらず、案をタスク化すると新しいタスクが増えるので、重複を確かめて採否を選んでください。";
9
9
  /** 取り消した Preflight の記録のエラー(失敗とは扱わない) */
10
10
  export const PREFLIGHT_CANCELLED = "中止しました";
11
- /** Preflight が失敗した(取消は含まない)。直接作る道を案内する */
12
- export const preflightFailed = (run) => run.status === "failed" && run.error !== PREFLIGHT_CANCELLED;
11
+ /** Preflight が失敗した(取消と、落ちたプロセスが残した run の中断は含まない。中断は始め直せばよい)。直接作る道を案内する */
12
+ export const preflightFailed = (run) => run.status === "failed" && run.error !== PREFLIGHT_CANCELLED && !run.interrupted;