@infodb/p3 0.12.0 → 0.13.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 (113) hide show
  1. package/README.md +32 -35
  2. package/dist/web/assets/CompletionReview-gZKZrDu_.js +1 -0
  3. package/dist/web/assets/ImprovementDialog-Dno6dPnG.js +1 -0
  4. package/dist/web/assets/Outputs-BgHalMGb.js +1 -0
  5. package/dist/web/assets/RequestStatus-hZcBUUIu.js +1 -0
  6. package/dist/web/assets/Tabs-C3NmwCc3.js +1 -0
  7. package/dist/web/assets/TagInput-B2b862qn.js +1 -0
  8. package/dist/web/assets/TaskDrawer-4BQBELXa.js +6 -0
  9. package/dist/web/assets/_requestId-BMAG1t3o.js +1 -0
  10. package/dist/web/assets/_requestId-tbg2pA2S.js +1 -0
  11. package/dist/web/assets/archive-DMl6WyOe.js +1 -0
  12. package/dist/web/assets/board-BMTcHKyt.js +1 -0
  13. package/dist/web/assets/done-CL6Nlsua.js +1 -0
  14. package/dist/web/assets/draft-BvGxfD7v.js +2 -0
  15. package/dist/web/assets/index-Dp7Fc4VI.css +2 -0
  16. package/dist/web/assets/index-KdlgMitg.js +12 -0
  17. package/dist/web/assets/metrics-Cu7gJ7Rk.js +1 -0
  18. package/dist/web/assets/new-DTXWHuFO.js +1 -0
  19. package/dist/web/assets/outputs-CXqnjSqV.js +1 -0
  20. package/dist/web/assets/preflightInput-ClKwkp8R.js +2 -0
  21. package/dist/web/assets/preload-helper-oLCrNCwz.js +1 -0
  22. package/dist/web/assets/{quality-Pu6EISAM.js → quality-RFd-7k3r.js} +1 -1
  23. package/dist/web/assets/release-notes-Bpdi6RdY.js +5 -0
  24. package/dist/web/assets/requestData-CbFxwW5w.js +1 -0
  25. package/dist/web/assets/routes-BIt8bExF.js +6 -0
  26. package/dist/web/assets/settings-CsCqF_1B.js +1 -0
  27. package/dist/web/assets/ui-BGK72r3u.js +1 -0
  28. package/dist/web/assets/workTarget-CySfKyfB.js +30 -0
  29. package/dist/web/index.html +4 -4
  30. package/docs/architecture.md +300 -36
  31. package/docs/development.md +60 -16
  32. package/docs/how-to-use.md +381 -28
  33. package/docs/installation.md +235 -144
  34. package/docs/publishing.md +1 -1
  35. package/lib/cli/agentsStatus.js +197 -0
  36. package/lib/cli/args.js +72 -8
  37. package/lib/cli/guide.js +27 -0
  38. package/lib/cli/guide.md +214 -0
  39. package/lib/cli/help.js +44 -6
  40. package/lib/cli/main.js +76 -20
  41. package/lib/cli/metricsCommands.js +77 -0
  42. package/lib/cli/output.js +12 -2
  43. package/lib/cli/project.js +13 -27
  44. package/lib/cli/qualityCommands.js +33 -8
  45. package/lib/cli/readOnly.js +15 -0
  46. package/lib/cli/requestCommands.js +21 -4
  47. package/lib/cli/requirementCommands.js +288 -0
  48. package/lib/cli/retroCommands.js +106 -0
  49. package/lib/cli/revisitCommands.js +73 -0
  50. package/lib/cli/showView.js +119 -6
  51. package/lib/cli/taskCommands.js +42 -16
  52. package/lib/cli/userConfig.js +47 -0
  53. package/lib/core/completionRefs.js +46 -0
  54. package/lib/core/metrics/definitions.js +434 -0
  55. package/lib/core/metrics/index.js +88 -0
  56. package/lib/core/metrics/manual.js +180 -0
  57. package/lib/core/ops.js +15 -2
  58. package/lib/core/preflight/carryover.js +5 -1
  59. package/lib/core/preflight/codexEngine.js +34 -17
  60. package/lib/core/preflight/diagnose.js +4 -9
  61. package/lib/core/preflight/engine.js +9 -0
  62. package/lib/core/preflight/hostPaths.js +260 -0
  63. package/lib/core/preflight/input.js +33 -5
  64. package/lib/core/preflight/instructions.js +18 -1
  65. package/lib/core/preflight/mockEngine.js +20 -2
  66. package/lib/core/preflight/render.js +22 -3
  67. package/lib/core/preflight/service.js +59 -9
  68. package/lib/core/preflight/uiRender.js +3 -0
  69. package/lib/core/requestOps.js +206 -14
  70. package/lib/core/retrospective.js +208 -0
  71. package/lib/core/reviewCandidates.js +56 -0
  72. package/lib/core/store/collection.js +20 -1
  73. package/lib/core/store/normalize.js +22 -4
  74. package/lib/core/store/preflightStore.js +19 -5
  75. package/lib/core/store/workspace.js +17 -1
  76. package/lib/core/taskReview/material.js +7 -0
  77. package/lib/core/taskReview/review.js +9 -2
  78. package/lib/server/api/manifest.js +51 -3
  79. package/lib/server/api/routes.js +131 -11
  80. package/lib/shared/acceptance.js +258 -18
  81. package/lib/shared/completionRecord.js +327 -0
  82. package/lib/shared/metrics.js +42 -0
  83. package/lib/shared/preflightInput.js +1 -1
  84. package/lib/shared/requirementSource.js +635 -0
  85. package/lib/shared/retrospective.js +286 -0
  86. package/lib/shared/reviewCandidate.js +308 -0
  87. package/lib/shared/reworkHistory.js +81 -0
  88. package/package.json +3 -2
  89. package/skills/p3/SKILL.md +9 -181
  90. package/dist/web/assets/ImprovementDialog-kQaVBGWH.js +0 -1
  91. package/dist/web/assets/Outputs-_nU_p3nu.js +0 -1
  92. package/dist/web/assets/RequestStatus-RG-OVQYY.js +0 -1
  93. package/dist/web/assets/Tabs-ew9i5SKX.js +0 -1
  94. package/dist/web/assets/TagInput-BtlJTF7i.js +0 -1
  95. package/dist/web/assets/TaskDrawer-DW8GyJqI.js +0 -6
  96. package/dist/web/assets/_requestId-6Nb727dD.js +0 -1
  97. package/dist/web/assets/_requestId-BykTgPax.js +0 -1
  98. package/dist/web/assets/appCtx-CxDdXABS.js +0 -1
  99. package/dist/web/assets/archive-Ckh295Xe.js +0 -1
  100. package/dist/web/assets/board-BVAIjK-Y.js +0 -1
  101. package/dist/web/assets/done-BGfA-3MA.js +0 -1
  102. package/dist/web/assets/draft-CfJeyLOl.js +0 -1
  103. package/dist/web/assets/index-CgRU744I.css +0 -2
  104. package/dist/web/assets/index-DacQ0yl4.js +0 -12
  105. package/dist/web/assets/new-DVygWvVc.js +0 -1
  106. package/dist/web/assets/outputs-B6xDsLZf.js +0 -1
  107. package/dist/web/assets/preflightInput-BAeEJYUK.js +0 -2
  108. package/dist/web/assets/preload-helper-DyCqp21K.js +0 -1
  109. package/dist/web/assets/release-notes-CCpzyiNf.js +0 -5
  110. package/dist/web/assets/requestData-D5vBnuMh.js +0 -1
  111. package/dist/web/assets/routes-Q91zvNc0.js +0 -4
  112. package/dist/web/assets/settings-BzRgcmUm.js +0 -1
  113. package/dist/web/assets/workTarget-C9c57JAO.js +0 -30
@@ -0,0 +1,180 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { MetricsError } from "../../shared/metrics.js";
4
+ import { withFileLock, writeFileAtomic } from "../store/fsutil.js";
5
+ import { METRIC_DEFINITIONS } from "./definitions.js";
6
+ /**
7
+ * 人が記録する指標の値(費用・リリース後の不具合など。記録から出せないもの)の保存。記録は CLI の p3 metrics record からだけ(API・画面は読むだけ)。
8
+ *
9
+ * <data>/metrics/manual.json {version: 1, seq, records: [...]}(プロジェクトのデータと一緒に共有する)
10
+ * <data>/metrics/.manual.lock 書くときのロック(同じマシンのプロセスの間)
11
+ *
12
+ * - 1件は 指標・範囲(project かマイルストーン ID)・観測期間(開始日・終了日)・単位 で決まる。同じ内容の再送は何も変えない。値・出典・メモを
13
+ * 変える訂正は、読んだ版(rev)を渡したときだけ(渡さない・違えば競合で何も書かない)
14
+ * - 値は0以上(不具合は整数)。費用は通貨コードごとで、通貨・期間の違う値を1つに合算しない。範囲の間(全体とマイルストーン)も合算しない
15
+ * - ロックの中で読み直してから書き、置き換えで書く(途中の状態を読ませない)。壊れたファイルは空とみなさず、読めないと知らせて書かない
16
+ * - 記録のあるマイルストーンは通常の削除で消さない(core/requestOps.ts の checkMilestoneRemoval)。直接編集で消えたら知らせる
17
+ */
18
+ const DIR = "metrics";
19
+ const FILE = "manual.json";
20
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
21
+ const CURRENCY = /^[A-Z]{3}$/;
22
+ const SOURCE_MAX = 1000;
23
+ export const manualFile = (dataDir) => join(dataDir, DIR, FILE);
24
+ const lockFile = (dataDir) => join(dataDir, DIR, `.${FILE.replace(".json", "")}.lock`);
25
+ const validDate = (v) => DATE.test(v) && new Date(`${v}T00:00:00Z`).toISOString().slice(0, 10) === v;
26
+ function readRecord(raw, i) {
27
+ const o = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : undefined;
28
+ const at = `${i + 1} 件目`;
29
+ if (!o)
30
+ throw new Error(`${at} がオブジェクトではありません`);
31
+ const s = (k) => (typeof o[k] === "string" && o[k] ? o[k] : undefined);
32
+ const id = s("id");
33
+ if (!id || !/^M\d+$/.test(id))
34
+ throw new Error(`${at} の id が読めません(M1, M2, ...)`);
35
+ for (const k of ["metric", "scope", "from", "to", "unit", "source", "createdAt", "updatedAt"])
36
+ if (!s(k))
37
+ throw new Error(`${at}(${id})の ${k} がありません`);
38
+ if (typeof o.value !== "number" || !Number.isFinite(o.value) || o.value < 0)
39
+ throw new Error(`${at}(${id})の value が 0 以上の数ではありません`);
40
+ if (!Number.isInteger(o.rev) || o.rev < 1)
41
+ throw new Error(`${at}(${id})の rev が読めません`);
42
+ return {
43
+ id,
44
+ metric: s("metric"),
45
+ scope: s("scope"),
46
+ from: s("from"),
47
+ to: s("to"),
48
+ value: o.value,
49
+ unit: s("unit"),
50
+ source: s("source"),
51
+ ...(s("note") ? { note: s("note") } : {}),
52
+ rev: o.rev,
53
+ createdAt: s("createdAt"),
54
+ ...(s("createdBy") ? { createdBy: s("createdBy") } : {}),
55
+ updatedAt: s("updatedAt"),
56
+ ...(s("updatedBy") ? { updatedBy: s("updatedBy") } : {}),
57
+ };
58
+ }
59
+ /** 記録を読む。無ければ空、壊れていれば problem(空とみなさない) */
60
+ export async function readManual(dataDir) {
61
+ let text;
62
+ try {
63
+ text = await readFile(manualFile(dataDir), "utf8");
64
+ }
65
+ catch (e) {
66
+ if (e.code === "ENOENT")
67
+ return { records: [], seq: 0 };
68
+ return { records: [], seq: 0, problem: `読めません: ${e.message}` };
69
+ }
70
+ try {
71
+ const j = JSON.parse(text);
72
+ if (!j || typeof j !== "object" || j.version !== 1 || !Array.isArray(j.records))
73
+ throw new Error("{version: 1, records: [...]} の形ではありません");
74
+ const records = j.records.map(readRecord);
75
+ const seq = Math.max(Number.isInteger(j.seq) ? j.seq : 0, ...records.map((r) => Number(r.id.slice(1))));
76
+ return { records, seq };
77
+ }
78
+ catch (e) {
79
+ return { records: [], seq: 0, problem: `${DIR}/${FILE} が読めません(直してください。記録は書き足しません): ${e.message}` };
80
+ }
81
+ }
82
+ const manualSpec = (metric) => {
83
+ const d = METRIC_DEFINITIONS.find((x) => x.id === metric);
84
+ if (!d?.manual) {
85
+ const ids = METRIC_DEFINITIONS.filter((x) => x.manual).map((x) => x.id);
86
+ throw new MetricsError(`人が記録する指標ではありません: ${metric}(${ids.join(" / ")})`);
87
+ }
88
+ return d.manual;
89
+ };
90
+ /** 入力を確かめて、識別に使う値と保存する値にする(何も書かない) */
91
+ export function cleanManual(ctx, i) {
92
+ const spec = manualSpec(i.metric);
93
+ const scope = i.scope || "project";
94
+ if (scope !== "project" && !ctx.ws.project.milestones.some((m) => m.id === scope))
95
+ throw new MetricsError(`マイルストーン ${scope} は登録されていません(project か登録済みのマイルストーン ID)`);
96
+ if (!validDate(i.from) || !validDate(i.to))
97
+ throw new MetricsError(`観測期間は YYYY-MM-DD の日付で指定してください(--from ${i.from || "?"} --to ${i.to || "?"})`);
98
+ if (i.from > i.to)
99
+ throw new MetricsError(`観測期間の開始日 ${i.from} が終了日 ${i.to} より後です`);
100
+ const value = typeof i.value === "number" ? i.value : i.value.trim() === "" ? NaN : Number(i.value);
101
+ if (!Number.isFinite(value))
102
+ throw new MetricsError(`値が数ではありません: ${String(i.value)}`);
103
+ if (value < 0)
104
+ throw new MetricsError(`値は 0 以上です: ${value}`);
105
+ if (spec.value === "integer" && !Number.isInteger(value))
106
+ throw new MetricsError(`${i.metric} の値は 0 以上の整数です: ${value}`);
107
+ let unit;
108
+ if (spec.unit === "currency") {
109
+ unit = (i.unit ?? "").trim().toUpperCase();
110
+ if (!CURRENCY.test(unit))
111
+ throw new MetricsError(`${i.metric} は通貨コード(--unit JPY / USD など 3 文字)が要ります`);
112
+ }
113
+ else {
114
+ unit = spec.unit;
115
+ if (i.unit !== undefined && i.unit.trim() !== unit)
116
+ throw new MetricsError(`${i.metric} の単位は「${unit}」だけです(--unit は省いてください)`);
117
+ }
118
+ const source = i.source?.trim() ?? "";
119
+ if (!source)
120
+ throw new MetricsError("出典(--source 請求書・課金の画面・不具合の管理表など)が要ります");
121
+ if (source.length > SOURCE_MAX)
122
+ throw new MetricsError(`出典は ${SOURCE_MAX} 文字までです`);
123
+ const note = i.note?.trim();
124
+ return { metric: i.metric, scope, from: i.from, to: i.to, value, unit, source, ...(note ? { note } : {}) };
125
+ }
126
+ const sameKey = (a, b) => a.metric === b.metric && a.scope === b.scope && a.from === b.from && a.to === b.to && a.unit === b.unit;
127
+ async function writeManual(dataDir, f) {
128
+ await writeFileAtomic(manualFile(dataDir), `${JSON.stringify(f, null, 2)}\n`);
129
+ }
130
+ async function locked(dataDir, fn) {
131
+ return withFileLock(lockFile(dataDir), async () => {
132
+ const cur = await readManual(dataDir);
133
+ if (cur.problem)
134
+ throw new MetricsError(cur.problem, "metrics_unreadable");
135
+ return fn(cur);
136
+ });
137
+ }
138
+ /**
139
+ * 記録する。同じ識別(指標・範囲・期間・単位)が無ければ足す。あって値・出典・メモが同じなら何もしない(changed: false)。
140
+ * 違えば訂正で、expectedRev がその記録の rev と同じときだけ書く(無い・違う → metrics_conflict)
141
+ */
142
+ export async function recordManual(ctx, input, opts = {}) {
143
+ const v = cleanManual(ctx, input);
144
+ const dataDir = ctx.ws.dataDir;
145
+ return locked(dataDir, async (cur) => {
146
+ const now = new Date().toISOString();
147
+ const hit = cur.records.find((r) => sameKey(r, v));
148
+ if (!hit) {
149
+ if (opts.expectedRev !== undefined && opts.expectedRev !== 0)
150
+ throw new MetricsError(`同じ指標・範囲・期間・単位の記録はありません(--rev ${opts.expectedRev} は使えません)`, "metrics_conflict");
151
+ const record = { id: `M${cur.seq + 1}`, ...v, rev: 1, createdAt: now, ...(opts.actor ? { createdBy: opts.actor } : {}), updatedAt: now, ...(opts.actor ? { updatedBy: opts.actor } : {}) };
152
+ await writeManual(dataDir, { version: 1, seq: cur.seq + 1, records: [...cur.records, record] });
153
+ return { record, changed: true, created: true };
154
+ }
155
+ if (hit.value === v.value && hit.source === v.source && (hit.note ?? "") === (v.note ?? ""))
156
+ return { record: hit, changed: false, created: false };
157
+ if (opts.expectedRev === undefined) {
158
+ throw new MetricsError(`${hit.id} に同じ指標・範囲・期間・単位の記録があります(値 ${hit.value} ${hit.unit}・版 ${hit.rev})。訂正するなら --rev ${hit.rev} を付けてください`, "metrics_conflict");
159
+ }
160
+ if (opts.expectedRev !== hit.rev)
161
+ throw new MetricsError(`${hit.id} は他で変わりました(読んだ版 ${opts.expectedRev}・今の版 ${hit.rev})。p3 metrics で確かめてからやり直してください`, "metrics_conflict");
162
+ const { note: _n, ...rest } = hit;
163
+ const record = { ...rest, value: v.value, source: v.source, ...(v.note ? { note: v.note } : {}), rev: hit.rev + 1, updatedAt: now, ...(opts.actor ? { updatedBy: opts.actor } : {}) };
164
+ await writeManual(dataDir, { version: 1, seq: cur.seq, records: cur.records.map((r) => (r.id === hit.id ? record : r)) });
165
+ return { record, changed: true, created: false };
166
+ });
167
+ }
168
+ /** 記録を消す(ID は使い直さない)。expectedRev を渡せば照らす */
169
+ export async function removeManual(ctx, id, opts = {}) {
170
+ const dataDir = ctx.ws.dataDir;
171
+ return locked(dataDir, async (cur) => {
172
+ const hit = cur.records.find((r) => r.id === id);
173
+ if (!hit)
174
+ throw new MetricsError(`人の記録 ${id} はありません(p3 metrics records で確かめてください)`);
175
+ if (opts.expectedRev !== undefined && opts.expectedRev !== hit.rev)
176
+ throw new MetricsError(`${id} は他で変わりました(読んだ版 ${opts.expectedRev}・今の版 ${hit.rev})`, "metrics_conflict");
177
+ await writeManual(dataDir, { version: 1, seq: cur.seq, records: cur.records.filter((r) => r.id !== id) });
178
+ return hit;
179
+ });
180
+ }
package/lib/core/ops.js CHANGED
@@ -1,7 +1,10 @@
1
+ import { evidenceSummary } from "../shared/acceptance.js";
1
2
  import { normalizeTaskId } from "../shared/refs.js";
2
3
  import { REQUEST_STATUSES, TASK_STATUSES } from "../shared/types.js";
3
4
  import { hierarchyNow } from "./requestStatus.js";
4
- export function listTasks({ ws }, f = {}) {
5
+ import { requestReviewCounts, taskReview } from "./reviewCandidates.js";
6
+ export function listTasks(ctx, f = {}) {
7
+ const { ws } = ctx;
5
8
  let tasks = f.request ? ws.tasksOf(f.request).list() : ws.allTasks();
6
9
  if (f.status?.length)
7
10
  tasks = tasks.filter((t) => f.status.includes(t.status));
@@ -12,6 +15,8 @@ export function listTasks({ ws }, f = {}) {
12
15
  tasks = tasks.filter((t) => (t.repo ?? null) === (f.repo === "none" ? null : f.repo));
13
16
  if (f.blocked)
14
17
  tasks = tasks.filter((t) => !!t.block);
18
+ if (f.review)
19
+ tasks = tasks.filter((t) => taskReview(ctx, t)?.state === "candidate");
15
20
  if (f.q) {
16
21
  const q = f.q.toLowerCase();
17
22
  tasks = tasks.filter((t) => `${t.ref} ${t.title} ${t.body}`.toLowerCase().includes(q));
@@ -110,7 +115,14 @@ export function progress(ctx) {
110
115
  }
111
116
  return {
112
117
  request,
113
- tasks: tasks.map(({ id, ref, title, status, createdAt, startedAt, doneAt, checkedAt, block }) => ({ id, ref, title, status, createdAt, startedAt, doneAt, checkedAt, ...(block ? { block } : {}) })),
118
+ tasks: tasks.map((t) => {
119
+ const { id, ref, title, status, createdAt, startedAt, doneAt, checkedAt, block } = t;
120
+ // 証拠の小さな概要(本文は載せない。規則は shared/acceptance.ts)
121
+ const evidence = evidenceSummary(t);
122
+ // 完了したタスクの見直しの診断の状態(理由は詳細で読む)
123
+ const review = taskReview(ctx, t)?.state;
124
+ return { id, ref, title, status, createdAt, startedAt, doneAt, checkedAt, ...(block ? { block } : {}), ...(evidence ? { evidence } : {}), ...(review ? { review } : {}) };
125
+ }),
114
126
  counts,
115
127
  total: tasks.length,
116
128
  done: done.length,
@@ -119,6 +131,7 @@ export function progress(ctx) {
119
131
  children: h.children(request.id).map((c) => c.id),
120
132
  subtree: sub,
121
133
  hierarchyIssues: h.issuesAround(request.id),
134
+ review: requestReviewCounts(ctx, request, h),
122
135
  };
123
136
  })
124
137
  .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || byId(a.request.id, b.request.id));
@@ -82,7 +82,11 @@ export function renderCarryover(c) {
82
82
  const list = (xs) => (xs.length ? xs.map((x) => `- ${x}`).join("\n") : "(なし)");
83
83
  if (c.requestChange)
84
84
  out.push(requestChangeSection(c.requestChange, p.id));
85
- out.push(`## 前回の評価(${p.id})`, `判定: ${a.verdict} / 妥当性 ${a.validity.score} / 実現可能性 ${a.feasibility.score}`, a.summary, `### 確認事項\n${list(a.questions)}`, `### リスク\n${list(a.risks)}`,
85
+ out.push(`## 前回の評価(${p.id})`, `判定: ${a.verdict} / 妥当性 ${a.validity.score} / 実現可能性 ${a.feasibility.score}`, a.summary, `### 確認事項\n${list(a.questions)}`, ...(a.clarifications?.length
86
+ ? [
87
+ `### 構造化した確認事項(回答は要望の「要求の出典と確認」に元の組のまま載せています)\n${list(a.clarifications.map((q) => `${p.id}/${q.id}: ${q.question}(確認先: ${q.ask} / 対象: ${q.target}${q.needed ? ` / 必要な根拠: ${q.needed}` : ""})`))}`,
88
+ ]
89
+ : []), `### リスク\n${list(a.risks)}`,
86
90
  // 前回の根拠は前回の時点のもの。今回の確かめた根拠としてそのまま写させない
87
91
  `### 前回の根拠(前回の時点のもの。使うなら今回あらためて確かめ、確かめていなければ assumed にする)\n${a.evidence === undefined
88
92
  ? "(記録なし)"
@@ -60,7 +60,8 @@ import { redact } from "../redact.js";
60
60
  import { ensureCodexImage } from "./codexImage.js";
61
61
  import { CONTAINER_LABEL, containerName, DOCKER_LIMITS, DockerAbortError, removeContainer, removeLog, withContainerName } from "./docker.js";
62
62
  import { renderManuscripts } from "./uiRender.js";
63
- import { describeMapping, diagnoseLaunch, mapPath } from "./diagnose.js";
63
+ import { describeMapping, diagnoseLaunch } from "./diagnose.js";
64
+ import { resolveHostPaths, unresolvedMessage } from "./hostPaths.js";
64
65
  import { prepareLaunch } from "./launch.js";
65
66
  import { hideConfigPath } from "../userConfig.js";
66
67
  import { CONTAINER_DATA, containerEnv, developerInstructions, entryMissing, preflightPrompt } from "./instructions.js";
@@ -124,6 +125,27 @@ function localPath(job, p) {
124
125
  }
125
126
  return abs;
126
127
  }
128
+ /**
129
+ * マウントするパスを Docker のホストのパスに決める(hostPaths.ts)。1つでも決まらなければ、コンテナを起こさずに理由と次にすることで投げる。
130
+ * 実際のパスはエラーに書かない(共有の記録に残る)
131
+ */
132
+ async function mountPaths(cfg, targets, what, signal) {
133
+ let r;
134
+ try {
135
+ r = await resolveHostPaths(targets.map((t) => t.local), { pathMap: cfg.pathMap, signal, probe: cfg.hostProbe });
136
+ }
137
+ catch (e) {
138
+ if (e instanceof DockerAbortError)
139
+ throw new Error("中止しました", { cause: e });
140
+ throw e;
141
+ }
142
+ if (!r.ok)
143
+ throw new Error(unresolvedMessage(what, targets.map((t, i) => ({ label: t.label, result: r.paths[i] }))));
144
+ return targets.map((t, i) => {
145
+ const p = r.paths[i];
146
+ return { label: t.label, local: t.local, host: p.host, rule: p.rule, container: t.container, resolved: p };
147
+ });
148
+ }
127
149
  /**
128
150
  * llmcs の codex-workspace(TypeScript 版。npm の @infodb/codex-workspace)で、Docker コンテナ内の
129
151
  * codex app-server に preflight を頼む。
@@ -244,9 +266,6 @@ export class CodexWorkspaceEngine {
244
266
  this.checked = { at: Date.now(), key, status };
245
267
  return status;
246
268
  }
247
- hostPath(local) {
248
- return mapPath(this.cfg.pathMap, local).host;
249
- }
250
269
  async run(job, log, signal) {
251
270
  return this.authorized("Preflight", log, (a) => this.runWith(a.cfg, job, a.auth, a.env, a.log, signal));
252
271
  }
@@ -259,15 +278,12 @@ export class CodexWorkspaceEngine {
259
278
  async ask(input, log, signal) {
260
279
  return this.authorized(input.label, log, async ({ cfg, auth, env, log }) => {
261
280
  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
- }));
281
+ const mappings = readable.length
282
+ ? await mountPaths(cfg, readable.map((r) => ({ label: `参照先 ${r.name}`, local: r.local, container: `${CONTAINER_WORKSPACE}/${r.mount}` })), input.label, signal)
283
+ : [];
268
284
  const repos = readable.map((r, i) => ({ name: r.name, host: mappings[i].host, container: mappings[i].container }));
269
285
  if (mappings.length) {
270
- log({ kind: "info", text: "パスの対応(個人設定の codex.pathMap。読むだけでマウントします):" });
286
+ log({ kind: "info", text: "パスの対応(Docker のホストから見たパス。読むだけでマウントします):" });
271
287
  for (const m of mappings)
272
288
  log({ kind: "info", text: ` ${describeMapping(m, cfg.pathMap.length)}` });
273
289
  }
@@ -392,13 +408,14 @@ export class CodexWorkspaceEngine {
392
408
  }
393
409
  async runWith(cfg, job, auth, env, log, signal) {
394
410
  const readable = job.refs.filter((r) => r.status === "ok" && r.local);
395
- const mappings = [
396
- ...readable.map((r) => ({ label: `参照先 ${r.name}`, local: r.local, ...mapPath(cfg.pathMap, r.local), container: `${CONTAINER_WORKSPACE}/${r.mount}` })),
397
- { label: "データ", local: job.dataDir, ...mapPath(cfg.pathMap, job.dataDir), container: CONTAINER_DATA },
398
- ];
411
+ // 全部の参照先とデータを、Codex のコンテナを起こす前にまとめて決める(1つでも決まらなければ起こさない)
412
+ const mappings = await mountPaths(cfg, [
413
+ ...readable.map((r) => ({ label: `参照先 ${r.name}`, local: r.local, container: `${CONTAINER_WORKSPACE}/${r.mount}` })),
414
+ { label: "データ", local: job.dataDir, container: CONTAINER_DATA },
415
+ ], "Preflight", signal);
399
416
  const repos = readable.map((r, i) => ({ name: r.name, host: mappings[i].host, container: mappings[i].container }));
400
417
  const data = mappings.at(-1).host;
401
- log({ kind: "info", text: "パスの対応(個人設定の codex.pathMap):" });
418
+ log({ kind: "info", text: "パスの対応(Docker のホストから見たパス):" });
402
419
  for (const m of mappings)
403
420
  log({ kind: "info", text: ` ${describeMapping(m, cfg.pathMap.length)}` });
404
421
  for (const r of readable)
@@ -411,7 +428,7 @@ export class CodexWorkspaceEngine {
411
428
  const outcome = await this.launched("preflight", cfg, command, mappings, log, signal, (launch, onError) => this.session(cfg, launch, env, log, onError, (session) => this.turn(session, job, auth, log, signal)));
412
429
  // 画面イメージ: Codex が書いた原稿を、Codex の後に P3 が描画のコンテナで PNG にする(Codex のコンテナに Docker は渡さない)。
413
430
  // 描けなくても評価は残す(取り込みで不足として扱う)
414
- await renderManuscripts(job.runDir, { pathMap: cfg.pathMap, signal, log, render: cfg.render });
431
+ await renderManuscripts(job.runDir, { pathMap: cfg.pathMap, signal, log, render: cfg.render, hostProbe: cfg.hostProbe });
415
432
  return outcome;
416
433
  }
417
434
  /** 起こして、work(スレッドを立てて頼む)を行う。失敗は onError で診断をつけてから投げる */
@@ -1,17 +1,12 @@
1
- /** 前から順に、境界(/)が合う最初の対応を使う */
2
- export function mapPath(pathMap, local) {
3
- for (const rule of pathMap) {
4
- const [from, to] = rule;
5
- if (local === from || local.startsWith(`${from}/`))
6
- return { host: to + local.slice(from.length), rule };
7
- }
8
- return { host: local };
9
- }
1
+ import { originText } from "./hostPaths.js";
2
+ export { mapPath } from "./hostPaths.js";
10
3
  /**
11
4
  * パスの対応の説明。共有の記録(run.json)に残るので、このマシンのパスと Docker のホストのパスは出さず、
12
5
  * 参照先の名前・コンテナの中のパス・codex.pathMap の対応が当たったかだけを書く
13
6
  */
14
7
  export function describeMapping(m, rules) {
8
+ if (m.resolved)
9
+ return `${m.label} → コンテナ ${m.container}(${originText(m.resolved, rules)})`;
15
10
  const how = m.rule
16
11
  ? m.rule[0] === m.rule[1]
17
12
  ? "codex.pathMap の対応あり(パスは変わらない)"
@@ -5,6 +5,10 @@ export const ASSESSMENT_SPEC = `{
5
5
  "feasibility": { "score": 0-100, "reasons": ["実現可能か: 既存コード・技術的制約・規模"] },
6
6
  "risks": ["..."],
7
7
  "questions": ["要望者に確認すべき事項"],
8
+ "clarifications": [
9
+ { "id": "Q1", "target": "確かめたい要望の前提の文、または D1/A2 のような案と基準", "ask": "確認先(役割名。分からなければ「要望者に確認先を特定してもらう」)",
10
+ "question": "質問", "needed": "答えに要る根拠(業務の担当が承認した計算例・規則や契約の該当箇所など)", "impact": "判断への影響(答えでタスク案・基準がどう変わるか)" }
11
+ ],
8
12
  "areas": ["影響するコード領域やコンポーネント(リポジトリ相対パス推奨)"],
9
13
  "split": { "decision": "split" | "keep", "estimatedTasks": 想定するタスクの数(概算), "reasons": ["分割する・しない理由"] },
10
14
  "evidence": [
@@ -14,6 +18,11 @@ export const ASSESSMENT_SPEC = `{
14
18
  ]
15
19
  }
16
20
 
21
+ clarifications は questions のうち、誰かに確かめないと決まらないものを構造化したものです(questions にも同じ趣旨を文で残す)。
22
+ 業務上の正解(計算式・規則・契約など)がコードや履歴から分からず、判定やタスク案に影響するときは verdict を clarify にし、
23
+ 足りない根拠と確認先を clarifications に書いてください。確認先が分からなければ ask は「要望者に確認先を特定してもらう」とし、
24
+ 誰かに確かめたように書かないでください。要望に出典や根拠の記録が無いというだけの理由で clarify にしないでください。
25
+
17
26
  evidence には、判断に使ったファイル・箇所を書いてください。実際に読んで確かめたものは verified(repo・file を必ず書く)、
18
27
  読まずに推測した判断も消さずに assumed として書いてください(推測で書いた部分が分かるように)。`;
19
28
  /** 分割の基準(SPLIT_HINT_TASKS と同じ数を書く) */
@@ -0,0 +1,260 @@
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
+ import { hostname as osHostname } from "node:os";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { DOCKER_LIMITS, DockerAbortError, DockerCommandError, dockerExec } from "./docker.js";
5
+ const read = (p) => {
6
+ try {
7
+ return readFileSync(p, "utf8");
8
+ }
9
+ catch {
10
+ return null;
11
+ }
12
+ };
13
+ /** あるところまで realpath し、無い残りを足す */
14
+ function realpathLoose(p) {
15
+ const rest = [];
16
+ let cur = p;
17
+ for (;;) {
18
+ try {
19
+ return join(realpathSync(cur), ...rest.toReversed());
20
+ }
21
+ catch {
22
+ const up = dirname(cur);
23
+ if (up === cur)
24
+ return p;
25
+ rest.push(basename(cur));
26
+ cur = up;
27
+ }
28
+ }
29
+ }
30
+ /** 手で書いた対応: 前から順に、境界(/)が合う最初の対応を使う(当たらなければ元のパス) */
31
+ export function mapPath(pathMap, local) {
32
+ for (const rule of pathMap) {
33
+ const [from, to] = rule;
34
+ if (local === from || local.startsWith(`${from}/`))
35
+ return { host: to + local.slice(from.length), rule };
36
+ }
37
+ return { host: local };
38
+ }
39
+ /** コンテナの外として振る舞う(P3_HOST_PATHS=direct のとき) */
40
+ export const DIRECT_PROBE = {
41
+ mountinfo: () => null,
42
+ cgroup: () => null,
43
+ dockerenv: () => false,
44
+ hostname: () => "",
45
+ realpath: (p) => p,
46
+ inspect: async () => null,
47
+ };
48
+ /** 実際の OS と docker の CLI(接続先は docker の CLI が環境変数と context から決める) */
49
+ export function systemProbe(docker = "docker", timeoutMs = DOCKER_LIMITS.inspectMs) {
50
+ return {
51
+ mountinfo: () => read("/proc/self/mountinfo"),
52
+ cgroup: () => read("/proc/self/cgroup"),
53
+ dockerenv: () => existsSync("/.dockerenv"),
54
+ hostname: () => osHostname(),
55
+ realpath: realpathLoose,
56
+ inspect: async (id, signal) => {
57
+ try {
58
+ const { stdout } = await dockerExec(docker, ["inspect", "--type", "container", "--format", "{{json .}}", id], {
59
+ stage: "自分のコンテナの確認(docker inspect)",
60
+ timeoutMs,
61
+ signal,
62
+ });
63
+ return JSON.parse(stdout);
64
+ }
65
+ catch (e) {
66
+ if (e instanceof DockerCommandError && /no such (container|object)/i.test(e.stderr))
67
+ return null;
68
+ throw e;
69
+ }
70
+ },
71
+ };
72
+ }
73
+ /** mountinfo の \040 などのエスケープを戻す */
74
+ const unescape = (s) => s.replace(/\\([0-7]{3})/g, (_, o) => String.fromCharCode(Number.parseInt(o, 8)));
75
+ export function parseMountinfo(text) {
76
+ const out = [];
77
+ for (const line of text.split("\n")) {
78
+ const f = line.trim().split(" ");
79
+ const sep = f.indexOf("-");
80
+ if (f.length < 7 || sep < 6)
81
+ continue;
82
+ out.push({ root: unescape(f[3]), mountPoint: unescape(f[4]), fsType: f[sep + 1] ?? "" });
83
+ }
84
+ return out;
85
+ }
86
+ const ID = /(?:^|\/)(?:containers|overlay-containers)\/([0-9a-f]{64})(?:\/|$)/;
87
+ /** Docker(と Podman)がコンテナごとに置くファイル */
88
+ const PER_CONTAINER = new Set(["/etc/hostname", "/etc/hosts", "/etc/resolv.conf"]);
89
+ /** 自分のコンテナの ID の候補(mountinfo の /etc/hostname などの元の場所、cgroup v1 の docker の行) */
90
+ export function containerIdCandidates(mountinfo, cgroup) {
91
+ const ids = new Set();
92
+ for (const m of mountinfo ? parseMountinfo(mountinfo) : []) {
93
+ if (!PER_CONTAINER.has(m.mountPoint))
94
+ continue;
95
+ const id = ID.exec(m.root)?.[1];
96
+ if (id)
97
+ ids.add(id);
98
+ }
99
+ for (const line of cgroup?.split("\n") ?? []) {
100
+ const id = /\/docker[/-]([0-9a-f]{64})(?:\.scope)?$/.exec(line.trim())?.[1];
101
+ if (id)
102
+ ids.add(id);
103
+ }
104
+ return [...ids];
105
+ }
106
+ /** 境界(/)が合うか */
107
+ const under = (p, base) => base === "/" || p === base || p.startsWith(`${base}/`);
108
+ const trimSlash = (p) => (p.length > 1 ? p.replace(/\/+$/, "") : p);
109
+ /** p を含む一番深いマウントの場所(同じ場所に重なっていれば後のもの) */
110
+ export function deepestMount(mounts, p) {
111
+ let best;
112
+ for (const m of mounts)
113
+ if (under(p, m.mountPoint) && (!best || m.mountPoint.length >= best.mountPoint.length))
114
+ best = m;
115
+ return best;
116
+ }
117
+ const MANUAL_HINT = "p3 user-config set codex.pathMap+=<このマシンのパス>=<Docker のホストから見たパス>";
118
+ /** 自分のコンテナを確かめる */
119
+ async function identify(probe, signal) {
120
+ const mountinfo = probe.mountinfo();
121
+ const candidates = containerIdCandidates(mountinfo, probe.cgroup());
122
+ if (!candidates.length) {
123
+ if (probe.dockerenv())
124
+ return { env: { kind: "container-unknown", reason: "self-unknown", detail: "コンテナの中で動いているようですが、自分のコンテナの ID が分かりません" } };
125
+ return { env: { kind: "direct" } };
126
+ }
127
+ const found = [];
128
+ for (const id of candidates) {
129
+ let c;
130
+ try {
131
+ c = await probe.inspect(id, signal);
132
+ }
133
+ catch (e) {
134
+ if (e instanceof DockerAbortError && e.reason === "aborted")
135
+ throw e;
136
+ const why = e.code === "ENOENT" ? "docker コマンドがありません" : e.message.split("\n")[0];
137
+ return { env: { kind: "container-unknown", reason: "inspect-failed", detail: `自分のコンテナを Docker に問い合わせられません(${why})` } };
138
+ }
139
+ if (c && c.Id === id)
140
+ found.push(c);
141
+ }
142
+ if (!found.length)
143
+ return {
144
+ env: {
145
+ kind: "container-unknown",
146
+ reason: "self-not-found",
147
+ detail: "接続先の Docker のデーモンに、p3 が動いているコンテナがありません(リモートの Docker・別のデーモンに繋がっている)",
148
+ },
149
+ };
150
+ if (found.length > 1)
151
+ return { env: { kind: "container-unknown", reason: "self-ambiguous", detail: `自分のコンテナの候補が ${found.length} つあり、1つに決まりません` } };
152
+ const c = found[0];
153
+ const host = c.Config?.Hostname;
154
+ if (host && host !== probe.hostname())
155
+ return {
156
+ env: { kind: "container-unknown", reason: "self-mismatch", detail: "docker inspect で見つけたコンテナのホスト名が、このマシンのホスト名と合いません" },
157
+ };
158
+ return { env: { kind: "container", containerId: c.Id }, container: c };
159
+ }
160
+ /** 自分のコンテナのマウントから1つのパスを求める */
161
+ function fromMounts(local, mounts, c, probe) {
162
+ const real = probe.realpath(local);
163
+ const m = deepestMount(mounts, real);
164
+ if (!m || m.mountPoint === "/")
165
+ return { ok: false, reason: "container-layer", detail: "このフォルダはホストのフォルダ(bind マウント)の下にありません(コンテナの中だけにある)" };
166
+ const mount = (c.Mounts ?? []).find((x) => x.Destination && trimSlash(x.Destination) === m.mountPoint);
167
+ if (!mount)
168
+ return {
169
+ ok: false,
170
+ reason: "not-bind",
171
+ detail: `このフォルダは Docker が付けたマウントではない場所(${m.fsType})の下にあります`,
172
+ };
173
+ if (mount.Type !== "bind")
174
+ return { ok: false, reason: "not-bind", detail: `このフォルダはホストのフォルダではないマウント(${mount.Type ?? "不明"})の下にあります` };
175
+ const src = mount.Source ?? "";
176
+ if (!src.startsWith("/"))
177
+ return { ok: false, reason: "unsupported-source", detail: "このフォルダのマウントの元が、そのまま渡せる形(/ で始まるパス)ではありません" };
178
+ return { ok: true, host: trimSlash(src) + real.slice(m.mountPoint.length), destination: m.mountPoint };
179
+ }
180
+ /** 止める理由ごとの次にすること(1つ) */
181
+ export function nextStep(reason) {
182
+ switch (reason) {
183
+ case "not-bind":
184
+ case "container-layer":
185
+ return "このフォルダを、ホストのフォルダをマウント(bind)した場所の下へ移してください";
186
+ case "conflict":
187
+ return "手で書いた対応を直すか外してください(p3 user-config set codex.pathMap-=<このマシンのパス>。外せば自動で決めます)";
188
+ case "inspect-failed":
189
+ return "docker version で Docker に繋がるか確かめてください";
190
+ default:
191
+ return `ホストから見たパスを手で書いてください: ${MANUAL_HINT}`;
192
+ }
193
+ }
194
+ /**
195
+ * 対象のパスごとに、Docker のデーモンから見たパスを決める。1つでも決まらなければ ok: false(呼ぶ側はコンテナを起こさない)
196
+ */
197
+ export async function resolveHostPaths(locals, opts) {
198
+ // P3_HOST_PATHS=direct: 自動で決めず、コンテナの外と同じに扱う(手で書いた対応だけ。テストと切り分け用)
199
+ const probe = opts.probe ?? (process.env.P3_HOST_PATHS === "direct" ? DIRECT_PROBE : systemProbe(opts.docker, opts.timeoutMs));
200
+ const manual = (local) => {
201
+ const m = mapPath(opts.pathMap, local);
202
+ return m.rule ? m : undefined;
203
+ };
204
+ const self = await identify(probe, opts.signal);
205
+ const mounts = self.container ? parseMountinfo(probe.mountinfo() ?? "") : [];
206
+ const paths = locals.map((local) => {
207
+ const hand = manual(local);
208
+ if (self.env.kind === "direct")
209
+ return hand ? { ok: true, local, host: hand.host, origin: "manual", rule: hand.rule, verified: false } : { ok: true, local, host: local, origin: "direct" };
210
+ if (self.env.kind === "container-unknown") {
211
+ if (hand)
212
+ return { ok: true, local, host: hand.host, origin: "manual", rule: hand.rule, verified: false };
213
+ return { ok: false, local, reason: self.env.reason, detail: self.env.detail, next: nextStep(self.env.reason) };
214
+ }
215
+ const auto = fromMounts(local, mounts, self.container, probe);
216
+ if (hand) {
217
+ if (auto.ok && trimSlash(auto.host) !== trimSlash(hand.host))
218
+ return {
219
+ ok: false,
220
+ local,
221
+ reason: "conflict",
222
+ detail: "手で書いた対応(codex.pathMap)と、p3 が自分のコンテナのマウントから求めたホストのパスが違います",
223
+ next: nextStep("conflict"),
224
+ };
225
+ return { ok: true, local, host: hand.host, origin: "manual", rule: hand.rule, verified: auto.ok };
226
+ }
227
+ if (!auto.ok)
228
+ return { ok: false, local, reason: auto.reason, detail: auto.detail, next: nextStep(auto.reason) };
229
+ return { ok: true, local, host: auto.host, origin: "auto", destination: auto.destination };
230
+ });
231
+ return { ok: paths.every((p) => p.ok), environment: self.env, paths };
232
+ }
233
+ /** ローカルで確かめるコマンド(実際のパスはこの CLI の出力だけに出す) */
234
+ export const PATHS_CHECK = "p3 user-config paths <このマシンのパス>";
235
+ /**
236
+ * 決まらなかったときのエラーの文。共有の記録(run.json・ログ)に残るので、このマシンのパス・ホストのパス・コンテナの ID は書かず、
237
+ * 対象の名前・理由・次にすること・確かめ方だけにする
238
+ */
239
+ export function unresolvedMessage(what, items) {
240
+ const ng = items.filter((i) => !i.result.ok);
241
+ const nexts = [...new Set(ng.map((i) => i.result.next))];
242
+ return [
243
+ `${what}でマウントするフォルダが Docker のホストのどこにあるか決められないので、コンテナを起こしません(どのフォルダもマウントしていません)`,
244
+ ...ng.map((i) => ` ${i.label}: ${i.result.detail}`),
245
+ ...nexts.map((n) => `次にすること: ${n}`),
246
+ `確かめる: このマシンで ${PATHS_CHECK}(実際のパスと決め方が出ます)`,
247
+ ].join("\n");
248
+ }
249
+ /** 決め方の説明(共有の記録に残してよい言葉だけ) */
250
+ export function originText(r, rules) {
251
+ if (r.origin === "auto")
252
+ return "自動(p3 が動いているコンテナのマウントから)";
253
+ if (r.origin === "manual")
254
+ return r.rule && r.rule[0] === r.rule[1]
255
+ ? `codex.pathMap の対応あり(パスは変わらない)${r.verified ? "。コンテナのマウントとも一致" : ""}`
256
+ : `codex.pathMap の対応あり${r.verified ? "。コンテナのマウントとも一致" : ""}`;
257
+ return rules
258
+ ? `codex.pathMap の対応なし(${rules} 件のどれにも当たらない。このマシンのパスのまま渡す)`
259
+ : "codex.pathMap の対応なし(このマシンのパスのまま渡す)";
260
+ }