@infodb/p3 0.10.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 (48) hide show
  1. package/README.md +2 -0
  2. package/dist/web/assets/{Outputs-B4Tr7JzU.js → Outputs-ddwte0jj.js} +1 -1
  3. package/dist/web/assets/{RequestStatus-DGaoQoIa.js → RequestStatus-Bg1OLbRc.js} +1 -1
  4. package/dist/web/assets/{Tabs-D16MqQxu.js → Tabs-DTmggzgg.js} +1 -1
  5. package/dist/web/assets/{TagInput-pSYxm4bz.js → TagInput-BHAgjLP7.js} +1 -1
  6. package/dist/web/assets/{TaskDrawer-1Ev3RpRV.js → TaskDrawer-Dz_5c2NH.js} +1 -1
  7. package/dist/web/assets/{_requestId-BKhn019m.js → _requestId-D9-gtIcG.js} +1 -1
  8. package/dist/web/assets/{_requestId-Btpvuu7-.js → _requestId-DzCNYvqf.js} +1 -1
  9. package/dist/web/assets/{appCtx-D_Iaoh2e.js → appCtx-Cm24VpAf.js} +1 -1
  10. package/dist/web/assets/{board-DeHdxbN4.js → board-MCHcZ-PU.js} +1 -1
  11. package/dist/web/assets/{done-BFaHGt03.js → done-zq10Bt08.js} +1 -1
  12. package/dist/web/assets/{index-CDWcKy1L.js → index-Ce0ndpne.js} +3 -3
  13. package/dist/web/assets/index-D68mkSnw.css +2 -0
  14. package/dist/web/assets/{new-ChFzBoL2.js → new-9TKiNT4O.js} +1 -1
  15. package/dist/web/assets/{preload-helper-hSId95YD.js → preload-helper-FBLw7u7x.js} +1 -1
  16. package/dist/web/assets/release-notes-hK5XezLW.js +5 -0
  17. package/dist/web/assets/{requestData-B_320uxL.js → requestData-BnN7mctX.js} +1 -1
  18. package/dist/web/assets/{routes-BBD464IS.js → routes-usHwrrA0.js} +1 -1
  19. package/dist/web/assets/{settings-D7PPrGjT.js → settings-BVZDnL6O.js} +1 -1
  20. package/dist/web/index.html +4 -4
  21. package/docs/architecture.md +77 -1
  22. package/docs/how-to-use.md +77 -5
  23. package/docs/installation.md +5 -5
  24. package/lib/cli/help.js +7 -0
  25. package/lib/cli/main.js +16 -2
  26. package/lib/cli/requestCommands.js +207 -14
  27. package/lib/core/context.js +4 -1
  28. package/lib/core/milestoneReview/code.js +129 -0
  29. package/lib/core/milestoneReview/material.js +138 -0
  30. package/lib/core/milestoneReview/mockReviewer.js +27 -0
  31. package/lib/core/milestoneReview/review.js +261 -0
  32. package/lib/core/milestoneReview/service.js +278 -0
  33. package/lib/core/milestoneReview/store.js +226 -0
  34. package/lib/core/preflight/codexEngine.js +20 -6
  35. package/lib/core/projectRegistry.js +3 -3
  36. package/lib/core/requestOps.js +4 -0
  37. package/lib/core/store/normalize.js +27 -1
  38. package/lib/core/store/projectFile.js +8 -1
  39. package/lib/core/store/workspace.js +89 -11
  40. package/lib/server/api/manifest.js +19 -1
  41. package/lib/server/api/milestoneReviewRoutes.js +69 -0
  42. package/lib/server/api/routes.js +19 -3
  43. package/lib/server/server.js +2 -2
  44. package/lib/shared/milestoneGoals.js +57 -0
  45. package/lib/shared/milestoneReview.js +26 -0
  46. package/package.json +1 -1
  47. package/dist/web/assets/index-BF1xMdJo.css +0 -2
  48. package/dist/web/assets/release-notes-BWNDFDkH.js +0 -3
@@ -0,0 +1,278 @@
1
+ import { ChatGptAuthError } from "../chatgpt.js";
2
+ import { CodexUnavailableError, CodexUsageLimitError } from "../preflight/codexEngine.js";
3
+ import { currentOwner, ownerState, systemProbe } from "../preflight/owner.js";
4
+ import { extractReviewInput } from "./material.js";
5
+ import { InvalidReview, parseReview, REVIEW_INPUT_LIMIT, reviewPrompt } from "./review.js";
6
+ import { checkReviewMilestoneId, newReviewRunId, ReviewStoreError } from "./store.js";
7
+ /**
8
+ * マイルストーンレビューを任意のときに実行して記録する(CLI・API はここを呼ぶ)。材料の規則は material.ts、依頼文と結果の
9
+ * 確かめ方は review.ts、保存は store.ts。
10
+ *
11
+ * - 頼む先は Preflight と同じ Codex の接続(CodexWorkspaceEngine の ask。認証・診断・使用量の上限・取消を共有する)。
12
+ * 参照先(このマシンのパス)を Preflight と同じく読むだけでマウントし、コードと git の履歴を読ませる。
13
+ * Mock は明示したときだけ(失敗しても Mock に切り替えない)
14
+ * - 同じデータ・同じマイルストーンで実行中の run は1つだけ(プロセスの間もロックの中で確かめる)。別のマイルストーンは独立
15
+ * - 実行しているプロセスが死んだと確かめられた run(owner.ts の ownerState が dead)だけ、失敗(crashed)として終わりにする。
16
+ * 分からない・ほかの環境の run は自動で終わりにしない。人が明示して中断できる(abandon。ほかの環境のプロセスを止めたとは限らない)
17
+ * - 取消は、このプロセスの run なら止め、ほかのプロセスの run なら要求を run.json に書く(所有者が見つけて止める)
18
+ * - 終わりの状態はロックの中で、まだ実行中かを確かめてから書く(中断した後に届いた結果は取り込まない)
19
+ * - レビューの結果は要望の状態・リリースノート・リリース済みを変えず、完了やリリースの条件にもしない
20
+ */
21
+ /** 1回の時間の上限(既定) */
22
+ export const REVIEW_TIMEOUT_MS = 20 * 60_000;
23
+ /** 始められない(Codex は呼んでいない) */
24
+ export class ReviewRejected extends Error {
25
+ code;
26
+ running;
27
+ constructor(
28
+ /** unknown_milestone: 無い / no_goals: 目的も予定機能も無い / too_large: 入力が上限を超える / running: 実行中 / unavailable: 頼む先が無い */
29
+ code, message, running) {
30
+ super(message);
31
+ this.code = code;
32
+ this.running = running;
33
+ }
34
+ }
35
+ /** 取消・中断を受け付けない(終わっている・動いている所有者がいる) */
36
+ export class ReviewCancelRefused extends Error {
37
+ code;
38
+ constructor(code, message) {
39
+ super(message);
40
+ this.code = code;
41
+ }
42
+ }
43
+ /** 開始の日時(このプロセスでは前より必ず後にする。一覧を開始の順に並べるので、同じミリ秒の開始でも順が分かるように) */
44
+ let lastStart = 0;
45
+ function startedNow() {
46
+ lastStart = Math.max(Date.now(), lastStart + 1);
47
+ return new Date(lastStart).toISOString();
48
+ }
49
+ export class MilestoneReviewService {
50
+ ws;
51
+ reviewers;
52
+ opts;
53
+ local = new Map();
54
+ constructor(ws, reviewers, opts = {}) {
55
+ this.ws = ws;
56
+ this.reviewers = reviewers;
57
+ this.opts = opts;
58
+ }
59
+ get store() {
60
+ return this.ws.milestoneReviews;
61
+ }
62
+ ownerOf(r) {
63
+ if (this.local.has(r.id))
64
+ return { state: "local" };
65
+ return ownerState(r.owner, this.opts.probe ?? systemProbe);
66
+ }
67
+ /** 始める(終わるのは wait で待つ)。材料はここで固定する */
68
+ async start(mid, actor, engine) {
69
+ checkReviewMilestoneId(mid);
70
+ const refs = this.ws.refs();
71
+ const input = await extractReviewInput(this.ws.dataDir, mid, refs);
72
+ if (!input.milestone.known)
73
+ throw new ReviewRejected("unknown_milestone", `マイルストーンがありません: ${mid}`);
74
+ if (!input.units.length) {
75
+ throw new ReviewRejected("no_goals", `マイルストーン ${mid} に目的も予定機能もありません。先に書いてください(画面のリリースノートの「マイルストーン」タブ、または p3 milestone purpose ${mid} --file 目的.md / p3 milestone goal add ${mid} "文")`);
76
+ }
77
+ const { instructions, prompt, size } = reviewPrompt(input);
78
+ if (size > REVIEW_INPUT_LIMIT) {
79
+ throw new ReviewRejected("too_large", `材料が上限を超えています(${size} 文字 / 上限 ${REVIEW_INPUT_LIMIT} 文字)。切り詰めずに断ります。マイルストーンを分けるか、要望の本文を整理してください`);
80
+ }
81
+ const name = engine ?? (await this.opts.engine?.().catch(() => "codex")) ?? "codex";
82
+ const reviewer = this.reviewers[name];
83
+ if (!reviewer)
84
+ throw new ReviewRejected("unavailable", `レビューを頼む先(${name})がありません`);
85
+ const run = {
86
+ id: newReviewRunId(),
87
+ milestone: mid,
88
+ status: "running",
89
+ engine: name,
90
+ startedAt: startedNow(),
91
+ ...(actor ? { startedBy: actor } : {}),
92
+ ...(currentOwner() ? { owner: currentOwner() } : {}),
93
+ inputHash: input.hash,
94
+ log: [],
95
+ };
96
+ await this.store.withLock(mid, async () => {
97
+ await this.recoverLocked(mid);
98
+ for (const id of await this.store.runIds(mid)) {
99
+ const r = await this.store.readRun(mid, id).catch(() => undefined);
100
+ if (r?.status !== "running")
101
+ continue;
102
+ const o = this.ownerOf(r);
103
+ const hint = o.state === "unknown"
104
+ ? `。実行しているプロセスを確かめられません(${o.reason})。止まっていると確かめたら p3 milestone review-cancel ${mid} ${r.id} --acknowledge-stopped で中断できます`
105
+ : "。終わるのを待つか取り消してください";
106
+ throw new ReviewRejected("running", `${mid} のレビューは実行中です(${r.id})${hint}`, r.id);
107
+ }
108
+ await this.store.create(input, run);
109
+ });
110
+ const abort = new AbortController();
111
+ const job = { mid, abort, done: Promise.resolve() };
112
+ this.local.set(run.id, job);
113
+ this.emit(run);
114
+ job.done = this.execute(run, input, { instructions, prompt, refs }, reviewer, abort).finally(() => this.local.delete(run.id));
115
+ return run;
116
+ }
117
+ emit(r) {
118
+ this.ws.emit({ type: "milestone-review", id: r.id, milestone: r.milestone, status: r.status });
119
+ }
120
+ async execute(run, input, ask, reviewer, abort) {
121
+ const { milestone: mid, id } = run;
122
+ const log = [];
123
+ const push = (e) => log.push({ at: new Date().toISOString(), ...e });
124
+ const timeoutMs = this.opts.timeoutMs ?? REVIEW_TIMEOUT_MS;
125
+ const timeout = AbortSignal.timeout(timeoutMs);
126
+ const signal = AbortSignal.any([abort.signal, timeout]);
127
+ let flushed = 0;
128
+ // ほかのプロセスからの取消の要求を見つけ、ログを run.json に書き足す
129
+ const poll = setInterval(() => {
130
+ void this.store
131
+ .withLock(mid, async () => {
132
+ const cur = await this.store.readRun(mid, id);
133
+ if (cur.status !== "running")
134
+ return abort.abort(new Error("ended"));
135
+ if (cur.cancelRequested)
136
+ abort.abort(new Error("cancelled"));
137
+ if (log.length !== flushed) {
138
+ flushed = log.length;
139
+ await this.store.updateRunning(mid, id, (r) => ({ ...r, log: [...log] }));
140
+ }
141
+ })
142
+ .catch(() => undefined);
143
+ }, this.opts.pollMs ?? 1000);
144
+ poll.unref?.();
145
+ let end;
146
+ let result;
147
+ try {
148
+ const code = (input.code ?? []).filter((c) => c.status === "ok");
149
+ push({
150
+ kind: "info",
151
+ text: `材料: 比較単位 ${input.units.length} 件・要望 ${input.requests.length} 件・タスク ${input.requests.reduce((n, r) => n + r.tasks.length, 0)} 件・参照先 ${code.length ? code.map((c) => `${c.name}${c.head ? `@${c.head.slice(0, 7)}` : ""}`).join(", ") : "なし(記録だけの点検)"}`,
152
+ });
153
+ // マウントするのは、材料を取り出したときに読めた参照先だけ
154
+ const readable = ask.refs.filter((r) => r.status === "ok" && r.local && code.some((c) => c.name === r.name));
155
+ const r = await reviewer.ask({ instructions: ask.instructions, prompt: ask.prompt, refs: readable, label: "マイルストーンのレビュー" }, push, signal);
156
+ if (signal.aborted)
157
+ throw signal.reason;
158
+ const locals = Object.fromEntries(readable.map((x) => [x.name, x.local]));
159
+ result = parseReview(r.message, input, r.model, locals);
160
+ end = { status: "completed" };
161
+ }
162
+ catch (e) {
163
+ if (abort.signal.aborted)
164
+ end = { status: "cancelled", error: "取り消しました" };
165
+ else if (timeout.aborted)
166
+ end = { status: "failed", failure: "timeout", error: `時間切れです(${Math.round(timeoutMs / 1000)} 秒)` };
167
+ else {
168
+ const [failure, error] = classify(e);
169
+ end = { status: "failed", failure, error };
170
+ }
171
+ push({ kind: "error", text: end.error });
172
+ }
173
+ finally {
174
+ clearInterval(poll);
175
+ }
176
+ try {
177
+ const fin = await this.store.withLock(mid, () => this.store.finish(mid, id, { ...end, log: [...log] }, end.status === "completed" ? result : undefined));
178
+ this.emit(fin);
179
+ }
180
+ catch (e) {
181
+ // 既に終わっていた(人が中断した・回復した): 遅れて届いた結果は取り込まない
182
+ if (!(e instanceof ReviewStoreError && e.code === "finished"))
183
+ throw e;
184
+ this.emit({ id, milestone: mid, status: (await this.store.readRun(mid, id).catch(() => run)).status });
185
+ }
186
+ }
187
+ /** 死んだと確かめられた所有者の run を失敗(crashed)にする(ロックの中で呼ぶ) */
188
+ async recoverLocked(mid) {
189
+ for (const id of await this.store.runIds(mid)) {
190
+ const r = await this.store.readRun(mid, id).catch(() => undefined);
191
+ if (r?.status !== "running" || this.local.has(r.id))
192
+ continue;
193
+ const o = this.ownerOf(r);
194
+ if (o.state !== "dead")
195
+ continue;
196
+ const fin = await this.store.finish(mid, id, { status: "failed", failure: "crashed", error: `実行していたプロセスが途中で終わりました(${o.reason})` });
197
+ this.emit(fin);
198
+ }
199
+ }
200
+ /** 死んだ所有者の run を回復する(一覧・取得の前に) */
201
+ async recover(mid) {
202
+ checkReviewMilestoneId(mid);
203
+ if (!(await this.store.hasHistory(mid)))
204
+ return;
205
+ await this.store.withLock(mid, () => this.recoverLocked(mid));
206
+ }
207
+ async list(mid) {
208
+ await this.recover(mid);
209
+ return this.store.list(mid);
210
+ }
211
+ async get(mid, run) {
212
+ await this.recover(mid);
213
+ const rec = await this.store.get(mid, run);
214
+ return { ...rec, ...(rec.run.status === "running" ? { owner: this.ownerOf(rec.run) } : {}) };
215
+ }
216
+ /**
217
+ * 取り消す。このプロセスの run は止め、ほかのプロセスの run は要求を書く(所有者が見つけて止める)。
218
+ * acknowledgeStopped: 人が「実行しているプロセスは止まっている」と確かめた。所有者が分からない run を、記録の上で中断にする
219
+ * (動いていると確かめられる所有者がいれば断る。ほかの環境のプロセスを止めたとは限らない)
220
+ */
221
+ async cancel(mid, run, by, opts = {}) {
222
+ checkReviewMilestoneId(mid);
223
+ const local = this.local.get(run);
224
+ const out = await this.store.withLock(mid, async () => {
225
+ const cur = await this.store.readRun(mid, run);
226
+ if (cur.status !== "running")
227
+ throw new ReviewCancelRefused("finished", `${mid}/${run} は既に終わっています(${cur.status})`);
228
+ const o = this.ownerOf(cur);
229
+ if (opts.acknowledgeStopped && !local) {
230
+ if (o.state === "alive")
231
+ throw new ReviewCancelRefused("owner_alive", `${mid}/${run} を実行しているプロセスは動いています。--acknowledge-stopped ではなく取消を使ってください`);
232
+ const at = new Date().toISOString();
233
+ const fin = await this.store.finish(mid, run, {
234
+ status: "cancelled",
235
+ abandoned: { at, ...(by ? { by } : {}) },
236
+ error: "人が中断しました(ほかの環境で動いているプロセスを止めたとは限りません)",
237
+ });
238
+ return { run: fin, requested: false };
239
+ }
240
+ if (o.state === "dead") {
241
+ const fin = await this.store.finish(mid, run, { status: "failed", failure: "crashed", error: `実行していたプロセスが途中で終わりました(${o.reason})` });
242
+ return { run: fin, requested: false };
243
+ }
244
+ const next = await this.store.updateRunning(mid, run, (r) => ({ ...r, cancelRequested: { at: new Date().toISOString(), ...(by ? { by } : {}) } }));
245
+ return { run: next, requested: true };
246
+ });
247
+ local?.abort.abort(new Error("cancelled"));
248
+ this.emit(out.run);
249
+ return out;
250
+ }
251
+ /** 終わるまで待つ(このプロセスの run だけ) */
252
+ async wait(mid, run) {
253
+ await this.local.get(run)?.done;
254
+ return this.get(mid, run);
255
+ }
256
+ /** このプロセスで実行中の数 */
257
+ running() {
258
+ return this.local.size;
259
+ }
260
+ /** このプロセスの実行が全部終わるまで待つ(cancel: 先に全部を取り消す) */
261
+ async settle(opts = {}) {
262
+ const jobs = [...this.local.values()];
263
+ if (opts.cancel)
264
+ for (const j of jobs)
265
+ j.abort.abort(new Error("cancelled"));
266
+ await Promise.allSettled(jobs.map((j) => j.done));
267
+ }
268
+ }
269
+ function classify(e) {
270
+ const msg = e?.message ?? String(e);
271
+ if (e instanceof CodexUnavailableError || e instanceof ChatGptAuthError)
272
+ return ["unavailable", msg];
273
+ if (e instanceof CodexUsageLimitError)
274
+ return ["usage_limit", msg];
275
+ if (e instanceof InvalidReview)
276
+ return ["invalid_output", msg];
277
+ return ["error", msg];
278
+ }
@@ -0,0 +1,226 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { mkdir, readdir, readFile } from "node:fs/promises";
3
+ import { join, resolve, sep } from "node:path";
4
+ import { REVIEW_STATUSES, REVIEW_VERDICTS, } from "../../shared/milestoneReview.js";
5
+ import { withFileLock, writeFileAtomic } from "../store/fsutil.js";
6
+ /**
7
+ * マイルストーンレビューの履歴。
8
+ *
9
+ * <data>/milestone-reviews/<マイルストーンID>/<run>/input.json 固定した比較材料(作ったら変えない)
10
+ * <data>/milestone-reviews/<マイルストーンID>/<run>/run.json 実行の記録(状態・実行者・エンジン・所有者・失敗の理由・取消の要求)
11
+ * <data>/milestone-reviews/<マイルストーンID>/<run>/review.json 結果(completed のときだけ。書き終えてから completed にする)
12
+ * <data>/milestone-reviews/.locks/<マイルストーンID>.lock 状態を変えるときのロック(プロセス間)
13
+ *
14
+ * - 状態は running → completed / failed / cancelled の一方向。終わった run は変えない(遅れて届いた結果も取り込まない)
15
+ * - パスの ID(マイルストーン・run)は形を確かめ、保存先の外を指すもの・「.」「..」は断る。同じ run は作り直さない
16
+ * - ファイルは tmp に書いてから rename する。壊れた記録は「無い」と分けて返す(一覧からも隠さない)
17
+ * - 今の要望・目的と比べても、過去の input / review は変えない
18
+ */
19
+ export const MILESTONE_REVIEWS_DIR = "milestone-reviews";
20
+ const MILESTONE_ID = /^[A-Za-z0-9._-]+$/;
21
+ const RUN_ID = /^MR-\d{8}-\d{6}-[0-9a-f]{4}$/;
22
+ /** 履歴の操作の失敗。not_found: 無い / broken: 読めない / bad_id: ID が使えない / exists: 既にある / finished: 終わった run */
23
+ export class ReviewStoreError extends Error {
24
+ code;
25
+ constructor(code, message) {
26
+ super(message);
27
+ this.code = code;
28
+ }
29
+ }
30
+ export function checkReviewMilestoneId(id) {
31
+ if (!MILESTONE_ID.test(id) || id === "." || id === "..")
32
+ throw new ReviewStoreError("bad_id", `マイルストーンの ID に使えません: ${JSON.stringify(id)}(英数字と . _ -)`);
33
+ }
34
+ export function checkRunId(id) {
35
+ if (!RUN_ID.test(id))
36
+ throw new ReviewStoreError("bad_id", `レビューの run の ID ではありません: ${JSON.stringify(id)}(MR-YYYYMMDD-HHMMSS-xxxx)`);
37
+ }
38
+ export function newReviewRunId(now = new Date()) {
39
+ const s = now.toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
40
+ return `MR-${s}-${randomBytes(2).toString("hex")}`;
41
+ }
42
+ const isTerminal = (r) => r.status !== "running";
43
+ export class MilestoneReviewStore {
44
+ dataDir;
45
+ constructor(dataDir) {
46
+ this.dataDir = dataDir;
47
+ }
48
+ get dir() {
49
+ return join(this.dataDir, MILESTONE_REVIEWS_DIR);
50
+ }
51
+ within(...parts) {
52
+ const p = resolve(this.dir, ...parts);
53
+ if (!p.startsWith(resolve(this.dir) + sep))
54
+ throw new ReviewStoreError("bad_id", `保存先の外を指します: ${parts.join("/")}`);
55
+ return p;
56
+ }
57
+ milestoneDir(mid) {
58
+ checkReviewMilestoneId(mid);
59
+ return this.within(mid);
60
+ }
61
+ runDir(mid, run) {
62
+ checkReviewMilestoneId(mid);
63
+ checkRunId(run);
64
+ return this.within(mid, run);
65
+ }
66
+ /** マイルストーンの状態を変えるときのロック(ほかのプロセスの開始・終わり・取消と1つずつにする) */
67
+ withLock(mid, fn) {
68
+ checkReviewMilestoneId(mid);
69
+ return withFileLock(join(this.dir, ".locks", `${mid}.lock`), fn, {
70
+ busyMessage: `マイルストーン ${mid} のレビューの記録を変えられませんでした(別のプロセスが使っています。少し待ってやり直してください)`,
71
+ });
72
+ }
73
+ /** 履歴のあるマイルストーン(run のフォルダが1つでもあるもの。project.yaml に無い孤立も含む) */
74
+ async milestones() {
75
+ const out = [];
76
+ for (const d of await dirs(this.dir)) {
77
+ if (d.startsWith(".") || !MILESTONE_ID.test(d) || d === "..")
78
+ continue;
79
+ if ((await dirs(join(this.dir, d))).some((r) => RUN_ID.test(r)))
80
+ out.push(d);
81
+ }
82
+ return out.sort();
83
+ }
84
+ async hasHistory(mid) {
85
+ return (await this.runIds(mid)).length > 0;
86
+ }
87
+ /** run の ID(新しい順) */
88
+ async runIds(mid) {
89
+ return (await dirs(this.milestoneDir(mid))).filter((r) => RUN_ID.test(r)).sort().reverse();
90
+ }
91
+ /**
92
+ * 新しい run を作る(input.json と running の run.json)。同じ ID が既にあれば exists で断る(上書きしない)。
93
+ * 呼ぶ側がロックの中で呼ぶ(同時に実行中の run を作らないため)
94
+ */
95
+ async create(input, run) {
96
+ const dir = this.runDir(run.milestone, run.id);
97
+ await mkdir(this.milestoneDir(run.milestone), { recursive: true });
98
+ try {
99
+ await mkdir(dir);
100
+ }
101
+ catch (e) {
102
+ if (e.code === "EEXIST")
103
+ throw new ReviewStoreError("exists", `既にある run です: ${run.milestone}/${run.id}`);
104
+ throw e;
105
+ }
106
+ await writeJson(join(dir, "input.json"), input);
107
+ await writeJson(join(dir, "run.json"), run);
108
+ }
109
+ async readRun(mid, run) {
110
+ return readJson(join(this.runDir(mid, run), "run.json"), `${mid}/${run}`, checkRunShape);
111
+ }
112
+ async readInput(mid, run) {
113
+ return readJson(join(this.runDir(mid, run), "input.json"), `${mid}/${run} の input.json`, (x) => {
114
+ const i = x;
115
+ if (!i.milestone || !Array.isArray(i.units) || !Array.isArray(i.requests) || typeof i.hash !== "string")
116
+ throw new Error("形が違います");
117
+ });
118
+ }
119
+ async readResult(mid, run) {
120
+ return readJson(join(this.runDir(mid, run), "review.json"), `${mid}/${run} の review.json`, (x) => {
121
+ const r = x;
122
+ if (typeof r.overall !== "string" || !Array.isArray(r.units))
123
+ throw new Error("形が違います");
124
+ });
125
+ }
126
+ /** 1回分(無ければ not_found、どれかが読めなければ broken) */
127
+ async get(mid, run) {
128
+ const r = await this.readRun(mid, run);
129
+ const input = await this.readInput(mid, run);
130
+ const result = r.status === "completed" ? await this.readResult(mid, run) : undefined;
131
+ return { run: r, input, ...(result ? { result } : {}) };
132
+ }
133
+ /** 一覧(新しい順)。読めない記録も broken として出す */
134
+ async list(mid) {
135
+ const out = [];
136
+ for (const id of await this.runIds(mid)) {
137
+ try {
138
+ const rec = await this.get(mid, id);
139
+ const verdicts = {};
140
+ for (const u of rec.result?.units ?? [])
141
+ verdicts[u.verdict] = (verdicts[u.verdict] ?? 0) + 1;
142
+ out.push({
143
+ state: "ok",
144
+ run: rec.run,
145
+ units: rec.input.units,
146
+ ...(rec.input.milestone.purpose ? { purpose: rec.input.milestone.purpose } : {}),
147
+ inputHash: rec.input.hash,
148
+ ...(rec.result ? { verdicts } : {}),
149
+ });
150
+ }
151
+ catch (e) {
152
+ out.push({ state: "broken", id, error: e.message });
153
+ }
154
+ }
155
+ // 同じ秒の run は ID では並ばないので、始めた時刻(ミリ秒)の新しい順にする(読めない記録は ID の時刻で)
156
+ const at = (x) => (x.state === "ok" ? x.run.startedAt.replace(/[-:]/g, "").replace("T", "-") : x.id.slice(3, 18));
157
+ return out.sort((a, b) => (at(a) < at(b) ? 1 : at(a) > at(b) ? -1 : 0));
158
+ }
159
+ /** run.json を書き換える(呼ぶ側がロックの中で呼ぶ)。終わった run は finished で断る */
160
+ async updateRunning(mid, run, fn) {
161
+ const cur = await this.readRun(mid, run);
162
+ if (isTerminal(cur))
163
+ throw new ReviewStoreError("finished", `${mid}/${run} は既に終わっています(${cur.status})`);
164
+ const next = fn(cur);
165
+ await writeJson(join(this.runDir(mid, run), "run.json"), next);
166
+ return next;
167
+ }
168
+ /**
169
+ * 終わりにする(呼ぶ側がロックの中で呼ぶ)。completed は結果を書き終えてから run.json を completed にする。
170
+ * 既に終わっていれば finished で断り、何も書かない
171
+ */
172
+ async finish(mid, run, patch, result) {
173
+ const cur = await this.readRun(mid, run);
174
+ if (isTerminal(cur))
175
+ throw new ReviewStoreError("finished", `${mid}/${run} は既に終わっています(${cur.status})`);
176
+ if (patch.status === "completed") {
177
+ if (!result)
178
+ throw new Error("completed には結果が要ります");
179
+ await writeJson(join(this.runDir(mid, run), "review.json"), result);
180
+ }
181
+ const next = { ...cur, ...patch, finishedAt: patch.finishedAt ?? new Date().toISOString() };
182
+ await writeJson(join(this.runDir(mid, run), "run.json"), next);
183
+ return next;
184
+ }
185
+ }
186
+ function checkRunShape(x) {
187
+ const r = x;
188
+ if (typeof r.id !== "string" || typeof r.milestone !== "string" || !REVIEW_STATUSES.includes(r.status) || typeof r.startedAt !== "string")
189
+ throw new Error("形が違います");
190
+ if (!Array.isArray(r.log))
191
+ throw new Error("log がありません");
192
+ }
193
+ /** 判定の区分か */
194
+ export const isVerdict = (v) => REVIEW_VERDICTS.includes(v);
195
+ async function dirs(path) {
196
+ try {
197
+ return (await readdir(path, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name);
198
+ }
199
+ catch (e) {
200
+ if (e.code === "ENOENT")
201
+ return [];
202
+ throw e;
203
+ }
204
+ }
205
+ async function writeJson(path, v) {
206
+ await writeFileAtomic(path, `${JSON.stringify(v, null, 2)}\n`);
207
+ }
208
+ async function readJson(path, label, check) {
209
+ let text;
210
+ try {
211
+ text = await readFile(path, "utf8");
212
+ }
213
+ catch (e) {
214
+ if (e.code === "ENOENT")
215
+ throw new ReviewStoreError("not_found", `レビューの記録がありません: ${label}`);
216
+ throw e;
217
+ }
218
+ try {
219
+ const v = JSON.parse(text);
220
+ check(v);
221
+ return v;
222
+ }
223
+ catch (e) {
224
+ throw new ReviewStoreError("broken", `レビューの記録を読めません: ${label}(${e.message})`);
225
+ }
226
+ }
@@ -251,16 +251,30 @@ export class CodexWorkspaceEngine {
251
251
  return this.authorized("Preflight", log, (a) => this.runWith(a.cfg, job, a.auth, a.env, a.log, signal));
252
252
  }
253
253
  /**
254
- * Preflight 以外の1回の頼みごと(リリースノートの要約など)。設定・認証・イメージ・起動の診断は Preflight と同じものを使い、
255
- * 参照先もデータのフォルダもマウントしない(/workspace は空の tmpfs で、終われば消える)。渡すのは依頼文だけで、
256
- * 結果は最後の応答の文。評価やタスク化はしない。結果を確かめて取り込むのは呼ぶ側
254
+ * Preflight 以外の1回の頼みごと(リリースノートの要約・マイルストーンのレビュー)。設定・認証・イメージ・起動の診断は Preflight と
255
+ * 同じものを使い、データのフォルダはマウントしない(/workspace は tmpfs で、終われば消える)。refs を渡したときだけ、その参照先を
256
+ * Preflight と同じく /workspace/<名前> に読むだけでマウントする(コードと git の履歴を読ませる)。結果は最後の応答の文。
257
+ * 評価やタスク化はしない。結果を確かめて取り込むのは呼ぶ側
257
258
  */
258
259
  async ask(input, log, signal) {
259
260
  return this.authorized(input.label, log, async ({ cfg, auth, env, log }) => {
261
+ const readable = (input.refs ?? []).filter((r) => r.status === "ok" && r.local);
262
+ const mappings = readable.map((r) => ({
263
+ label: `参照先 ${r.name}`,
264
+ local: r.local,
265
+ ...mapPath(cfg.pathMap, r.local),
266
+ container: `${CONTAINER_WORKSPACE}/${r.mount}`,
267
+ }));
268
+ const repos = readable.map((r, i) => ({ name: r.name, host: mappings[i].host, container: mappings[i].container }));
269
+ if (mappings.length) {
270
+ log({ kind: "info", text: "パスの対応(個人設定の codex.pathMap。読むだけでマウントします):" });
271
+ for (const m of mappings)
272
+ log({ kind: "info", text: ` ${describeMapping(m, cfg.pathMap.length)}` });
273
+ }
260
274
  await this.prepareImage(cfg, log, signal);
261
- const command = cfg.command?.({ repos: [], data: null, auth: auth.mode }) ??
262
- withMounts(dockerCommand(PLACEHOLDER, auth.mode === "chatgpt" ? { accessTokenEnv: ACCESS_TOKEN_ENV } : { authVolume: cfg.authVolume, authFile: cfg.authFile }), [], null);
263
- return this.launched("ask", cfg, command, [], log, signal, (launch, onError) => this.session(cfg, launch, env, log, onError, async (session) => {
275
+ const command = cfg.command?.({ repos, data: null, auth: auth.mode }) ??
276
+ withMounts(dockerCommand(PLACEHOLDER, auth.mode === "chatgpt" ? { accessTokenEnv: ACCESS_TOKEN_ENV } : { authVolume: cfg.authVolume, authFile: cfg.authFile }), repos, null);
277
+ return this.launched("ask", cfg, command, mappings, log, signal, (launch, onError) => this.session(cfg, launch, env, log, onError, async (session) => {
264
278
  await checkUsage(session, auth, log);
265
279
  await session.startThread(input.instructions);
266
280
  log({ kind: "info", text: `スレッドを立てました (model: ${session.model})` });
@@ -110,7 +110,7 @@ export class ProjectRegistry {
110
110
  e.ctx = undefined;
111
111
  const settle = Promise.all([
112
112
  ...all.map(async (ctx) => {
113
- await Promise.all([ctx.preflight.settle({ cancel: true }), ctx.releaseGenerator.settle({ cancel: true })]);
113
+ await Promise.all([ctx.preflight.settle({ cancel: true }), ctx.releaseGenerator.settle({ cancel: true }), ctx.milestoneReview.settle({ cancel: true })]);
114
114
  ctx.ws.close();
115
115
  }),
116
116
  ...this.retiring,
@@ -118,7 +118,7 @@ export class ProjectRegistry {
118
118
  const timedOut = await Promise.race([settle, new Promise((r) => setTimeout(() => r(true), opts.timeoutMs ?? 10_000).unref())]);
119
119
  for (const ctx of all)
120
120
  ctx.ws.close();
121
- return { pending: timedOut ? all.reduce((n, c) => n + c.preflight.running() + c.releaseGenerator.running(), 0) : 0 };
121
+ return { pending: timedOut ? all.reduce((n, c) => n + c.preflight.running() + c.releaseGenerator.running() + c.milestoneReview.running(), 0) : 0 };
122
122
  }
123
123
  async load() {
124
124
  let projects;
@@ -171,7 +171,7 @@ export class ProjectRegistry {
171
171
  void e.ctx?.then((ctx) => this.retire(ctx), () => undefined);
172
172
  }
173
173
  retire(ctx) {
174
- const p = Promise.all([ctx.preflight.settle(), ctx.releaseGenerator.settle()]).then(() => ctx.ws.close());
174
+ const p = Promise.all([ctx.preflight.settle(), ctx.releaseGenerator.settle(), ctx.milestoneReview.settle()]).then(() => ctx.ws.close());
175
175
  this.retiring.add(p);
176
176
  void p.finally(() => this.retiring.delete(p));
177
177
  }
@@ -40,6 +40,10 @@ export async function checkMilestoneRemoval(ctx, next) {
40
40
  if (notes.length) {
41
41
  throw new OpRuleError(`リリースノートのあるマイルストーンは消せません: ${notes.join(", ")}(release-notes/<ID>.md を残すなら消さないでください)`);
42
42
  }
43
+ const reviewed = (await ctx.ws.milestoneReviews.milestones()).filter((id) => removed.includes(id));
44
+ if (reviewed.length) {
45
+ throw new OpRuleError(`レビューの履歴のあるマイルストーンは消せません(ID も変えられません): ${reviewed.join(", ")}(milestone-reviews/<ID>/ に残っています)`);
46
+ }
43
47
  }
44
48
  /** 要望を変えた後: 配下に未完了ができたら対応済の祖先を進行中に戻し(変更通知も)、完了済の祖先は警告にする */
45
49
  async function afterRequestWrite(ctx, rid, actor) {
@@ -84,6 +84,26 @@ function runnerOf(v) {
84
84
  return {};
85
85
  return isPreflightRunner(raw) ? { runner: raw } : { invalidRunner: raw };
86
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
+ }
87
107
  export function normalizeProject(d) {
88
108
  const preflight = (d.preflight ?? {});
89
109
  return {
@@ -93,7 +113,13 @@ export function normalizeProject(d) {
93
113
  milestones: Array.isArray(d.milestones)
94
114
  ? d.milestones
95
115
  .filter((m) => !!m && typeof m === "object" && !!m.id)
96
- .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
+ }))
97
123
  : [],
98
124
  branchPattern: str(d.branchPattern) ?? "req/{id}-{slug}",
99
125
  preflight: { instructions: str(preflight.instructions) ?? "", ...runnerOf(preflight.runner) },
@@ -11,7 +11,14 @@ 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
24
  preflight: preflightPlain(cfg.preflight),