@infodb/p3 0.13.0 → 0.14.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 (204) hide show
  1. package/README.md +1 -0
  2. package/bin/p3.mjs +3 -2
  3. package/dist/web/assets/{CompletionReview-gZKZrDu_.js → CompletionReview-BD7d6Yzt.js} +1 -1
  4. package/dist/web/assets/ImprovementDialog-BoAZN1KR.js +1 -0
  5. package/dist/web/assets/{Outputs-BgHalMGb.js → Outputs-D-ZouoxF.js} +1 -1
  6. package/dist/web/assets/{RequestStatus-hZcBUUIu.js → RequestStatus-Bl3fdSbM.js} +1 -1
  7. package/dist/web/assets/{Tabs-C3NmwCc3.js → Tabs-CxeceOL-.js} +1 -1
  8. package/dist/web/assets/{TagInput-B2b862qn.js → TagInput-CeAbmGRR.js} +1 -1
  9. package/dist/web/assets/TaskDrawer-BCriSnhe.js +6 -0
  10. package/dist/web/assets/_requestId-CZKMe_mC.js +1 -0
  11. package/dist/web/assets/_requestId-Fx4lLkFo.js +1 -0
  12. package/dist/web/assets/appCtx-BdxbkSZa.js +1 -0
  13. package/dist/web/assets/archive-D5IIxcSV.js +1 -0
  14. package/dist/web/assets/board-p6R9KMqd.js +1 -0
  15. package/dist/web/assets/done-BTOF188x.js +1 -0
  16. package/dist/web/assets/{draft-BvGxfD7v.js → draft-BWYpm3PD.js} +2 -2
  17. package/dist/web/assets/index-DFbY8NAR.css +2 -0
  18. package/dist/web/assets/index-Dpqi2dcC.js +12 -0
  19. package/dist/web/assets/link-D481whDt.js +1 -0
  20. package/dist/web/assets/metrics-CAzP6V8I.js +1 -0
  21. package/dist/web/assets/new-C65IJJg3.js +1 -0
  22. package/dist/web/assets/preload-helper-_dAYMct_.js +1 -0
  23. package/dist/web/assets/{release-notes-Bpdi6RdY.js → release-notes-Dtif8xsQ.js} +4 -4
  24. package/dist/web/assets/{requestData-CbFxwW5w.js → requestData-SPc36t8Q.js} +1 -1
  25. package/dist/web/assets/routes-DJj8CWuk.js +6 -0
  26. package/dist/web/assets/settings-DKJd7CLe.js +1 -0
  27. package/dist/web/assets/ui-CbEOnPnF.js +1 -0
  28. package/dist/web/assets/{workTarget-CySfKyfB.js → workTarget-DavxMs-c.js} +3 -3
  29. package/dist/web/index.html +6 -4
  30. package/docs/architecture.md +165 -71
  31. package/docs/chatgpt-sign-in.md +2 -2
  32. package/docs/development.md +87 -54
  33. package/docs/feature-inventory.md +139 -0
  34. package/docs/how-to-use.md +10 -5
  35. package/docs/installation.md +31 -8
  36. package/docs/publishing.md +32 -13
  37. package/docs/refactoring.md +332 -0
  38. package/lib/cli/agentsStatus.js +2 -1
  39. package/lib/cli/guide.md +4 -1
  40. package/lib/cli/help.js +1 -1
  41. package/lib/cli/main.js +33 -238
  42. package/lib/cli/project.js +21 -267
  43. package/lib/core/projectRegistry.js +2 -2
  44. package/lib/kit/appInfo.js +13 -0
  45. package/lib/kit/usage.js +27 -0
  46. package/lib/server/api/projectsRoutes.js +5 -5
  47. package/lib/server/server.js +7 -4
  48. package/lib/{cli → tasks/cli}/args.js +2 -2
  49. package/lib/{cli → tasks/cli}/chatgpt.js +1 -1
  50. package/lib/{cli → tasks/cli}/codex.js +1 -1
  51. package/lib/{cli → tasks/cli}/output.js +2 -2
  52. package/lib/{cli → tasks/cli}/preflightCommands.js +1 -1
  53. package/lib/tasks/cli/readOnly.js +75 -0
  54. package/lib/{cli → tasks/cli}/render.js +1 -1
  55. package/lib/{cli → tasks/cli}/requestCommands.js +6 -6
  56. package/lib/{cli → tasks/cli}/showView.js +4 -4
  57. package/lib/{cli → tasks/cli}/taskCommands.js +16 -8
  58. package/lib/tasks/cli/tasksCli.js +149 -0
  59. package/lib/{core → tasks/core}/context.js +6 -9
  60. package/lib/tasks/core/errorOutcome.js +125 -0
  61. package/lib/{core → tasks/core}/hierarchy.js +1 -1
  62. package/lib/{core → tasks/core}/ops.js +6 -4
  63. package/lib/{core → tasks/core}/preflight/codexEngine.js +2 -11
  64. package/lib/{core → tasks/core}/preflight/hostPaths.js +39 -0
  65. package/lib/{core → tasks/core}/preflight/input.js +1 -1
  66. package/lib/{core → tasks/core}/preflight/instructions.js +2 -2
  67. package/lib/{core → tasks/core}/preflight/mockEngine.js +8 -7
  68. package/lib/{core → tasks/core}/preflight/service.js +38 -13
  69. package/lib/{core → tasks/core}/preflight/uiRender.js +2 -2
  70. package/lib/{core → tasks/core}/requestOps.js +19 -14
  71. package/lib/{core → tasks/core}/reviewRuns.js +127 -22
  72. package/lib/{core → tasks/core}/store/attachments.js +3 -2
  73. package/lib/{core → tasks/core}/store/collection.js +2 -2
  74. package/lib/tasks/core/store/fieldGroups.js +30 -0
  75. package/lib/tasks/core/store/jsonRecord.js +30 -0
  76. package/lib/{core → tasks/core}/store/normalize.js +13 -26
  77. package/lib/{core → tasks/core}/store/noteStore.js +2 -2
  78. package/lib/{core → tasks/core}/store/preflightStore.js +44 -21
  79. package/lib/{core → tasks/core}/store/projectFile.js +1 -1
  80. package/lib/{core → tasks/core}/store/workspace.js +11 -5
  81. package/lib/{core → tasks/core}/userConfig.js +1 -1
  82. package/lib/{core → tasks/core}/workTargets.js +1 -1
  83. package/lib/{cli → tasks/features/metrics/cli}/metricsCommands.js +3 -3
  84. package/lib/{core/metrics → tasks/features/metrics/core}/definitions.js +19 -8
  85. package/lib/{core/metrics → tasks/features/metrics/core}/index.js +41 -17
  86. package/lib/{core/metrics → tasks/features/metrics/core}/manual.js +27 -28
  87. package/lib/tasks/features/metrics/server/metricsRoutes.js +8 -0
  88. package/lib/{core/milestoneReview → tasks/features/milestoneReview/core}/code.js +2 -11
  89. package/lib/{core/milestoneReview → tasks/features/milestoneReview/core}/material.js +5 -6
  90. package/lib/{core/milestoneReview → tasks/features/milestoneReview/core}/review.js +2 -2
  91. package/lib/{core/milestoneReview → tasks/features/milestoneReview/core}/service.js +38 -100
  92. package/lib/{core/milestoneReview → tasks/features/milestoneReview/core}/store.js +3 -3
  93. package/lib/{server/api → tasks/features/milestoneReview/server}/milestoneReviewRoutes.js +7 -13
  94. package/lib/{cli → tasks/features/quality/cli}/qualityCommands.js +3 -3
  95. package/lib/{core → tasks/features/quality/core}/qualityImprovement.js +16 -15
  96. package/lib/{cli → tasks/features/records/cli}/revisitCommands.js +2 -2
  97. package/lib/{core → tasks/features/records/core}/reviewCandidates.js +26 -6
  98. package/lib/{shared → tasks/features/records/shared}/completionRecord.js +5 -3
  99. package/lib/{shared → tasks/features/records/shared}/reviewCandidate.js +13 -8
  100. package/lib/{shared → tasks/features/records/shared}/reworkHistory.js +5 -0
  101. package/lib/{cli → tasks/features/releaseNotes/cli}/releaseNotesCommands.js +7 -7
  102. package/lib/{core/releaseNotes → tasks/features/releaseNotes/core}/completeRequests.js +5 -6
  103. package/lib/{core/releaseNotes → tasks/features/releaseNotes/core}/generate.js +3 -14
  104. package/lib/{core/releaseNotes → tasks/features/releaseNotes/core}/material.js +3 -4
  105. package/lib/{core/releaseNotes → tasks/features/releaseNotes/core}/service.js +1 -1
  106. package/lib/{core/releaseNotes → tasks/features/releaseNotes/core}/store.js +2 -2
  107. package/lib/{server/api → tasks/features/releaseNotes/server}/releaseNoteRoutes.js +11 -20
  108. package/lib/{cli → tasks/features/requirements/cli}/requirementCommands.js +8 -7
  109. package/lib/{shared → tasks/features/requirements/shared}/acceptance.js +41 -7
  110. package/lib/{cli → tasks/features/retro/cli}/retroCommands.js +1 -1
  111. package/lib/{core → tasks/features/retro/core}/retrospective.js +42 -53
  112. package/lib/tasks/features/settings/cli/projectSettings.js +245 -0
  113. package/lib/{cli → tasks/features/settings/cli}/userConfig.js +5 -5
  114. package/lib/{core → tasks/features/settings/core}/machineSettingsEdit.js +2 -2
  115. package/lib/{core → tasks/features/settings/core}/repoAdmin.js +3 -3
  116. package/lib/{core → tasks/features/settings/core}/userTheme.js +2 -2
  117. package/lib/{server/api → tasks/features/settings/server}/repoRoutes.js +2 -2
  118. package/lib/{server/api → tasks/features/settings/server}/userThemeRoutes.js +3 -3
  119. package/lib/{cli → tasks/features/taskReview/cli}/taskReviewCommands.js +5 -5
  120. package/lib/{core/taskReview → tasks/features/taskReview/core}/material.js +7 -8
  121. package/lib/{core/taskReview → tasks/features/taskReview/core}/review.js +2 -2
  122. package/lib/{core/taskReview → tasks/features/taskReview/core}/service.js +24 -85
  123. package/lib/{core/taskReview → tasks/features/taskReview/core}/store.js +4 -4
  124. package/lib/{server/api → tasks/features/taskReview/server}/taskReviewRoutes.js +7 -14
  125. package/lib/{server → tasks/server}/api/routes.js +24 -75
  126. package/lib/tasks/shared/commitRefs.js +10 -0
  127. package/package.json +1 -44
  128. package/dist/web/assets/ImprovementDialog-Dno6dPnG.js +0 -1
  129. package/dist/web/assets/TaskDrawer-4BQBELXa.js +0 -6
  130. package/dist/web/assets/_requestId-BMAG1t3o.js +0 -1
  131. package/dist/web/assets/_requestId-tbg2pA2S.js +0 -1
  132. package/dist/web/assets/archive-DMl6WyOe.js +0 -1
  133. package/dist/web/assets/board-BMTcHKyt.js +0 -1
  134. package/dist/web/assets/done-CL6Nlsua.js +0 -1
  135. package/dist/web/assets/index-Dp7Fc4VI.css +0 -2
  136. package/dist/web/assets/index-KdlgMitg.js +0 -12
  137. package/dist/web/assets/metrics-Cu7gJ7Rk.js +0 -1
  138. package/dist/web/assets/new-DTXWHuFO.js +0 -1
  139. package/dist/web/assets/preload-helper-oLCrNCwz.js +0 -1
  140. package/dist/web/assets/routes-BIt8bExF.js +0 -6
  141. package/dist/web/assets/settings-CsCqF_1B.js +0 -1
  142. package/dist/web/assets/ui-BGK72r3u.js +0 -1
  143. package/lib/cli/readOnly.js +0 -53
  144. /package/lib/{core/store → kit}/frontmatter.js +0 -0
  145. /package/lib/{core/store → kit}/fsutil.js +0 -0
  146. /package/lib/{cli → tasks/cli}/format.js +0 -0
  147. /package/lib/{core → tasks/core}/chatgpt.js +0 -0
  148. /package/lib/{core → tasks/core}/machineSettings.js +0 -0
  149. /package/lib/{core → tasks/core}/preflight/carryover.js +0 -0
  150. /package/lib/{core → tasks/core}/preflight/codexImage.js +0 -0
  151. /package/lib/{core → tasks/core}/preflight/diagnose.js +0 -0
  152. /package/lib/{core → tasks/core}/preflight/docker.js +0 -0
  153. /package/lib/{core → tasks/core}/preflight/engine.js +0 -0
  154. /package/lib/{core → tasks/core}/preflight/launch.js +0 -0
  155. /package/lib/{core → tasks/core}/preflight/launcher.mjs +0 -0
  156. /package/lib/{core → tasks/core}/preflight/mock-ui.html +0 -0
  157. /package/lib/{core → tasks/core}/preflight/mock-ui.png +0 -0
  158. /package/lib/{core → tasks/core}/preflight/owner.js +0 -0
  159. /package/lib/{core → tasks/core}/preflight/render-image/Dockerfile +0 -0
  160. /package/lib/{core → tasks/core}/preflight/render-image/fonts-ja.conf +0 -0
  161. /package/lib/{core → tasks/core}/preflight/render-image/render.mjs +0 -0
  162. /package/lib/{core → tasks/core}/preflight/render.js +0 -0
  163. /package/lib/{core → tasks/core}/preflight/split.js +0 -0
  164. /package/lib/{core → tasks/core}/preflight/uiMaterials.js +0 -0
  165. /package/lib/{core → tasks/core}/preflight/wireframe.js +0 -0
  166. /package/lib/{core → tasks/core}/preflight/xlsx.js +0 -0
  167. /package/lib/{core → tasks/core}/redact.js +0 -0
  168. /package/lib/{core → tasks/core}/repoRefs.js +0 -0
  169. /package/lib/{core → tasks/core}/requestStatus.js +0 -0
  170. /package/lib/{core → tasks/core}/store/archivedTasks.js +0 -0
  171. /package/lib/{core → tasks/core}/store/dataWatcher.js +0 -0
  172. /package/lib/{core → tasks/core}/store/locate.js +0 -0
  173. /package/lib/{core → tasks/core}/supersede.js +0 -0
  174. /package/lib/{shared → tasks/features/metrics/shared}/metrics.js +0 -0
  175. /package/lib/{core/milestoneReview → tasks/features/milestoneReview/core}/mockReviewer.js +0 -0
  176. /package/lib/{shared → tasks/features/milestoneReview/shared}/milestoneReview.js +0 -0
  177. /package/lib/{core → tasks/features/quality/core}/quality.js +0 -0
  178. /package/lib/{shared → tasks/features/quality/shared}/quality.js +0 -0
  179. /package/lib/{shared → tasks/features/quality/shared}/qualityImprovement.js +0 -0
  180. /package/lib/{shared → tasks/features/quality/shared}/qualityTemplates.js +0 -0
  181. /package/lib/{core → tasks/features/records/core}/completionRefs.js +0 -0
  182. /package/lib/{core/releaseNotes → tasks/features/releaseNotes/core}/mockSummarizer.js +0 -0
  183. /package/lib/{shared → tasks/features/requirements/shared}/requirementSource.js +0 -0
  184. /package/lib/{shared → tasks/features/retro/shared}/retrospective.js +0 -0
  185. /package/lib/{core/taskReview → tasks/features/taskReview/core}/mockReviewer.js +0 -0
  186. /package/lib/{core/taskReview → tasks/features/taskReview/core}/paths.js +0 -0
  187. /package/lib/{shared → tasks/features/taskReview/shared}/taskReview.js +0 -0
  188. /package/lib/{server → tasks/server}/api/chatgptRoutes.js +0 -0
  189. /package/lib/{server → tasks/server}/api/local.js +0 -0
  190. /package/lib/{server → tasks/server}/api/manifest.js +0 -0
  191. /package/lib/{shared → tasks/shared}/dates.js +0 -0
  192. /package/lib/{shared → tasks/shared}/directTask.js +0 -0
  193. /package/lib/{shared → tasks/shared}/hierarchy.js +0 -0
  194. /package/lib/{shared → tasks/shared}/milestoneGoals.js +0 -0
  195. /package/lib/{shared → tasks/shared}/milestoneOrder.js +0 -0
  196. /package/lib/{shared → tasks/shared}/preflightInput.js +0 -0
  197. /package/lib/{shared → tasks/shared}/preflightRunner.js +0 -0
  198. /package/lib/{shared → tasks/shared}/refs.js +0 -0
  199. /package/lib/{shared → tasks/shared}/repos.js +0 -0
  200. /package/lib/{shared → tasks/shared}/scopeView.js +0 -0
  201. /package/lib/{shared → tasks/shared}/tags.js +0 -0
  202. /package/lib/{shared → tasks/shared}/taskBlock.js +0 -0
  203. /package/lib/{shared → tasks/shared}/types.js +0 -0
  204. /package/lib/{shared → tasks/shared}/workTarget.js +0 -0
@@ -0,0 +1,30 @@
1
+ import { ACCEPTANCE_KEYS, readAcceptance } from "../../features/requirements/shared/acceptance.js";
2
+ import { BLOCK_KEYS, readBlock } from "../../shared/taskBlock.js";
3
+ import { COMPLETION_KEYS, readCompletion } from "../../features/records/shared/completionRecord.js";
4
+ import { PREMISE_KEYS, readPremises } from "../../features/records/shared/reviewCandidate.js";
5
+ import { readRework, REWORK_KEYS } from "../../features/records/shared/reworkHistory.js";
6
+ import { readRequirement, REQUIREMENT_KEYS } from "../../features/requirements/shared/requirementSource.js";
7
+ export const TASK_FIELD_GROUPS = [
8
+ { name: "受け入れ基準・証拠・基準の根拠", keys: ACCEPTANCE_KEYS, problems: "acceptanceProblems", read: readAcceptance },
9
+ { name: "停止と履歴", keys: BLOCK_KEYS, problems: "blockProblems", read: readBlock },
10
+ { name: "完了の記録", keys: COMPLETION_KEYS, problems: "completionProblems", read: readCompletion },
11
+ { name: "手戻りの履歴", keys: REWORK_KEYS, problems: "reworkProblems", read: readRework },
12
+ ];
13
+ export const REQUEST_FIELD_GROUPS = [
14
+ { name: "要求の根拠・回答", keys: REQUIREMENT_KEYS, problems: "requirementProblems", read: readRequirement },
15
+ { name: "完了の記録", keys: COMPLETION_KEYS, problems: "completionProblems", read: readCompletion },
16
+ { name: "前提の変更", keys: PREMISE_KEYS, problems: "premiseProblems", read: readPremises },
17
+ ];
18
+ /** まとまりを順に読んだ値(読む順は定義の順。後のまとまりが前の項目を上書きしない) */
19
+ export const readFieldGroups = (groups, d) => Object.assign({}, ...groups.map((g) => g.read(d)));
20
+ /** 元の値のまま書き戻す項目(problems があるまとまりの項目) */
21
+ export const keepRawOf = (groups) => (item) => groups.flatMap((g) => (item[g.problems]?.length ? g.keys : []));
22
+ /** ファイルに書かない項目(problems) */
23
+ export const problemKeysOf = (groups) => [...new Set(groups.map((g) => g.problems))];
24
+ /** CLI・API の入力から外す項目(まとまりの項目と problems。p3 が操作でだけ変える) */
25
+ export const managedKeysOf = (groups) => [...new Set(groups.flatMap((g) => [...g.keys, g.problems]))];
26
+ /** 入力から p3 が管理する項目を外す(値をそのまま書く道を持たない) */
27
+ export function withoutManaged(input, groups) {
28
+ const managed = new Set(managedKeysOf(groups));
29
+ return Object.fromEntries(Object.entries(input).filter(([k]) => !managed.has(k)));
30
+ }
@@ -0,0 +1,30 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { writeFileAtomic } from "../../../kit/fsutil.js";
3
+ export async function readJsonRecord(path, policy) {
4
+ let text;
5
+ try {
6
+ text = await readFile(path, "utf8");
7
+ }
8
+ catch (e) {
9
+ const err = e;
10
+ if (err.code === "ENOENT")
11
+ return policy.missing();
12
+ if (policy.readFailed)
13
+ return policy.readFailed(err);
14
+ throw e;
15
+ }
16
+ if (text === "" && policy.blank)
17
+ return policy.blank();
18
+ let raw;
19
+ try {
20
+ raw = JSON.parse(text);
21
+ }
22
+ catch (e) {
23
+ return policy.invalidJson(e.message);
24
+ }
25
+ return policy.shape(raw);
26
+ }
27
+ /** 整形した JSON を置き換えで書く(末尾に改行) */
28
+ export async function writeJsonRecord(path, value) {
29
+ await writeFileAtomic(path, `${JSON.stringify(value, null, 2)}\n`);
30
+ }
@@ -1,10 +1,5 @@
1
- import { ACCEPTANCE_KEYS, readAcceptance } from "../../shared/acceptance.js";
2
- import { BLOCK_KEYS, readBlock } from "../../shared/taskBlock.js";
3
- import { COMPLETION_KEYS, readCompletion } from "../../shared/completionRecord.js";
4
- import { PREMISE_KEYS, readPremises } from "../../shared/reviewCandidate.js";
5
- import { readRework, REWORK_KEYS } from "../../shared/reworkHistory.js";
6
- import { qualityVersion, readQuality } from "../../shared/quality.js";
7
- import { readRequirement, REQUIREMENT_KEYS } from "../../shared/requirementSource.js";
1
+ import { qualityVersion, readQuality } from "../../features/quality/shared/quality.js";
2
+ import { keepRawOf, problemKeysOf, readFieldGroups, REQUEST_FIELD_GROUPS, TASK_FIELD_GROUPS } from "./fieldGroups.js";
8
3
  import { repoNameProblem } from "../../shared/repos.js";
9
4
  import { isPreflightRunner } from "../../shared/preflightRunner.js";
10
5
  import { isTaskStatus, RELATION_TYPES, REQUEST_STATUSES } from "../../shared/types.js";
@@ -45,10 +40,8 @@ export const normalizeTaskIn = (requestId) => (d, body, id) => ({
45
40
  doneAt: d.doneAt ? iso(d.doneAt) : undefined,
46
41
  checkedAt: d.checkedAt ? iso(d.checkedAt) : undefined,
47
42
  record: str(d.record)?.trim() || undefined,
48
- ...readAcceptance(d),
49
- ...readBlock(d),
50
- ...readCompletion(d),
51
- ...readRework(d),
43
+ // 受け入れ基準・停止・完了の記録・手戻り(fieldGroups.ts)
44
+ ...readFieldGroups(TASK_FIELD_GROUPS, d),
52
45
  relations: normalizeRelations(d.relations),
53
46
  rev: num(d.rev) ?? 1,
54
47
  createdAt: iso(d.createdAt),
@@ -57,17 +50,12 @@ export const normalizeTaskIn = (requestId) => (d, body, id) => ({
57
50
  body,
58
51
  });
59
52
  /** タスクのうちファイルに書かないキー(場所から決まるもの・読んだときの問題) */
60
- export const TASK_DERIVED = ["request", "ref", "acceptanceProblems", "blockProblems", "completionProblems", "reworkProblems"];
61
- /** 基準・証拠が壊れていたら、関係のない更新ではファイルの元の値のまま書き戻す(shared/acceptance.ts) */
62
- export const taskKeepRaw = (t) => [
63
- ...(t.acceptanceProblems?.length ? ACCEPTANCE_KEYS : []),
64
- ...(t.blockProblems?.length ? BLOCK_KEYS : []),
65
- ...(t.completionProblems?.length ? COMPLETION_KEYS : []),
66
- ...(t.reworkProblems?.length ? REWORK_KEYS : []),
67
- ];
53
+ export const TASK_DERIVED = ["request", "ref", ...problemKeysOf(TASK_FIELD_GROUPS)];
54
+ /** 項目のまとまりが壊れていたら、関係のない更新ではファイルの元の値のまま書き戻す(fieldGroups.ts) */
55
+ export const taskKeepRaw = keepRawOf(TASK_FIELD_GROUPS);
68
56
  export const TASK_KEY_ORDER = [
69
57
  "id", "title", "status", "repo", "labels", "areas", "outputs", "repoOutputs", "record",
70
- "acceptanceCriteria", "acceptanceEvidence", "acceptanceSeq", "acceptanceSources", "block", "blockHistory", "relations", "rev", "createdAt", "startedAt", "doneAt", "checkedAt", "updatedAt", "updatedBy", "reworkHistory", "completionRecords",
58
+ "acceptanceCriteria", "acceptanceEvidence", "acceptanceSeq", "acceptanceSources", "acceptanceSourceSeq", "block", "blockHistory", "relations", "rev", "createdAt", "startedAt", "doneAt", "checkedAt", "updatedAt", "updatedBy", "reworkHistory", "completionRecords",
71
59
  ];
72
60
  export function normalizeRequest(d, body, id) {
73
61
  const status = str(d.status);
@@ -86,9 +74,8 @@ export function normalizeRequest(d, body, id) {
86
74
  tags: strs(d.tags),
87
75
  ...(d.workstreams && typeof d.workstreams === "object" ? { workstreams: normalizeWorkstreams(d.workstreams) } : {}),
88
76
  lastPreflight: str(d.lastPreflight),
89
- ...readRequirement(d),
90
- ...readCompletion(d),
91
- ...readPremises(d),
77
+ // 要求の根拠・完了の記録・前提(fieldGroups.ts)
78
+ ...readFieldGroups(REQUEST_FIELD_GROUPS, d),
92
79
  rev: num(d.rev) ?? 1,
93
80
  createdAt: iso(d.createdAt),
94
81
  updatedAt: iso(d.updatedAt),
@@ -101,9 +88,9 @@ export const REQUEST_KEY_ORDER = [
101
88
  "requirementSources", "requirementSeq", "clarifyAnswers", "rev", "createdAt", "updatedAt", "updatedBy", "premiseChanges", "completionRecords",
102
89
  ];
103
90
  /** 要望のうちファイルに書かないキー(読んだときの問題) */
104
- export const REQUEST_DERIVED = ["requirementProblems", "completionProblems", "premiseProblems"];
105
- /** 要求の根拠・回答が壊れていたら、関係のない更新ではファイルの元の値のまま書き戻す(shared/requirementSource.ts) */
106
- export const requestKeepRaw = (r) => [...(r.requirementProblems?.length ? REQUIREMENT_KEYS : []), ...(r.completionProblems?.length ? COMPLETION_KEYS : []), ...(r.premiseProblems?.length ? PREMISE_KEYS : [])];
91
+ export const REQUEST_DERIVED = problemKeysOf(REQUEST_FIELD_GROUPS);
92
+ /** 項目のまとまりが壊れていたら、関係のない更新ではファイルの元の値のまま書き戻す(fieldGroups.ts) */
93
+ export const requestKeepRaw = keepRawOf(REQUEST_FIELD_GROUPS);
107
94
  /** preflight.runner(未設定は書かない。読めない値は invalidRunner に残し、担当を推測しない) */
108
95
  function runnerOf(v) {
109
96
  const raw = str(v)?.trim();
@@ -1,8 +1,8 @@
1
1
  import { readdir, readFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
3
  import { randomBytes } from "node:crypto";
4
- import { parseFrontmatter, stringifyFrontmatter } from "./frontmatter.js";
5
- import { createExclusive, nowIso } from "./fsutil.js";
4
+ import { parseFrontmatter, stringifyFrontmatter } from "../../../kit/frontmatter.js";
5
+ import { createExclusive, nowIso } from "../../../kit/fsutil.js";
6
6
  export const NOTE_ID = /^N-\d{8}-\d{6}-[0-9a-f]{4}$/;
7
7
  /**
8
8
  * requests/<要望ID>/notes/N-....md Preflight へのメモ(1件1ファイル。書き足すだけで、直さない)
@@ -1,17 +1,39 @@
1
1
  import { readdir, readFile, mkdir, rm, stat } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
- import { readDraftCriteria } from "../../shared/acceptance.js";
4
- import { readCriterionSources } from "../../shared/requirementSource.js";
5
- import { parseFrontmatter, stringifyFrontmatter } from "./frontmatter.js";
3
+ import { readDraftCriteria, readSourceSeq } from "../../features/requirements/shared/acceptance.js";
4
+ import { readCriterionSources } from "../../features/requirements/shared/requirementSource.js";
5
+ import { parseFrontmatter, stringifyFrontmatter } from "../../../kit/frontmatter.js";
6
6
  /** 案の受け入れ基準と要求の根拠(無い古い案は何も足さない。読めない項目は acceptanceProblems に理由) */
7
- function draftCriteriaOf(raw, rawSources) {
7
+ function draftCriteriaOf(raw, rawSources, rawSourceSeq) {
8
8
  const { criteria, problems = [] } = readDraftCriteria(raw);
9
9
  const sourceProblems = [];
10
10
  const sources = readCriterionSources(rawSources, sourceProblems);
11
+ const seq = readSourceSeq(rawSourceSeq, sourceProblems);
11
12
  const all = [...problems, ...sourceProblems];
12
- return { ...(criteria ? { acceptanceCriteria: criteria } : {}), ...(sources ? { acceptanceSources: sources } : {}), ...(all.length ? { acceptanceProblems: all } : {}) };
13
+ return {
14
+ ...(criteria ? { acceptanceCriteria: criteria } : {}),
15
+ ...(sources ? { acceptanceSources: sources } : {}),
16
+ ...(seq !== undefined ? { acceptanceSourceSeq: seq } : {}),
17
+ ...(all.length ? { acceptanceProblems: all } : {}),
18
+ };
19
+ }
20
+ import { withFileLock, writeFileAtomic } from "../../../kit/fsutil.js";
21
+ import { writeJsonRecord } from "./jsonRecord.js";
22
+ /** 案のファイル1つを読む(f: ファイル名。key が無い古い案はファイル名から) */
23
+ function draftOf(f, text) {
24
+ const { data, body } = parseFrontmatter(text);
25
+ return {
26
+ key: String(data.key ?? f.replace(/\.md$/, "")),
27
+ title: String(data.title ?? ""),
28
+ description: body.trim(),
29
+ areas: Array.isArray(data.areas) ? data.areas.map(String) : [],
30
+ dependsOn: Array.isArray(data.dependsOn) ? data.dependsOn.map(String) : [],
31
+ supersedes: Array.isArray(data.supersedes) ? data.supersedes.map(String) : [],
32
+ include: data.include !== false,
33
+ ...("repo" in data ? { repo: data.repo === null || data.repo === "" || data.repo === "none" ? null : String(data.repo) } : {}),
34
+ ...draftCriteriaOf(data.acceptanceCriteria, data.acceptanceSources, data.acceptanceSourceSeq),
35
+ };
13
36
  }
14
- import { writeFileAtomic } from "./fsutil.js";
15
37
  /**
16
38
  * requests/<要望ID>/preflight/<RUN-ID>/
17
39
  * run.json 評価結果・ログ・文脈(機械向け)
@@ -32,7 +54,7 @@ export class PreflightStore {
32
54
  async save(run) {
33
55
  // 中断の依頼は別のファイル(cancel-request.json。頼む側と実行する側が同じファイルを書き合わないように)
34
56
  const { drafts, children, cancelRequested, ...meta } = run;
35
- await writeFileAtomic(join(this.runDir(run.requestId, run.id), "run.json"), JSON.stringify(meta, null, 2) + "\n");
57
+ await writeJsonRecord(join(this.runDir(run.requestId, run.id), "run.json"), meta);
36
58
  }
37
59
  async saveDrafts(requestId, runId, drafts) {
38
60
  const dir = join(this.runDir(requestId, runId), "drafts");
@@ -46,6 +68,10 @@ export class PreflightStore {
46
68
  const { description, acceptanceProblems: _p, ...meta } = d;
47
69
  await writeFileAtomic(join(this.runDir(requestId, runId), "drafts", `${d.key}.md`), stringifyFrontmatter({ ...meta, include: d.include }, description));
48
70
  }
71
+ /** 案を読んで直して書くまでを、同じ案の他の更新と重ねない(同じマシンのプロセスの間。根拠の採番を同じ番号で払い出さない) */
72
+ withDraftLock(requestId, runId, key, fn) {
73
+ return withFileLock(join(this.runDir(requestId, runId), "drafts", `.${key}.lock`), fn);
74
+ }
49
75
  /** 案のファイルの frontmatter の元の値(読めなかった項目を、関係のない更新で消さないため) */
50
76
  async rawDraftField(requestId, runId, key, field) {
51
77
  const text = await readFile(join(this.runDir(requestId, runId), "drafts", `${key}.md`), "utf8").catch(() => undefined);
@@ -60,22 +86,19 @@ export class PreflightStore {
60
86
  const dir = join(this.runDir(requestId, runId), "drafts");
61
87
  const files = await readdir(dir).catch(() => []);
62
88
  const drafts = [];
63
- for (const f of files.filter((f) => f.endsWith(".md"))) {
64
- const { data, body } = parseFrontmatter(await readFile(join(dir, f), "utf8"));
65
- drafts.push({
66
- key: String(data.key ?? f.replace(/\.md$/, "")),
67
- title: String(data.title ?? ""),
68
- description: body.trim(),
69
- areas: Array.isArray(data.areas) ? data.areas.map(String) : [],
70
- dependsOn: Array.isArray(data.dependsOn) ? data.dependsOn.map(String) : [],
71
- supersedes: Array.isArray(data.supersedes) ? data.supersedes.map(String) : [],
72
- include: data.include !== false,
73
- ...("repo" in data ? { repo: data.repo === null || data.repo === "" || data.repo === "none" ? null : String(data.repo) } : {}),
74
- ...draftCriteriaOf(data.acceptanceCriteria, data.acceptanceSources),
75
- });
76
- }
89
+ for (const f of files.filter((f) => f.endsWith(".md")))
90
+ drafts.push(draftOf(f, await readFile(join(dir, f), "utf8")));
77
91
  return drafts.sort((a, b) => a.key.localeCompare(b.key, undefined, { numeric: true }));
78
92
  }
93
+ /**
94
+ * 1つの案を読み直す(loadDrafts と同じ規則。無ければ undefined)。案の更新は保存した後にこれで読み直して返し、更新の応答と
95
+ * 再読込で基準・根拠・採番と読めない理由(acceptanceProblems)を同じにする
96
+ */
97
+ async loadDraft(requestId, runId, key) {
98
+ const f = `${key}.md`;
99
+ const text = await readFile(join(this.runDir(requestId, runId), "drafts", f), "utf8").catch(() => undefined);
100
+ return text === undefined ? undefined : draftOf(f, text);
101
+ }
79
102
  async saveChild(requestId, runId, c) {
80
103
  const { description, ...meta } = c;
81
104
  await writeFileAtomic(join(this.runDir(requestId, runId), "children", `${c.key}.md`), stringifyFrontmatter({ ...meta, include: c.include }, description));
@@ -1,6 +1,6 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import YAML from "yaml";
3
- import { writeFileAtomic } from "./fsutil.js";
3
+ import { writeFileAtomic } from "../../../kit/fsutil.js";
4
4
  /** 設定の保存(画面・p3 config)で書き換える項目。repos は p3 repo だけが項目ごとに書く(writeRepoEntry) */
5
5
  const ORDER = ["name", "description", "milestones", "branchPattern", "preflight"];
6
6
  /** ファイルの中の並び */
@@ -4,9 +4,9 @@ import { join } from "node:path";
4
4
  import YAML from "yaml";
5
5
  import { parseRef, REQUEST_ID, TASK_ID, taskId } from "../../shared/refs.js";
6
6
  import { milestoneGoalProblems, tidyMilestoneGoals } from "../../shared/milestoneGoals.js";
7
- import { QualityInputError, qualityPlain } from "../../shared/quality.js";
7
+ import { QualityInputError, qualityPlain } from "../../features/quality/shared/quality.js";
8
8
  import { fileLayout, folderLayout, MarkdownCollection, NotFoundError } from "./collection.js";
9
- import { newRequestId, withFileLock } from "./fsutil.js";
9
+ import { newRequestId, withFileLock } from "../../../kit/fsutil.js";
10
10
  import { normalizeProject, normalizeRequest, normalizeTaskIn, REQUEST_KEY_ORDER, REQUEST_DERIVED, requestKeepRaw, TASK_DERIVED, TASK_KEY_ORDER, taskKeepRaw } from "./normalize.js";
11
11
  import { AttachmentStore } from "./attachments.js";
12
12
  import { DataWatcher } from "./dataWatcher.js";
@@ -14,9 +14,9 @@ import { NoteStore } from "./noteStore.js";
14
14
  import { PreflightStore } from "./preflightStore.js";
15
15
  import { writeProjectFile, writeQualityFile } from "./projectFile.js";
16
16
  import { resolveRefs } from "../repoRefs.js";
17
- import { RELEASE_NOTES_DIR, ReleaseNoteStore } from "../releaseNotes/store.js";
18
- import { MILESTONE_REVIEWS_DIR, MilestoneReviewStore } from "../milestoneReview/store.js";
19
- import { TASK_REVIEWS_DIR, TaskReviewStore } from "../taskReview/store.js";
17
+ import { RELEASE_NOTES_DIR, ReleaseNoteStore } from "../../features/releaseNotes/core/store.js";
18
+ import { MILESTONE_REVIEWS_DIR, MilestoneReviewStore } from "../../features/milestoneReview/core/store.js";
19
+ import { TASK_REVIEWS_DIR, TaskReviewStore } from "../../features/taskReview/core/store.js";
20
20
  /** 保存する並びの各項目で、purpose / goals のキーが無ければ同じ ID の今の値を残す */
21
21
  function keepGoals(next, cur) {
22
22
  return next.map((m) => {
@@ -135,6 +135,12 @@ export class Workspace {
135
135
  refs() {
136
136
  return resolveRefs(this.project, { localRepos: this.localRepos });
137
137
  }
138
+ /** ディスクから読み直した別の Workspace(材料の取り出しなど。画面・CLI のキャッシュに左右されない。複数のファイルを同じ時点で読んだとは保証しない) */
139
+ static async snapshot(dataDir) {
140
+ const snap = new Workspace(dataDir);
141
+ await snap.load();
142
+ return snap;
143
+ }
138
144
  async load() {
139
145
  await this.loadAll(false);
140
146
  }
@@ -3,7 +3,7 @@ import { homedir } from "node:os";
3
3
  import { join, resolve } from "node:path";
4
4
  import YAML from "yaml";
5
5
  import { isTheme } from "../shared/types.js";
6
- import { withFileLock, writeFileAtomic } from "./store/fsutil.js";
6
+ import { withFileLock, writeFileAtomic } from "../../kit/fsutil.js";
7
7
  export const SETTINGS_SECTIONS = ["codex", "preflight", "serve"];
8
8
  export const PROJECT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
9
9
  /** 個人設定のファイル。XDG_CONFIG_HOME があればそれに従う(設定ファイルの置き場所を決めるだけで、プロジェクトの切り替えには使わない) */
@@ -1,5 +1,5 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { slugify } from "./store/fsutil.js";
2
+ import { slugify } from "../../kit/fsutil.js";
3
3
  import { repoTargetProblem, requestWorkstreams } from "../shared/workTarget.js";
4
4
  /** 作業先にできない(参照先に無い・参照だけ)。何も変えていない */
5
5
  export class RepoTargetError extends Error {
@@ -1,7 +1,7 @@
1
- import { metricScopeOf, metricsReport } from "../core/metrics/index.js";
2
- import { readManual, recordManual, removeManual } from "../core/metrics/manual.js";
1
+ import { metricScopeOf, metricsReport } from "../core/index.js";
2
+ import { readManual, recordManual, removeManual } from "../core/manual.js";
3
3
  import { MetricsError, METRIC_STATE_LABEL, METRIC_UNIT_LABEL } from "../shared/metrics.js";
4
- import { UsageError } from "./project.js";
4
+ import { UsageError } from "../../../../kit/usage.js";
5
5
  /**
6
6
  * 開発の指標(定義は core/metrics/definitions.ts)。読むだけ。
7
7
  *
@@ -1,6 +1,7 @@
1
- import { acceptanceStatus, evidenceBasisOf, EVIDENCE_BASIS_LABEL, EVIDENCE_BASIS_KINDS } from "../../shared/acceptance.js";
2
- import { median } from "../../shared/metrics.js";
3
- import { REWORK_CAUSE_LABEL, REWORK_CAUSES } from "../../shared/reworkHistory.js";
1
+ import { acceptanceStatus, evidenceBasisOf, EVIDENCE_BASIS_LABEL, EVIDENCE_BASIS_KINDS } from "../../requirements/shared/acceptance.js";
2
+ import { firstCompletion } from "../../records/shared/completionRecord.js";
3
+ import { median } from "../shared/metrics.js";
4
+ import { REWORK_CAUSE_LABEL, REWORK_CAUSES, reworkPerRev } from "../../records/shared/reworkHistory.js";
4
5
  /**
5
6
  * タスクの完了したレビューから集計に使う1件を選ぶ(一覧は core/taskReview/store.ts の list)。完了時刻(finishedAt)の新しいもの、
6
7
  * 同時刻なら run ID の大きいもの。読めない run(どれが最新か分からない)・完了時刻の無い完了の run があれば欠損にする
@@ -39,7 +40,7 @@ function reachOf(r, trigger) {
39
40
  if (r.completionProblems?.length)
40
41
  return { kind: "missing", reason: `完了の記録が読めません(${r.completionProblems.join(" / ")})` };
41
42
  const records = r.completionRecords ?? [];
42
- const first = records.find((c) => c.trigger === trigger);
43
+ const first = firstCompletion(records, trigger);
43
44
  if (first) {
44
45
  const at = time(first.at);
45
46
  const created = time(r.createdAt);
@@ -55,7 +56,7 @@ function reachOf(r, trigger) {
55
56
  if (r.status === "resolved")
56
57
  return { kind: "missing", reason: "対応済ですが対応済の記録がありません(記録を始める前のデータ)" };
57
58
  if (r.status === "done") {
58
- if (records.some((c) => c.trigger === "request_done"))
59
+ if (firstCompletion(records, "request_done"))
59
60
  return { kind: "not_reached" };
60
61
  return { kind: "missing", reason: "完了済ですが記録が無く、対応済を経たか分かりません", unknown: true };
61
62
  }
@@ -95,6 +96,17 @@ function durationMetric(trigger) {
95
96
  return { state, value: m === undefined ? null : round(m), targets, observed: hours.length, missing: missingItems.length, breakdown, missingItems };
96
97
  };
97
98
  }
99
+ /**
100
+ * 基準の集計を材料ごとに1回だけ行う(5つの基準の指標が同じ結果を使う)。材料(MetricsInput)はレポートごとに作るので、
101
+ * 集計もそのレポートの中だけで使われ、材料が要らなくなれば一緒に消える(WeakMap)
102
+ */
103
+ const criteriaCounts = new WeakMap();
104
+ function sharedCriteria(input) {
105
+ let c = criteriaCounts.get(input);
106
+ if (!c)
107
+ criteriaCounts.set(input, (c = countCriteria(input)));
108
+ return c;
109
+ }
98
110
  /** 今完了しているタスクの、今の基準と保存された証拠の照合(shared/acceptance.ts の acceptanceStatus) */
99
111
  function countCriteria(input) {
100
112
  const c = {
@@ -143,7 +155,7 @@ const CRITERION_LABEL = {
143
155
  };
144
156
  function criteriaMetric(state) {
145
157
  return (input) => {
146
- const c = countCriteria(input);
158
+ const c = sharedCriteria(input);
147
159
  const brokenTasks = c.missingItems.length;
148
160
  const value = c.byState[state];
149
161
  // 数えた基準が無いとき、欠損があれば「欠損で出せない」、無ければ「対象なし」(0 件とは言わない)
@@ -181,8 +193,7 @@ function reworkMetric(input) {
181
193
  missingItems.push({ target: t.ref, reason: `手戻りの履歴が読めません(${t.reworkProblems.join(" / ")})` });
182
194
  continue;
183
195
  }
184
- const seen = new Set();
185
- const list = (t.reworkHistory ?? []).filter((e) => !seen.has(e.rev) && seen.add(e.rev));
196
+ const list = reworkPerRev(t.reworkHistory);
186
197
  if (!list.length)
187
198
  without += 1;
188
199
  else
@@ -1,4 +1,4 @@
1
- import { MetricsError } from "../../shared/metrics.js";
1
+ import { MetricsError } from "../shared/metrics.js";
2
2
  import { METRIC_DEFINITIONS, selectTaskReview } from "./definitions.js";
3
3
  import { readManual } from "./manual.js";
4
4
  /**
@@ -21,27 +21,49 @@ export function metricScopeOf(ctx, milestone) {
21
21
  }
22
22
  return { kind: "milestone", id: milestone };
23
23
  }
24
- /** 今完了しているタスクのレビューを、selectTaskReview の規則で1件選んで読む(読むだけ) */
25
- async function reviewsOf(ctx, rid, tasks) {
26
- const out = {};
27
- for (const t of tasks) {
28
- if (t.status !== "done")
29
- continue;
30
- const key = `${rid}/${t.id}`;
24
+ /** 1回のレポートで同時に読む完了タスクのレビューの数の上限(要望をまたいでレポート全体で数える) */
25
+ export const REVIEW_READ_CONCURRENCY = 8;
26
+ /** 同時に動かす数を n までにする(待っているものは来た順に始める。終わったものの枠をそのまま次に渡す) */
27
+ function limiter(n) {
28
+ let running = 0;
29
+ const waiting = [];
30
+ return async (fn) => {
31
+ if (running < n)
32
+ running += 1;
33
+ else
34
+ await new Promise((go) => waiting.push(go));
35
+ try {
36
+ return await fn();
37
+ }
38
+ finally {
39
+ const next = waiting.shift();
40
+ if (next)
41
+ next();
42
+ else
43
+ running -= 1;
44
+ }
45
+ };
46
+ }
47
+ /**
48
+ * 今完了しているタスクのレビューを、selectTaskReview の規則で1件選んで読む(読むだけ)。タスクごとに一覧・選択・結果の取得を
49
+ * limit の中で並行に行い、結果はタスク ID に結ぶ(読み終わった順に関係なく、集計は要望・タスクの順で読む)
50
+ */
51
+ async function reviewsOf(ctx, rid, tasks, limit) {
52
+ const one = async (key) => {
31
53
  try {
32
54
  const sel = selectTaskReview(await ctx.ws.taskReviews.list(key));
33
55
  if (sel.state !== "ok")
34
- out[t.id] = sel;
35
- else {
36
- const rec = await ctx.ws.taskReviews.get(key, sel.run);
37
- out[t.id] = rec.result ? { state: "ok", run: sel.run, result: rec.result } : { state: "missing", reason: `${sel.run} の結果がありません` };
38
- }
56
+ return sel;
57
+ const rec = await ctx.ws.taskReviews.get(key, sel.run);
58
+ return rec.result ? { state: "ok", run: sel.run, result: rec.result } : { state: "missing", reason: `${sel.run} の結果がありません` };
39
59
  }
40
60
  catch (e) {
41
- out[t.id] = { state: "missing", reason: `レビューの記録が読めません: ${e.message}` };
61
+ return { state: "missing", reason: `レビューの記録が読めません: ${e.message}` };
42
62
  }
43
- }
44
- return out;
63
+ };
64
+ const done = tasks.filter((t) => t.status === "done");
65
+ const results = await Promise.all(done.map((t) => limit(() => one(`${rid}/${t.id}`))));
66
+ return Object.fromEntries(done.map((t, i) => [t.id, results[i]]));
45
67
  }
46
68
  export async function metricsInput(ctx, scope, manual) {
47
69
  const m = manual ?? (await readManual(ctx.ws.dataDir));
@@ -50,11 +72,13 @@ export async function metricsInput(ctx, scope, manual) {
50
72
  .list()
51
73
  .filter((r) => r.status !== "rejected" && (scope.kind === "project" || r.milestone === scope.id))
52
74
  .sort((a, b) => a.id.localeCompare(b.id));
75
+ // レビューの読み取りの上限は、このレポートの全部の要望で1つ
76
+ const limit = limiter(REVIEW_READ_CONCURRENCY);
53
77
  return {
54
78
  requests: await Promise.all(requests.map(async (request) => {
55
79
  const col = ctx.ws.tasksOf(request.id);
56
80
  const tasks = col.list();
57
- return { request, tasks, brokenTasks: [...col.errors.keys()].sort(), reviews: await reviewsOf(ctx, request.id, tasks) };
81
+ return { request, tasks, brokenTasks: [...col.errors.keys()].sort(), reviews: await reviewsOf(ctx, request.id, tasks, limit) };
58
82
  })),
59
83
  manual: { records: m.records.filter((r) => r.scope === scopeKey), ...(m.problem ? { problem: m.problem } : {}) },
60
84
  };
@@ -1,7 +1,7 @@
1
- import { readFile } from "node:fs/promises";
2
1
  import { join } from "node:path";
3
- import { MetricsError } from "../../shared/metrics.js";
4
- import { withFileLock, writeFileAtomic } from "../store/fsutil.js";
2
+ import { MetricsError } from "../shared/metrics.js";
3
+ import { withFileLock } from "../../../../kit/fsutil.js";
4
+ import { readJsonRecord, writeJsonRecord } from "../../../core/store/jsonRecord.js";
5
5
  import { METRIC_DEFINITIONS } from "./definitions.js";
6
6
  /**
7
7
  * 人が記録する指標の値(費用・リリース後の不具合など。記録から出せないもの)の保存。記録は CLI の p3 metrics record からだけ(API・画面は読むだけ)。
@@ -10,7 +10,8 @@ import { METRIC_DEFINITIONS } from "./definitions.js";
10
10
  * <data>/metrics/.manual.lock 書くときのロック(同じマシンのプロセスの間)
11
11
  *
12
12
  * - 1件は 指標・範囲(project かマイルストーン ID)・観測期間(開始日・終了日)・単位 で決まる。同じ内容の再送は何も変えない。値・出典・メモを
13
- * 変える訂正は、読んだ版(rev)を渡したときだけ(渡さない・違えば競合で何も書かない)
13
+ * 変える訂正は、読んだ版(rev)を渡したときだけ(渡さない・違えば競合で何も書かない)。訂正の updatedBy はその訂正の主体で、主体が
14
+ * 分からない訂正では省く(前の更新者を残さない)。createdBy・createdAt は作ったときのまま
14
15
  * - 値は0以上(不具合は整数)。費用は通貨コードごとで、通貨・期間の違う値を1つに合算しない。範囲の間(全体とマイルストーン)も合算しない
15
16
  * - ロックの中で読み直してから書き、置き換えで書く(途中の状態を読ませない)。壊れたファイルは空とみなさず、読めないと知らせて書かない
16
17
  * - 記録のあるマイルストーンは通常の削除で消さない(core/requestOps.ts の checkMilestoneRemoval)。直接編集で消えたら知らせる
@@ -58,26 +59,25 @@ function readRecord(raw, i) {
58
59
  }
59
60
  /** 記録を読む。無ければ空、壊れていれば problem(空とみなさない) */
60
61
  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
- }
62
+ const broken = (m) => ({ records: [], seq: 0, problem: `${DIR}/${FILE} が読めません(直してください。記録は書き足しません): ${m}` });
63
+ return readJsonRecord(manualFile(dataDir), {
64
+ missing: () => ({ records: [], seq: 0 }),
65
+ readFailed: (e) => ({ records: [], seq: 0, problem: `読めません: ${e.message}` }),
66
+ invalidJson: broken,
67
+ shape: (raw) => {
68
+ try {
69
+ const j = raw;
70
+ if (!j || typeof j !== "object" || j.version !== 1 || !Array.isArray(j.records))
71
+ throw new Error("{version: 1, records: [...]} の形ではありません");
72
+ const records = j.records.map(readRecord);
73
+ const seq = Math.max(Number.isInteger(j.seq) ? j.seq : 0, ...records.map((r) => Number(r.id.slice(1))));
74
+ return { records, seq };
75
+ }
76
+ catch (e) {
77
+ return broken(e.message);
78
+ }
79
+ },
80
+ });
81
81
  }
82
82
  const manualSpec = (metric) => {
83
83
  const d = METRIC_DEFINITIONS.find((x) => x.id === metric);
@@ -124,9 +124,7 @@ export function cleanManual(ctx, i) {
124
124
  return { metric: i.metric, scope, from: i.from, to: i.to, value, unit, source, ...(note ? { note } : {}) };
125
125
  }
126
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
- }
127
+ const writeManual = (dataDir, f) => writeJsonRecord(manualFile(dataDir), f);
130
128
  async function locked(dataDir, fn) {
131
129
  return withFileLock(lockFile(dataDir), async () => {
132
130
  const cur = await readManual(dataDir);
@@ -159,7 +157,8 @@ export async function recordManual(ctx, input, opts = {}) {
159
157
  }
160
158
  if (opts.expectedRev !== hit.rev)
161
159
  throw new MetricsError(`${hit.id} は他で変わりました(読んだ版 ${opts.expectedRev}・今の版 ${hit.rev})。p3 metrics で確かめてからやり直してください`, "metrics_conflict");
162
- const { note: _n, ...rest } = hit;
160
+ // 更新者はこの訂正をした人だけ(主体が分からない訂正では前の人を残さず省く)。作った人・日時は残す
161
+ const { note: _n, updatedBy: _u, ...rest } = hit;
163
162
  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
163
  await writeManual(dataDir, { version: 1, seq: cur.seq, records: cur.records.map((r) => (r.id === hit.id ? record : r)) });
165
164
  return { record, changed: true, created: false };
@@ -0,0 +1,8 @@
1
+ import { Hono } from "hono";
2
+ import { metricScopeOf, metricsReport } from "../core/index.js";
3
+ /** 開発の指標の API(読むだけ)。GET /metrics[?milestone=<ID>]。API の組み立て(server/api/routes.ts)がつなぐ */
4
+ export function metricsRoutes(ctx) {
5
+ const app = new Hono();
6
+ app.get("/metrics", async (c) => c.json(await metricsReport(ctx, metricScopeOf(ctx, c.req.query("milestone")))));
7
+ return app;
8
+ }
@@ -2,23 +2,14 @@ import { execFile } from "node:child_process";
2
2
  import { createHash } from "node:crypto";
3
3
  import { isAbsolute, relative } from "node:path";
4
4
  import { promisify } from "node:util";
5
- import { gitHistory } from "../repoRefs.js";
5
+ import { gitHistory } from "../../../core/repoRefs.js";
6
6
  const run = promisify(execFile);
7
7
  /**
8
8
  * マイルストーンレビューのコードの材料。Codex には参照先を読むだけでマウントして、コードと git の履歴を読ませる。
9
9
  * ここでは、そのとき読んだものが後から分かるように、参照先ごとの状態・HEAD・ブランチ・未コミットの変更の数と、
10
10
  * タスクの成果物に残したコミット(参照先の履歴にあるか)を取り出す。コードの中身は保存しない。git は読むだけの操作だけ。
11
11
  */
12
- /** 成果物の文字列からコミットを取り出す(…/commit/<sha> の URL か、sha だけの文字列) */
13
- export function commitsInOutput(output) {
14
- const out = new Set();
15
- for (const m of output.matchAll(/\/commit\/([0-9a-f]{7,40})\b/gi))
16
- out.add(m[1].toLowerCase());
17
- const bare = output.trim();
18
- if (/^[0-9a-f]{7,40}$/i.test(bare))
19
- out.add(bare.toLowerCase());
20
- return [...out];
21
- }
12
+ import { commitsInOutput } from "../../../shared/commitRefs.js";
22
13
  const git = async (local, args) => (await run("git", ["-C", local, ...args], { timeout: 10_000, maxBuffer: 4 * 1024 * 1024 })).stdout.trim();
23
14
  const tryGit = (local, args) => git(local, args).catch(() => undefined);
24
15
  /** git を動かして標準出力を返す(標準入力を渡せる。大きな差分も読む) */