@infodb/p3 0.10.0 → 0.12.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 (104) hide show
  1. package/README.md +6 -1
  2. package/dist/web/assets/ImprovementDialog-kQaVBGWH.js +1 -0
  3. package/dist/web/assets/Outputs-_nU_p3nu.js +1 -0
  4. package/dist/web/assets/{RequestStatus-DGaoQoIa.js → RequestStatus-RG-OVQYY.js} +1 -1
  5. package/dist/web/assets/{Tabs-D16MqQxu.js → Tabs-ew9i5SKX.js} +1 -1
  6. package/dist/web/assets/TagInput-BtlJTF7i.js +1 -0
  7. package/dist/web/assets/TaskDrawer-DW8GyJqI.js +6 -0
  8. package/dist/web/assets/_requestId-6Nb727dD.js +1 -0
  9. package/dist/web/assets/_requestId-BykTgPax.js +1 -0
  10. package/dist/web/assets/appCtx-CxDdXABS.js +1 -0
  11. package/dist/web/assets/archive-Ckh295Xe.js +1 -0
  12. package/dist/web/assets/board-BVAIjK-Y.js +1 -0
  13. package/dist/web/assets/done-BGfA-3MA.js +1 -0
  14. package/dist/web/assets/index-CgRU744I.css +2 -0
  15. package/dist/web/assets/index-DacQ0yl4.js +12 -0
  16. package/dist/web/assets/{new-ChFzBoL2.js → new-DVygWvVc.js} +1 -1
  17. package/dist/web/assets/outputs-B6xDsLZf.js +1 -0
  18. package/dist/web/assets/preload-helper-DyCqp21K.js +1 -0
  19. package/dist/web/assets/quality-Pu6EISAM.js +1 -0
  20. package/dist/web/assets/release-notes-CCpzyiNf.js +5 -0
  21. package/dist/web/assets/requestData-D5vBnuMh.js +1 -0
  22. package/dist/web/assets/routes-Q91zvNc0.js +4 -0
  23. package/dist/web/assets/settings-BzRgcmUm.js +1 -0
  24. package/dist/web/assets/taskReview-_WCgnQit.js +1 -0
  25. package/dist/web/assets/workTarget-C9c57JAO.js +30 -0
  26. package/dist/web/index.html +4 -4
  27. package/docs/architecture.md +392 -3
  28. package/docs/development.md +1 -1
  29. package/docs/how-to-use.md +261 -5
  30. package/docs/installation.md +5 -5
  31. package/lib/cli/args.js +45 -0
  32. package/lib/cli/help.js +43 -1
  33. package/lib/cli/main.js +42 -4
  34. package/lib/cli/output.js +9 -1
  35. package/lib/cli/preflightCommands.js +7 -1
  36. package/lib/cli/project.js +3 -0
  37. package/lib/cli/qualityCommands.js +163 -0
  38. package/lib/cli/readOnly.js +2 -0
  39. package/lib/cli/requestCommands.js +219 -14
  40. package/lib/cli/showView.js +69 -3
  41. package/lib/cli/taskCommands.js +312 -17
  42. package/lib/cli/taskReviewCommands.js +178 -0
  43. package/lib/core/context.js +7 -1
  44. package/lib/core/milestoneReview/code.js +129 -0
  45. package/lib/core/milestoneReview/material.js +148 -0
  46. package/lib/core/milestoneReview/mockReviewer.js +28 -0
  47. package/lib/core/milestoneReview/review.js +325 -0
  48. package/lib/core/milestoneReview/service.js +214 -0
  49. package/lib/core/milestoneReview/store.js +176 -0
  50. package/lib/core/ops.js +9 -2
  51. package/lib/core/preflight/carryover.js +1 -1
  52. package/lib/core/preflight/codexEngine.js +20 -6
  53. package/lib/core/preflight/engine.js +6 -0
  54. package/lib/core/preflight/instructions.js +18 -1
  55. package/lib/core/preflight/mockEngine.js +4 -0
  56. package/lib/core/preflight/service.js +45 -4
  57. package/lib/core/projectRegistry.js +3 -3
  58. package/lib/core/quality.js +21 -0
  59. package/lib/core/qualityImprovement.js +221 -0
  60. package/lib/core/requestOps.js +101 -6
  61. package/lib/core/reviewRuns.js +205 -0
  62. package/lib/core/store/archivedTasks.js +74 -0
  63. package/lib/core/store/collection.js +12 -2
  64. package/lib/core/store/normalize.js +43 -2
  65. package/lib/core/store/preflightStore.js +9 -1
  66. package/lib/core/store/projectFile.js +18 -1
  67. package/lib/core/store/workspace.js +122 -14
  68. package/lib/core/taskReview/material.js +452 -0
  69. package/lib/core/taskReview/mockReviewer.js +30 -0
  70. package/lib/core/taskReview/paths.js +15 -0
  71. package/lib/core/taskReview/review.js +305 -0
  72. package/lib/core/taskReview/service.js +187 -0
  73. package/lib/core/taskReview/store.js +214 -0
  74. package/lib/server/api/manifest.js +74 -5
  75. package/lib/server/api/milestoneReviewRoutes.js +70 -0
  76. package/lib/server/api/routes.js +164 -20
  77. package/lib/server/api/taskReviewRoutes.js +66 -0
  78. package/lib/server/server.js +2 -2
  79. package/lib/shared/acceptance.js +378 -0
  80. package/lib/shared/milestoneGoals.js +57 -0
  81. package/lib/shared/milestoneReview.js +27 -0
  82. package/lib/shared/quality.js +391 -0
  83. package/lib/shared/qualityImprovement.js +1 -0
  84. package/lib/shared/qualityTemplates.js +31 -0
  85. package/lib/shared/taskBlock.js +142 -0
  86. package/lib/shared/taskReview.js +56 -0
  87. package/package.json +1 -1
  88. package/skills/p3/SKILL.md +31 -2
  89. package/dist/web/assets/Outputs-B4Tr7JzU.js +0 -1
  90. package/dist/web/assets/TagInput-pSYxm4bz.js +0 -1
  91. package/dist/web/assets/TaskDrawer-1Ev3RpRV.js +0 -3
  92. package/dist/web/assets/_requestId-BKhn019m.js +0 -1
  93. package/dist/web/assets/_requestId-Btpvuu7-.js +0 -30
  94. package/dist/web/assets/appCtx-D_Iaoh2e.js +0 -1
  95. package/dist/web/assets/board-DeHdxbN4.js +0 -1
  96. package/dist/web/assets/done-BFaHGt03.js +0 -1
  97. package/dist/web/assets/index-BF1xMdJo.css +0 -2
  98. package/dist/web/assets/index-CDWcKy1L.js +0 -12
  99. package/dist/web/assets/preload-helper-hSId95YD.js +0 -1
  100. package/dist/web/assets/release-notes-BWNDFDkH.js +0 -3
  101. package/dist/web/assets/requestData-B_320uxL.js +0 -1
  102. package/dist/web/assets/routes-BBD464IS.js +0 -3
  103. package/dist/web/assets/settings-D7PPrGjT.js +0 -1
  104. package/dist/web/assets/workTarget-Cijqq4yH.js +0 -1
@@ -0,0 +1,178 @@
1
+ import { resolveRequestId } from "../core/ops.js";
2
+ import { NotFoundError } from "../core/store/collection.js";
3
+ import { normalizeTaskId } from "../shared/refs.js";
4
+ import { previewOf, QUALITY_VERDICT_LABELS, TASK_REVIEW_SCOPE, TASK_REVIEW_VERDICT_LABELS, TASK_REVIEW_VERDICTS } from "../shared/taskReview.js";
5
+ import { table } from "./format.js";
6
+ import { UsageError } from "./project.js";
7
+ /**
8
+ * タスクの AI レビュー(core/taskReview。画面と同じサービス)。
9
+ * review <T> [--target ...] [--viewpoint ...] [--engine codex|mock] [--preview] 材料を固定して始め、終わるまで待つ(進み具合は stderr、
10
+ * Ctrl-C で取り消す)。--preview は材料を見るだけ
11
+ * reviews <T> / review-show <T> <run> / review-cancel <T> <run> [--acknowledge-stopped]
12
+ * 結果は参考の記録で、タスクの状態・済み・基準・証拠を変えない。アーカイブしたタスクの履歴も読める
13
+ */
14
+ const STATUS_LABEL = { running: "実行中", completed: "完了", failed: "失敗", cancelled: "取消" };
15
+ /** タスクの参照(アーカイブしたタスクも読むので、今のタスクの一覧では探さない) */
16
+ function taskKey({ ctx, current }, raw) {
17
+ if (!raw)
18
+ throw new UsageError("タスクを指定してください(T003 / <要望>/T003)");
19
+ const [head, tail] = raw.split("/", 2);
20
+ const rid = tail !== undefined ? resolveRequestId(ctx, head) : current;
21
+ if (tail === undefined && !current)
22
+ throw new UsageError(`${raw}: 要望を --req で指定してください`);
23
+ if (!rid)
24
+ throw new NotFoundError(head);
25
+ const tid = normalizeTaskId(tail ?? head);
26
+ if (!tid)
27
+ throw new UsageError(`${raw}: タスクの ID(T003)を指定してください`);
28
+ return { rid, tid };
29
+ }
30
+ export async function taskReviewCommand(cmd, env) {
31
+ if (cmd !== "review" && cmd !== "reviews" && cmd !== "review-show" && cmd !== "review-cancel")
32
+ return undefined;
33
+ const { ctx, out, args, o, actor } = env;
34
+ const svc = ctx.taskReview;
35
+ const { rid, tid } = taskKey(env, args[0]);
36
+ const key = `${rid}/${tid}`;
37
+ if (cmd === "reviews") {
38
+ const items = await svc.list(rid, tid);
39
+ return out.result(items, () => items.length
40
+ ? table(items.map((x) => x.state === "broken"
41
+ ? [x.id, "読めない", x.error]
42
+ : [x.run.id, STATUS_LABEL[x.run.status], x.run.startedAt.slice(0, 16).replace("T", " "), verdictSummary(x.verdicts), x.run.error ?? ""]))
43
+ : `レビューの履歴はありません(p3 review ${key})`);
44
+ }
45
+ if (cmd === "review-show" || cmd === "review-cancel") {
46
+ const run = args[1];
47
+ if (!run)
48
+ throw new UsageError(`p3 ${cmd} ${key} <run>`);
49
+ if (cmd === "review-show") {
50
+ const d = await svc.get(rid, tid, run);
51
+ return out.result(d, () => formatTaskReview(d));
52
+ }
53
+ const r = await svc.cancel(rid, tid, run, actor, { acknowledgeStopped: o["acknowledge-stopped"] });
54
+ return out.result(r, () => r.requested
55
+ ? `取消を頼みました: ${key}/${run}(実行しているプロセスが見つけて止めます)`
56
+ : r.run.abandoned
57
+ ? `中断にしました: ${key}/${run}(記録の上で終わりにしました。ほかの環境で動いているプロセスを止めたとは限りません)`
58
+ : `終わりにしました: ${key}/${run}(${STATUS_LABEL[r.run.status]}${r.run.error ? `: ${r.run.error}` : ""})`);
59
+ }
60
+ if (o.engine !== undefined && o.engine !== "codex" && o.engine !== "mock")
61
+ throw new UsageError("--engine は codex か mock");
62
+ const opts = { targets: o.target, viewpoint: o.viewpoint };
63
+ if (o.preview) {
64
+ const p = await svc.preview(rid, tid, opts);
65
+ const view = { ...previewOf(p.input), engineRequired: p.engineRequired };
66
+ return out.result(view, () => formatPreview(view));
67
+ }
68
+ const started = await svc.start(rid, tid, actor, { ...opts, engine: o.engine });
69
+ process.stderr.write(`レビューを始めました: ${key}/${started.id}(Ctrl-C で取り消す)\n`);
70
+ let shown = 0;
71
+ const tick = setInterval(() => {
72
+ void svc.get(rid, tid, started.id).then((d) => {
73
+ for (const e of d.run.log.slice(shown))
74
+ process.stderr.write(` ${e.text}\n`);
75
+ shown = Math.max(shown, d.run.log.length);
76
+ }, () => undefined);
77
+ }, 500);
78
+ const onInt = () => void svc.cancel(rid, tid, started.id, actor).catch(() => undefined);
79
+ process.on("SIGINT", onInt);
80
+ const d = await svc.wait(rid, tid, started.id);
81
+ clearInterval(tick);
82
+ process.removeListener("SIGINT", onInt);
83
+ for (const e of d.run.log.slice(shown))
84
+ process.stderr.write(` ${e.text}\n`);
85
+ if (d.run.status !== "completed") {
86
+ if (out.json)
87
+ out.result(d, () => "");
88
+ else
89
+ process.stderr.write(`${STATUS_LABEL[d.run.status]}: ${d.run.error ?? ""}\n`);
90
+ return 1;
91
+ }
92
+ return out.result(d, () => formatTaskReview(d));
93
+ }
94
+ function verdictSummary(v) {
95
+ if (!v)
96
+ return "";
97
+ return TASK_REVIEW_VERDICTS.filter((k) => v[k]).map((k) => `${TASK_REVIEW_VERDICT_LABELS[k]} ${v[k]}`).join(" · ");
98
+ }
99
+ function formatPreview(p) {
100
+ const lines = [`${p.task.ref} ${p.task.title}`, `材料の hash: ${p.hash}`, "", "比較項目:"];
101
+ for (const i of p.items)
102
+ lines.push(` ${i.id} ${i.text.split("\n")[0]}${i.kind === "body" ? "(本文から)" : ""}`);
103
+ lines.push("", "比較対象:");
104
+ for (const t of p.targets) {
105
+ lines.push(` ${t.repo} ${t.kind === "range" ? `${t.range.baseSpec}..${t.range.headSpec}(merge-base ${t.range.mergeBase.slice(0, 12)})` : "コミット"} 変更 ${t.changes} 件 出典: ${t.sources.join(", ")}`);
106
+ for (const c of t.commits)
107
+ lines.push(` ${c.sha.slice(0, 12)} ${c.subject}${c.otherTasks.length ? ` ※ほかのタスク ${c.otherTasks.join(", ")}` : ""}`);
108
+ }
109
+ if (p.quality)
110
+ lines.push("", `品質基準: ${p.quality.state === "set" ? `版 ${p.quality.version}・判定する ${p.quality.applies.map((q) => q.id).join(", ") || "なし"}${p.quality.exempt.length ? `・除外 ${p.quality.exempt.map((q) => q.id).join(", ")}` : ""}` : p.quality.state === "unset" ? "未設定" : "読めません"}`);
111
+ lines.push("", `観点: ${p.viewpoint.source}${p.viewpoint.repo ? `(${p.viewpoint.repo}@${p.viewpoint.sha?.slice(0, 12)}:${p.viewpoint.path})` : ""}`);
112
+ for (const n of p.notes)
113
+ lines.push(` ⚠ ${n.message}`);
114
+ if (p.engineRequired)
115
+ lines.push("", "※ Preflight の担当が agent なので、Codex で実行するなら --engine codex を付けてください");
116
+ return lines.join("\n");
117
+ }
118
+ /** 品質の表示(評価した版・最新との差・基準ごとの判定・違反の指摘)。古い記録は品質を評価していない */
119
+ function qualityLines(input, result) {
120
+ const q = input.quality;
121
+ if (!q)
122
+ return ["品質: 評価していません(品質基準を材料に入れる前の記録です)"];
123
+ if (q.latest.state !== "set")
124
+ return [`品質: 評価していません(品質基準が${q.latest.state === "unset" ? "未設定" : "読めません"})`];
125
+ const lines = [`品質(最新の品質基準 版 ${q.latest.version}。タスクに取り込んだ版: ${q.imported.length ? [...new Set(q.imported.map((x) => x.version))].join(", ") : "なし"}):`];
126
+ for (const d of q.diff.filter((x) => x.kind !== "edited"))
127
+ lines.push(` 差: ${d.kind}:${d.quality}${d.reason ? `(${d.reason})` : ""}`);
128
+ for (const r of result.quality ?? []) {
129
+ lines.push(` ${r.verdict === "violated" ? "✗" : "・"} ${r.standard} ${QUALITY_VERDICT_LABELS[r.verdict]} ${r.reason}`);
130
+ if (r.evidence.length)
131
+ lines.push(` 根拠: ${r.evidence.join(", ")}`);
132
+ if (r.unread)
133
+ lines.push(` 確かめられなかった範囲: ${r.unread}`);
134
+ }
135
+ for (const e of q.exempt)
136
+ lines.push(` ・ ${e.id} 除外(${e.exempt?.reason ?? ""})`);
137
+ const violated = (result.quality ?? []).filter((r) => r.verdict === "violated");
138
+ if (violated.length)
139
+ lines.push(`品質の指摘: ${violated.map((r) => r.standard).join(", ")} に違反があります(作業した側の証拠とは別の判定です)`);
140
+ return lines;
141
+ }
142
+ /** review-show の人向けの表示 */
143
+ export function formatTaskReview(d) {
144
+ const { run, input, result } = d;
145
+ const lines = [`${run.request}/${run.task}/${run.id} ${STATUS_LABEL[run.status]} ${run.startedAt}${run.startedBy ? ` ${run.startedBy}` : ""} (${run.engine}${run.model ? ` ${run.model}` : ""})`];
146
+ if (run.error)
147
+ lines.push(` ${run.error}`);
148
+ if (d.owner && d.owner.state !== "local" && d.owner.state !== "alive") {
149
+ lines.push(` 実行しているプロセスを確かめられません(${"reason" in d.owner ? d.owner.reason : ""})。止まっていると確かめたら p3 review-cancel ${run.request}/${run.task} ${run.id} --acknowledge-stopped`);
150
+ }
151
+ lines.push(`材料: 比較項目 ${input.items.length} 件・ファイル ${input.files.length} 件・観点 ${input.viewpoint.source}(${input.extractedAt})`);
152
+ for (const t of input.targets)
153
+ lines.push(` ${t.repo}: ${t.kind === "range" ? `${t.range.base.slice(0, 12)}..${t.range.head.slice(0, 12)}` : t.commits.map((c) => c.sha.slice(0, 12)).join(", ")}`);
154
+ for (const n of input.notes)
155
+ lines.push(` ⚠ ${n.message}`);
156
+ if (result) {
157
+ const text = new Map(input.items.map((i) => [i.id, i.text]));
158
+ lines.push("", "全体の所見:", ...result.overall.split("\n").map((l) => ` ${l}`), "");
159
+ for (const i of result.items) {
160
+ lines.push(`■ ${i.item} ${TASK_REVIEW_VERDICT_LABELS[i.verdict]} ${(text.get(i.item) ?? "").split("\n")[0]}`);
161
+ lines.push(` 理由: ${i.reason}`);
162
+ if (i.evidence.length)
163
+ lines.push(` 根拠: ${i.evidence.join(", ")}`);
164
+ for (const g of i.gaps)
165
+ lines.push(` 不足: ${g}`);
166
+ }
167
+ lines.push("", "意図しない変更の候補:");
168
+ if (!result.unplanned.length)
169
+ lines.push(" (見つかっていません)");
170
+ for (const u of result.unplanned)
171
+ lines.push(` - ${u.text}${u.evidence.length ? `(根拠: ${u.evidence.join(", ")})` : ""}`);
172
+ if (result.checks.length)
173
+ lines.push("", "人が確かめる点:", ...result.checks.map((c) => ` - ${c}`));
174
+ lines.push("", ...qualityLines(input, result));
175
+ lines.push("", `読めた範囲: ${result.coverage.read}`, `読めなかった範囲: ${result.coverage.unread || "(なし)"}`, "", `範囲: ${TASK_REVIEW_SCOPE}`);
176
+ }
177
+ return lines.join("\n");
178
+ }
@@ -8,6 +8,10 @@ import { checkDataDir } from "./store/locate.js";
8
8
  import { Workspace } from "./store/workspace.js";
9
9
  import { ReleaseGenerator } from "./releaseNotes/generate.js";
10
10
  import { MockSummarizer } from "./releaseNotes/mockSummarizer.js";
11
+ import { MilestoneReviewService } from "./milestoneReview/service.js";
12
+ import { MockReviewer } from "./milestoneReview/mockReviewer.js";
13
+ import { TaskReviewService } from "./taskReview/service.js";
14
+ import { MockTaskReviewer } from "./taskReview/mockReviewer.js";
11
15
  /** p3 本体(パッケージ)のルート */
12
16
  export const P3_ROOT = fileURLToPath(new URL("../../", import.meta.url));
13
17
  /**
@@ -37,5 +41,7 @@ export async function openProject(dataDir, opts = {}) {
37
41
  }, { pathMap: async () => (await source.get()).codex.pathMap });
38
42
  // 要約の生成も Preflight と同じ接続と既定のエンジン(preflight.engine)を使う
39
43
  const releaseGenerator = new ReleaseGenerator(ws, { codex, mock: new MockSummarizer() }, { engine: async () => (await source.get()).preflight.engine });
40
- return { ws, preflight, releaseGenerator, chatgpt, projectName: opts.projectName };
44
+ const milestoneReview = new MilestoneReviewService(ws, { codex, mock: new MockReviewer() }, { engine: async () => (await source.get()).preflight.engine });
45
+ const taskReview = new TaskReviewService(ws, { codex, mock: new MockTaskReviewer() }, { engine: async () => (await source.get()).preflight.engine });
46
+ return { ws, preflight, releaseGenerator, milestoneReview, taskReview, chatgpt, projectName: opts.projectName };
41
47
  }
@@ -0,0 +1,129 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { isAbsolute, relative } from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { gitHistory } from "../repoRefs.js";
6
+ const run = promisify(execFile);
7
+ /**
8
+ * マイルストーンレビューのコードの材料。Codex には参照先を読むだけでマウントして、コードと git の履歴を読ませる。
9
+ * ここでは、そのとき読んだものが後から分かるように、参照先ごとの状態・HEAD・ブランチ・未コミットの変更の数と、
10
+ * タスクの成果物に残したコミット(参照先の履歴にあるか)を取り出す。コードの中身は保存しない。git は読むだけの操作だけ。
11
+ */
12
+ /** 成果物の文字列からコミットを取り出す(…/commit/<sha> の URL か、sha だけの文字列) */
13
+ export function commitsInOutput(output) {
14
+ const out = new Set();
15
+ for (const m of output.matchAll(/\/commit\/([0-9a-f]{7,40})\b/gi))
16
+ out.add(m[1].toLowerCase());
17
+ const bare = output.trim();
18
+ if (/^[0-9a-f]{7,40}$/i.test(bare))
19
+ out.add(bare.toLowerCase());
20
+ return [...out];
21
+ }
22
+ const git = async (local, args) => (await run("git", ["-C", local, ...args], { timeout: 10_000, maxBuffer: 4 * 1024 * 1024 })).stdout.trim();
23
+ const tryGit = (local, args) => git(local, args).catch(() => undefined);
24
+ /** git を動かして標準出力を返す(標準入力を渡せる。大きな差分も読む) */
25
+ function gitRaw(local, args, input) {
26
+ return new Promise((resolve) => {
27
+ const child = execFile("git", ["-C", local, ...args], { timeout: 30_000, maxBuffer: 256 * 1024 * 1024, encoding: "utf8" }, (err, stdout) => resolve(err ? undefined : stdout));
28
+ // git が先に終わっても(EPIPE)落とさない。結果は終わり方で決める
29
+ child.stdin?.on("error", () => undefined);
30
+ child.stdin?.end(input);
31
+ });
32
+ }
33
+ /**
34
+ * 未コミットの変更の中身の識別子(差分と、追跡していないファイルの中身から。中身そのものは保存しない)。
35
+ * 変更の数が同じでも中身が変われば変わる(材料が変わったと分かるように)
36
+ */
37
+ async function dirtyDigest(local, head, pathspec) {
38
+ const tracked = head
39
+ ? await gitRaw(local, ["diff", "--binary", "HEAD", "--", ...pathspec])
40
+ : [await gitRaw(local, ["diff", "--binary", "--cached", "--", ...pathspec]), await gitRaw(local, ["diff", "--binary", "--", ...pathspec])].join("\n");
41
+ const others = (await gitRaw(local, ["ls-files", "--others", "--exclude-standard", "-z", "--", ...pathspec])) ?? "";
42
+ const names = others.split("\0").filter(Boolean).sort();
43
+ const blobs = names.length ? await gitRaw(local, ["hash-object", "--stdin-paths"], `${names.join("\n")}\n`) : "";
44
+ if (tracked === undefined || blobs === undefined)
45
+ return undefined;
46
+ return createHash("sha256").update(tracked).update("\0").update(names.join("\0")).update("\0").update(blobs).digest("hex");
47
+ }
48
+ /**
49
+ * 参照先ごとのコードの材料と警告。dataDir: データのフォルダ(参照先の中にあれば、未コミットの変更の数に入れない。
50
+ * 要望・タスクの記録は別に材料にしている)
51
+ */
52
+ export async function reviewCode(refs, requests, dataDir) {
53
+ const warnings = [];
54
+ // 成果物に残したコミット("<参照先>: <成果物>" は、その参照先のもの)
55
+ const wanted = [];
56
+ const names = new Set(refs.map((r) => r.name));
57
+ for (const r of requests) {
58
+ for (const t of r.tasks) {
59
+ for (const o of t.outputs) {
60
+ const m = /^([^:\s]+): (.*)$/s.exec(o);
61
+ const repo = m && names.has(m[1]) ? m[1] : undefined;
62
+ for (const sha of commitsInOutput(repo ? m[2] : o)) {
63
+ if (!wanted.some((w) => w.sha === sha && w.from === t.ref))
64
+ wanted.push({ sha, from: t.ref, repo });
65
+ }
66
+ }
67
+ }
68
+ }
69
+ const code = [];
70
+ for (const r of refs) {
71
+ const base = { name: r.name, mount: r.mount, ...(r.role ? { role: r.role } : {}), status: r.status };
72
+ if (r.status !== "ok" || !r.local) {
73
+ code.push({ ...base, ...(r.reason ? { reason: r.reason } : {}), commits: [] });
74
+ warnings.push({ code: "code_unavailable", target: r.name, message: `参照先 ${r.name} を読めません(${r.reason ?? r.status})。そのコードは確かめられません` });
75
+ continue;
76
+ }
77
+ const history = gitHistory(r.local).status;
78
+ const ref = { ...base, history, commits: [] };
79
+ if (history !== "unavailable") {
80
+ const head = await tryGit(r.local, ["rev-parse", "--verify", "-q", "HEAD"]);
81
+ const branch = await tryGit(r.local, ["branch", "--show-current"]);
82
+ const rel = dataDir ? relative(r.local, dataDir) : "..";
83
+ const inside = rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
84
+ const pathspec = [".", ...(inside ? [`:(exclude)${rel}`] : [])];
85
+ const status = await tryGit(r.local, ["status", "--porcelain", "--", ...pathspec]);
86
+ if (head)
87
+ ref.head = head;
88
+ if (branch)
89
+ ref.branch = branch;
90
+ const dirty = status ? status.split("\n").filter(Boolean).length : 0;
91
+ if (dirty) {
92
+ ref.dirty = dirty;
93
+ const digest = await dirtyDigest(r.local, head, pathspec);
94
+ if (digest)
95
+ ref.dirtyDigest = digest;
96
+ warnings.push({ code: "dirty_worktree", target: r.name, message: `参照先 ${r.name} に未コミットの変更が ${dirty} 件あります(作業ツリーのコードを読むので、コミットとずれることがあります)` });
97
+ }
98
+ }
99
+ code.push(ref);
100
+ }
101
+ // コミットは、指定の参照先か、履歴のある参照先のどれかで探す
102
+ for (const w of wanted) {
103
+ const candidates = code.filter((c) => c.status === "ok" && c.history && c.history !== "unavailable" && (!w.repo || c.name === w.repo));
104
+ let placed = false;
105
+ for (const c of candidates) {
106
+ const local = refs.find((r) => r.name === c.name).local;
107
+ const full = await tryGit(local, ["rev-parse", "--verify", "-q", `${w.sha}^{commit}`]);
108
+ if (full) {
109
+ add(c.commits, { sha: full, from: w.from, found: true });
110
+ placed = true;
111
+ break;
112
+ }
113
+ }
114
+ if (!placed) {
115
+ const target = code.find((c) => c.name === w.repo) ?? candidates[0];
116
+ if (target)
117
+ add(target.commits, { sha: w.sha, from: w.from, found: false });
118
+ warnings.push({ code: "commit_missing", target: w.from, message: `${w.from} の成果物のコミット ${w.sha} が参照先の履歴にありません(中身を確かめられません)` });
119
+ }
120
+ }
121
+ if (!code.some((c) => c.status === "ok")) {
122
+ warnings.push({ code: "no_code", target: "repos", message: "読める参照先(リポジトリ)がありません。実装は確かめられず、記録だけの点検になります(p3 repo path <名前> <パス> で登録できます)" });
123
+ }
124
+ return { code, warnings };
125
+ }
126
+ function add(list, c) {
127
+ if (!list.some((x) => x.sha === c.sha && x.from === c.from))
128
+ list.push(c);
129
+ }
@@ -0,0 +1,148 @@
1
+ import { createHash } from "node:crypto";
2
+ import { PURPOSE_UNIT_ID, REVIEW_SCOPE, REVIEW_SCOPE_RECORDS_ONLY, } from "../../shared/milestoneReview.js";
3
+ import { qualitySnapshot } from "../../shared/quality.js";
4
+ import { hierarchyNow } from "../requestStatus.js";
5
+ import { Workspace } from "../store/workspace.js";
6
+ import { reviewCode } from "./code.js";
7
+ /**
8
+ * マイルストーンレビューの比較材料を取り出す。リリースノートの材料(releaseNotes/material.ts)とは別の規則で、あちらの収録の
9
+ * 条件は変えない。
10
+ *
11
+ * - 比べるのは保存してある目的・予定機能(画面の書きかけは使わない)。比較単位は予定機能。予定機能が無く目的だけなら目的そのもの
12
+ * - 確かめる対象は参照先のコード(code.ts。Codex に読むだけでマウントする)。参照先ごとの HEAD・未コミットの変更・
13
+ * タスクに残したコミットを固定する。読める参照先が無ければ警告し、範囲を「記録だけ」にする
14
+ * - 材料は、マイルストーンに直接属する要望の全部の状態(下書き・進行中・対応済・完了済・見送り)。要望の本文、各タスクの本文・状態・
15
+ * 変更の記録・成果物の参照の文字列。未完了・記録なしも省かない(見送りは状態のまま残し、成果と混同しないよう評価の指示で扱う)
16
+ * - 親子: 親・子が別のマイルストーンなら文脈(context)として ID・題・状態だけを持ち、材料には数えない(二重に数えない)
17
+ * - アーカイブした要望は通常の一覧と同じく含めない。成果物の URL・添付の中身は読まない
18
+ * - 読めない要望は所属が分からないので全体の警告、読めないタスクはその要望の欠落の警告
19
+ * - hash には目的・予定機能・所属・本文・状態・記録・関係・欠落を入れ、抽出の日時は入れない
20
+ *
21
+ * 抽出のたびにディスクから読み直した別の Workspace を使う(画面・CLI のキャッシュに左右されない)。複数のファイルを同じ時点で
22
+ * 読んだとは保証しない(抽出の始めと終わりを残す)。何も書かない。
23
+ */
24
+ export async function extractReviewInput(dataDir, mid, refs = []) {
25
+ const extractedAt = new Date().toISOString();
26
+ const snap = new Workspace(dataDir);
27
+ await snap.load();
28
+ const records = reviewInputOf(snap, mid, extractedAt);
29
+ const { code, warnings } = await reviewCode(refs, records.requests, dataDir);
30
+ return withCode(records, code, warnings);
31
+ }
32
+ /** 記録の材料にコードの材料を足す(範囲・警告・hash も合わせる) */
33
+ export function withCode(i, code, warnings = []) {
34
+ const body = {
35
+ milestone: i.milestone,
36
+ units: i.units,
37
+ requests: i.requests,
38
+ context: i.context,
39
+ warnings: [...i.warnings, ...warnings],
40
+ code,
41
+ ...(i.quality ? { quality: i.quality } : {}),
42
+ scope: code.some((c) => c.status === "ok") ? REVIEW_SCOPE : REVIEW_SCOPE_RECORDS_ONLY,
43
+ };
44
+ return { ...body, extractedAt: i.extractedAt, extractedUntil: new Date().toISOString(), hash: reviewInputHash(body) };
45
+ }
46
+ const byId = (a, b) => a.localeCompare(b, undefined, { numeric: true });
47
+ /** 比較単位(予定機能。無ければ目的) */
48
+ export function reviewUnits(m) {
49
+ if (m?.goals?.length)
50
+ return m.goals.map((g) => ({ id: g.id, text: g.text }));
51
+ return m?.purpose ? [{ id: PURPOSE_UNIT_ID, text: m.purpose }] : [];
52
+ }
53
+ export function reviewInputOf(ws, mid, extractedAt = new Date().toISOString()) {
54
+ const m = ws.project.milestones.find((x) => x.id === mid);
55
+ const warnings = [];
56
+ if (!m)
57
+ warnings.push({ code: "unknown_milestone", target: mid, message: `マイルストーン ${mid} は project.yaml にありません` });
58
+ else if (!m.purpose && !m.goals?.length) {
59
+ warnings.push({ code: "no_goals", target: mid, message: `マイルストーン ${mid} に目的も予定機能もありません(マイルストーンのタブか p3 milestone purpose / goal add で書けます)` });
60
+ }
61
+ for (const [id, e] of ws.requests.errors) {
62
+ warnings.push({ code: "broken_request", target: `requests/${id}/request.md`, message: `要望のファイルを読めないため、このマイルストーンに属するか分かりません: ${e}` });
63
+ }
64
+ const h = hierarchyNow(ws);
65
+ const members = ws.requests
66
+ .list()
67
+ .filter((r) => r.milestone === mid)
68
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt) || byId(a.id, b.id));
69
+ const memberIds = new Set(members.map((r) => r.id));
70
+ const requests = [];
71
+ const context = [];
72
+ const addContext = (c) => {
73
+ if (!context.some((x) => x.id === c.id && x.of === c.of && x.relation === c.relation))
74
+ context.push(c);
75
+ };
76
+ for (const r of members) {
77
+ const col = ws.tasksOf(r.id);
78
+ const broken = [...col.errors.keys()].sort(byId);
79
+ for (const t of broken)
80
+ warnings.push({ code: "broken_task", target: `${r.id}/${t}`, message: `${r.id}/${t} のタスクのファイルを読めません(材料から欠けています)` });
81
+ const tasks = [...col.list()].sort((a, b) => byId(a.id, b.id));
82
+ for (const t of tasks) {
83
+ if (t.status === "done" && !t.record?.trim())
84
+ warnings.push({ code: "missing_record", target: t.ref, message: `${t.ref} は完了していますが変更の記録がありません` });
85
+ }
86
+ const kids = h.children(r.id);
87
+ requests.push({
88
+ id: r.id,
89
+ title: r.title,
90
+ status: r.status,
91
+ body: r.body.trim(),
92
+ ...(r.parent ? { parent: r.parent } : {}),
93
+ ...(kids.length ? { children: kids.map((k) => ({ id: k.id, ...(k.milestone ? { milestone: k.milestone } : {}), status: k.status })) } : {}),
94
+ tasks: tasks.map((t) => ({
95
+ id: t.id,
96
+ ref: t.ref,
97
+ title: t.title,
98
+ status: t.status,
99
+ body: t.body.trim(),
100
+ ...(t.record?.trim() ? { record: t.record.trim() } : {}),
101
+ outputs: [...t.outputs, ...(t.repoOutputs ?? []).map((o) => `${o.repo}: ${o.output}`)],
102
+ })),
103
+ });
104
+ const parent = r.parent ? ws.requests.get(r.parent) : undefined;
105
+ if (parent && !memberIds.has(parent.id))
106
+ addContext({ id: parent.id, title: parent.title, status: parent.status, milestone: parent.milestone, relation: "parent", of: r.id });
107
+ for (const k of kids) {
108
+ if (!memberIds.has(k.id))
109
+ addContext({ id: k.id, title: k.title, status: k.status, milestone: k.milestone, relation: "child", of: r.id });
110
+ }
111
+ }
112
+ if (!members.length)
113
+ warnings.push({ code: "no_requests", target: mid, message: `マイルストーン ${mid} に属する要望がありません(判断材料が無いことを記録します)` });
114
+ const milestone = {
115
+ id: mid,
116
+ title: m?.title ?? mid,
117
+ ...(m?.due ? { due: m.due } : {}),
118
+ ...(m?.done ? { done: true } : {}),
119
+ known: !!m,
120
+ ...(m?.purpose ? { purpose: m.purpose } : {}),
121
+ ...(m?.goals?.length ? { goals: m.goals.map((g) => ({ id: g.id, text: g.text })) } : {}),
122
+ };
123
+ const units = reviewUnits(m);
124
+ // 品質基準(版つき)。未設定・読めないは警告にして、設定や改善の要望へ案内する
125
+ const quality = qualitySnapshot(ws.project.quality, ws.project.qualityVersion);
126
+ if (quality.state === "unset")
127
+ warnings.push({ code: "quality_unset", target: "project.yaml", message: "プロジェクトの品質基準は未設定です(品質は評価しません。p3 quality で設定するか、設定する要望を登録できます)" });
128
+ if (quality.state === "invalid")
129
+ warnings.push({ code: "quality_invalid", target: "project.yaml", message: `プロジェクトの品質基準が読めません(品質は評価しません。project.yaml を直してください): ${(quality.problems ?? []).join(" / ")}` });
130
+ const body = { milestone, units, requests, context, warnings, scope: REVIEW_SCOPE_RECORDS_ONLY, quality };
131
+ return { ...body, extractedAt, extractedUntil: new Date().toISOString(), hash: reviewInputHash(body) };
132
+ }
133
+ /** 材料の識別子(抽出の日時・警告の文言は含めない) */
134
+ export function reviewInputHash(i) {
135
+ const key = {
136
+ milestone: [i.milestone.id, i.milestone.title, i.milestone.known, i.milestone.purpose ?? null, (i.milestone.goals ?? []).map((g) => [g.id, g.text])],
137
+ requests: i.requests,
138
+ context: i.context.map((c) => [c.id, c.status, c.milestone ?? null, c.relation, c.of]),
139
+ missing: i.warnings.filter((w) => w.code === "broken_request" || w.code === "broken_task").map((w) => w.target),
140
+ // 読んだコード(HEAD・ブランチ・未コミットの変更の中身・コミットが見つかるか)が変われば材料が変わった
141
+ ...(i.code
142
+ ? { code: i.code.map((c) => [c.name, c.status, c.head ?? null, c.branch ?? null, c.dirty ?? 0, c.dirtyDigest ?? null, c.commits.map((x) => [x.sha, x.from, x.found])]) }
143
+ : {}),
144
+ // 品質基準(状態と版。変われば材料が変わった)
145
+ ...(i.quality ? { quality: [i.quality.state, i.quality.version] } : {}),
146
+ };
147
+ return createHash("sha256").update(JSON.stringify(key)).digest("hex");
148
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Codex を使わずにレビューの契約(最後の応答の JSON)を再現する(オフライン開発・デモ・テスト用)。評価はせず、比較単位ごとに
3
+ * 「判断材料不足」を返す。--engine mock か個人設定の preflight.engine: mock で明示したときだけ使う(Preflight と同じ)
4
+ */
5
+ export class MockReviewer {
6
+ opts;
7
+ /** 待ち時間(ms。画面で実行中が見えるように少し待つ。テストでは 0) */
8
+ constructor(opts = {}) {
9
+ this.opts = opts;
10
+ }
11
+ async ask(input, log, signal) {
12
+ log({ kind: "info", text: "Mock でレビューします(評価はせず、どの比較単位も判断材料不足にします)" });
13
+ await new Promise((res, rej) => {
14
+ const t = setTimeout(res, this.opts.delayMs ?? 1500);
15
+ signal.addEventListener("abort", () => (clearTimeout(t), rej(new Error("aborted"))), { once: true });
16
+ });
17
+ const json = /<material>\n([\s\S]*?)\n<\/material>/.exec(input.prompt)?.[1];
18
+ const material = JSON.parse(json ?? "{}");
19
+ return {
20
+ message: JSON.stringify({
21
+ overall: `(Mock)評価していません。所属する要望 ${material.requests?.length ?? 0} 件を材料にしました`,
22
+ units: (material.units ?? []).map((u) => ({ unit: u.id, verdict: "insufficient", reason: "(Mock)評価していません", evidence: [], gaps: ["Codex で実行すると評価します"] })),
23
+ ...(material.quality ? { quality: material.quality.standards.map((q) => ({ standard: q.id, verdict: "undetermined", reason: "(Mock)評価していません", evidence: [] })) } : {}),
24
+ }),
25
+ seconds: 0,
26
+ };
27
+ }
28
+ }