@infodb/p3 0.11.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 (138) hide show
  1. package/README.md +33 -33
  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-RFd-7k3r.js +1 -0
  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/taskReview-_WCgnQit.js +1 -0
  28. package/dist/web/assets/ui-BGK72r3u.js +1 -0
  29. package/dist/web/assets/workTarget-CySfKyfB.js +30 -0
  30. package/dist/web/index.html +4 -4
  31. package/docs/architecture.md +610 -33
  32. package/docs/development.md +61 -17
  33. package/docs/how-to-use.md +554 -17
  34. package/docs/installation.md +235 -144
  35. package/docs/publishing.md +1 -1
  36. package/lib/cli/agentsStatus.js +197 -0
  37. package/lib/cli/args.js +111 -2
  38. package/lib/cli/guide.js +27 -0
  39. package/lib/cli/guide.md +214 -0
  40. package/lib/cli/help.js +74 -1
  41. package/lib/cli/main.js +97 -17
  42. package/lib/cli/metricsCommands.js +77 -0
  43. package/lib/cli/output.js +19 -1
  44. package/lib/cli/preflightCommands.js +7 -1
  45. package/lib/cli/project.js +13 -24
  46. package/lib/cli/qualityCommands.js +188 -0
  47. package/lib/cli/readOnly.js +17 -0
  48. package/lib/cli/requestCommands.js +33 -4
  49. package/lib/cli/requirementCommands.js +288 -0
  50. package/lib/cli/retroCommands.js +106 -0
  51. package/lib/cli/revisitCommands.js +73 -0
  52. package/lib/cli/showView.js +183 -4
  53. package/lib/cli/taskCommands.js +341 -20
  54. package/lib/cli/taskReviewCommands.js +178 -0
  55. package/lib/cli/userConfig.js +47 -0
  56. package/lib/core/completionRefs.js +46 -0
  57. package/lib/core/context.js +4 -1
  58. package/lib/core/metrics/definitions.js +434 -0
  59. package/lib/core/metrics/index.js +88 -0
  60. package/lib/core/metrics/manual.js +180 -0
  61. package/lib/core/milestoneReview/material.js +11 -1
  62. package/lib/core/milestoneReview/mockReviewer.js +1 -0
  63. package/lib/core/milestoneReview/review.js +70 -6
  64. package/lib/core/milestoneReview/service.js +29 -93
  65. package/lib/core/milestoneReview/store.js +12 -62
  66. package/lib/core/ops.js +23 -3
  67. package/lib/core/preflight/carryover.js +6 -2
  68. package/lib/core/preflight/codexEngine.js +34 -17
  69. package/lib/core/preflight/diagnose.js +4 -9
  70. package/lib/core/preflight/engine.js +15 -0
  71. package/lib/core/preflight/hostPaths.js +260 -0
  72. package/lib/core/preflight/input.js +33 -5
  73. package/lib/core/preflight/instructions.js +36 -2
  74. package/lib/core/preflight/mockEngine.js +24 -2
  75. package/lib/core/preflight/render.js +22 -3
  76. package/lib/core/preflight/service.js +99 -8
  77. package/lib/core/preflight/uiRender.js +3 -0
  78. package/lib/core/projectRegistry.js +3 -3
  79. package/lib/core/quality.js +21 -0
  80. package/lib/core/qualityImprovement.js +221 -0
  81. package/lib/core/requestOps.js +294 -11
  82. package/lib/core/retrospective.js +208 -0
  83. package/lib/core/reviewCandidates.js +56 -0
  84. package/lib/core/reviewRuns.js +205 -0
  85. package/lib/core/store/archivedTasks.js +74 -0
  86. package/lib/core/store/collection.js +32 -3
  87. package/lib/core/store/normalize.js +35 -2
  88. package/lib/core/store/preflightStore.js +23 -1
  89. package/lib/core/store/projectFile.js +10 -0
  90. package/lib/core/store/workspace.js +49 -3
  91. package/lib/core/taskReview/material.js +459 -0
  92. package/lib/core/taskReview/mockReviewer.js +30 -0
  93. package/lib/core/taskReview/paths.js +15 -0
  94. package/lib/core/taskReview/review.js +312 -0
  95. package/lib/core/taskReview/service.js +187 -0
  96. package/lib/core/taskReview/store.js +214 -0
  97. package/lib/server/api/manifest.js +104 -5
  98. package/lib/server/api/milestoneReviewRoutes.js +4 -3
  99. package/lib/server/api/routes.js +265 -17
  100. package/lib/server/api/taskReviewRoutes.js +66 -0
  101. package/lib/server/server.js +2 -2
  102. package/lib/shared/acceptance.js +618 -0
  103. package/lib/shared/completionRecord.js +327 -0
  104. package/lib/shared/metrics.js +42 -0
  105. package/lib/shared/milestoneReview.js +2 -1
  106. package/lib/shared/preflightInput.js +1 -1
  107. package/lib/shared/quality.js +391 -0
  108. package/lib/shared/qualityImprovement.js +1 -0
  109. package/lib/shared/qualityTemplates.js +31 -0
  110. package/lib/shared/requirementSource.js +635 -0
  111. package/lib/shared/retrospective.js +286 -0
  112. package/lib/shared/reviewCandidate.js +308 -0
  113. package/lib/shared/reworkHistory.js +81 -0
  114. package/lib/shared/taskBlock.js +142 -0
  115. package/lib/shared/taskReview.js +56 -0
  116. package/package.json +3 -2
  117. package/skills/p3/SKILL.md +9 -152
  118. package/dist/web/assets/Outputs-ddwte0jj.js +0 -1
  119. package/dist/web/assets/RequestStatus-Bg1OLbRc.js +0 -1
  120. package/dist/web/assets/Tabs-DTmggzgg.js +0 -1
  121. package/dist/web/assets/TagInput-BHAgjLP7.js +0 -1
  122. package/dist/web/assets/TaskDrawer-Dz_5c2NH.js +0 -3
  123. package/dist/web/assets/_requestId-D9-gtIcG.js +0 -1
  124. package/dist/web/assets/_requestId-DzCNYvqf.js +0 -30
  125. package/dist/web/assets/appCtx-Cm24VpAf.js +0 -1
  126. package/dist/web/assets/board-MCHcZ-PU.js +0 -1
  127. package/dist/web/assets/done-zq10Bt08.js +0 -1
  128. package/dist/web/assets/draft-CfJeyLOl.js +0 -1
  129. package/dist/web/assets/index-Ce0ndpne.js +0 -12
  130. package/dist/web/assets/index-D68mkSnw.css +0 -2
  131. package/dist/web/assets/new-9TKiNT4O.js +0 -1
  132. package/dist/web/assets/preflightInput-BAeEJYUK.js +0 -2
  133. package/dist/web/assets/preload-helper-FBLw7u7x.js +0 -1
  134. package/dist/web/assets/release-notes-hK5XezLW.js +0 -5
  135. package/dist/web/assets/requestData-BnN7mctX.js +0 -1
  136. package/dist/web/assets/routes-usHwrrA0.js +0 -3
  137. package/dist/web/assets/settings-BVZDnL6O.js +0 -1
  138. package/dist/web/assets/workTarget-Cijqq4yH.js +0 -1
@@ -5,9 +5,22 @@ import { normalizeTaskId } from "../../shared/refs.js";
5
5
  import { REQUEST_STATUSES, TASK_STATUSES } from "../../shared/types.js";
6
6
  import { listTasks, progress, resolve } from "../../core/ops.js";
7
7
  import { ConflictError, NotFoundError } from "../../core/store/collection.js";
8
+ import { ACCEPTANCE_RESULTS, AcceptanceInputError, acceptanceStatus } from "../../shared/acceptance.js";
9
+ import { requestRequirementView, RequirementInputError } from "../../shared/requirementSource.js";
10
+ import { PremiseInputError } from "../../shared/reviewCandidate.js";
11
+ import { MILESTONE_REVIEW_SECTIONS, RetrospectiveError, RISK_STATES, TASK_REVIEW_SECTIONS } from "../../shared/retrospective.js";
12
+ import { confirmRetrospectiveTarget, judgeRisk, retrospectiveView } from "../../core/retrospective.js";
13
+ import { metricScopeOf, metricsReport } from "../../core/metrics/index.js";
14
+ import { MetricsError } from "../../shared/metrics.js";
15
+ import { requestReview, reviewCandidates, taskReview } from "../../core/reviewCandidates.js";
16
+ import { BlockInputError } from "../../shared/taskBlock.js";
17
+ import { QualityInputError, taskQualityDiff } from "../../shared/quality.js";
18
+ import { qualityTemplate, qualityView, updateQuality } from "../../core/quality.js";
19
+ import { diagnoseQuality, ImprovementError, improvementDraft, registerImprovement } from "../../core/qualityImprovement.js";
8
20
  import { ATTACHMENT_LIMITS, ATTACHMENT_TYPES, AttachmentError, safeFileName } from "../../core/store/attachments.js";
9
21
  import { bodyLimit } from "hono/body-limit";
10
22
  import { MilestonesConflictError, ReloadError } from "../../core/store/workspace.js";
23
+ import { ArchivedTaskReadError, getArchivedTask, listArchivedTasks } from "../../core/store/archivedTasks.js";
11
24
  import { completionCheckOf, hierarchyNow, resolvedIssue } from "../../core/requestStatus.js";
12
25
  import { HierarchyError, hierarchyView } from "../../core/hierarchy.js";
13
26
  import { supersededMarks } from "../../core/supersede.js";
@@ -18,7 +31,8 @@ import { AI_MANIFEST } from "./manifest.js";
18
31
  import { repoRoutes } from "./repoRoutes.js";
19
32
  import { releaseNoteRoutes } from "./releaseNoteRoutes.js";
20
33
  import { milestoneReviewRoutes } from "./milestoneReviewRoutes.js";
21
- import { archiveTask, checkMilestoneRemoval, createRequest, createTask, orderChildren, updateRequest, updateTask } from "../../core/requestOps.js";
34
+ import { taskReviewRoutes } from "./taskReviewRoutes.js";
35
+ import { archiveTask, checkMilestoneRemoval, createRequest, createTask, orderChildren, updateRequest, updateTask, importQuality, saveClarifyAnswer, updateRequirement, recordPremise } from "../../core/requestOps.js";
22
36
  import { PREFLIGHT_RUNNERS } from "../../shared/preflightRunner.js";
23
37
  import { StaleInputError } from "../../core/preflight/input.js";
24
38
  import { CancelRefusedError, ChildConflictError, ChildDraftsChangedError, DraftConflictError, PulseInputError } from "../../core/preflight/service.js";
@@ -28,10 +42,13 @@ import { CancelRefusedError, ChildConflictError, ChildDraftsChangedError, DraftC
28
42
  * /requests 要望(進捗つき)
29
43
  * /requests/:rid 要望の詳細
30
44
  * /requests/:rid/tasks[/:tid] 要望のタスク
45
+ * /requests/:rid/archived-tasks[/:tid] アーカイブしたタスク(読むだけ)
31
46
  * /requests/:rid/preflight[/:run] Preflight
32
47
  * /requests/:rid/notes Preflight へのメモ
33
48
  * /release-notes[/:mid] マイルストーンのリリースノート(releaseNoteRoutes.ts)
49
+ * /metrics[?milestone=<ID>] 開発の指標(core/metrics。読むだけ)
34
50
  * /milestones/:mid/review[s...] マイルストーンレビュー(milestoneReviewRoutes.ts)
51
+ * /requests/:rid/tasks/:tid/review[s...] タスクの AI レビュー(taskReviewRoutes.ts)
35
52
  */
36
53
  const date = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
37
54
  const taskInput = z.object({
@@ -47,8 +64,50 @@ const taskInput = z.object({
47
64
  /** 変更の記録(Markdown。完了にするときに書く) */
48
65
  record: z.string().nullable().optional(),
49
66
  });
50
- /** checked: 完了したタスクに人が「済み」を付ける / 外す */
51
- const taskPatch = taskInput.partial().extend({ rev: z.number().int().optional(), checked: z.boolean().optional() });
67
+ /** 受け入れ基準・証拠への操作(規則は shared/acceptance.ts。CLI の criteria / evidence と同じ) */
68
+ const acceptanceOp = z.discriminatedUnion("op", [
69
+ z.object({ op: z.literal("add"), text: z.string() }),
70
+ z.object({ op: z.literal("edit"), id: z.string(), text: z.string() }),
71
+ z.object({ op: z.literal("remove"), id: z.string() }),
72
+ z.object({ op: z.literal("order"), ids: z.array(z.string()) }),
73
+ // basis(根拠)の形と組み合わせは shared/acceptance.ts の cleanBasis・basisMismatch が確かめる(規則を2か所に書かない)
74
+ z.object({ op: z.literal("record"), id: z.string(), result: z.enum(ACCEPTANCE_RESULTS), evidence: z.string().default(""), basis: z.custom((v) => v !== null && typeof v === "object").optional() }),
75
+ z.object({ op: z.literal("unrecord"), id: z.string() }),
76
+ // 基準ごとの要求の根拠(出典・確認)。操作の形と規則は shared/requirementSource.ts の applySourceOps が確かめる
77
+ z.object({ op: z.literal("source"), id: z.string(), source: z.custom((v) => v !== null && typeof v === "object") }),
78
+ ]);
79
+ /** 品質基準の操作(規則は shared/quality.ts。CLI の p3 quality と同じ) */
80
+ const qualityCheck = z.discriminatedUnion("kind", [
81
+ z.object({ kind: z.literal("machine"), command: z.string(), success: z.string() }),
82
+ z.object({ kind: z.literal("manual"), reference: z.string() }),
83
+ ]);
84
+ const qualityInput = z.object({ text: z.string(), repos: z.array(z.string()).optional(), check: qualityCheck });
85
+ const qualityOp = z.discriminatedUnion("op", [
86
+ z.object({ op: z.literal("init") }),
87
+ z.object({ op: z.literal("adopt"), template: z.string(), version: z.number().int().optional() }),
88
+ z.object({ op: z.literal("upgrade"), template: z.string() }),
89
+ z.object({ op: z.literal("add"), standard: qualityInput }),
90
+ z.object({
91
+ op: z.literal("replace"),
92
+ standards: z.array(qualityInput.extend({ id: z.string().optional(), exemptReason: z.string().optional(), source: z.object({ template: z.string(), version: z.number().int(), key: z.string() }).optional() })).max(200),
93
+ templates: z.array(z.object({ id: z.string(), version: z.number().int() })).optional(),
94
+ }),
95
+ z.object({ op: z.literal("edit"), id: z.string(), standard: qualityInput.partial() }),
96
+ z.object({ op: z.literal("remove"), id: z.string() }),
97
+ z.object({ op: z.literal("exempt"), id: z.string(), reason: z.string() }),
98
+ z.object({ op: z.literal("unexempt"), id: z.string() }),
99
+ ]);
100
+ /** 作るとき: 受け入れ基準は文の並び(ID は p3 が振る) */
101
+ const taskCreate = taskInput.extend({ criteria: z.array(z.string()).optional(), quality: z.union([z.enum(["auto", "none"]), z.array(z.string())]).optional() });
102
+ /** checked: 完了したタスクに人が「済み」を付ける / 外す。acceptance: 基準・証拠への操作(順に当て、1つでも合わなければ何も書かない) */
103
+ /** 停止の操作(規則は shared/taskBlock.ts。CLI の block / unblock と同じ。日時・履歴は受け付けない) */
104
+ const blockOp = z.discriminatedUnion("op", [
105
+ z.object({ op: z.literal("set"), reason: z.string(), decision: z.string().optional() }),
106
+ z.object({ op: z.literal("clear"), resolution: z.string() }),
107
+ ]);
108
+ const taskPatch = taskInput
109
+ .partial()
110
+ .extend({ rev: z.number().int().optional(), checked: z.boolean().optional(), acceptance: z.array(acceptanceOp).optional(), blockOp: blockOp.optional() });
52
111
  const requestInput = z.object({
53
112
  title: z.string().min(1),
54
113
  body: z.string().optional(),
@@ -141,12 +200,41 @@ export function apiRoutes(ctx, opts = {}) {
141
200
  return c.json({ error: err.message, code: err.code, milestonesVersion: err.current }, 409);
142
201
  if (err instanceof z.ZodError)
143
202
  return c.json({ error: "invalid input", issues: err.issues }, 400);
203
+ // 受け入れ基準・証拠の操作が規則に合わない(何も書いていない)
204
+ if (err instanceof AcceptanceInputError)
205
+ return c.json({ error: err.message, code: err.code }, 400);
206
+ // 要求の根拠・回答の操作が規則に合わない(何も書いていない)
207
+ if (err instanceof RequirementInputError)
208
+ return c.json({ error: err.message, code: err.code }, 400);
209
+ // 前提の変更の操作が規則に合わない・対象が無い(何も書いていない)
210
+ if (err instanceof PremiseInputError)
211
+ return c.json({ error: err.message, code: err.code }, 400);
212
+ // 振り返り: 候補でない・理由が無い → 400、版の競合・記録が読めない → 409(何も書いていない)
213
+ if (err instanceof RetrospectiveError)
214
+ return c.json({ error: err.message, code: err.code }, err.code === "retro_invalid" ? 400 : 409);
215
+ // 指標: 知らない範囲(登録されていないマイルストーン)
216
+ if (err instanceof MetricsError)
217
+ return c.json({ error: err.message, code: err.code }, 400);
218
+ // 停止の操作が規則に合わない・止まったままの移動(何も書いていない)
219
+ if (err instanceof BlockInputError)
220
+ return c.json({ error: err.message, code: err.code }, err.code === "blocked" ? 409 : 400);
221
+ // 品質基準(版が違えば 409 quality_conflict。何も書いていない)
222
+ if (err instanceof QualityInputError)
223
+ return c.json({ error: err.message, code: err.code }, err.code === "quality_conflict" ? 409 : 400);
224
+ // 改善要望(診断が変わった・登録先がある → 409。作っていない)
225
+ if (err instanceof ImprovementError) {
226
+ const status = err.code === "not_found" ? 404 : err.code === "diagnosis_changed" || err.code === "existing" || err.code === "closed_existing" ? 409 : 400;
227
+ return c.json({ error: err.message, code: err.code, ...(err.existing ? { existing: err.existing } : {}) }, status);
228
+ }
144
229
  // 個人設定のファイルが読めない・壊れている(ファイルは変えていない)
145
230
  if (err instanceof UserConfigError)
146
231
  return c.json({ error: err.message }, 500);
147
232
  // データのフォルダが読めない(メモリ上の状態は変えていない)
148
233
  if (err instanceof ReloadError)
149
234
  return c.json({ error: err.message }, 503);
235
+ // アーカイブのフォルダ・ファイルが読めない(無いのは 404)
236
+ if (err instanceof ArchivedTaskReadError)
237
+ return c.json({ error: err.message, code: err.code }, 500);
150
238
  console.error(err);
151
239
  return c.json({ error: err.message }, 400);
152
240
  });
@@ -187,6 +275,7 @@ export function apiRoutes(ctx, opts = {}) {
187
275
  /** マイルストーンのリリースノート(材料・保存・出力・要約の生成) */
188
276
  app.route("/", releaseNoteRoutes(ctx));
189
277
  app.route("/", milestoneReviewRoutes(ctx));
278
+ app.route("/", taskReviewRoutes(ctx));
190
279
  // --- requests -------------------------------------------------------------
191
280
  app.get("/requests", (c) => {
192
281
  // ?parent=<ID>: 直下の子だけを、親の表示順(子の一覧・詳細と同じ)で。省くと更新の新しい順
@@ -205,6 +294,8 @@ export function apiRoutes(ctx, opts = {}) {
205
294
  const id = rid(c);
206
295
  return c.json({
207
296
  request: ws.requests.get(id),
297
+ // 要求の根拠の記録と回答の状態(shared/requirementSource.ts。申告の記録で、P3 の保証ではない)
298
+ requirement: requestRequirementView(ws.requests.require(id)),
208
299
  tasks: ws.tasksOf(id).list(),
209
300
  runs: await Promise.all((await preflight.list(id)).map((r) => preflight.withInputMatch(id, r))),
210
301
  // 対応済なのに未完了のタスクがある(外部の直接編集など)
@@ -212,6 +303,8 @@ export function apiRoutes(ctx, opts = {}) {
212
303
  // 親子(parent・ancestors・children・hierarchyIssues)と、対応済にできるか(blocker・見送りで対象外の子 excluded)
213
304
  ...(await hierarchyView(ws, id)),
214
305
  completion: completionCheckOf(ws, hierarchyNow(ws), id),
306
+ // 見直しが必要(候補): 要望自身(対応済・完了済)・タスクごとの概要・配下の件数(読むだけ。shared/reviewCandidate.ts)
307
+ review: requestReview(ctx, id),
215
308
  // 置き換えられたタスクの印(T001 → 置き換えた側)
216
309
  superseded: Object.fromEntries([...supersededMarks(ws)].filter(([ref]) => ref.startsWith(`${id}/`)).map(([ref, m]) => [ref.slice(id.length + 1), m])),
217
310
  });
@@ -220,6 +313,84 @@ export function apiRoutes(ctx, opts = {}) {
220
313
  const { rev, ...patch } = requestPatch.parse(await c.req.json());
221
314
  return c.json(await updateRequest(ctx, rid(c), unnull(patch), { expectedRev: expectedRev(c, { rev }), actor: actorOf(c) }));
222
315
  });
316
+ /** 要望の要求の根拠の記録を変える(CLI の p3 source と同じ操作。順に当て、1つでも合わなければ何も書かない) */
317
+ app.post("/requests/:rid/sources", async (c) => {
318
+ const { ops, rev } = z.object({ ops: z.array(z.custom((v) => v !== null && typeof v === "object")).min(1), rev: z.number().int().optional() }).parse(await c.req.json());
319
+ const r = await updateRequirement(ctx, rid(c), ops, { expectedRev: expectedRev(c, { rev }), actor: actorOf(c) });
320
+ return c.json({ request: r, requirement: requestRequirementView(r) });
321
+ });
322
+ /**
323
+ * Preflight の確認事項に回答する(CLI の p3 answer と同じ)。answer: null で回答を消す。回答は要望に残し、過去の run は書き換えない。
324
+ * 回答しただけでは根拠の記録を確認記録ありにしない。再評価は別に明示して始める
325
+ */
326
+ /**
327
+ * 前提の変更(外部の規則の変更など)を記録する。add: {op: "add", targets, reason, condition} / ack: {op: "ack", id, target, condition}。
328
+ * 過去の完了の記録・状態・済みは変えない。対象が無い・規則に合わなければ 400 premise_invalid、rev が違えば 409(何も書かない)
329
+ */
330
+ app.get("/requests/:rid/premises", (c) => c.json(ws.requests.require(rid(c)).premiseChanges ?? []));
331
+ app.post("/requests/:rid/premises", async (c) => {
332
+ const b = z
333
+ .discriminatedUnion("op", [
334
+ z.object({ op: z.literal("add"), targets: z.array(z.string()), reason: z.string(), condition: z.string(), rev: z.number().int().optional() }),
335
+ z.object({ op: z.literal("ack"), id: z.string(), target: z.string(), condition: z.string(), rev: z.number().int().optional() }),
336
+ ])
337
+ .parse(await c.req.json());
338
+ const { rev, ...op } = b;
339
+ const r = await recordPremise(ctx, rid(c), op, { expectedRev: expectedRev(c, { rev }), actor: actorOf(c) });
340
+ return c.json({ change: r.change, rev: r.request.rev });
341
+ });
342
+ /** 要望の振り返り: 確定した対象・訂正の履歴・候補(採用を終えた run と根拠)。読むだけ */
343
+ app.get("/requests/:rid/retrospective", async (c) => c.json(await retrospectiveView(ctx, rid(c))));
344
+ /** 振り返りの対象を確定する {run, reason?(2回目からの訂正で必須), version?(読んだときの版)} */
345
+ app.post("/requests/:rid/retrospective/target", async (c) => {
346
+ const b = z.object({ run: z.string().min(1), reason: z.string().optional(), version: z.number().int().optional() }).parse(await c.req.json());
347
+ return c.json(await confirmRetrospectiveTarget(ctx, rid(c), { run: b.run, reason: b.reason }, { expectedVersion: b.version, actor: actorOf(c) }));
348
+ });
349
+ /** リスクの確認を記録する {risk(0 から), state, facts?, scope?, reason?, evidence: [根拠の指定], version?}(人の判断。追記) */
350
+ app.post("/requests/:rid/retrospective/judgments", async (c) => {
351
+ const ev = z.discriminatedUnion("kind", [
352
+ z.object({ kind: z.literal("task_review"), task: z.string(), run: z.string(), section: z.enum(TASK_REVIEW_SECTIONS), index: z.number().int().optional() }),
353
+ z.object({ kind: z.literal("milestone_review"), milestone: z.string(), run: z.string(), section: z.enum(MILESTONE_REVIEW_SECTIONS), index: z.number().int().optional(), reason: z.string().optional() }),
354
+ z.object({ kind: z.literal("rework"), task: z.string(), history: z.string() }),
355
+ z.object({ kind: z.literal("manual"), reference: z.string(), note: z.string().optional() }),
356
+ ]);
357
+ const b = z
358
+ .object({ risk: z.number().int().min(0), state: z.enum(RISK_STATES), facts: z.string().optional(), scope: z.string().optional(), reason: z.string().optional(), evidence: z.array(ev).default([]), version: z.number().int().optional() })
359
+ .parse(await c.req.json());
360
+ const { version, ...input } = b;
361
+ return c.json(await judgeRisk(ctx, rid(c), input, { expectedVersion: version, actor: actorOf(c) }));
362
+ });
363
+ /** 見直しが必要(候補)の一覧(完了したタスクと対応済・完了済の要望。完了済みも含む。?request= でその要望だけ) */
364
+ app.get("/metrics", async (c) => c.json(await metricsReport(ctx, metricScopeOf(ctx, c.req.query("milestone")))));
365
+ app.get("/revisit", (c) => {
366
+ const request = c.req.query("request");
367
+ return c.json(reviewCandidates(ctx, request ? { request } : {}));
368
+ });
369
+ app.post("/requests/:rid/answers", async (c) => {
370
+ const b = z
371
+ .object({
372
+ run: z.string(),
373
+ question: z.string(),
374
+ answer: z.string().nullable(),
375
+ by: z.string().optional(),
376
+ on: z.string().optional(),
377
+ source: z.string().optional(),
378
+ basis: z.string().optional(),
379
+ links: z.array(z.string()).optional(),
380
+ rev: z.number().int().optional(),
381
+ })
382
+ .parse(await c.req.json());
383
+ const id = rid(c);
384
+ const run = await preflight.get(id, b.run);
385
+ if (!run)
386
+ throw new NotFoundError(b.run);
387
+ const q = run.assessment?.clarifications?.find((x) => x.id === b.question);
388
+ if (!q)
389
+ return c.json({ error: `${b.run} に確認事項 ${b.question} はありません`, code: "requirement_invalid" }, 400);
390
+ const input = b.answer === null ? null : { answer: b.answer, by: b.by, on: b.on, source: b.source, basis: b.basis, links: b.links };
391
+ const r = await saveClarifyAnswer(ctx, id, b.run, q, input, { expectedRev: expectedRev(c, b), actor: actorOf(c) });
392
+ return c.json({ request: r.request, answer: r.answer ?? null, requirement: requestRequirementView(r.request) });
393
+ });
223
394
  /** 子の表示順(直下の子を全部、上から順に。CLI の request order と同じ操作) */
224
395
  app.put("/requests/:rid/child-order", async (c) => {
225
396
  const { children, rev } = childOrderInput.parse(await c.req.json());
@@ -227,13 +398,42 @@ export function apiRoutes(ctx, opts = {}) {
227
398
  const r = await orderChildren(ctx, id, children, { expectedRev: expectedRev(c, { rev }), actor: actorOf(c) });
228
399
  return c.json({ request: r, children: hierarchyNow(ws).children(id).map((k) => k.id) });
229
400
  });
401
+ // --- 品質基準(project.yaml の quality。core/quality.ts) ----------------------------
402
+ app.get("/quality", (c) => c.json(qualityView(ws)));
403
+ app.get("/quality/templates/:id", (c) => {
404
+ const v = c.req.query("version");
405
+ const t = qualityTemplate(c.req.param("id"), v ? Number(v) : undefined);
406
+ return t ? c.json(t) : c.json({ error: `テンプレートがありません: ${c.req.param("id")}`, code: "not_found" }, 404);
407
+ });
408
+ app.post("/quality", async (c) => {
409
+ const { ops, version } = z.object({ ops: z.array(qualityOp).min(1).max(200), version: z.string().optional() }).parse(await c.req.json());
410
+ return c.json(await updateQuality(ws, ops, { expectedVersion: version }));
411
+ });
412
+ // --- 品質の改善要望(core/qualityImprovement.ts。診断と原稿は読むだけ、登録は明示したときだけ) ------------
413
+ const improvementSource = z.discriminatedUnion("type", [
414
+ z.object({ type: z.literal("project") }),
415
+ z.object({ type: z.literal("task-review"), request: z.string(), task: z.string(), run: z.string() }),
416
+ z.object({ type: z.literal("milestone-review"), milestone: z.string(), run: z.string() }),
417
+ ]);
418
+ app.post("/quality/improvements/preview", async (c) => {
419
+ const { source, keys } = z.object({ source: improvementSource, keys: z.array(z.string()).optional() }).parse(await c.req.json());
420
+ const d = await diagnoseQuality(ctx, source);
421
+ const picked = keys ?? d.findings.filter((f) => f.suggested).map((f) => f.key);
422
+ return c.json({ ...d, picked, ...(picked.length ? { draft: improvementDraft(d, picked) } : {}) });
423
+ });
424
+ app.post("/quality/improvements", async (c) => {
425
+ const body = z
426
+ .object({ source: improvementSource, keys: z.array(z.string()).min(1), title: z.string(), body: z.string(), hash: z.string(), reopenClosed: z.boolean().optional() })
427
+ .parse(await c.req.json());
428
+ return c.json(await registerImprovement(ctx, body, actorOf(c)), 201);
429
+ });
230
430
  // --- tasks(要望の中) --------------------------------------------------------
231
431
  app.get("/requests/:rid/tasks", (c) => {
232
- const { status, area, q } = c.req.query();
233
- return c.json(listTasks(ctx, { request: rid(c), status: status?.split(","), area, q }));
432
+ const { status, area, q, blocked, review } = c.req.query();
433
+ return c.json(listTasks(ctx, { request: rid(c), status: status?.split(","), area, q, blocked: blocked === "true", review: review === "true" }));
234
434
  });
235
435
  app.post("/requests/:rid/tasks", async (c) => {
236
- const raw = taskInput.parse(await c.req.json());
436
+ const raw = taskCreate.parse(await c.req.json());
237
437
  const { repo, ...b } = unnull(raw);
238
438
  // 作業先は null(作業先なし)を残す。書かなければ既定(requestOps.createTask)
239
439
  const input = { ...b, ...("repo" in raw ? { repo: raw.repo ?? null } : {}) };
@@ -242,19 +442,48 @@ export function apiRoutes(ctx, opts = {}) {
242
442
  });
243
443
  app.get("/requests/:rid/tasks/:tid", (c) => {
244
444
  const task = ws.tasksOf(rid(c)).require(tid(c));
245
- return c.json({ task, superseded: supersededMarks(ws).get(task.ref) ?? [] });
445
+ return c.json({ task, superseded: supersededMarks(ws).get(task.ref) ?? [], acceptance: acceptanceStatus(task) ?? null, review: taskReview(ctx, task) ?? null });
246
446
  });
247
447
  app.patch("/requests/:rid/tasks/:tid", async (c) => {
248
- const { rev, checked, ...patch } = taskPatch.parse(await c.req.json());
249
- const next = { ...unnull(patch), ...("repo" in patch ? { repo: patch.repo ?? null } : {}), ...(checked !== undefined ? { checked } : {}) };
250
- // 置き換えられたタスクを作業中にしたら警告を添える(操作は続ける)
251
- const { task, warnings, reopened, reopenedAncestors } = await updateTask(ctx, rid(c), tid(c), next, { expectedRev: expectedRev(c, { rev }), actor: actorOf(c) });
252
- return c.json({ ...task, ...(warnings.length ? { warnings } : {}), ...(reopened ? { reopened } : {}), ...(reopenedAncestors ? { reopenedAncestors } : {}) });
448
+ const { rev, checked, acceptance, blockOp: bop, ...patch } = taskPatch.parse(await c.req.json());
449
+ const next = {
450
+ ...(bop ? { blockOp: bop } : {}),
451
+ ...unnull(patch),
452
+ ...("repo" in patch ? { repo: patch.repo ?? null } : {}),
453
+ ...(checked !== undefined ? { checked } : {}),
454
+ ...(acceptance?.length ? { acceptance } : {}),
455
+ };
456
+ // 置き換えられたタスクを作業中にしたら警告を添える(操作は続ける)。基準・証拠が変わって済みを外したら checkCleared
457
+ // 完了の記録が壊れていて足せなかったら completionSkipped(状態は変えた)
458
+ const { task, warnings, reopened, reopenedAncestors, checkCleared, completionSkipped, reworkSkipped } = await updateTask(ctx, rid(c), tid(c), next, { expectedRev: expectedRev(c, { rev }), actor: actorOf(c) });
459
+ return c.json({
460
+ ...task,
461
+ ...(warnings.length ? { warnings } : {}),
462
+ ...(reopened ? { reopened } : {}),
463
+ ...(reopenedAncestors ? { reopenedAncestors } : {}),
464
+ ...(checkCleared ? { checkCleared } : {}),
465
+ ...(completionSkipped ? { completionSkipped } : {}),
466
+ ...(reworkSkipped ? { reworkSkipped } : {}),
467
+ });
468
+ });
469
+ /** 今の品質基準との差分(読むだけ。タスクは書き換えない) */
470
+ app.get("/requests/:rid/tasks/:tid/quality-diff", (c) => {
471
+ const task = ws.tasksOf(rid(c)).require(tid(c));
472
+ return c.json({ quality: ws.project.quality?.state ?? "unset", version: ws.project.qualityVersion, diff: taskQualityDiff(task.acceptanceCriteria ?? [], ws.project.quality, task.repo) });
473
+ });
474
+ /** 差分を明示して取り込む(keys: "<kind>:<品質 ID>"。省くと「直した」以外の全部) */
475
+ app.post("/requests/:rid/tasks/:tid/quality-import", async (c) => {
476
+ const { keys, rev } = z.object({ keys: z.array(z.string()).optional(), rev: z.number().int().optional() }).parse(await c.req.json().catch(() => ({})));
477
+ const r = await importQuality(ctx, rid(c), tid(c), keys, { expectedRev: expectedRev(c, { rev }), actor: actorOf(c) });
478
+ return c.json({ ...r.task, applied: r.applied, ...(r.checkCleared ? { checkCleared: r.checkCleared } : {}) });
253
479
  });
254
480
  app.delete("/requests/:rid/tasks/:tid", async (c) => {
255
481
  await archiveTask(ctx, rid(c), tid(c));
256
482
  return c.json({ ok: true });
257
483
  });
484
+ // --- アーカイブしたタスク(読むだけ。通常のタスクの道はアーカイブを探さない) ------------------------
485
+ app.get("/requests/:rid/archived-tasks", async (c) => c.json(await listArchivedTasks(ws, c.req.param("rid"))));
486
+ app.get("/requests/:rid/archived-tasks/:tid", async (c) => c.json({ task: await getArchivedTask(ws, c.req.param("rid"), tid(c)) }));
258
487
  // --- preflight ----------------------------------------------------------
259
488
  app.post("/requests/:rid/preflight", async (c) => {
260
489
  const body = z
@@ -380,11 +609,30 @@ export function apiRoutes(ctx, opts = {}) {
380
609
  });
381
610
  app.patch("/requests/:rid/preflight/:run/drafts/:key", async (c) => {
382
611
  // expectedTitle: 編集を始めたときの題(制御用。案には書かない)。今の題と違えば 409 で書かない
383
- const { expectedTitle, ...patch } = z
384
- .object({ title: z.string(), description: z.string(), include: z.boolean(), repo: z.string().nullable(), expectedTitle: z.string() })
612
+ // acceptanceCriteria: 受け入れ基準の並び全体(id は残し、無い項目に振る)。expectedCriteria: 編集を始めたときの基準(違えば 409)
613
+ const criterion = z.object({ id: z.string().nullish(), text: z.string() });
614
+ // sourceOps: 基準ごとの要求の根拠への操作。expectedSources: 編集を始めたときの根拠の記録(違えば 409。根拠だけの編集の競合も見る)
615
+ const { expectedTitle, expectedCriteria, expectedSources, ...patch } = z
616
+ .object({
617
+ title: z.string(),
618
+ description: z.string(),
619
+ include: z.boolean(),
620
+ repo: z.string().nullable(),
621
+ acceptanceCriteria: z.array(criterion),
622
+ sourceOps: z.array(z.object({ id: z.string(), source: z.custom((v) => v !== null && typeof v === "object") })),
623
+ expectedTitle: z.string(),
624
+ expectedCriteria: z.array(z.object({ id: z.string(), text: z.string() })),
625
+ expectedSources: z.array(z.custom((v) => v !== null && typeof v === "object")),
626
+ })
385
627
  .partial()
386
628
  .parse(await c.req.json());
387
- return c.json(await preflight.updateDraft(rid(c), c.req.param("run"), c.req.param("key"), patch, { expectedTitle }));
629
+ if (patch.acceptanceCriteria !== undefined && expectedCriteria === undefined) {
630
+ return c.json({ error: "受け入れ基準を直すときは expectedCriteria(編集を始めたときの基準)を渡してください", code: "acceptance_invalid" }, 400);
631
+ }
632
+ if (patch.sourceOps?.length && expectedSources === undefined) {
633
+ return c.json({ error: "要求の根拠を直すときは expectedSources(編集を始めたときの根拠の記録)を渡してください", code: "requirement_invalid" }, 400);
634
+ }
635
+ return c.json(await preflight.updateDraft(rid(c), c.req.param("run"), c.req.param("key"), patch, { expectedTitle, expectedCriteria, expectedSources, actor: actorOf(c) }));
388
636
  });
389
637
  /** 子の要望の案(分割の run)を直す。expectedTitle は上と同じ */
390
638
  app.patch("/requests/:rid/preflight/:run/children/:key", async (c) => {
@@ -409,8 +657,8 @@ export function apiRoutes(ctx, opts = {}) {
409
657
  });
410
658
  // --- 横断 --------------------------------------------------------------
411
659
  app.get("/tasks", (c) => {
412
- const { status, area, q } = c.req.query();
413
- return c.json(listTasks(ctx, { status: status?.split(","), area, q }));
660
+ const { status, area, q, blocked, review } = c.req.query();
661
+ return c.json(listTasks(ctx, { status: status?.split(","), area, q, blocked: blocked === "true", review: review === "true" }));
414
662
  });
415
663
  /** 参照・タイトルから対象を特定する(?request= で今の要望を優先) */
416
664
  app.get("/resolve", (c) => c.json(resolve(ctx, c.req.query("q") ?? "", c.req.query("request"))));
@@ -0,0 +1,66 @@
1
+ import { Hono } from "hono";
2
+ import { z } from "zod";
3
+ import { ReviewCancelRefused, ReviewStoreError } from "../../core/reviewRuns.js";
4
+ import { NotFoundError } from "../../core/store/collection.js";
5
+ import { TaskReviewRejected } from "../../core/taskReview/material.js";
6
+ import { previewOf } from "../../shared/taskReview.js";
7
+ /**
8
+ * タスクの AI レビュー(画面のため)。規則と保存は core/taskReview(CLI の p3 review と同じサービス)。
9
+ *
10
+ * POST /requests/:rid/tasks/:tid/review-preview 今の材料の要約と hash({targets?, viewpoint?}。何も書かない)
11
+ * GET /requests/:rid/tasks/:tid/reviews 履歴(新しい順。読めない記録も broken で出す。アーカイブしたタスクも読める)
12
+ * POST /requests/:rid/tasks/:tid/reviews 始める(202。{targets?, viewpoint?, engine?, expectedHash?})。
13
+ * 材料が変わっていれば 409 material_changed、実行中なら 409 running、Preflight の担当が agent で
14
+ * engine を明示していなければ 400 engine_required
15
+ * GET /requests/:rid/tasks/:tid/reviews/:run 1回分(固定した材料・結果。実行中は所有者の状態 owner)
16
+ * POST /requests/:rid/tasks/:tid/reviews/:run/cancel 取り消す({acknowledgeStopped?}。マイルストーンレビューと同じ)
17
+ *
18
+ * 結果を直す口は作らない(直すなら材料を直して別の run でレビューし直す)
19
+ */
20
+ const actorOf = (c) => c.req.header("x-p3-actor") ?? "human:web";
21
+ const startBody = z.object({
22
+ targets: z.array(z.string().min(1)).max(50).optional(),
23
+ viewpoint: z.string().max(2000).optional(),
24
+ engine: z.enum(["codex", "mock"]).optional(),
25
+ expectedHash: z.string().optional(),
26
+ });
27
+ export function taskReviewRoutes(ctx) {
28
+ const app = new Hono();
29
+ const svc = () => ctx.taskReview;
30
+ app.onError((err, c) => {
31
+ if (err instanceof NotFoundError)
32
+ return c.json({ error: err.message, code: "not_found" }, 404);
33
+ if (err instanceof ReviewStoreError) {
34
+ const status = err.code === "not_found" ? 404 : err.code === "bad_id" ? 400 : err.code === "broken" ? 422 : 409;
35
+ return c.json({ error: err.message, code: err.code }, status);
36
+ }
37
+ if (err instanceof TaskReviewRejected) {
38
+ const status = err.code === "running" || err.code === "material_changed" ? 409 : 400;
39
+ return c.json({ error: err.message, code: err.code, ...(err.running ? { run: err.running } : {}) }, status);
40
+ }
41
+ if (err instanceof ReviewCancelRefused)
42
+ return c.json({ error: err.message, code: err.code }, 409);
43
+ if (err instanceof z.ZodError)
44
+ return c.json({ error: "invalid input", issues: err.issues }, 400);
45
+ console.error(err);
46
+ return c.json({ error: err.message }, 400);
47
+ });
48
+ const rid = (c) => c.req.param("rid");
49
+ const tid = (c) => c.req.param("tid");
50
+ app.post("/requests/:rid/tasks/:tid/review-preview", async (c) => {
51
+ const { targets, viewpoint } = startBody.parse(await c.req.json().catch(() => ({})));
52
+ const p = await svc().preview(rid(c), tid(c), { targets, viewpoint });
53
+ return c.json({ ...previewOf(p.input), engineRequired: p.engineRequired });
54
+ });
55
+ app.get("/requests/:rid/tasks/:tid/reviews", async (c) => c.json({ items: await svc().list(rid(c), tid(c)) }));
56
+ app.post("/requests/:rid/tasks/:tid/reviews", async (c) => {
57
+ const body = startBody.parse(await c.req.json().catch(() => ({})));
58
+ return c.json(await svc().start(rid(c), tid(c), actorOf(c), body), 202);
59
+ });
60
+ app.get("/requests/:rid/tasks/:tid/reviews/:run", async (c) => c.json(await svc().get(rid(c), tid(c), c.req.param("run"))));
61
+ app.post("/requests/:rid/tasks/:tid/reviews/:run/cancel", async (c) => {
62
+ const { acknowledgeStopped } = z.object({ acknowledgeStopped: z.boolean().optional() }).parse(await c.req.json().catch(() => ({})));
63
+ return c.json(await svc().cancel(rid(c), tid(c), c.req.param("run"), actorOf(c), { acknowledgeStopped }));
64
+ });
65
+ return app;
66
+ }
@@ -75,10 +75,10 @@ export async function startServer(opts) {
75
75
  pending = (await registry.close({ timeoutMs })).pending;
76
76
  else if (ctx) {
77
77
  const c = ctx;
78
- const settle = Promise.all([c.preflight.settle({ cancel: true }), c.releaseGenerator.settle({ cancel: true }), c.milestoneReview.settle({ cancel: true })]).then(() => false);
78
+ const settle = Promise.all([c.preflight.settle({ cancel: true }), c.releaseGenerator.settle({ cancel: true }), c.milestoneReview.settle({ cancel: true }), c.taskReview.settle({ cancel: true })]).then(() => false);
79
79
  const timedOut = await Promise.race([settle, new Promise((r) => setTimeout(() => r(true), timeoutMs).unref())]);
80
80
  c.ws.close();
81
- pending = timedOut ? c.preflight.running() + c.releaseGenerator.running() + c.milestoneReview.running() : 0;
81
+ pending = timedOut ? c.preflight.running() + c.releaseGenerator.running() + c.milestoneReview.running() + c.taskReview.running() : 0;
82
82
  }
83
83
  await Promise.race([closed, new Promise((r) => setTimeout(r, 1000).unref())]);
84
84
  return { pending };