@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,286 @@
1
+ export const ADOPTION_KIND_LABEL = {
2
+ tasks: "タスク化",
3
+ split: "分割の採用",
4
+ legacy: "タスク化(旧記録)",
5
+ };
6
+ // --- リスクの確認 ---------------------------------------------------------------
7
+ /** 確認の状態。occurred: 起きた / not_occurred: 起きなかった / unchecked: 確かめていない */
8
+ export const RISK_STATES = ["occurred", "not_occurred", "unchecked"];
9
+ export const isRiskState = (v) => typeof v === "string" && RISK_STATES.includes(v);
10
+ export const RISK_STATE_LABEL = { occurred: "起きた", not_occurred: "起きなかった", unchecked: "未確認" };
11
+ /** タスクレビューの所見の場所(結果の項目と位置) */
12
+ export const TASK_REVIEW_SECTIONS = ["overall", "items", "quality", "unplanned", "checks"];
13
+ /** マイルストーンレビューの所見の場所 */
14
+ export const MILESTONE_REVIEW_SECTIONS = ["overall", "units", "quality", "unplanned"];
15
+ export const RETRO_EVIDENCE_LABEL = {
16
+ task_review: "タスクの AI レビュー",
17
+ milestone_review: "マイルストーンレビュー",
18
+ rework: "手戻り",
19
+ manual: "人が書いた参照",
20
+ };
21
+ export const EVIDENCE_CHECK_LABEL = { ok: "照合済み", changed: "記録が差し替わった", missing: "今は見つからない", manual: "人の参照(照合しない)" };
22
+ export const JUDGMENT_LIMITS = { text: 4000, evidence: 30, excerpt: 1000 };
23
+ /** 対象とリスクの今の確認(無ければ undefined = 未確認) */
24
+ export const latestJudgment = (f, target, risk) => [...(f.judgments ?? [])].reverse().find((j) => j.target === target && j.risk === risk);
25
+ /** 今の対象の三状態の件数(確認の無いリスクは未確認) */
26
+ export function riskCounts(f) {
27
+ const counts = { occurred: 0, not_occurred: 0, unchecked: 0 };
28
+ const t = currentTarget(f);
29
+ for (const r of t?.risks ?? [])
30
+ counts[latestJudgment(f, t.id, r.index)?.state ?? "unchecked"]++;
31
+ return counts;
32
+ }
33
+ /**
34
+ * リスクの確認を足す(足した値を返す)。対象は今の確定した対象だけ。起きた → 確認した事実と根拠、起きなかった → 確認した範囲と根拠が要る。
35
+ * 根拠を結び付けるだけなら未確認のまま。決めた確認を変える・未確認に戻すには理由が要る。規則に合わなければ RetrospectiveError(何も当てない)
36
+ */
37
+ export function addJudgment(file, input, ctx) {
38
+ const t = currentTarget(file);
39
+ if (!t)
40
+ throw new RetrospectiveError("retro_invalid", "振り返りの対象が確定していません(先に p3 retro confirm <run>)");
41
+ const risk = t.risks.find((r) => r.index === input.risk);
42
+ if (!risk)
43
+ throw new RetrospectiveError("retro_invalid", `対象 ${t.id}(${t.run})にリスク ${input.risk + 1} はありません(リスクは ${t.risks.length} 件)`);
44
+ if (!isRiskState(input.state))
45
+ throw new RetrospectiveError("retro_invalid", `状態は ${RISK_STATES.join(" / ")} です`);
46
+ const facts = input.facts?.trim() || undefined;
47
+ const scope = input.scope?.trim() || undefined;
48
+ const reason = input.reason?.trim() || undefined;
49
+ for (const [k, v] of [["事実", facts], ["範囲", scope], ["理由", reason]])
50
+ if (v && v.length > JUDGMENT_LIMITS.text)
51
+ throw new RetrospectiveError("retro_invalid", `${k}は ${JUDGMENT_LIMITS.text} 文字までです`);
52
+ if (input.evidence.length > JUDGMENT_LIMITS.evidence)
53
+ throw new RetrospectiveError("retro_invalid", `根拠は ${JUDGMENT_LIMITS.evidence} 件までです`);
54
+ if (input.state === "occurred" && (!facts || !input.evidence.length))
55
+ throw new RetrospectiveError("retro_invalid", "「起きた」には確認した事実(facts)と根拠(evidence)が要ります");
56
+ if (input.state === "not_occurred" && (!scope || !input.evidence.length))
57
+ throw new RetrospectiveError("retro_invalid", "「起きなかった」には確認した範囲(scope)と根拠(evidence)が要ります");
58
+ const prev = latestJudgment(file, t.id, input.risk);
59
+ if (prev && prev.state !== "unchecked" && !reason)
60
+ throw new RetrospectiveError("retro_invalid", `リスク ${input.risk + 1} は「${RISK_STATE_LABEL[prev.state]}」と確認済みです。変える・未確認に戻すには理由(reason)を書いてください`);
61
+ if (input.state === "unchecked" && !input.evidence.length && !prev)
62
+ throw new RetrospectiveError("retro_invalid", "未確認のままにするなら、結び付ける根拠を1つ以上指定してください");
63
+ const n = Math.max(0, ...(file.judgments ?? []).map((j) => Number(j.id.slice(1)))) + 1;
64
+ const j = {
65
+ id: `J${n}`,
66
+ target: t.id,
67
+ risk: input.risk,
68
+ riskText: risk.text,
69
+ state: input.state,
70
+ ...(facts ? { facts } : {}),
71
+ ...(scope ? { scope } : {}),
72
+ evidence: input.evidence,
73
+ ...(reason ? { reason } : {}),
74
+ at: ctx.now,
75
+ ...(ctx.actor ? { by: ctx.actor } : {}),
76
+ };
77
+ return { ...file, version: file.version + 1, judgments: [...(file.judgments ?? []), j] };
78
+ }
79
+ export class RetrospectiveError extends Error {
80
+ code;
81
+ constructor(code, message) {
82
+ super(message);
83
+ this.code = code;
84
+ }
85
+ }
86
+ export const RETRO_LIMITS = { reason: 2000 };
87
+ /** 評価の版(評価の内容の hash。依存を足さない) */
88
+ export function assessmentVersion(assessment) {
89
+ const s = JSON.stringify(assessment ?? null);
90
+ let h1 = 0x811c9dc5;
91
+ let h2 = 0x01000193;
92
+ for (let i = 0; i < s.length; i++) {
93
+ const c = s.charCodeAt(i);
94
+ h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0;
95
+ h2 = Math.imul(h2 ^ c, 0x85ebca6b) >>> 0;
96
+ }
97
+ return `${h1.toString(16).padStart(8, "0")}${h2.toString(16).padStart(8, "0")}`;
98
+ }
99
+ /** 1つの run の採用(候補にならなければ undefined) */
100
+ function adoptionOf(requestId, run, lookup) {
101
+ if (run.status !== "completed" || !run.assessment)
102
+ return undefined;
103
+ const base = { run: run.id, ...(run.finishedAt ? { finishedAt: run.finishedAt } : {}), risks: run.assessment.risks?.length ?? 0, verdict: run.assessment.verdict };
104
+ if (run.materialization) {
105
+ if (!run.materialization.done)
106
+ return undefined;
107
+ const basis = Object.entries(run.materialization.created).map(([key, tid]) => ({ key, target: tid, state: lookup.task(tid) }));
108
+ return basis.length ? { ...base, kind: "tasks", basis } : undefined;
109
+ }
110
+ if (run.adoption) {
111
+ if (!run.adoption.done)
112
+ return undefined;
113
+ const basis = run.adoption.created.map((key) => {
114
+ const id = run.adoption.reserved[key];
115
+ const c = id ? lookup.child(id) : undefined;
116
+ return { key, target: id ?? key, state: !c ? "missing" : c.splitFrom === `${run.id}/${key}` && c.parent === requestId ? "present" : "mismatch" };
117
+ });
118
+ return basis.length ? { ...base, kind: "split", basis } : undefined;
119
+ }
120
+ if (run.materialized?.length)
121
+ return { ...base, kind: "legacy", basis: run.materialized.map((tid) => ({ target: tid, state: lookup.task(tid) })) };
122
+ return undefined;
123
+ }
124
+ /**
125
+ * 要望の候補(新しい順。runs は新しい順で渡す)。見送りの要望は候補なし(none に理由)。
126
+ */
127
+ export function retroCandidates(requestId, status, runs, lookup) {
128
+ if (status === "rejected")
129
+ return { candidates: [], none: "見送りの要望は振り返りの対象にしません" };
130
+ const list = runs.flatMap((r) => {
131
+ const a = adoptionOf(requestId, r, lookup);
132
+ return a ? [a] : [];
133
+ });
134
+ if (!list.length)
135
+ return { candidates: [], none: "採用を終えた Preflight がありません(直接作ったタスクだけ・採用の前・評価の途中など)" };
136
+ return { candidates: list.map((c, i) => ({ ...c, latest: i === 0 })) };
137
+ }
138
+ /** 今の対象(無ければ undefined) */
139
+ export const currentTarget = (f) => f.targets.at(-1);
140
+ /**
141
+ * 対象を確定する(足した値を返す)。run は候補の中の1つで、評価があること。2件目からは訂正の理由が要る。
142
+ * 規則に合わなければ RetrospectiveError(何も当てない)
143
+ */
144
+ export function confirmTarget(file, input, ctx) {
145
+ const cand = ctx.candidates.find((c) => c.run === input.run);
146
+ if (!cand)
147
+ throw new RetrospectiveError("retro_invalid", `${input.run} は振り返りの対象の候補ではありません(${ctx.none ?? `候補: ${ctx.candidates.map((c) => c.run).join(", ")}`})`);
148
+ const risks = ctx.risksOf(input.run);
149
+ const assessment = ctx.assessmentOf(input.run);
150
+ if (!risks || assessment === undefined)
151
+ throw new RetrospectiveError("retro_invalid", `${input.run} の評価が読めないため確定できません`);
152
+ const prev = currentTarget(file);
153
+ const reason = input.reason?.trim();
154
+ if (prev && prev.run === input.run && prev.assessmentVersion === assessmentVersion(assessment))
155
+ throw new RetrospectiveError("retro_invalid", `${input.run} は既に振り返りの対象です`);
156
+ if (prev && !reason)
157
+ throw new RetrospectiveError("retro_invalid", `対象を訂正するには理由(reason)を書いてください(今の対象: ${prev.run})`);
158
+ if (reason && reason.length > RETRO_LIMITS.reason)
159
+ throw new RetrospectiveError("retro_invalid", `理由は ${RETRO_LIMITS.reason} 文字までです`);
160
+ const n = Math.max(0, ...file.targets.map((t) => Number(t.id.slice(1)))) + 1;
161
+ const target = {
162
+ id: `V${n}`,
163
+ run: input.run,
164
+ kind: cand.kind,
165
+ assessmentVersion: assessmentVersion(assessment),
166
+ risks: risks.map((text, index) => ({ index, text })),
167
+ basis: cand.basis,
168
+ at: ctx.now,
169
+ ...(ctx.actor ? { by: ctx.actor } : {}),
170
+ ...(reason ? { reason } : {}),
171
+ ...(prev ? { replaces: prev.id } : {}),
172
+ };
173
+ return { ...file, version: file.version + 1, targets: [...file.targets, target] };
174
+ }
175
+ // --- 読む ---------------------------------------------------------------------
176
+ const str = (v) => (typeof v === "string" && v ? v : undefined);
177
+ function readBasis(v) {
178
+ if (!Array.isArray(v))
179
+ return undefined;
180
+ const out = [];
181
+ for (const x of v) {
182
+ const o = x && typeof x === "object" ? x : {};
183
+ if (!str(o.target) || !["present", "archived", "missing", "mismatch"].includes(String(o.state)))
184
+ return undefined;
185
+ out.push({ ...(str(o.key) ? { key: str(o.key) } : {}), target: str(o.target), state: o.state });
186
+ }
187
+ return out;
188
+ }
189
+ function readTarget(v, at) {
190
+ const o = v && typeof v === "object" ? v : {};
191
+ const id = str(o.id) ?? "";
192
+ if (!/^V\d+$/.test(id))
193
+ return `${at} の id が読めません(V1, V2, ...)`;
194
+ const kind = o.kind;
195
+ if (kind !== "tasks" && kind !== "split" && kind !== "legacy")
196
+ return `${at}(${id})の kind が読めません`;
197
+ const risks = Array.isArray(o.risks) ? o.risks : undefined;
198
+ if (!risks || risks.some((r) => !r || typeof r !== "object" || !Number.isInteger(r.index) || typeof r.text !== "string"))
199
+ return `${at}(${id})の risks が読めません`;
200
+ const basis = readBasis(o.basis);
201
+ if (!str(o.run) || !str(o.assessmentVersion) || !str(o.at) || !basis)
202
+ return `${at}(${id})には run・assessmentVersion・basis・at が要ります`;
203
+ return {
204
+ id,
205
+ run: str(o.run),
206
+ kind,
207
+ assessmentVersion: str(o.assessmentVersion),
208
+ risks: risks.map((r) => ({ index: r.index, text: r.text })),
209
+ basis,
210
+ at: str(o.at),
211
+ ...(str(o.by) ? { by: str(o.by) } : {}),
212
+ ...(str(o.reason) ? { reason: str(o.reason) } : {}),
213
+ ...(str(o.replaces) ? { replaces: str(o.replaces) } : {}),
214
+ };
215
+ }
216
+ /** retrospective.json を読む(壊れていれば RetrospectiveError retro_unreadable。黙って空にしない) */
217
+ export function readRetrospective(raw) {
218
+ const o = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : undefined;
219
+ if (!o)
220
+ throw new RetrospectiveError("retro_unreadable", "retrospective.json が読めません(オブジェクトではありません)");
221
+ const version = Number.isInteger(o.version) && o.version >= 0 ? o.version : undefined;
222
+ if (version === undefined)
223
+ throw new RetrospectiveError("retro_unreadable", "retrospective.json の version が読めません");
224
+ const targets = [];
225
+ for (const [i, t] of (Array.isArray(o.targets) ? o.targets : []).entries()) {
226
+ const r = readTarget(t, `振り返りの対象 ${i + 1} 件目`);
227
+ if (typeof r === "string")
228
+ throw new RetrospectiveError("retro_unreadable", `retrospective.json: ${r}`);
229
+ targets.push(r);
230
+ }
231
+ const judgments = [];
232
+ for (const [i, j] of (Array.isArray(o.judgments) ? o.judgments : []).entries()) {
233
+ const r = readJudgment(j, `リスクの確認 ${i + 1} 件目`);
234
+ if (typeof r === "string")
235
+ throw new RetrospectiveError("retro_unreadable", `retrospective.json: ${r}`);
236
+ judgments.push(r);
237
+ }
238
+ return { ...o, version, targets, ...(judgments.length ? { judgments } : {}) };
239
+ }
240
+ function readEvidence(v) {
241
+ const o = v && typeof v === "object" ? v : {};
242
+ const idx = Number.isInteger(o.index) ? o.index : undefined;
243
+ if (o.kind === "task_review" && str(o.request) && str(o.task) && str(o.run) && TASK_REVIEW_SECTIONS.includes(o.section) && idx !== undefined && str(o.resultVersion) && typeof o.excerpt === "string")
244
+ return { kind: "task_review", request: str(o.request), task: str(o.task), run: str(o.run), section: o.section, index: idx, resultVersion: str(o.resultVersion), excerpt: o.excerpt };
245
+ if (o.kind === "milestone_review" && str(o.milestone) && str(o.run) && MILESTONE_REVIEW_SECTIONS.includes(o.section) && idx !== undefined && str(o.resultVersion) && typeof o.excerpt === "string")
246
+ return {
247
+ kind: "milestone_review",
248
+ milestone: str(o.milestone),
249
+ run: str(o.run),
250
+ section: o.section,
251
+ index: idx,
252
+ resultVersion: str(o.resultVersion),
253
+ excerpt: o.excerpt,
254
+ ...(o.inputChanged === true ? { inputChanged: true } : {}),
255
+ ...(str(o.reason) ? { reason: str(o.reason) } : {}),
256
+ };
257
+ if (o.kind === "rework" && str(o.request) && str(o.task) && str(o.history) && typeof o.excerpt === "string")
258
+ return { kind: "rework", request: str(o.request), task: str(o.task), history: str(o.history), excerpt: o.excerpt };
259
+ if (o.kind === "manual" && str(o.reference))
260
+ return { kind: "manual", reference: str(o.reference), ...(str(o.note) ? { note: str(o.note) } : {}) };
261
+ return undefined;
262
+ }
263
+ function readJudgment(v, at) {
264
+ const o = v && typeof v === "object" ? v : {};
265
+ const id = str(o.id) ?? "";
266
+ if (!/^J\d+$/.test(id))
267
+ return `${at} の id が読めません(J1, J2, ...)`;
268
+ const evidence = Array.isArray(o.evidence) ? o.evidence.map(readEvidence) : undefined;
269
+ if (!evidence || evidence.some((e) => !e))
270
+ return `${at}(${id})の evidence が読めません`;
271
+ if (!str(o.target) || !Number.isInteger(o.risk) || typeof o.riskText !== "string" || !isRiskState(o.state) || !str(o.at))
272
+ return `${at}(${id})には target・risk・riskText・state・at が要ります`;
273
+ return {
274
+ id,
275
+ target: str(o.target),
276
+ risk: o.risk,
277
+ riskText: o.riskText,
278
+ state: o.state,
279
+ ...(str(o.facts) ? { facts: str(o.facts) } : {}),
280
+ ...(str(o.scope) ? { scope: str(o.scope) } : {}),
281
+ evidence: evidence,
282
+ ...(str(o.reason) ? { reason: str(o.reason) } : {}),
283
+ at: str(o.at),
284
+ ...(str(o.by) ? { by: str(o.by) } : {}),
285
+ };
286
+ }
@@ -0,0 +1,308 @@
1
+ import { latestCompletion } from "./completionRecord.js";
2
+ import { checkLine, standardHash, standardsFor } from "./quality.js";
3
+ import { criterionSubject, requestSubject, sourceState } from "./requirementSource.js";
4
+ export const REVIEW_STATE_LABEL = {
5
+ no_record: "記録なし",
6
+ unreadable: "比較不能",
7
+ none: "差分なし",
8
+ candidate: "見直しが必要(候補)",
9
+ };
10
+ export const REVIEW_STATE_HINT = {
11
+ no_record: "完了したときの条件の記録がありません(この機能より前・直接編集で完了したもの)。比べる基点がないので、必要なら人がもう一度確かめて済みにしてください",
12
+ unreadable: "完了の記録が読めないため比べられません。ファイルの completionRecords を直してください",
13
+ none: "完了したときの条件と今の条件に、見直しにつながる差はありません",
14
+ candidate: "完了したときの条件から変わったものがあります。過去の判断が誤りという意味ではありません。確かめて、必要ならもう一度済みにしてください",
15
+ };
16
+ export const REVIEW_CODES = [
17
+ "quality_added",
18
+ "quality_changed",
19
+ "quality_removed",
20
+ "quality_exempted",
21
+ "quality_state",
22
+ "criterion_added",
23
+ "criterion_changed",
24
+ "criterion_removed",
25
+ "source_changed",
26
+ "source_removed",
27
+ "source_unconfirmed",
28
+ "premise_changed",
29
+ ];
30
+ export const REVIEW_CODE_LABEL = {
31
+ quality_added: "品質基準が新たに当てはまる",
32
+ quality_changed: "品質基準が変わった",
33
+ quality_removed: "品質基準が消えた・当てはまらなくなった",
34
+ quality_exempted: "品質基準が除外になった",
35
+ quality_state: "品質基準の設定の状態が変わった",
36
+ criterion_added: "受け入れ基準が増えた",
37
+ criterion_changed: "受け入れ基準の文が変わった",
38
+ criterion_removed: "受け入れ基準が消えた",
39
+ source_changed: "要求の根拠の内容が変わった",
40
+ source_removed: "要求の根拠が消えた",
41
+ source_unconfirmed: "要求の根拠の確認が効かなくなった",
42
+ premise_changed: "前提の変更が記録された",
43
+ };
44
+ export const PREMISE_LIMITS = { changes: 200, targets: 50, reason: 2000, condition: 1000, acks: 200 };
45
+ export const PREMISE_KEYS = ["premiseChanges"];
46
+ export const PREMISE_ID_RE = /^P\d+$/;
47
+ /** 入力が規則に合わない(何も書いていない)。CLI は使い方の誤り、API は 400 */
48
+ export class PremiseInputError extends Error {
49
+ code = "premise_invalid";
50
+ }
51
+ const str = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
52
+ const iso = (v) => (v instanceof Date ? v.toISOString() : str(v));
53
+ function readAck(v) {
54
+ const o = v && typeof v === "object" ? v : undefined;
55
+ const target = str(o?.target);
56
+ const condition = str(o?.condition);
57
+ const at = iso(o?.at);
58
+ if (!target || !condition || !at)
59
+ return undefined;
60
+ return { target, condition, at, ...(str(o?.by) ? { by: str(o?.by) } : {}) };
61
+ }
62
+ /** 要望の premiseChanges を読む(無ければ何も足さない) */
63
+ export function readPremises(d) {
64
+ if (d.premiseChanges === undefined || d.premiseChanges === null)
65
+ return {};
66
+ if (!Array.isArray(d.premiseChanges))
67
+ return { premiseProblems: ["premiseChanges が並びになっていません"] };
68
+ const list = [];
69
+ const problems = [];
70
+ for (const [i, raw] of d.premiseChanges.entries()) {
71
+ const o = raw && typeof raw === "object" ? raw : {};
72
+ const id = str(o.id) ?? "";
73
+ const at = `前提の変更 ${i + 1} 件目${id ? `(${id})` : ""}`;
74
+ const targets = Array.isArray(o.targets) ? o.targets.map(str).filter((x) => !!x) : [];
75
+ const acks = Array.isArray(o.acks) ? o.acks.map(readAck) : [];
76
+ if (!PREMISE_ID_RE.test(id))
77
+ problems.push(`${at} の id が読めません(P1, P2, ...)`);
78
+ else if (list.some((x) => x.id === id))
79
+ problems.push(`前提の変更の id が重複しています: ${id}`);
80
+ else if (!targets.length)
81
+ problems.push(`${at} の targets がありません`);
82
+ else if (!str(o.reason) || !str(o.condition) || !iso(o.at))
83
+ problems.push(`${at} には reason・condition・at が要ります`);
84
+ else if (acks.some((a) => !a))
85
+ problems.push(`${at} の acks の項目が読めません(target・condition・at が要ります)`);
86
+ else
87
+ list.push({
88
+ id,
89
+ targets,
90
+ reason: str(o.reason),
91
+ condition: str(o.condition),
92
+ at: iso(o.at),
93
+ ...(str(o.by) ? { by: str(o.by) } : {}),
94
+ ...(acks.length ? { acks: acks } : {}),
95
+ });
96
+ }
97
+ return { ...(list.length ? { premiseChanges: list } : {}), ...(problems.length ? { premiseProblems: problems } : {}) };
98
+ }
99
+ /**
100
+ * 前提の変更への操作を当てる(足す・確認を記録する)。exists: 対象が今あるか(要望 ID・タスク ID・要望の根拠の ID)。
101
+ * 規則に合わなければ PremiseInputError(何も当てない)
102
+ */
103
+ export function applyPremiseOp(list, op, ctx) {
104
+ const condition = str(op.condition);
105
+ if (!condition)
106
+ throw new PremiseInputError("新しい条件・版(condition)を書いてください");
107
+ if (condition.length > PREMISE_LIMITS.condition)
108
+ throw new PremiseInputError(`条件は ${PREMISE_LIMITS.condition} 文字までです`);
109
+ if (op.op === "add") {
110
+ const reason = str(op.reason);
111
+ if (!reason)
112
+ throw new PremiseInputError("変更の理由(reason)を書いてください");
113
+ if (reason.length > PREMISE_LIMITS.reason)
114
+ throw new PremiseInputError(`理由は ${PREMISE_LIMITS.reason} 文字までです`);
115
+ const targets = [...new Set((op.targets ?? []).map((t) => t.trim()).filter(Boolean))];
116
+ if (!targets.length)
117
+ throw new PremiseInputError("対象(要望 ID・タスク ID・要望の根拠の ID)を1つ以上指定してください");
118
+ if (targets.length > PREMISE_LIMITS.targets)
119
+ throw new PremiseInputError(`対象は ${PREMISE_LIMITS.targets} 件までです`);
120
+ const missing = targets.filter((t) => !ctx.exists(t));
121
+ if (missing.length)
122
+ throw new PremiseInputError(`対象がありません: ${missing.join(", ")}(要望 ID・この要望のタスク ID・要望の根拠の ID)`);
123
+ if (list.length >= PREMISE_LIMITS.changes)
124
+ throw new PremiseInputError(`前提の変更は ${PREMISE_LIMITS.changes} 件までです`);
125
+ const n = Math.max(0, ...list.map((c) => Number(c.id.slice(1)))) + 1;
126
+ return [...list, { id: `P${n}`, targets, reason, condition, at: ctx.now, ...(ctx.actor ? { by: ctx.actor } : {}) }];
127
+ }
128
+ const cur = list.find((c) => c.id === op.id);
129
+ if (!cur)
130
+ throw new PremiseInputError(`前提の変更 ${op.id} はありません`);
131
+ const target = str(op.target);
132
+ if (!target || !cur.targets.includes(target))
133
+ throw new PremiseInputError(`${op.id} の対象ではありません: ${op.target}(対象: ${cur.targets.join(", ")})`);
134
+ if ((cur.acks?.length ?? 0) >= PREMISE_LIMITS.acks)
135
+ throw new PremiseInputError(`確認の記録は ${PREMISE_LIMITS.acks} 件までです`);
136
+ const ack = { target, condition, at: ctx.now, ...(ctx.actor ? { by: ctx.actor } : {}) };
137
+ return list.map((c) => (c === cur ? { ...c, acks: [...(c.acks ?? []), ack] } : c));
138
+ }
139
+ // --- 診断 ---------------------------------------------------------------------
140
+ const short = (s, n = 200) => (s === undefined ? undefined : s.length > n ? `${s.slice(0, n)}…` : s);
141
+ const stdLine = (s) => `${s.text}(${checkLine(s.check)})${s.repos?.length ? `(対象: ${s.repos.join(", ")})` : ""}${s.exempt ? `(除外: ${s.exempt.reason})` : ""}`;
142
+ const sourceLine = (s) => [s.target, s.source, s.basis].filter(Boolean).join(" / ");
143
+ const sourceKey = (s) => JSON.stringify([s.target ?? "", s.source ?? "", s.basis ?? ""]);
144
+ function qualityReasons(rec, now, repo, out, unreadable) {
145
+ const q = rec.quality;
146
+ const st = now ?? { state: "unset" };
147
+ if (q.state === "invalid") {
148
+ unreadable.push("完了したときの品質基準が読めなかったため、品質は比べられません");
149
+ return;
150
+ }
151
+ if (st.state === "invalid") {
152
+ out.push({ code: "quality_state", target: "quality", was: q.state === "set" ? "設定済" : "未設定", now: "読めない" });
153
+ unreadable.push("今の品質基準が読めないため、項目は比べられません");
154
+ return;
155
+ }
156
+ if (q.state === "set" && st.state === "unset") {
157
+ out.push({ code: "quality_state", target: "quality", was: "設定済", now: "未設定" });
158
+ return;
159
+ }
160
+ // 要望の記録は項目を写さない(状態だけ比べる)
161
+ if (q.standards === undefined && q.state === "set")
162
+ return;
163
+ if (st.state !== "set")
164
+ return;
165
+ const then = q.standards ?? [];
166
+ const { applies, exempt } = standardsFor(st.config, repo);
167
+ for (const s of applies) {
168
+ const was = then.find((x) => x.id === s.id);
169
+ if (!was || was.exempt)
170
+ out.push({ code: "quality_added", target: s.id, ...(was ? { was: stdLine(was) } : {}), now: stdLine(s) });
171
+ else if (standardHash(was) !== standardHash(s))
172
+ out.push({ code: "quality_changed", target: s.id, was: stdLine(was), now: stdLine(s) });
173
+ }
174
+ for (const was of then.filter((x) => !x.exempt)) {
175
+ if (applies.some((s) => s.id === was.id))
176
+ continue;
177
+ const ex = exempt.find((s) => s.id === was.id);
178
+ if (ex)
179
+ out.push({ code: "quality_exempted", target: was.id, was: stdLine(was), now: stdLine(ex) });
180
+ else
181
+ out.push({ code: "quality_removed", target: was.id, was: stdLine(was), now: st.config.standards.some((s) => s.id === was.id) ? "作業先に当てはまらない" : undefined });
182
+ }
183
+ }
184
+ function sourceReasons(then, now, nowState, label, out, related) {
185
+ for (const was of then) {
186
+ const cur = now.find((s) => label(s) === label(was));
187
+ const rel = related?.(was);
188
+ const extra = rel?.length ? { related: rel } : {};
189
+ if (!cur)
190
+ out.push({ code: "source_removed", target: label(was), was: short(sourceLine(was)), ...extra });
191
+ else if (sourceKey(cur) !== sourceKey(was))
192
+ out.push({ code: "source_changed", target: label(was), was: short(sourceLine(was)), now: short(sourceLine(cur)), ...extra });
193
+ else if (was.confirmed && nowState(cur) !== "confirmed")
194
+ out.push({ code: "source_unconfirmed", target: label(was), was: `確認記録あり(${was.confirmed.by}・${was.confirmed.on})`, now: nowState(cur) === "reconfirm" ? "再確認が必要" : "未確認", ...extra });
195
+ }
196
+ }
197
+ function premiseReasons(changes, since, keys, out) {
198
+ for (const c of changes ?? []) {
199
+ if (c.at <= since)
200
+ continue;
201
+ const hit = c.targets.filter((t) => keys.includes(t) && !c.acks?.some((a) => a.target === t && a.at >= c.at));
202
+ if (hit.length)
203
+ out.push({ code: "premise_changed", target: c.id, now: short(`${c.reason}(新しい条件: ${c.condition})`), related: hit });
204
+ }
205
+ }
206
+ /** 同じ理由(理由と対象)を1件にする */
207
+ const dedupe = (list) => list.filter((r, i) => list.findIndex((x) => x.code === r.code && x.target === r.target) === i);
208
+ function finish(target, rec, reasons, unreadable, qualityVersion) {
209
+ const rs = dedupe(reasons);
210
+ return {
211
+ target,
212
+ state: rs.length ? "candidate" : "none",
213
+ record: rec.id,
214
+ ...(qualityVersion !== undefined ? { qualityVersion } : {}),
215
+ reasons: rs,
216
+ ...(unreadable.length ? { unreadable } : {}),
217
+ };
218
+ }
219
+ /** 完了したタスクか(診断の対象) */
220
+ export const isReviewTarget = (t) => t.status === "done";
221
+ /** 対応済・完了済の要望か(自身の条件の差を診断する対象) */
222
+ export const isReviewRequest = (r) => r.status === "resolved" || r.status === "done";
223
+ /** タスクの診断(完了していないタスクは undefined) */
224
+ export function diagnoseTask(task, request, now) {
225
+ if (!isReviewTarget(task))
226
+ return undefined;
227
+ if (task.completionProblems?.length)
228
+ return { target: task.ref, state: "unreadable", reasons: [], unreadable: [...task.completionProblems] };
229
+ const rec = latestCompletion(task.completionRecords);
230
+ if (!rec)
231
+ return { target: task.ref, state: "no_record", reasons: [] };
232
+ const reasons = [];
233
+ const unreadable = [];
234
+ qualityReasons(rec, now.quality, task.repo, reasons, unreadable);
235
+ // 基準
236
+ if (rec.acceptance?.problems)
237
+ unreadable.push("完了したときの受け入れ基準が読めなかったため、基準は比べられません");
238
+ else if (task.acceptanceProblems?.length)
239
+ unreadable.push("今の受け入れ基準が読めないため、基準は比べられません");
240
+ else {
241
+ const then = rec.acceptance?.criteria ?? [];
242
+ const cur = task.acceptanceCriteria ?? [];
243
+ for (const c of cur) {
244
+ const was = then.find((x) => x.id === c.id);
245
+ if (!was)
246
+ reasons.push({ code: "criterion_added", target: c.id, now: short(c.text) });
247
+ else if (was.text !== c.text)
248
+ reasons.push({ code: "criterion_changed", target: c.id, was: short(was.text), now: short(c.text) });
249
+ }
250
+ for (const was of then)
251
+ if (!cur.some((c) => c.id === was.id))
252
+ reasons.push({ code: "criterion_removed", target: was.id, was: short(was.text) });
253
+ // 基準ごとの根拠(基準 ID / 記録 ID)
254
+ const textOf = (id) => cur.find((c) => c.id === id)?.text;
255
+ const label = (s) => `${s.criterionId}/${s.id}`;
256
+ sourceReasons(rec.acceptance?.sources ?? [], task.acceptanceSources ?? [], (s) => {
257
+ const t = textOf(s.criterionId);
258
+ return t === undefined ? "unlinked" : sourceState(s, criterionSubject(t));
259
+ }, label, reasons);
260
+ // 写した元の要望の根拠(当時の元と今の元)
261
+ const fromIds = [...new Set((rec.acceptance?.sources ?? []).flatMap((s) => (s.from ? [s.from] : [])))];
262
+ if (fromIds.length) {
263
+ if (rec.requirement?.problems)
264
+ unreadable.push("完了したときの要望の根拠が読めなかったため、写した元は比べられません");
265
+ else if (request?.requirementProblems?.length)
266
+ unreadable.push("今の要望の根拠が読めないため、写した元は比べられません");
267
+ else if (request) {
268
+ const thenReq = (rec.requirement?.sources ?? []).filter((s) => fromIds.includes(s.id));
269
+ const subject = requestSubject(request);
270
+ const users = (id) => (rec.acceptance?.sources ?? []).filter((s) => s.from === id).map(label);
271
+ sourceReasons(thenReq, request.requirementSources ?? [], (s) => sourceState(s, subject), (s) => s.id, reasons, (s) => users(s.id));
272
+ }
273
+ }
274
+ }
275
+ // 前提の変更(タスク ID か、基準の根拠が写した要望の根拠の ID を対象にしたもの)
276
+ if (request?.premiseProblems?.length)
277
+ unreadable.push("前提の変更の記録が読めないため、前提の変更は比べられません");
278
+ const keys = [task.id, ...new Set((task.acceptanceSources ?? []).flatMap((s) => (s.from ? [s.from] : [])))];
279
+ premiseReasons(request?.premiseChanges, rec.at, keys, reasons);
280
+ return finish(task.ref, rec, reasons, unreadable, now.qualityVersion);
281
+ }
282
+ /** 要望自身の診断(対応済・完了済でなければ undefined)。配下の件数は含めない */
283
+ export function diagnoseRequest(request, now) {
284
+ if (!isReviewRequest(request))
285
+ return undefined;
286
+ if (request.completionProblems?.length)
287
+ return { target: request.id, state: "unreadable", reasons: [], unreadable: [...request.completionProblems] };
288
+ const rec = latestCompletion(request.completionRecords);
289
+ if (!rec)
290
+ return { target: request.id, state: "no_record", reasons: [] };
291
+ const reasons = [];
292
+ const unreadable = [];
293
+ qualityReasons(rec, now.quality, null, reasons, unreadable);
294
+ if (rec.requirement?.problems)
295
+ unreadable.push("完了したときの要望の根拠が読めなかったため、根拠は比べられません");
296
+ else if (request.requirementProblems?.length)
297
+ unreadable.push("今の要望の根拠が読めないため、根拠は比べられません");
298
+ else {
299
+ const subject = requestSubject(request);
300
+ sourceReasons(rec.requirement?.sources ?? [], request.requirementSources ?? [], (s) => sourceState(s, subject), (s) => s.id, reasons);
301
+ }
302
+ if (request.premiseProblems?.length)
303
+ unreadable.push("前提の変更の記録が読めないため、前提の変更は比べられません");
304
+ // 前提の変更(要望 ID か、要望の根拠の ID を対象にしたもの)
305
+ premiseReasons(request.premiseChanges, rec.at, [request.id, ...(request.requirementSources ?? []).map((s) => s.id), ...(rec.requirement?.sources ?? []).map((s) => s.id)], reasons);
306
+ return finish(request.id, rec, reasons, unreadable, now.qualityVersion);
307
+ }
308
+ export const reviewSummary = (d) => ({ state: d.state, ...(d.record ? { record: d.record } : {}), reasons: d.reasons.length, codes: [...new Set(d.reasons.map((r) => r.code))] });