@infodb/p3 0.0.0-stage → 0.2.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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -2
  3. package/bin/p3.mjs +18 -0
  4. package/dist/web/apple-touch-icon.png +0 -0
  5. package/dist/web/assets/Outputs-Ni3pNuGU.js +1 -0
  6. package/dist/web/assets/RequestStatus-K8TZwpur.js +1 -0
  7. package/dist/web/assets/TagInput-BICKVH2x.js +1 -0
  8. package/dist/web/assets/TaskDrawer-BkDIstIN.js +3 -0
  9. package/dist/web/assets/_requestId-B5O_ytaq.js +1 -0
  10. package/dist/web/assets/_requestId-C66puEMO.js +30 -0
  11. package/dist/web/assets/action-CMjATXqv.js +1 -0
  12. package/dist/web/assets/board-CbfDjkls.js +1 -0
  13. package/dist/web/assets/copy-B1ZbihKL.js +2 -0
  14. package/dist/web/assets/done-CPQbCFHg.js +1 -0
  15. package/dist/web/assets/draft-dT3gLDIt.js +1 -0
  16. package/dist/web/assets/format-DuK6P1hb.js +1 -0
  17. package/dist/web/assets/index-BUcs2J6N.js +12 -0
  18. package/dist/web/assets/index-C3DkqwJ9.css +2 -0
  19. package/dist/web/assets/link-_s8ndNKS.js +1 -0
  20. package/dist/web/assets/new-T60RB7de.js +1 -0
  21. package/dist/web/assets/preload-helper-dXqN7N-I.js +1 -0
  22. package/dist/web/assets/release-notes-DxrPhDbt.js +3 -0
  23. package/dist/web/assets/requestData-D8ZiSZss.js +1 -0
  24. package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
  25. package/dist/web/assets/routes-D9ZxXoLk.js +2 -0
  26. package/dist/web/assets/search-CJ8MBKTz.js +1 -0
  27. package/dist/web/assets/settings-DsHVyqzJ.js +1 -0
  28. package/dist/web/assets/supersede-CLXlhCq0.js +1 -0
  29. package/dist/web/assets/ui-Cvke4y4X.js +1 -0
  30. package/dist/web/favicon.ico +0 -0
  31. package/dist/web/favicon.svg +12 -0
  32. package/dist/web/index.html +23 -0
  33. package/docs/architecture.md +591 -0
  34. package/docs/chatgpt-sign-in.md +163 -0
  35. package/docs/development.md +194 -0
  36. package/docs/how-to-use.md +524 -0
  37. package/docs/installation.md +284 -0
  38. package/docs/publishing.md +65 -0
  39. package/package.json +86 -3
  40. package/skills/p3/SKILL.md +95 -0
  41. package/src/cli/args.ts +179 -0
  42. package/src/cli/chatgpt.ts +74 -0
  43. package/src/cli/codex.ts +28 -0
  44. package/src/cli/format.ts +9 -0
  45. package/src/cli/help.ts +99 -0
  46. package/src/cli/main.ts +267 -0
  47. package/src/cli/output.ts +99 -0
  48. package/src/cli/preflightCommands.ts +237 -0
  49. package/src/cli/project.ts +508 -0
  50. package/src/cli/readOnly.ts +36 -0
  51. package/src/cli/releaseNotesCommands.ts +139 -0
  52. package/src/cli/render.ts +60 -0
  53. package/src/cli/requestCommands.ts +170 -0
  54. package/src/cli/showView.ts +110 -0
  55. package/src/cli/taskCommands.ts +167 -0
  56. package/src/cli/userConfig.ts +58 -0
  57. package/src/core/chatgpt.ts +33 -0
  58. package/src/core/context.ts +57 -0
  59. package/src/core/machineSettings.ts +207 -0
  60. package/src/core/machineSettingsEdit.ts +156 -0
  61. package/src/core/ops.ts +114 -0
  62. package/src/core/preflight/carryover.ts +133 -0
  63. package/src/core/preflight/codexEngine.ts +702 -0
  64. package/src/core/preflight/codexImage.ts +98 -0
  65. package/src/core/preflight/diagnose.ts +124 -0
  66. package/src/core/preflight/engine.ts +92 -0
  67. package/src/core/preflight/input.ts +65 -0
  68. package/src/core/preflight/launch.ts +86 -0
  69. package/src/core/preflight/launcher.mjs +75 -0
  70. package/src/core/preflight/mock-ui.html +24 -0
  71. package/src/core/preflight/mock-ui.png +0 -0
  72. package/src/core/preflight/mockEngine.ts +145 -0
  73. package/src/core/preflight/render-image/Dockerfile +23 -0
  74. package/src/core/preflight/render-image/render.mjs +53 -0
  75. package/src/core/preflight/render.ts +336 -0
  76. package/src/core/preflight/service.ts +690 -0
  77. package/src/core/preflight/uiMaterials.ts +272 -0
  78. package/src/core/preflight/uiRender.ts +84 -0
  79. package/src/core/preflight/wireframe.ts +69 -0
  80. package/src/core/preflight/xlsx.ts +328 -0
  81. package/src/core/redact.ts +31 -0
  82. package/src/core/releaseNotes/generate.ts +271 -0
  83. package/src/core/releaseNotes/material.ts +114 -0
  84. package/src/core/releaseNotes/mockSummarizer.ts +28 -0
  85. package/src/core/releaseNotes/service.ts +106 -0
  86. package/src/core/releaseNotes/store.ts +216 -0
  87. package/src/core/repoAdmin.ts +81 -0
  88. package/src/core/repoRefs.ts +90 -0
  89. package/src/core/requestOps.ts +140 -0
  90. package/src/core/requestStatus.ts +58 -0
  91. package/src/core/store/attachments.ts +228 -0
  92. package/src/core/store/collection.ts +282 -0
  93. package/src/core/store/frontmatter.ts +22 -0
  94. package/src/core/store/fsutil.ts +90 -0
  95. package/src/core/store/locate.ts +181 -0
  96. package/src/core/store/normalize.ts +155 -0
  97. package/src/core/store/noteStore.ts +56 -0
  98. package/src/core/store/preflightStore.ts +136 -0
  99. package/src/core/store/projectFile.ts +101 -0
  100. package/src/core/store/workspace.ts +328 -0
  101. package/src/core/supersede.ts +74 -0
  102. package/src/core/userConfig.ts +180 -0
  103. package/src/core/userTheme.ts +22 -0
  104. package/src/core/workTargets.ts +120 -0
  105. package/src/server/api/chatgptRoutes.ts +48 -0
  106. package/src/server/api/local.ts +33 -0
  107. package/src/server/api/manifest.ts +119 -0
  108. package/src/server/api/releaseNoteRoutes.ts +78 -0
  109. package/src/server/api/repoRoutes.ts +67 -0
  110. package/src/server/api/routes.ts +374 -0
  111. package/src/server/api/userThemeRoutes.ts +62 -0
  112. package/src/server/server.ts +49 -0
  113. package/src/shared/dates.ts +12 -0
  114. package/src/shared/preflightInput.ts +27 -0
  115. package/src/shared/refs.ts +55 -0
  116. package/src/shared/repos.ts +113 -0
  117. package/src/shared/scopeView.ts +48 -0
  118. package/src/shared/tags.ts +27 -0
  119. package/src/shared/types.ts +700 -0
  120. package/src/shared/workTarget.ts +44 -0
@@ -0,0 +1,99 @@
1
+ import { absRef } from "../shared/refs.ts";
2
+ import { relationRole, type Request, type SupersededMark, type Task } from "../shared/types.ts";
3
+ import { type P3Context } from "../core/context.ts";
4
+ import { resolve, titleOf } from "../core/ops.ts";
5
+ import { type Warning } from "../core/supersede.ts";
6
+ import { table } from "./format.ts";
7
+ import { taskWork } from "../core/workTargets.ts";
8
+
9
+ /** CLI の出力(人向けの表と --json)と、表示の部品 */
10
+
11
+ // --- 表示 -----------------------------------------------------------------
12
+
13
+ export class Output {
14
+ constructor(readonly json: boolean) {}
15
+ result(data: unknown, human: () => string): number {
16
+ process.stdout.write(this.json ? `${JSON.stringify(data, null, 2)}\n` : `${human()}\n`);
17
+ return 0;
18
+ }
19
+ }
20
+
21
+ /** 同じ要望の中で、このタスクに依存しているタスク */
22
+ export const dependentsOf = (ctx: P3Context, t: Task): Task[] =>
23
+ ctx.ws.tasksOf(t.request).list().filter((x) => x.relations.some((r) => r.type === "depends_on" && r.target === t.id));
24
+
25
+ export function formatEntity(ctx: P3Context, item: Task | Request, file: string): string {
26
+ const head = "ref" in item ? item.ref : item.id;
27
+ const home = "ref" in item ? item.request : item.id;
28
+ const lines = [`${head} ${item.title}`, ""];
29
+ if ("ref" in item) lines.push(` ${"作業先".padEnd(11)} ${workHint(ctx, item).replace(/^作業先: /, "")}`);
30
+ const skip = new Set(["id", "ref", "request", "title", "body", "relations", "repo", "record"]);
31
+ for (const [k, v] of Object.entries(item)) {
32
+ if (skip.has(k) || v === undefined || (Array.isArray(v) && !v.length)) continue;
33
+ lines.push(` ${k.padEnd(13)} ${typeof v === "object" ? JSON.stringify(v) : v}`);
34
+ }
35
+ if (item.body.trim()) lines.push("", indent(item.body.trim()));
36
+ if ("record" in item && item.record) lines.push("", "変更の記録:", indent(item.record));
37
+ if ("ref" in item) {
38
+ const out = item.relations.map((r) => ` → ${pad(relationRole(r.type, "out"))} ${r.target} ${titleOf(ctx, `${home}/${r.target}`)}`);
39
+ const inc = [
40
+ ...dependentsOf(ctx, item).map((t) => ` ← ${pad(relationRole("depends_on", "in"))} ${t.id} ${t.title}`),
41
+ ...ctx.ws.tasksOf(home).list().filter((t) => t.relations.some((r) => r.type === "supersedes" && r.target === item.id)).map((t) => ` ← ${pad(relationRole("supersedes", "in"))} ${t.id} ${t.title}`),
42
+ ];
43
+ if (out.length || inc.length) lines.push("", "関係:", ...out, ...inc);
44
+ }
45
+ lines.push("", `ファイル: ${file}`);
46
+ return lines.join("\n");
47
+ }
48
+
49
+ export function ambiguous(out: Output, ctx: P3Context, query: string, current?: string): number {
50
+ const r = resolve(ctx, query, current);
51
+ out.result(r, () =>
52
+ r.candidates.length ? `候補が複数あります:\n${table(r.candidates.map((c) => [c.ref, c.score.toFixed(2), c.title]))}` : `見つかりません: ${query}`,
53
+ );
54
+ return r.candidates.length ? 1 : 2; // 候補が複数なら使い方の誤り(1)、何も無ければ見つからない(2)
55
+ }
56
+
57
+ /** 依存先(同じ要望なら T003、別の要望なら絶対参照) */
58
+ /** 置き換えられたタスクの印(同じ要望の中は T005 と短く) */
59
+ export const replacedBy = (t: Task, marks: Map<string, SupersededMark[]>) => {
60
+ const m = marks.get(t.ref);
61
+ return m?.length ? `※置換 ← ${m.map((x) => (x.from.startsWith(`${t.request}/`) ? x.from.slice(t.request.length + 1) : x.from)).join(",")}` : "";
62
+ };
63
+
64
+ /** タスクを変えた後、対応済の要望を進行中に戻していたら知らせる(requestOps が戻す)。戻した要望の ID を返す */
65
+ export function reopenedNote(rid: string | undefined): string | undefined {
66
+ if (rid) process.stderr.write(`要望 ${rid} を対応済から進行中に戻しました(未完了のタスクがあるため)\n`);
67
+ return rid;
68
+ }
69
+
70
+ /** 警告は stderr に出す(--json の stdout を汚さない。JSON では warnings フィールドで返す) */
71
+ export const warn = (warnings: Warning[]) => {
72
+ for (const w of warnings) process.stderr.write(`警告: ${w.message}\n`);
73
+ };
74
+
75
+ export const deps = (t: Task) => {
76
+ const d = t.relations.filter((r) => r.type === "depends_on").map((r) => (absRef(r.target, t.request)?.startsWith(`${t.request}/`) ? r.target : (absRef(r.target, t.request) ?? r.target)));
77
+ return d.length ? `← ${d.join(",")}` : "";
78
+ };
79
+
80
+ export const bar = (ratio: number, width = 10) => {
81
+ const n = Math.round(ratio * width);
82
+ return `${"█".repeat(n)}${"░".repeat(width - n)}`;
83
+ };
84
+
85
+ export const indent = (s: string) => s.split("\n").map((l) => ` ${l}`).join("\n");
86
+
87
+ /** 関係の役割を同じ幅にそろえる(全角は2桁として数える。CLI の詳細で相手の列がそろうように) */
88
+ export function pad(label: string, width = 8): string {
89
+ const w = Array.from(label).reduce((n, ch) => n + (ch.charCodeAt(0) > 0xff ? 2 : 1), 0);
90
+ return label + " ".repeat(Math.max(1, width - w));
91
+ }
92
+
93
+ /** 作業先の案内(このマシンのパスが無ければ登録の仕方) */
94
+ export function workHint(ctx: P3Context, t: Task): string {
95
+ const w = taskWork(ctx.ws, t);
96
+ if (!w.repo) return "作業先: なし";
97
+ return `作業先: ${w.repo}${w.branch ? ` ブランチ ${w.branch}` : "(ブランチなし)"}${w.registered ? "" : `\n このマシンのパスが未登録です: p3 repo path ${w.repo} <パス>`}`;
98
+ }
99
+
@@ -0,0 +1,237 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { basename, join, relative, resolve as resolvePath } from "node:path";
3
+ import { AttachmentError, safeFileName } from "../core/store/attachments.ts";
4
+ import { type PreflightRun, type InputMatch, type MaterializeResult, type UiMaterialsStatus, UI_MATERIAL_KINDS, type Attachment, ATTACHMENT_FORMATS } from "../shared/types.ts";
5
+ import { type P3Context } from "../core/context.ts";
6
+ import { NotFoundError } from "../core/store/collection.ts";
7
+ import { table } from "./format.ts";
8
+ import { evidenceLines, scopeLines } from "../shared/scopeView.ts";
9
+ import { UsageError } from "./project.ts";
10
+ import { StaleInputError, staleMessage } from "../core/preflight/input.ts";
11
+ import { changedLabel, isMaterialized } from "../shared/preflightInput.ts";
12
+ import { readBody, type CommandEnv } from "./args.ts";
13
+ import { deps, indent } from "./output.ts";
14
+
15
+ /** Preflight のコマンド(preflight / attach / notes / drafts / accept)。扱わないコマンドは undefined */
16
+
17
+ export async function preflightCommand(cmd: string, env: CommandEnv): Promise<number | undefined> {
18
+ const { ctx, out, args, o, actor, requestArg, cwd } = env;
19
+ switch (cmd) {
20
+ // --- Preflight ----------------------------------------------------------
21
+ case "preflight": {
22
+ const rid = requestArg(args[0]);
23
+ const engine = o.engine as "codex" | "mock" | undefined;
24
+ if (o["note-only"] && o.note === undefined) throw new UsageError("--note-only には --note でメモを渡してください");
25
+ if (o["note-only"] && engine) throw new UsageError("--note-only は実行しないので --engine は使えません");
26
+ const note = o.note === undefined ? undefined : await ctx.preflight.addNote(rid, readBody(o.note), actor);
27
+ if (o["note-only"]) return out.result(note, () => `メモ ${note!.id} を書き足しました(次の Preflight に渡します)`);
28
+ if (note && !out.json) process.stderr.write(`メモ ${note.id} を書き足しました\n`);
29
+ const off = ctx.ws.on((e) => {
30
+ if (e.type === "preflight-log" && !out.json) process.stderr.write(`${e.entry.at.slice(11, 19)} ${e.entry.text}\n`);
31
+ });
32
+ const started = await ctx.preflight.start(rid, { engine, actor }).catch((e: Error) => {
33
+ off();
34
+ // メモは残っているので、書き直さずに p3 preflight だけで再実行できる
35
+ throw note ? new Error(`${e.message}(メモ ${note.id} は保存済みです。p3 preflight ${rid} で再実行できます)`) : e;
36
+ });
37
+ if (!out.json) process.stderr.write(`preflight ${started.id} (${started.engine})\n`);
38
+ const run = await ctx.preflight.wait(rid, started.id);
39
+ off();
40
+ if (!run) throw new Error("preflight の結果が読めません");
41
+ out.result(run, () => formatRun(ctx, rid, run));
42
+ return run.status === "completed" ? 0 : 1;
43
+ }
44
+
45
+ case "attach": {
46
+ // 要望は --req(か今の要望)。serve なしでファイルを直接扱う(API と同じ確かめ方)
47
+ const rid = requestArg(undefined);
48
+ const [sub = "ls", target] = args;
49
+ const fmt = (a: Attachment) => [a.id, ATTACHMENT_FORMATS[a.format], `${Math.ceil(a.bytes / 1024)}KB`, a.name, a.description ?? "", a.source ? `出典: ${a.source}` : ""];
50
+ if (sub === "ls") {
51
+ const { items, invalid } = await ctx.ws.attachments.list(rid);
52
+ return out.result({ items, invalid }, () =>
53
+ [
54
+ items.length ? table(items.map(fmt)) : "添付はありません",
55
+ ...invalid.map((i) => `[読めない] ${i.id}: ${i.error}`),
56
+ "",
57
+ "次の Preflight を始めるときに、この添付を run に固定して渡します(後で足し・消ししても過去の run の資料は変わりません)",
58
+ ].join("\n"),
59
+ );
60
+ }
61
+ if (sub === "add") {
62
+ if (!target) throw new UsageError("p3 attach add <ファイル> [--description 説明] [--source 出典] --req <要望>");
63
+ const data = await readFile(resolvePath(cwd, target)).catch(() => {
64
+ throw new UsageError(`ファイルが読めません: ${target}`);
65
+ });
66
+ try {
67
+ const a = await ctx.preflight.addAttachment(rid, { data, name: basename(target), description: o.description, source: o.source }, actor);
68
+ return out.result(a, () => `添付しました: ${table([fmt(a)])}\n次の Preflight に渡します`);
69
+ } catch (e) {
70
+ throw e instanceof AttachmentError ? new UsageError(e.message) : e;
71
+ }
72
+ }
73
+ if (sub === "get") {
74
+ if (!target) throw new UsageError("p3 attach get <A-ID> [--out ファイル] [--run PF-...](--run でその run に固定した原本)");
75
+ const got = o.run ? await ctx.preflight.fixedAttachment(rid, o.run, target) : await ctx.ws.attachments.content(rid, target).catch((e) => {
76
+ throw e instanceof AttachmentError ? new NotFoundError(e.message) : e;
77
+ });
78
+ const file = resolvePath(cwd, o.out ?? safeFileName(got.meta.name, got.meta.format));
79
+ await writeFile(file, got.data, { flag: "wx" }).catch((e: NodeJS.ErrnoException) => {
80
+ throw e.code === "EEXIST" ? new UsageError(`${file} は既にあります(--out で別の名前に)`) : e;
81
+ });
82
+ return out.result({ ...got.meta, file }, () => `書き出しました: ${file}`);
83
+ }
84
+ if (sub === "rm") {
85
+ if (!target) throw new UsageError("p3 attach rm <A-ID>");
86
+ await ctx.preflight.removeAttachment(rid, target).catch((e) => {
87
+ throw e instanceof AttachmentError ? new NotFoundError(target) : e;
88
+ });
89
+ return out.result({ removed: target }, () => `添付を外しました: ${target}(固定済みの過去の run の資料は残ります)`);
90
+ }
91
+ throw new UsageError("p3 attach [ls | add <ファイル> | get <A-ID> | rm <A-ID>] --req <要望>");
92
+ }
93
+
94
+ case "notes": {
95
+ const rid = requestArg(args[0]);
96
+ const { notes, invalid } = await ctx.ws.notes.list(rid);
97
+ const carry = await ctx.preflight.carryover(rid);
98
+ const pending = new Set(carry.notes.map((n) => n.id));
99
+ const items = notes.map((n) => ({ ...n, pending: pending.has(n.id) }));
100
+ return out.result({ notes: items, invalid, previous: carry.previous?.id ?? null, previousSkipped: carry.previousSkipped ?? null }, () =>
101
+ [
102
+ `次の Preflight: ${carry.previous ? `前回 ${carry.previous.id} を引き継ぐ` : carry.previousSkipped ? `前回を引き継がない(${carry.previousSkipped})` : "前回なし"}・メモ ${carry.notes.length} 件を渡す`,
103
+ ...items.map((n) => `\n${n.pending ? "[未]" : "[済]"} ${n.id} ${n.createdBy ?? ""} ${n.createdAt.slice(0, 16).replace("T", " ")}\n${indent(n.body)}`),
104
+ ...invalid.map((i) => `\n[読めない] ${i.file}: ${i.error}`),
105
+ ].join("\n"),
106
+ );
107
+ }
108
+
109
+ case "drafts": {
110
+ const rid = requestArg(args[0]);
111
+ const run = await pickRun(ctx, rid, o.run);
112
+ // タスク化の前なら、置き換えられる既存タスクも見せる
113
+ const supersedes = run.materialized?.length ? [] : (await ctx.preflight.previewMaterialize(rid, run.id)).candidates;
114
+ const inputMatch = await ctx.preflight.inputMatch(rid, run);
115
+ return out.result({ ...run, inputMatch, supersedes }, () =>
116
+ [
117
+ formatRun(ctx, rid, run),
118
+ inputMatchLine(rid, run, inputMatch),
119
+ supersedes.length
120
+ ? `\n置き換えられる既存タスク(accept では残す。--archive-superseded でアーカイブ):\n${table(supersedes.map((c) => [c.id, c.status, c.title]))}`
121
+ : "",
122
+ ].join("\n"),
123
+ );
124
+ }
125
+
126
+ case "accept": {
127
+ const rid = requestArg(args[0]);
128
+ const run = await pickRun(ctx, rid, o.run);
129
+ const keys = (s: string | undefined) => s?.split(",").map((x) => x.trim().toUpperCase());
130
+ const only = keys(o.only);
131
+ const skip = keys(o.skip) ?? [];
132
+ for (const d of run.drafts) {
133
+ const include = (only ? only.includes(d.key) : d.include) && !skip.includes(d.key);
134
+ if (include !== d.include) await ctx.preflight.updateDraft(rid, run.id, d.key, { include });
135
+ }
136
+ // 置き換えられるタスクは --archive-superseded のときだけ、確定時点の候補(プレビューと同じ rev)をアーカイブする
137
+ const { candidates } = await ctx.preflight.previewMaterialize(rid, run.id);
138
+ const archive = o["archive-superseded"] ? candidates.map((c) => ({ id: c.id, rev: c.rev })) : [];
139
+ let r: MaterializeResult;
140
+ try {
141
+ r = await ctx.preflight.materialize(rid, run.id, actor, { archive });
142
+ } catch (e) {
143
+ if (!(e instanceof StaleInputError) || !o.json) throw e;
144
+ // --json では理由を機械可読で返す(終了コードは 1)
145
+ out.result({ error: e.message, code: e.code, request: rid, run: run.id, inputMatch: e.match }, () => "");
146
+ return 1;
147
+ }
148
+ return out.result(r, () =>
149
+ [
150
+ `タスク化 (${rid} / ${run.id}):\n${table(r.tasks.map((t) => [t.id, t.title, deps(t)]))}`,
151
+ r.archived.length ? `\n置き換えられたタスクをアーカイブしました: ${r.archived.join(", ")}` : "",
152
+ r.kept.length
153
+ ? `\n置き換えられるタスクを残しました(着手前に確かめ、不要なら p3 archive <T> か accept --archive-superseded):\n${table(
154
+ r.kept.map((c) => [c.id, c.status, c.title, c.reasons.map((x) => `案 ${x.draft}`).join(",")]),
155
+ )}`
156
+ : "",
157
+ ].join("\n"),
158
+ );
159
+ }
160
+
161
+ }
162
+ return undefined;
163
+ }
164
+
165
+ /** 評価対象と今の要望の比較(drafts の表示) */
166
+ function inputMatchLine(rid: string, run: PreflightRun, m: InputMatch): string {
167
+ if (m.status === "same") return "";
168
+ if (isMaterialized(run)) {
169
+ return `\n※ この評価のあとで要望が変わっています(${m.status === "changed" ? changedLabel(m.changed) : m.reason})。タスク化は済んでいます。作り直すなら p3 preflight ${rid}`;
170
+ }
171
+ return `\n※ ${staleMessage(rid, run.id, m)}`;
172
+ }
173
+
174
+ async function pickRun(ctx: P3Context, rid: string, runId?: string) {
175
+ const runs = await ctx.preflight.list(rid);
176
+ const run = runId ? runs.find((r) => r.id === runId) : runs[0];
177
+ if (!run) throw new NotFoundError(runId ?? `${rid} の preflight`);
178
+ return run;
179
+ }
180
+
181
+ function formatRun(ctx: P3Context, rid: string, run: Awaited<ReturnType<typeof pickRun>>): string {
182
+ const lines = [`${rid} / ${run.id} ${run.engine} ${run.status}${run.startedBy ? ` ${run.startedBy}` : ""}`];
183
+ if (run.previous || run.notes?.length) {
184
+ lines.push(`引き継ぎ: ${run.previous ? `前回 ${run.previous}` : "前回なし"}${run.notes?.length ? ` / メモ ${run.notes.join(", ")}` : ""}`);
185
+ }
186
+ if (run.error) lines.push(`エラー: ${run.error}`);
187
+ const a = run.assessment;
188
+ if (a) {
189
+ lines.push("", `判定: ${a.verdict} 妥当性 ${a.validity.score} / 実現可能性 ${a.feasibility.score}`, indent(a.summary));
190
+ if (a.risks.length) lines.push("", "リスク:", ...a.risks.map((x) => ` - ${x}`));
191
+ if (a.questions.length) lines.push("", "確認事項:", ...a.questions.map((x) => ` - ${x}`));
192
+ }
193
+ lines.push("", ...scopeLines(run.scope));
194
+ if (a) lines.push("", ...evidenceLines(a.evidence));
195
+ if (run.scope?.some((s) => s.status === "unregistered")) lines.push(" → このマシンのパスは p3 repo path <名前> <パス> で登録します");
196
+ if (run.drafts.length) {
197
+ lines.push("", `タスク案 (${run.drafts.filter((d) => d.include).length}/${run.drafts.length} 件を採用):`);
198
+ const multi = ctx.ws.project.repos.length > 0;
199
+ lines.push(
200
+ table(
201
+ run.drafts.map((d) => [
202
+ d.include ? "[x]" : "[ ]",
203
+ d.key,
204
+ ...(multi ? [d.repo ?? "(作業先なし)"] : []),
205
+ d.title,
206
+ d.dependsOn.length ? `← ${d.dependsOn.join(",")}` : "",
207
+ ]),
208
+ ),
209
+ );
210
+ lines.push("", `ファイル: ${relative(process.cwd(), join(ctx.ws.preflight.runDir(rid, run.id), "drafts"))}/`);
211
+ }
212
+ lines.push("", ...uiLines(run.ui, relative(process.cwd(), join(ctx.ws.preflight.runDir(rid, run.id), "ui"))));
213
+ if (run.materialized?.length) lines.push("", `タスク化済み: ${run.materialized.join(", ")}`);
214
+ return lines.join("\n");
215
+ }
216
+
217
+ const UI_STATUS: Record<UiMaterialsStatus, string> = { generating: "評価中", ready: "そろっています", not_needed: "不要", missing: "足りません" };
218
+
219
+ /** 画面資料(ui/)。資料 ID は画面・API(/api/requests/<要望>/preflight/<run>/ui/<ID>)と同じ */
220
+ function uiLines(ui: PreflightRun["ui"], dir: string): string[] {
221
+ if (!ui) return ["画面資料: 記録なし(以前の run)"];
222
+ const lines = [`画面資料: ${UI_STATUS[ui.status]}${ui.reason ? `(${ui.reason})` : ""}`];
223
+ if (ui.verdictAdjusted) lines.push(" → 必要な画面イメージが足りないので、判定を go から clarify にしました");
224
+ if (ui.items.length) {
225
+ lines.push(
226
+ table(
227
+ ui.items.map((m) => [` ${m.id}`, UI_MATERIAL_KINDS[m.kind], m.drafts.join(","), `${m.width}x${m.height}`, m.title, `ui/${m.file}`]),
228
+ ),
229
+ );
230
+ for (const m of ui.items.filter((x) => x.assumptions.length)) lines.push(` ${m.id} の前提: ${m.assumptions.join(" / ")}`);
231
+ if (ui.items.some((m) => m.rendered)) lines.push(" P3 が原稿から描いた画像です(Codex は画像を見ていません。読めるかは画像で確かめてください)");
232
+ lines.push(` ファイル: ${dir}/`);
233
+ }
234
+ for (const p of ui.problems) lines.push(` [取り込めない] ${p}`);
235
+ return lines;
236
+ }
237
+