@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.
- package/README.md +33 -33
- package/dist/web/assets/CompletionReview-gZKZrDu_.js +1 -0
- package/dist/web/assets/ImprovementDialog-Dno6dPnG.js +1 -0
- package/dist/web/assets/Outputs-BgHalMGb.js +1 -0
- package/dist/web/assets/RequestStatus-hZcBUUIu.js +1 -0
- package/dist/web/assets/Tabs-C3NmwCc3.js +1 -0
- package/dist/web/assets/TagInput-B2b862qn.js +1 -0
- package/dist/web/assets/TaskDrawer-4BQBELXa.js +6 -0
- package/dist/web/assets/_requestId-BMAG1t3o.js +1 -0
- package/dist/web/assets/_requestId-tbg2pA2S.js +1 -0
- package/dist/web/assets/archive-DMl6WyOe.js +1 -0
- package/dist/web/assets/board-BMTcHKyt.js +1 -0
- package/dist/web/assets/done-CL6Nlsua.js +1 -0
- package/dist/web/assets/draft-BvGxfD7v.js +2 -0
- package/dist/web/assets/index-Dp7Fc4VI.css +2 -0
- package/dist/web/assets/index-KdlgMitg.js +12 -0
- package/dist/web/assets/metrics-Cu7gJ7Rk.js +1 -0
- package/dist/web/assets/new-DTXWHuFO.js +1 -0
- package/dist/web/assets/outputs-CXqnjSqV.js +1 -0
- package/dist/web/assets/preflightInput-ClKwkp8R.js +2 -0
- package/dist/web/assets/preload-helper-oLCrNCwz.js +1 -0
- package/dist/web/assets/quality-RFd-7k3r.js +1 -0
- package/dist/web/assets/release-notes-Bpdi6RdY.js +5 -0
- package/dist/web/assets/requestData-CbFxwW5w.js +1 -0
- package/dist/web/assets/routes-BIt8bExF.js +6 -0
- package/dist/web/assets/settings-CsCqF_1B.js +1 -0
- package/dist/web/assets/taskReview-_WCgnQit.js +1 -0
- package/dist/web/assets/ui-BGK72r3u.js +1 -0
- package/dist/web/assets/workTarget-CySfKyfB.js +30 -0
- package/dist/web/index.html +4 -4
- package/docs/architecture.md +610 -33
- package/docs/development.md +61 -17
- package/docs/how-to-use.md +554 -17
- package/docs/installation.md +235 -144
- package/docs/publishing.md +1 -1
- package/lib/cli/agentsStatus.js +197 -0
- package/lib/cli/args.js +111 -2
- package/lib/cli/guide.js +27 -0
- package/lib/cli/guide.md +214 -0
- package/lib/cli/help.js +74 -1
- package/lib/cli/main.js +97 -17
- package/lib/cli/metricsCommands.js +77 -0
- package/lib/cli/output.js +19 -1
- package/lib/cli/preflightCommands.js +7 -1
- package/lib/cli/project.js +13 -24
- package/lib/cli/qualityCommands.js +188 -0
- package/lib/cli/readOnly.js +17 -0
- package/lib/cli/requestCommands.js +33 -4
- package/lib/cli/requirementCommands.js +288 -0
- package/lib/cli/retroCommands.js +106 -0
- package/lib/cli/revisitCommands.js +73 -0
- package/lib/cli/showView.js +183 -4
- package/lib/cli/taskCommands.js +341 -20
- package/lib/cli/taskReviewCommands.js +178 -0
- package/lib/cli/userConfig.js +47 -0
- package/lib/core/completionRefs.js +46 -0
- package/lib/core/context.js +4 -1
- package/lib/core/metrics/definitions.js +434 -0
- package/lib/core/metrics/index.js +88 -0
- package/lib/core/metrics/manual.js +180 -0
- package/lib/core/milestoneReview/material.js +11 -1
- package/lib/core/milestoneReview/mockReviewer.js +1 -0
- package/lib/core/milestoneReview/review.js +70 -6
- package/lib/core/milestoneReview/service.js +29 -93
- package/lib/core/milestoneReview/store.js +12 -62
- package/lib/core/ops.js +23 -3
- package/lib/core/preflight/carryover.js +6 -2
- package/lib/core/preflight/codexEngine.js +34 -17
- package/lib/core/preflight/diagnose.js +4 -9
- package/lib/core/preflight/engine.js +15 -0
- package/lib/core/preflight/hostPaths.js +260 -0
- package/lib/core/preflight/input.js +33 -5
- package/lib/core/preflight/instructions.js +36 -2
- package/lib/core/preflight/mockEngine.js +24 -2
- package/lib/core/preflight/render.js +22 -3
- package/lib/core/preflight/service.js +99 -8
- package/lib/core/preflight/uiRender.js +3 -0
- package/lib/core/projectRegistry.js +3 -3
- package/lib/core/quality.js +21 -0
- package/lib/core/qualityImprovement.js +221 -0
- package/lib/core/requestOps.js +294 -11
- package/lib/core/retrospective.js +208 -0
- package/lib/core/reviewCandidates.js +56 -0
- package/lib/core/reviewRuns.js +205 -0
- package/lib/core/store/archivedTasks.js +74 -0
- package/lib/core/store/collection.js +32 -3
- package/lib/core/store/normalize.js +35 -2
- package/lib/core/store/preflightStore.js +23 -1
- package/lib/core/store/projectFile.js +10 -0
- package/lib/core/store/workspace.js +49 -3
- package/lib/core/taskReview/material.js +459 -0
- package/lib/core/taskReview/mockReviewer.js +30 -0
- package/lib/core/taskReview/paths.js +15 -0
- package/lib/core/taskReview/review.js +312 -0
- package/lib/core/taskReview/service.js +187 -0
- package/lib/core/taskReview/store.js +214 -0
- package/lib/server/api/manifest.js +104 -5
- package/lib/server/api/milestoneReviewRoutes.js +4 -3
- package/lib/server/api/routes.js +265 -17
- package/lib/server/api/taskReviewRoutes.js +66 -0
- package/lib/server/server.js +2 -2
- package/lib/shared/acceptance.js +618 -0
- package/lib/shared/completionRecord.js +327 -0
- package/lib/shared/metrics.js +42 -0
- package/lib/shared/milestoneReview.js +2 -1
- package/lib/shared/preflightInput.js +1 -1
- package/lib/shared/quality.js +391 -0
- package/lib/shared/qualityImprovement.js +1 -0
- package/lib/shared/qualityTemplates.js +31 -0
- package/lib/shared/requirementSource.js +635 -0
- package/lib/shared/retrospective.js +286 -0
- package/lib/shared/reviewCandidate.js +308 -0
- package/lib/shared/reworkHistory.js +81 -0
- package/lib/shared/taskBlock.js +142 -0
- package/lib/shared/taskReview.js +56 -0
- package/package.json +3 -2
- package/skills/p3/SKILL.md +9 -152
- package/dist/web/assets/Outputs-ddwte0jj.js +0 -1
- package/dist/web/assets/RequestStatus-Bg1OLbRc.js +0 -1
- package/dist/web/assets/Tabs-DTmggzgg.js +0 -1
- package/dist/web/assets/TagInput-BHAgjLP7.js +0 -1
- package/dist/web/assets/TaskDrawer-Dz_5c2NH.js +0 -3
- package/dist/web/assets/_requestId-D9-gtIcG.js +0 -1
- package/dist/web/assets/_requestId-DzCNYvqf.js +0 -30
- package/dist/web/assets/appCtx-Cm24VpAf.js +0 -1
- package/dist/web/assets/board-MCHcZ-PU.js +0 -1
- package/dist/web/assets/done-zq10Bt08.js +0 -1
- package/dist/web/assets/draft-CfJeyLOl.js +0 -1
- package/dist/web/assets/index-Ce0ndpne.js +0 -12
- package/dist/web/assets/index-D68mkSnw.css +0 -2
- package/dist/web/assets/new-9TKiNT4O.js +0 -1
- package/dist/web/assets/preflightInput-BAeEJYUK.js +0 -2
- package/dist/web/assets/preload-helper-FBLw7u7x.js +0 -1
- package/dist/web/assets/release-notes-hK5XezLW.js +0 -5
- package/dist/web/assets/requestData-BnN7mctX.js +0 -1
- package/dist/web/assets/routes-usHwrrA0.js +0 -3
- package/dist/web/assets/settings-BVZDnL6O.js +0 -1
- package/dist/web/assets/workTarget-Cijqq4yH.js +0 -1
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { reworkLine } from "../shared/reworkHistory.js";
|
|
4
|
+
import { addJudgment, assessmentVersion, JUDGMENT_LIMITS, latestJudgment, MILESTONE_REVIEW_SECTIONS, riskCounts, TASK_REVIEW_SECTIONS, confirmTarget, currentTarget, readRetrospective, retroCandidates, RetrospectiveError, } from "../shared/retrospective.js";
|
|
5
|
+
import { getArchivedTask, listArchivedTasks } from "./store/archivedTasks.js";
|
|
6
|
+
import { NotFoundError } from "./store/collection.js";
|
|
7
|
+
import { withFileLock, writeFileAtomic } from "./store/fsutil.js";
|
|
8
|
+
/**
|
|
9
|
+
* 要望の振り返りの保存と読み取り(規則は shared/retrospective.ts)。記録は requests/<要望ID>/retrospective.json で、要望のロック
|
|
10
|
+
* (requestLock。要望・タスクの保存と同じ)の中で、読み直してから版を照らして書く。読み取りはファイルを書かない
|
|
11
|
+
*/
|
|
12
|
+
export const RETRO_FILE = "retrospective.json";
|
|
13
|
+
const pathOf = (ctx, rid) => join(ctx.ws.requestsDir, rid, RETRO_FILE);
|
|
14
|
+
/** 記録を読む(無ければ空。壊れていれば retro_unreadable) */
|
|
15
|
+
export async function loadRetrospective(ctx, rid) {
|
|
16
|
+
let text;
|
|
17
|
+
try {
|
|
18
|
+
text = await readFile(pathOf(ctx, rid), "utf8");
|
|
19
|
+
}
|
|
20
|
+
catch (e) {
|
|
21
|
+
if (e.code === "ENOENT")
|
|
22
|
+
return { version: 0, targets: [] };
|
|
23
|
+
throw e;
|
|
24
|
+
}
|
|
25
|
+
let raw;
|
|
26
|
+
try {
|
|
27
|
+
raw = JSON.parse(text);
|
|
28
|
+
}
|
|
29
|
+
catch (e) {
|
|
30
|
+
throw new RetrospectiveError("retro_unreadable", `retrospective.json が JSON として読めません: ${e.message}(ファイルを直してください)`);
|
|
31
|
+
}
|
|
32
|
+
return readRetrospective(raw);
|
|
33
|
+
}
|
|
34
|
+
/** 候補(新しい順)。runs と照らすタスク・子の要望はディスクと読み込んだ値から */
|
|
35
|
+
export async function retrospectiveCandidates(ctx, rid) {
|
|
36
|
+
const request = ctx.ws.requests.require(rid);
|
|
37
|
+
const runs = await ctx.preflight.list(rid);
|
|
38
|
+
const archived = new Set((await listArchivedTasks(ctx.ws, rid)).tasks.map((t) => t.id));
|
|
39
|
+
const tasks = ctx.ws.tasksOf(rid);
|
|
40
|
+
const lookup = {
|
|
41
|
+
task: (tid) => (tasks.get(tid) ? "present" : archived.has(tid) ? "archived" : "missing"),
|
|
42
|
+
child: (id) => {
|
|
43
|
+
const c = ctx.ws.requests.get(id);
|
|
44
|
+
return c ? { splitFrom: c.splitFrom, parent: c.parent } : undefined;
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
return { ...retroCandidates(rid, request.status, runs, lookup), runs };
|
|
48
|
+
}
|
|
49
|
+
export async function retrospectiveView(ctx, rid) {
|
|
50
|
+
const file = await loadRetrospective(ctx, rid);
|
|
51
|
+
const { candidates, none } = await retrospectiveCandidates(ctx, rid);
|
|
52
|
+
const target = currentTarget(file);
|
|
53
|
+
const judgments = file.judgments ?? [];
|
|
54
|
+
const risks = (target?.risks ?? []).map((r) => {
|
|
55
|
+
const j = latestJudgment(file, target.id, r.index);
|
|
56
|
+
return { index: r.index, text: r.text, state: j?.state ?? "unchecked", ...(j ? { judgment: j } : {}), history: judgments.filter((x) => x.target === target.id && x.risk === r.index) };
|
|
57
|
+
});
|
|
58
|
+
const checks = {};
|
|
59
|
+
for (const j of judgments)
|
|
60
|
+
checks[j.id] = await Promise.all(j.evidence.map((e) => checkEvidence(ctx, e)));
|
|
61
|
+
return { version: file.version, ...(target ? { target } : {}), targets: file.targets, candidates, ...(none ? { none } : {}), risks, counts: riskCounts(file), judgments, checks };
|
|
62
|
+
}
|
|
63
|
+
// --- リスクの確認の根拠 -----------------------------------------------------------
|
|
64
|
+
const bad = (m) => new RetrospectiveError("retro_invalid", m);
|
|
65
|
+
const clip = (s) => (s.length > JUDGMENT_LIMITS.excerpt ? `${s.slice(0, JUDGMENT_LIMITS.excerpt)}…` : s);
|
|
66
|
+
/** 結果の項目と位置から所見の文を取り出す(無ければ undefined) */
|
|
67
|
+
function findingOf(result, section, index) {
|
|
68
|
+
if (section === "overall")
|
|
69
|
+
return index === 0 && typeof result.overall === "string" ? result.overall : undefined;
|
|
70
|
+
const list = result[section];
|
|
71
|
+
if (!Array.isArray(list) || index < 0 || index >= list.length)
|
|
72
|
+
return undefined;
|
|
73
|
+
const x = list[index];
|
|
74
|
+
if (typeof x === "string")
|
|
75
|
+
return x;
|
|
76
|
+
const head = [x.item ?? x.unit ?? x.standard, x.verdict].filter((v) => typeof v === "string").join(": ");
|
|
77
|
+
return [head, typeof x.reason === "string" ? x.reason : typeof x.text === "string" ? x.text : ""].filter(Boolean).join(" ");
|
|
78
|
+
}
|
|
79
|
+
/** 所見がこの要望を根拠に挙げているか(マイルストーンレビューの所見の evidence に要望 ID かそのタスクの参照がある) */
|
|
80
|
+
function citesRequest(result, section, index, rid) {
|
|
81
|
+
const list = result[section];
|
|
82
|
+
const x = Array.isArray(list) ? list[index] : undefined;
|
|
83
|
+
const ev = x && Array.isArray(x.evidence) ? x.evidence : [];
|
|
84
|
+
return ev.some((e) => typeof e === "string" && (e === rid || e.startsWith(`${rid}/`)));
|
|
85
|
+
}
|
|
86
|
+
/** タスクを今の・アーカイブから引く(無ければ undefined) */
|
|
87
|
+
async function taskOf(ctx, rid, tid) {
|
|
88
|
+
return ctx.ws.tasksOf(rid).get(tid) ?? (await getArchivedTask(ctx.ws, rid, tid).catch(() => undefined));
|
|
89
|
+
}
|
|
90
|
+
/** 根拠の指定を今の記録と照らして、保存する根拠にする(範囲外・見つからない・所見が無いなどは retro_invalid) */
|
|
91
|
+
export async function resolveEvidence(ctx, rid, ref) {
|
|
92
|
+
if (ref.kind === "manual") {
|
|
93
|
+
const reference = ref.reference?.trim();
|
|
94
|
+
if (!reference)
|
|
95
|
+
throw bad("人が書く参照(reference)が空です");
|
|
96
|
+
return { kind: "manual", reference: clip(reference), ...(ref.note?.trim() ? { note: clip(ref.note.trim()) } : {}) };
|
|
97
|
+
}
|
|
98
|
+
if (ref.kind === "rework") {
|
|
99
|
+
const t = await taskOf(ctx, rid, ref.task);
|
|
100
|
+
if (!t)
|
|
101
|
+
throw bad(`${rid}/${ref.task} はこの要望のタスクにありません`);
|
|
102
|
+
const h = t.reworkHistory?.find((e) => e.id === ref.history);
|
|
103
|
+
if (!h)
|
|
104
|
+
throw bad(`${t.id} の手戻りの履歴に ${ref.history} はありません`);
|
|
105
|
+
return { kind: "rework", request: rid, task: t.id, history: h.id, excerpt: clip(reworkLine(h)) };
|
|
106
|
+
}
|
|
107
|
+
const index = ref.index ?? 0;
|
|
108
|
+
if (ref.kind === "task_review") {
|
|
109
|
+
if (!TASK_REVIEW_SECTIONS.includes(ref.section))
|
|
110
|
+
throw bad(`タスクレビューの所見の項目は ${TASK_REVIEW_SECTIONS.join(" / ")} です`);
|
|
111
|
+
if (!(await taskOf(ctx, rid, ref.task)))
|
|
112
|
+
throw bad(`${rid}/${ref.task} はこの要望のタスクにありません(ほかの要望のレビューは結び付けられません)`);
|
|
113
|
+
const rec = await ctx.ws.taskReviews.get(`${rid}/${ref.task}`, ref.run).catch(() => undefined);
|
|
114
|
+
if (!rec?.result)
|
|
115
|
+
throw bad(`${rid}/${ref.task} のレビュー ${ref.run} の結果がありません`);
|
|
116
|
+
const text = findingOf(rec.result, ref.section, index);
|
|
117
|
+
if (text === undefined)
|
|
118
|
+
throw bad(`レビュー ${ref.run} の ${ref.section}[${index}] に所見がありません`);
|
|
119
|
+
return { kind: "task_review", request: rid, task: ref.task, run: ref.run, section: ref.section, index, resultVersion: assessmentVersion(rec.result), excerpt: clip(text) };
|
|
120
|
+
}
|
|
121
|
+
if (!MILESTONE_REVIEW_SECTIONS.includes(ref.section))
|
|
122
|
+
throw bad(`マイルストーンレビューの所見の項目は ${MILESTONE_REVIEW_SECTIONS.join(" / ")} です`);
|
|
123
|
+
const rec = await ctx.ws.milestoneReviews.get(ref.milestone, ref.run).catch(() => undefined);
|
|
124
|
+
if (!rec?.result || !rec.input)
|
|
125
|
+
throw bad(`マイルストーン ${ref.milestone} のレビュー ${ref.run} の結果がありません`);
|
|
126
|
+
if (!rec.input.requests.some((r) => r.id === rid))
|
|
127
|
+
throw bad(`レビュー ${ref.run} の材料で、${rid} は直接の対象ではありません(範囲外の所見は結び付けられません)`);
|
|
128
|
+
const result = rec.result;
|
|
129
|
+
const text = findingOf(result, ref.section, index);
|
|
130
|
+
if (text === undefined)
|
|
131
|
+
throw bad(`レビュー ${ref.run} の ${ref.section}[${index}] に所見がありません`);
|
|
132
|
+
const reason = ref.reason?.trim();
|
|
133
|
+
if (!citesRequest(result, ref.section, index, rid) && !reason)
|
|
134
|
+
throw bad(`この所見は ${rid} を根拠に挙げていません。全体に関わる所見を結び付けるには、この要望と結び付く理由(reason)を書いてください`);
|
|
135
|
+
return {
|
|
136
|
+
kind: "milestone_review",
|
|
137
|
+
milestone: ref.milestone,
|
|
138
|
+
run: ref.run,
|
|
139
|
+
section: ref.section,
|
|
140
|
+
index,
|
|
141
|
+
resultVersion: assessmentVersion(rec.result),
|
|
142
|
+
excerpt: clip(text),
|
|
143
|
+
...(rec.run.inputChanged ? { inputChanged: true } : {}),
|
|
144
|
+
...(reason ? { reason: clip(reason) } : {}),
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
/** 保存した根拠を今の記録と照らす(ファイルは書かない) */
|
|
148
|
+
export async function checkEvidence(ctx, e) {
|
|
149
|
+
if (e.kind === "manual")
|
|
150
|
+
return "manual";
|
|
151
|
+
if (e.kind === "rework")
|
|
152
|
+
return (await taskOf(ctx, e.request, e.task))?.reworkHistory?.some((h) => h.id === e.history) ? "ok" : "missing";
|
|
153
|
+
const rec = e.kind === "task_review" ? await ctx.ws.taskReviews.get(`${e.request}/${e.task}`, e.run).catch(() => undefined) : await ctx.ws.milestoneReviews.get(e.milestone, e.run).catch(() => undefined);
|
|
154
|
+
if (!rec?.result)
|
|
155
|
+
return "missing";
|
|
156
|
+
return assessmentVersion(rec.result) === e.resultVersion ? "ok" : "changed";
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* リスクの確認を記録する(追記。今の確定した対象のリスクだけ)。根拠は保存するときに照らして抜粋と版を写す。
|
|
160
|
+
* expectedVersion が違えば retro_conflict、規則に合わない・範囲外の根拠は retro_invalid(どちらも何も書かない)
|
|
161
|
+
*/
|
|
162
|
+
export async function judgeRisk(ctx, rid, input, opts = {}) {
|
|
163
|
+
ctx.ws.requests.require(rid);
|
|
164
|
+
await withFileLock(ctx.ws.requestLock(rid), async () => {
|
|
165
|
+
if ("missing" in (await ctx.ws.requests.peek(rid)))
|
|
166
|
+
throw new NotFoundError(rid);
|
|
167
|
+
const file = await loadRetrospective(ctx, rid);
|
|
168
|
+
if (opts.expectedVersion !== undefined && opts.expectedVersion !== file.version) {
|
|
169
|
+
throw new RetrospectiveError("retro_conflict", `振り返りの記録が他で変わりました(版 ${opts.expectedVersion} → ${file.version})。読み直してからやり直してください`);
|
|
170
|
+
}
|
|
171
|
+
const evidence = [];
|
|
172
|
+
for (const ref of input.evidence)
|
|
173
|
+
evidence.push(await resolveEvidence(ctx, rid, ref));
|
|
174
|
+
const next = addJudgment(file, { ...input, evidence }, { now: new Date().toISOString(), actor: opts.actor });
|
|
175
|
+
await writeFileAtomic(pathOf(ctx, rid), `${JSON.stringify(next, null, 2)}\n`);
|
|
176
|
+
}, { busyMessage: "別のプロセスがこの要望を保存中です。少し待ってやり直してください" });
|
|
177
|
+
ctx.ws.emit({ type: "changed", kind: "request", request: rid });
|
|
178
|
+
return retrospectiveView(ctx, rid);
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* 振り返りの対象を確定する(訂正は理由つきで追記)。expectedVersion が今の版と違えば retro_conflict、候補でない・評価が無いなどは
|
|
182
|
+
* retro_invalid(どちらも何も書かない)
|
|
183
|
+
*/
|
|
184
|
+
export async function confirmRetrospectiveTarget(ctx, rid, input, opts = {}) {
|
|
185
|
+
ctx.ws.requests.require(rid);
|
|
186
|
+
await withFileLock(ctx.ws.requestLock(rid), async () => {
|
|
187
|
+
// ロックの中で要望があることを確かめる(アーカイブで移した後のフォルダに書き戻さない)
|
|
188
|
+
if ("missing" in (await ctx.ws.requests.peek(rid)))
|
|
189
|
+
throw new NotFoundError(rid);
|
|
190
|
+
const file = await loadRetrospective(ctx, rid);
|
|
191
|
+
if (opts.expectedVersion !== undefined && opts.expectedVersion !== file.version) {
|
|
192
|
+
throw new RetrospectiveError("retro_conflict", `振り返りの記録が他で変わりました(版 ${opts.expectedVersion} → ${file.version})。読み直してからやり直してください`);
|
|
193
|
+
}
|
|
194
|
+
const { candidates, none, runs } = await retrospectiveCandidates(ctx, rid);
|
|
195
|
+
const runOf = (id) => runs.find((r) => r.id === id);
|
|
196
|
+
const next = confirmTarget(file, input, {
|
|
197
|
+
candidates,
|
|
198
|
+
none,
|
|
199
|
+
risksOf: (id) => runOf(id)?.assessment?.risks,
|
|
200
|
+
assessmentOf: (id) => runOf(id)?.assessment,
|
|
201
|
+
now: new Date().toISOString(),
|
|
202
|
+
actor: opts.actor,
|
|
203
|
+
});
|
|
204
|
+
await writeFileAtomic(pathOf(ctx, rid), `${JSON.stringify(next, null, 2)}\n`);
|
|
205
|
+
}, { busyMessage: "別のプロセスがこの要望を保存中です。少し待ってやり直してください" });
|
|
206
|
+
ctx.ws.emit({ type: "changed", kind: "request", request: rid });
|
|
207
|
+
return retrospectiveView(ctx, rid);
|
|
208
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { diagnoseRequest, diagnoseTask, isReviewTarget, reviewSummary } from "../shared/reviewCandidate.js";
|
|
2
|
+
import { hierarchyNow } from "./requestStatus.js";
|
|
3
|
+
/**
|
|
4
|
+
* 見直し候補の読み取り(規則は shared/reviewCandidate.ts)。読み込んだ値だけで診断し、ファイルは書かない・git も実行しない。
|
|
5
|
+
* アーカイブした要望・タスクは見ない
|
|
6
|
+
*/
|
|
7
|
+
const nowOf = (ctx) => ({ quality: ctx.ws.project.quality, qualityVersion: ctx.ws.project.qualityVersion });
|
|
8
|
+
/** タスクの診断(完了していなければ undefined) */
|
|
9
|
+
export function taskReview(ctx, task) {
|
|
10
|
+
return diagnoseTask(task, ctx.ws.requests.get(task.request), nowOf(ctx));
|
|
11
|
+
}
|
|
12
|
+
/** 要望自身の診断(対応済・完了済でなければ undefined) */
|
|
13
|
+
export function requestSelfReview(ctx, r) {
|
|
14
|
+
return diagnoseRequest(r, nowOf(ctx));
|
|
15
|
+
}
|
|
16
|
+
const isCandidate = (d) => d?.state === "candidate";
|
|
17
|
+
/** 要望の概要(自身・自分のタスク・自分を除く配下)。配下は子孫の要望とそのタスクを1回ずつ数える */
|
|
18
|
+
export function requestReviewCounts(ctx, r, h = hierarchyNow(ctx.ws)) {
|
|
19
|
+
const self = requestSelfReview(ctx, r);
|
|
20
|
+
const tasksOf = (id) => ctx.ws.tasksOf(id).list().filter((t) => isCandidate(taskReview(ctx, t))).length;
|
|
21
|
+
let below = 0;
|
|
22
|
+
for (const d of h.descendants(r.id))
|
|
23
|
+
below += tasksOf(d.id) + (isCandidate(requestSelfReview(ctx, d)) ? 1 : 0);
|
|
24
|
+
return { ...(self ? { self: reviewSummary(self) } : {}), tasks: tasksOf(r.id), below };
|
|
25
|
+
}
|
|
26
|
+
/** 要望の詳細に添える診断(自身・タスクごとの概要・配下の件数) */
|
|
27
|
+
export function requestReview(ctx, rid) {
|
|
28
|
+
const r = ctx.ws.requests.require(rid);
|
|
29
|
+
const self = requestSelfReview(ctx, r);
|
|
30
|
+
const tasks = Object.fromEntries(ctx.ws
|
|
31
|
+
.tasksOf(rid)
|
|
32
|
+
.list()
|
|
33
|
+
.flatMap((t) => {
|
|
34
|
+
const d = taskReview(ctx, t);
|
|
35
|
+
return d ? [[t.id, reviewSummary(d)]] : [];
|
|
36
|
+
}));
|
|
37
|
+
return { ...(self ? { self } : {}), tasks, counts: requestReviewCounts(ctx, r) };
|
|
38
|
+
}
|
|
39
|
+
/** 見直し候補の一覧(タスクと要望。完了済みも含む)。request を渡すとその要望だけ */
|
|
40
|
+
export function reviewCandidates(ctx, opts = {}) {
|
|
41
|
+
const requests = opts.request ? [ctx.ws.requests.require(opts.request)] : ctx.ws.requests.list();
|
|
42
|
+
const out = [];
|
|
43
|
+
for (const r of requests) {
|
|
44
|
+
const self = requestSelfReview(ctx, r);
|
|
45
|
+
if (isCandidate(self))
|
|
46
|
+
out.push(self);
|
|
47
|
+
for (const t of ctx.ws.tasksOf(r.id).list()) {
|
|
48
|
+
if (!isReviewTarget(t))
|
|
49
|
+
continue;
|
|
50
|
+
const d = taskReview(ctx, t);
|
|
51
|
+
if (isCandidate(d))
|
|
52
|
+
out.push(d);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
2
|
+
import { ownerState, systemProbe } from "./preflight/owner.js";
|
|
3
|
+
import { writeFileAtomic } from "./store/fsutil.js";
|
|
4
|
+
/**
|
|
5
|
+
* レビューの実行の記録の共通部分(マイルストーンレビュー・タスクの AI レビュー)。比較材料と結果の形は各レビューに残し、ここには
|
|
6
|
+
* 「保存の仕方」と「実行中の run の扱い」だけを置く。
|
|
7
|
+
*
|
|
8
|
+
* - JSON は tmp に書いてから rename する。無いのは not_found、読めないのは broken(一覧からも隠さない)
|
|
9
|
+
* - 状態は running → completed / failed / cancelled の一方向。終わった run は変えない(finished で断る。遅れて届いた結果も取り込まない)
|
|
10
|
+
* - 同じ対象(キー)で実行中の run は1つだけ。確かめるのも変えるのもキーごとのロックの中
|
|
11
|
+
* - 実行しているプロセスが死んだと確かめられた run だけ自動で失敗(crashed)にする。分からない run は人が明示して中断する
|
|
12
|
+
* - 取消は、このプロセスの run なら止め、ほかのプロセスの run なら要求を run.json に書く(所有者が見つけて止める)
|
|
13
|
+
*/
|
|
14
|
+
/** 履歴の操作の失敗。not_found: 無い / broken: 読めない / bad_id: ID が使えない / exists: 既にある / finished: 終わった run */
|
|
15
|
+
export class ReviewStoreError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
constructor(code, message) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.code = code;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** 取消・中断を受け付けない(終わっている・動いている所有者がいる) */
|
|
23
|
+
export class ReviewCancelRefused extends Error {
|
|
24
|
+
code;
|
|
25
|
+
constructor(code, message) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.code = code;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export async function writeJson(path, v) {
|
|
31
|
+
await writeFileAtomic(path, `${JSON.stringify(v, null, 2)}\n`);
|
|
32
|
+
}
|
|
33
|
+
export async function readJson(path, label, check) {
|
|
34
|
+
let text;
|
|
35
|
+
try {
|
|
36
|
+
text = await readFile(path, "utf8");
|
|
37
|
+
}
|
|
38
|
+
catch (e) {
|
|
39
|
+
if (e.code === "ENOENT")
|
|
40
|
+
throw new ReviewStoreError("not_found", `レビューの記録がありません: ${label}`);
|
|
41
|
+
throw e;
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
const v = JSON.parse(text);
|
|
45
|
+
check(v);
|
|
46
|
+
return v;
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
throw new ReviewStoreError("broken", `レビューの記録を読めません: ${label}(${e.message})`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** フォルダの中のフォルダ(無ければ空。シンボリックリンクは含めない) */
|
|
53
|
+
export async function dirs(path) {
|
|
54
|
+
try {
|
|
55
|
+
return (await readdir(path, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name);
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
if (e.code === "ENOENT")
|
|
59
|
+
return [];
|
|
60
|
+
throw e;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** 開始の日時を run の ID にする形(YYYYMMDD-HHMMSS) */
|
|
64
|
+
export const runStamp = (now = new Date()) => now.toISOString().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
|
|
65
|
+
/** 開始の日時(このプロセスでは前より必ず後にする。一覧を開始の順に並べるので、同じミリ秒の開始でも順が分かるように) */
|
|
66
|
+
let lastStart = 0;
|
|
67
|
+
export function startedNow() {
|
|
68
|
+
lastStart = Math.max(Date.now(), lastStart + 1);
|
|
69
|
+
return new Date(lastStart).toISOString();
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* run.json の終わり・書き換えの規則(各ストアの finish / updateRunning の中身)。write は run.json を書く、writeResult は結果を書く
|
|
73
|
+
*/
|
|
74
|
+
export async function finishRunFile(label, cur, patch, result, io) {
|
|
75
|
+
if (cur.status !== "running")
|
|
76
|
+
throw new ReviewStoreError("finished", `${label} は既に終わっています(${cur.status})`);
|
|
77
|
+
if (patch.status === "completed") {
|
|
78
|
+
if (result === undefined)
|
|
79
|
+
throw new Error("completed には結果が要ります");
|
|
80
|
+
await io.writeResult(result);
|
|
81
|
+
}
|
|
82
|
+
const next = { ...cur, ...patch, finishedAt: patch.finishedAt ?? new Date().toISOString() };
|
|
83
|
+
await io.writeRun(next);
|
|
84
|
+
return next;
|
|
85
|
+
}
|
|
86
|
+
export async function updateRunFile(label, cur, fn, writeRun) {
|
|
87
|
+
if (cur.status !== "running")
|
|
88
|
+
throw new ReviewStoreError("finished", `${label} は既に終わっています(${cur.status})`);
|
|
89
|
+
const next = fn(cur);
|
|
90
|
+
await writeRun(next);
|
|
91
|
+
return next;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* 実行中の run の扱い(回復・二重の開始の確かめ・取消・ログの書き足しと取消の要求の見つけ方・終わりの書き方)。
|
|
95
|
+
* local: このプロセスで動いている run の ID
|
|
96
|
+
*/
|
|
97
|
+
export class RunControl {
|
|
98
|
+
store;
|
|
99
|
+
local;
|
|
100
|
+
probe;
|
|
101
|
+
onChange;
|
|
102
|
+
constructor(store, local, probe = systemProbe, onChange = () => undefined) {
|
|
103
|
+
this.store = store;
|
|
104
|
+
this.local = local;
|
|
105
|
+
this.probe = probe;
|
|
106
|
+
this.onChange = onChange;
|
|
107
|
+
}
|
|
108
|
+
ownerOf(r) {
|
|
109
|
+
if (this.local.has(r.id))
|
|
110
|
+
return { state: "local" };
|
|
111
|
+
return ownerState(r.owner, this.probe);
|
|
112
|
+
}
|
|
113
|
+
/** 死んだと確かめられた所有者の run を失敗(crashed)にする(ロックの中で呼ぶ) */
|
|
114
|
+
async recoverLocked(key) {
|
|
115
|
+
for (const id of await this.store.runIds(key)) {
|
|
116
|
+
const r = await this.store.readRun(key, id).catch(() => undefined);
|
|
117
|
+
if (r?.status !== "running" || this.local.has(r.id))
|
|
118
|
+
continue;
|
|
119
|
+
const o = this.ownerOf(r);
|
|
120
|
+
if (o.state !== "dead")
|
|
121
|
+
continue;
|
|
122
|
+
const fin = await this.store.finish(key, id, { status: "failed", failure: "crashed", error: `実行していたプロセスが途中で終わりました(${o.reason})` });
|
|
123
|
+
this.onChange(key, fin);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/** 実行中の run(回復した後に残るもの。ロックの中で呼ぶ) */
|
|
127
|
+
async runningLocked(key) {
|
|
128
|
+
await this.recoverLocked(key);
|
|
129
|
+
for (const id of await this.store.runIds(key)) {
|
|
130
|
+
const r = await this.store.readRun(key, id).catch(() => undefined);
|
|
131
|
+
if (r?.status === "running")
|
|
132
|
+
return { run: r, owner: this.ownerOf(r) };
|
|
133
|
+
}
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* 取り消す。このプロセスの run は abortLocal で止め、ほかのプロセスの run は要求を書く。
|
|
138
|
+
* acknowledgeStopped: 人が「実行しているプロセスは止まっている」と確かめた。所有者が分からない run を記録の上で中断にする
|
|
139
|
+
* (動いていると確かめられる所有者がいれば断る。ほかの環境のプロセスを止めたとは限らない)
|
|
140
|
+
*/
|
|
141
|
+
async cancel(key, run, by, opts) {
|
|
142
|
+
const isLocal = this.local.has(run);
|
|
143
|
+
const out = await this.store.withLock(key, async () => {
|
|
144
|
+
const cur = await this.store.readRun(key, run);
|
|
145
|
+
if (cur.status !== "running")
|
|
146
|
+
throw new ReviewCancelRefused("finished", `${opts.label} は既に終わっています(${cur.status})`);
|
|
147
|
+
const o = this.ownerOf(cur);
|
|
148
|
+
if (opts.acknowledgeStopped && !isLocal) {
|
|
149
|
+
if (o.state === "alive")
|
|
150
|
+
throw new ReviewCancelRefused("owner_alive", `${opts.label} を実行しているプロセスは動いています。--acknowledge-stopped ではなく取消を使ってください`);
|
|
151
|
+
const fin = await this.store.finish(key, run, {
|
|
152
|
+
status: "cancelled",
|
|
153
|
+
abandoned: { at: new Date().toISOString(), ...(by ? { by } : {}) },
|
|
154
|
+
error: "人が中断しました(ほかの環境で動いているプロセスを止めたとは限りません)",
|
|
155
|
+
});
|
|
156
|
+
return { run: fin, requested: false };
|
|
157
|
+
}
|
|
158
|
+
if (o.state === "dead") {
|
|
159
|
+
const fin = await this.store.finish(key, run, { status: "failed", failure: "crashed", error: `実行していたプロセスが途中で終わりました(${o.reason})` });
|
|
160
|
+
return { run: fin, requested: false };
|
|
161
|
+
}
|
|
162
|
+
const next = await this.store.updateRunning(key, run, (r) => ({ ...r, cancelRequested: { at: new Date().toISOString(), ...(by ? { by } : {}) } }));
|
|
163
|
+
return { run: next, requested: true };
|
|
164
|
+
});
|
|
165
|
+
opts.abortLocal?.();
|
|
166
|
+
this.onChange(key, out.run);
|
|
167
|
+
return out;
|
|
168
|
+
}
|
|
169
|
+
/** ほかのプロセスからの取消の要求を見つけ、ログを run.json に書き足す(止めるときは返した関数を呼ぶ) */
|
|
170
|
+
watch(key, run, log, abort, pollMs = 1000) {
|
|
171
|
+
let flushed = 0;
|
|
172
|
+
const timer = setInterval(() => {
|
|
173
|
+
void this.store
|
|
174
|
+
.withLock(key, async () => {
|
|
175
|
+
const cur = await this.store.readRun(key, run);
|
|
176
|
+
if (cur.status !== "running")
|
|
177
|
+
return abort.abort(new Error("ended"));
|
|
178
|
+
if (cur.cancelRequested)
|
|
179
|
+
abort.abort(new Error("cancelled"));
|
|
180
|
+
if (log.length !== flushed) {
|
|
181
|
+
flushed = log.length;
|
|
182
|
+
await this.store.updateRunning(key, run, (r) => ({ ...r, log: [...log] }));
|
|
183
|
+
}
|
|
184
|
+
})
|
|
185
|
+
.catch(() => undefined);
|
|
186
|
+
}, pollMs);
|
|
187
|
+
timer.unref?.();
|
|
188
|
+
return () => clearInterval(timer);
|
|
189
|
+
}
|
|
190
|
+
/** 終わりを書く(ロックの中で、まだ実行中かを確かめてから)。既に終わっていれば遅れて届いた結果を取り込まず、今の記録を返す */
|
|
191
|
+
async end(key, run, end, result) {
|
|
192
|
+
try {
|
|
193
|
+
const fin = await this.store.withLock(key, () => this.store.finish(key, run, end, end.status === "completed" ? result : undefined));
|
|
194
|
+
this.onChange(key, fin);
|
|
195
|
+
return fin;
|
|
196
|
+
}
|
|
197
|
+
catch (e) {
|
|
198
|
+
if (!(e instanceof ReviewStoreError && e.code === "finished"))
|
|
199
|
+
throw e;
|
|
200
|
+
const cur = await this.store.readRun(key, run);
|
|
201
|
+
this.onChange(key, cur);
|
|
202
|
+
return cur;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { readdir } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { REQUEST_ID, TASK_ID, taskId } from "../../shared/refs.js";
|
|
4
|
+
import { fileLayout, MarkdownCollection, NotFoundError } from "./collection.js";
|
|
5
|
+
import { normalizeTaskIn, TASK_DERIVED, TASK_KEY_ORDER } from "./normalize.js";
|
|
6
|
+
/**
|
|
7
|
+
* アーカイブしたタスク(requests/<要望ID>/tasks/.archive/<ID>.md)を読むだけの道。
|
|
8
|
+
*
|
|
9
|
+
* - 通常のタスクのコレクション(Workspace.tasksOf)・索引・変更通知には触れない。読むたびにディスクを読み、キャッシュしない
|
|
10
|
+
* - ファイル・rev・状態・採番の予約(collection.ts の reserved)を変えない
|
|
11
|
+
* - 明示した要望の中だけを読む。要望 ID・タスク ID の形を確かめ、ほかの場所は読ませない
|
|
12
|
+
* - 通常の一覧・進捗・対応済の判定・依存・レビューやリリースノートの材料はこれを使わない(docs/architecture.md「アーカイブしたタスク」)
|
|
13
|
+
*/
|
|
14
|
+
/** アーカイブのフォルダかファイルを読めない(無いのではない) */
|
|
15
|
+
export class ArchivedTaskReadError extends Error {
|
|
16
|
+
code = "archive_unreadable";
|
|
17
|
+
}
|
|
18
|
+
/** 要望が無ければ NotFoundError。読めない要望(壊れた request.md)でもアーカイブは読める */
|
|
19
|
+
function requestDir(ws, rid) {
|
|
20
|
+
if (!REQUEST_ID.test(rid) || (!ws.requests.get(rid) && !ws.requests.errors.has(rid)))
|
|
21
|
+
throw new NotFoundError(rid);
|
|
22
|
+
return join(ws.requestsDir, rid, "tasks", ".archive");
|
|
23
|
+
}
|
|
24
|
+
function reader(ws, rid) {
|
|
25
|
+
return new MarkdownCollection({
|
|
26
|
+
layout: fileLayout(requestDir(ws, rid), TASK_ID, taskId),
|
|
27
|
+
normalize: normalizeTaskIn(rid),
|
|
28
|
+
keyOrder: TASK_KEY_ORDER,
|
|
29
|
+
derived: TASK_DERIVED,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
const mark = (t) => ({ ...t, archived: true });
|
|
33
|
+
/** 要望のアーカイブの一覧(ID の数値順)。フォルダが無ければ空。フォルダを読めなければ ArchivedTaskReadError */
|
|
34
|
+
export async function listArchivedTasks(ws, rid) {
|
|
35
|
+
const dir = requestDir(ws, rid);
|
|
36
|
+
let names;
|
|
37
|
+
try {
|
|
38
|
+
names = await readdir(dir);
|
|
39
|
+
}
|
|
40
|
+
catch (e) {
|
|
41
|
+
if (e.code === "ENOENT")
|
|
42
|
+
return { request: rid, tasks: [], errors: [] };
|
|
43
|
+
throw new ArchivedTaskReadError(`${rid} のアーカイブを読めません: ${e.message}`);
|
|
44
|
+
}
|
|
45
|
+
const ids = names
|
|
46
|
+
.filter((f) => f.endsWith(".md"))
|
|
47
|
+
.map((f) => f.slice(0, -3))
|
|
48
|
+
.filter((id) => TASK_ID.test(id))
|
|
49
|
+
.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
|
|
50
|
+
const col = reader(ws, rid);
|
|
51
|
+
const tasks = [];
|
|
52
|
+
const errors = [];
|
|
53
|
+
for (const id of ids) {
|
|
54
|
+
const r = await col.peek(id);
|
|
55
|
+
if ("item" in r)
|
|
56
|
+
tasks.push(mark(r.item));
|
|
57
|
+
else if ("error" in r)
|
|
58
|
+
errors.push({ id, error: r.error });
|
|
59
|
+
// 一覧を作る間に消えたものは出さない
|
|
60
|
+
}
|
|
61
|
+
return { request: rid, tasks, errors };
|
|
62
|
+
}
|
|
63
|
+
/** アーカイブの1件。無ければ NotFoundError(<要望ID>/<ID>)、読めなければ ArchivedTaskReadError */
|
|
64
|
+
export async function getArchivedTask(ws, rid, tid) {
|
|
65
|
+
const col = reader(ws, rid);
|
|
66
|
+
if (!TASK_ID.test(tid))
|
|
67
|
+
throw new NotFoundError(`${rid}/${tid}`);
|
|
68
|
+
const r = await col.peek(tid);
|
|
69
|
+
if ("item" in r)
|
|
70
|
+
return mark(r.item);
|
|
71
|
+
if ("missing" in r)
|
|
72
|
+
throw new NotFoundError(`${rid}/${tid}`);
|
|
73
|
+
throw new ArchivedTaskReadError(`${rid}/${tid} のアーカイブを読めません: ${r.error}`);
|
|
74
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { access, mkdir, readFile, readdir, rename } from "node:fs/promises";
|
|
2
2
|
import { dirname, join } from "node:path";
|
|
3
3
|
import { parseFrontmatter, stringifyFrontmatter } from "./frontmatter.js";
|
|
4
|
-
import { createExclusive, nowIso, writeFileAtomic } from "./fsutil.js";
|
|
4
|
+
import { createExclusive, nowIso, withFileLock, writeFileAtomic } from "./fsutil.js";
|
|
5
5
|
export class ConflictError extends Error {
|
|
6
6
|
id;
|
|
7
7
|
expected;
|
|
@@ -20,6 +20,8 @@ export class NotFoundError extends Error {
|
|
|
20
20
|
this.id = id;
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
|
+
/** ロックを待ちきれなかったときの案内 */
|
|
24
|
+
const LOCK_BUSY = "別のプロセスがこの要望を保存中です。少し待ってやり直してください";
|
|
23
25
|
/**
|
|
24
26
|
* 1エンティティ = 1 Markdown ファイル(YAML frontmatter + 本文)のコレクション。
|
|
25
27
|
* メモリ上にキャッシュし、ファイル変更(人手・AI・Codex・git pull)は reload() で取り込む。
|
|
@@ -100,6 +102,9 @@ export class MarkdownCollection {
|
|
|
100
102
|
const item = this.opts.normalize(data, body, id);
|
|
101
103
|
const known = new Set(["body", ...this.opts.keyOrder, ...(this.opts.derived ?? []), ...Object.keys(item)]);
|
|
102
104
|
const extra = Object.fromEntries(Object.entries(data).filter(([k]) => !known.has(k)));
|
|
105
|
+
for (const k of this.opts.keepRaw?.(item) ?? [])
|
|
106
|
+
if (k in data)
|
|
107
|
+
extra[k] = data[k];
|
|
103
108
|
return { item, extra };
|
|
104
109
|
}
|
|
105
110
|
catch (e) {
|
|
@@ -151,9 +156,10 @@ export class MarkdownCollection {
|
|
|
151
156
|
const { body, ...rest } = item;
|
|
152
157
|
const skip = new Set(["body", ...(this.opts.derived ?? [])]);
|
|
153
158
|
const ordered = {};
|
|
159
|
+
// extra に知っているキーがあるのは keepRaw のとき(元の値のまま書く)
|
|
154
160
|
for (const k of this.opts.keyOrder)
|
|
155
161
|
if (!skip.has(k))
|
|
156
|
-
ordered[k] = rest[k];
|
|
162
|
+
ordered[k] = k in extra ? extra[k] : rest[k];
|
|
157
163
|
for (const [k, v] of Object.entries(rest))
|
|
158
164
|
if (!(k in ordered) && !skip.has(k))
|
|
159
165
|
ordered[k] = v;
|
|
@@ -164,6 +170,10 @@ export class MarkdownCollection {
|
|
|
164
170
|
}
|
|
165
171
|
/** 作る。省いた項目は normalize の既定値になる */
|
|
166
172
|
async create(input, actor) {
|
|
173
|
+
// タスクは要望のロックの中で作る(要望のアーカイブと重なって、移した後のフォルダに作らない)。要望(ID は新しく作る)は取らない
|
|
174
|
+
return this.locked("", () => this.createUnlocked(input, actor));
|
|
175
|
+
}
|
|
176
|
+
async createUnlocked(input, actor) {
|
|
167
177
|
// アーカイブ済みの ID も使わない(アーカイブしたタスクへの関係が新しいタスクを指さないように)
|
|
168
178
|
const existing = [...new Set([...this.items.keys(), ...(await this.layout.scan()), ...((await this.layout.reserved?.()) ?? [])])];
|
|
169
179
|
// 別のプロセス(CLI・AI)と同時に作っても、排他作成で衝突を検出して次の ID にする
|
|
@@ -196,17 +206,31 @@ export class MarkdownCollection {
|
|
|
196
206
|
}
|
|
197
207
|
/**
|
|
198
208
|
* 部分更新。expectedRev を渡すと楽観ロック(AI が古い状態を元に上書きするのを防ぐ)。
|
|
209
|
+
* patch に関数を渡すと、直前に読み直した今の値から patch を作る(基準の操作のように、今の値に当てる変更)。関数が投げたら書かない
|
|
199
210
|
*/
|
|
200
211
|
async update(id, patch, opts = {}) {
|
|
212
|
+
return this.locked(id, () => this.updateUnlocked(id, patch, opts));
|
|
213
|
+
}
|
|
214
|
+
/** ロックの中で動かす(ロックを持たないコレクションはそのまま) */
|
|
215
|
+
locked(id, fn) {
|
|
216
|
+
const lock = this.opts.lock?.(id);
|
|
217
|
+
return lock ? withFileLock(lock, fn, { busyMessage: LOCK_BUSY }) : fn();
|
|
218
|
+
}
|
|
219
|
+
async updateUnlocked(id, patch, opts) {
|
|
201
220
|
// 外部での編集を取りこぼさないよう、更新の直前にディスクから読み直す。
|
|
202
221
|
// この版が知らない項目(新しい版の p3 が書いた項目)は消さずに書き戻す(古い版の更新で親子などが消えないように)
|
|
203
222
|
const r = await this.read(id);
|
|
204
223
|
this.apply(id, r);
|
|
205
|
-
const extra = "item" in r ? r.extra : {};
|
|
224
|
+
const extra = "item" in r ? { ...r.extra } : {};
|
|
206
225
|
const cur = this.require(id);
|
|
207
226
|
if (opts.expectedRev !== undefined && opts.expectedRev !== cur.rev) {
|
|
208
227
|
throw new ConflictError(id, opts.expectedRev, cur.rev);
|
|
209
228
|
}
|
|
229
|
+
if (typeof patch === "function")
|
|
230
|
+
patch = patch(cur);
|
|
231
|
+
// patch で書き換えるキーは、元の値を残す対象(keepRaw・知らない項目)から外す
|
|
232
|
+
for (const k of Object.keys(patch))
|
|
233
|
+
delete extra[k];
|
|
210
234
|
const merged = {
|
|
211
235
|
...cur,
|
|
212
236
|
...patch,
|
|
@@ -223,6 +247,11 @@ export class MarkdownCollection {
|
|
|
223
247
|
}
|
|
224
248
|
/** 物理削除はせず .archive/ へ移す */
|
|
225
249
|
async archive(id) {
|
|
250
|
+
return this.locked(id, () => this.archiveUnlocked(id));
|
|
251
|
+
}
|
|
252
|
+
async archiveUnlocked(id) {
|
|
253
|
+
// ロックの中で読み直す(別のプロセスが先に移した・消したなら無い)
|
|
254
|
+
this.apply(id, await this.read(id));
|
|
226
255
|
this.require(id);
|
|
227
256
|
const { from, to } = this.layout.archive(id);
|
|
228
257
|
// 既にアーカイブに同じ ID があれば上書きしない(rename は黙って置き換えるので先に確かめる)
|