@infodb/p3 0.3.0 → 0.5.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/bin/p3.mjs +11 -5
- package/dist/web/assets/Outputs-C83ZDXvs.js +1 -0
- package/dist/web/assets/RequestStatus-GmiWYEcL.js +1 -0
- package/dist/web/assets/Tabs-CJn0Qy7W.js +1 -0
- package/dist/web/assets/TagInput-CtM8HM8Z.js +1 -0
- package/dist/web/assets/TaskDrawer-D5v36QoF.js +3 -0
- package/dist/web/assets/_requestId-BHUqLO-j.js +1 -0
- package/dist/web/assets/_requestId-DxwxbXY2.js +30 -0
- package/dist/web/assets/{ui-Sz7y5_TS.js → appCtx-B-VRVOyv.js} +1 -1
- package/dist/web/assets/board-DAaVR04x.js +1 -0
- package/dist/web/assets/copy-CKsXEjMi.js +1 -0
- package/dist/web/assets/done-CaqB_qTH.js +1 -0
- package/dist/web/assets/index-BF1xMdJo.css +2 -0
- package/dist/web/assets/index-BQYvKpjF.js +12 -0
- package/dist/web/assets/milestoneOrder-N7b5XFJP.js +1 -0
- package/dist/web/assets/new-DLVnRvrB.js +1 -0
- package/dist/web/assets/preflightInput-BAeEJYUK.js +2 -0
- package/dist/web/assets/preload-helper-B74h5i3O.js +1 -0
- package/dist/web/assets/progressTree-wp9mH4VF.js +1 -0
- package/dist/web/assets/release-notes-MTLcOcvZ.js +3 -0
- package/dist/web/assets/requestData-D-HXu-cy.js +1 -0
- package/dist/web/assets/routes-CI4Qfkjs.js +3 -0
- package/dist/web/assets/settings-CJMNgzi6.js +1 -0
- package/dist/web/index.html +4 -4
- package/docs/architecture.md +238 -9
- package/docs/development.md +16 -9
- package/docs/how-to-use.md +128 -12
- package/docs/installation.md +8 -6
- package/docs/publishing.md +4 -2
- package/lib/cli/args.js +172 -0
- package/lib/cli/chatgpt.js +70 -0
- package/lib/cli/codex.js +30 -0
- package/lib/cli/format.js +9 -0
- package/{src/cli/help.ts → lib/cli/help.js} +11 -8
- package/lib/cli/main.js +326 -0
- package/lib/cli/output.js +110 -0
- package/lib/cli/preflightCommands.js +301 -0
- package/lib/cli/project.js +649 -0
- package/lib/cli/readOnly.js +36 -0
- package/lib/cli/releaseNotesCommands.js +197 -0
- package/lib/cli/render.js +58 -0
- package/lib/cli/requestCommands.js +180 -0
- package/lib/cli/showView.js +100 -0
- package/lib/cli/taskCommands.js +152 -0
- package/lib/cli/userConfig.js +64 -0
- package/{src/core/chatgpt.ts → lib/core/chatgpt.js} +10 -16
- package/lib/core/context.js +41 -0
- package/lib/core/hierarchy.js +128 -0
- package/lib/core/machineSettings.js +146 -0
- package/lib/core/machineSettingsEdit.js +148 -0
- package/lib/core/ops.js +120 -0
- package/lib/core/preflight/carryover.js +105 -0
- package/lib/core/preflight/codexEngine.js +687 -0
- package/lib/core/preflight/codexImage.js +61 -0
- package/lib/core/preflight/diagnose.js +95 -0
- package/lib/core/preflight/engine.js +58 -0
- package/lib/core/preflight/input.js +83 -0
- package/lib/core/preflight/launch.js +68 -0
- package/lib/core/preflight/mockEngine.js +175 -0
- package/lib/core/preflight/render.js +304 -0
- package/lib/core/preflight/service.js +868 -0
- package/lib/core/preflight/split.js +83 -0
- package/lib/core/preflight/uiMaterials.js +281 -0
- package/lib/core/preflight/uiRender.js +89 -0
- package/lib/core/preflight/wireframe.js +63 -0
- package/lib/core/preflight/xlsx.js +324 -0
- package/lib/core/projectRegistry.js +207 -0
- package/lib/core/redact.js +28 -0
- package/lib/core/releaseNotes/completeRequests.js +106 -0
- package/lib/core/releaseNotes/generate.js +266 -0
- package/lib/core/releaseNotes/material.js +141 -0
- package/lib/core/releaseNotes/mockSummarizer.js +26 -0
- package/lib/core/releaseNotes/service.js +83 -0
- package/lib/core/releaseNotes/store.js +209 -0
- package/lib/core/repoAdmin.js +82 -0
- package/lib/core/repoRefs.js +72 -0
- package/lib/core/requestOps.js +154 -0
- package/lib/core/requestStatus.js +171 -0
- package/lib/core/store/attachments.js +242 -0
- package/lib/core/store/collection.js +254 -0
- package/lib/core/store/frontmatter.js +18 -0
- package/lib/core/store/fsutil.js +84 -0
- package/lib/core/store/locate.js +162 -0
- package/lib/core/store/normalize.js +150 -0
- package/lib/core/store/noteStore.js +59 -0
- package/lib/core/store/preflightStore.js +161 -0
- package/lib/core/store/projectFile.js +99 -0
- package/lib/core/store/workspace.js +320 -0
- package/lib/core/supersede.js +69 -0
- package/lib/core/userConfig.js +158 -0
- package/{src/core/userTheme.ts → lib/core/userTheme.js} +11 -13
- package/lib/core/workTargets.js +106 -0
- package/lib/server/api/chatgptRoutes.js +46 -0
- package/{src/server/api/local.ts → lib/server/api/local.js} +23 -22
- package/lib/server/api/manifest.js +140 -0
- package/lib/server/api/projectsRoutes.js +82 -0
- package/lib/server/api/releaseNoteRoutes.js +88 -0
- package/lib/server/api/repoRoutes.js +67 -0
- package/lib/server/api/routes.js +404 -0
- package/lib/server/api/userThemeRoutes.js +60 -0
- package/lib/server/server.js +85 -0
- package/lib/shared/dates.js +10 -0
- package/{src/shared/directTask.ts → lib/shared/directTask.js} +3 -11
- package/lib/shared/hierarchy.js +120 -0
- package/lib/shared/milestoneOrder.js +45 -0
- package/lib/shared/preflightInput.js +19 -0
- package/lib/shared/refs.js +44 -0
- package/lib/shared/repos.js +69 -0
- package/lib/shared/scopeView.js +39 -0
- package/{src/shared/tags.ts → lib/shared/tags.js} +9 -14
- package/lib/shared/types.js +74 -0
- package/lib/shared/workTarget.js +31 -0
- package/package.json +4 -7
- package/skills/p3/SKILL.md +29 -8
- package/dist/web/assets/Outputs-DqJdybkd.js +0 -1
- package/dist/web/assets/RequestStatus-DN-2iAM0.js +0 -1
- package/dist/web/assets/TagInput-D-1ILLDX.js +0 -1
- package/dist/web/assets/TaskDrawer-CHD7T-Su.js +0 -3
- package/dist/web/assets/_requestId-BzSepQIV.js +0 -30
- package/dist/web/assets/_requestId-pIds2tFU.js +0 -1
- package/dist/web/assets/board-BIkOpuC4.js +0 -1
- package/dist/web/assets/copy-B1ZbihKL.js +0 -2
- package/dist/web/assets/done-BUAUhIRr.js +0 -1
- package/dist/web/assets/index-Byv9j77D.js +0 -12
- package/dist/web/assets/index-DTfUhuQw.css +0 -2
- package/dist/web/assets/new-6kly4-PX.js +0 -1
- package/dist/web/assets/preload-helper-DlN0ouRj.js +0 -1
- package/dist/web/assets/release-notes-iwQWmfX6.js +0 -3
- package/dist/web/assets/requestData-DJ1Rlx-u.js +0 -1
- package/dist/web/assets/routes-Ciot9p4x.js +0 -2
- package/dist/web/assets/settings-DBCi6lAY.js +0 -1
- package/src/cli/args.ts +0 -186
- package/src/cli/chatgpt.ts +0 -74
- package/src/cli/codex.ts +0 -28
- package/src/cli/format.ts +0 -9
- package/src/cli/main.ts +0 -336
- package/src/cli/output.ts +0 -117
- package/src/cli/preflightCommands.ts +0 -245
- package/src/cli/project.ts +0 -672
- package/src/cli/readOnly.ts +0 -36
- package/src/cli/releaseNotesCommands.ts +0 -159
- package/src/cli/render.ts +0 -60
- package/src/cli/requestCommands.ts +0 -170
- package/src/cli/showView.ts +0 -110
- package/src/cli/taskCommands.ts +0 -167
- package/src/cli/userConfig.ts +0 -58
- package/src/core/context.ts +0 -58
- package/src/core/machineSettings.ts +0 -207
- package/src/core/machineSettingsEdit.ts +0 -156
- package/src/core/ops.ts +0 -114
- package/src/core/preflight/carryover.ts +0 -133
- package/src/core/preflight/codexEngine.ts +0 -703
- package/src/core/preflight/codexImage.ts +0 -98
- package/src/core/preflight/diagnose.ts +0 -124
- package/src/core/preflight/engine.ts +0 -92
- package/src/core/preflight/input.ts +0 -65
- package/src/core/preflight/launch.ts +0 -86
- package/src/core/preflight/mockEngine.ts +0 -145
- package/src/core/preflight/render.ts +0 -339
- package/src/core/preflight/service.ts +0 -707
- package/src/core/preflight/uiMaterials.ts +0 -272
- package/src/core/preflight/uiRender.ts +0 -84
- package/src/core/preflight/wireframe.ts +0 -69
- package/src/core/preflight/xlsx.ts +0 -328
- package/src/core/projectRegistry.ts +0 -264
- package/src/core/redact.ts +0 -31
- package/src/core/releaseNotes/generate.ts +0 -283
- package/src/core/releaseNotes/material.ts +0 -114
- package/src/core/releaseNotes/mockSummarizer.ts +0 -28
- package/src/core/releaseNotes/service.ts +0 -106
- package/src/core/releaseNotes/store.ts +0 -216
- package/src/core/repoAdmin.ts +0 -81
- package/src/core/repoRefs.ts +0 -90
- package/src/core/requestOps.ts +0 -140
- package/src/core/requestStatus.ts +0 -58
- package/src/core/store/attachments.ts +0 -228
- package/src/core/store/collection.ts +0 -282
- package/src/core/store/frontmatter.ts +0 -22
- package/src/core/store/fsutil.ts +0 -90
- package/src/core/store/locate.ts +0 -181
- package/src/core/store/normalize.ts +0 -155
- package/src/core/store/noteStore.ts +0 -56
- package/src/core/store/preflightStore.ts +0 -136
- package/src/core/store/projectFile.ts +0 -101
- package/src/core/store/workspace.ts +0 -328
- package/src/core/supersede.ts +0 -74
- package/src/core/userConfig.ts +0 -205
- package/src/core/workTargets.ts +0 -120
- package/src/server/api/chatgptRoutes.ts +0 -49
- package/src/server/api/manifest.ts +0 -128
- package/src/server/api/projectsRoutes.ts +0 -89
- package/src/server/api/releaseNoteRoutes.ts +0 -78
- package/src/server/api/repoRoutes.ts +0 -67
- package/src/server/api/routes.ts +0 -382
- package/src/server/api/userThemeRoutes.ts +0 -62
- package/src/server/server.ts +0 -108
- package/src/shared/dates.ts +0 -12
- package/src/shared/preflightInput.ts +0 -27
- package/src/shared/refs.ts +0 -55
- package/src/shared/repos.ts +0 -113
- package/src/shared/scopeView.ts +0 -48
- package/src/shared/types.ts +0 -700
- package/src/shared/workTarget.ts +0 -44
- /package/{src → lib}/core/preflight/launcher.mjs +0 -0
- /package/{src → lib}/core/preflight/mock-ui.html +0 -0
- /package/{src → lib}/core/preflight/mock-ui.png +0 -0
- /package/{src → lib}/core/preflight/render-image/Dockerfile +0 -0
- /package/{src → lib}/core/preflight/render-image/fonts-ja.conf +0 -0
- /package/{src → lib}/core/preflight/render-image/render.mjs +0 -0
|
@@ -1,707 +0,0 @@
|
|
|
1
|
-
import { lstat, mkdir, readFile, rm, writeFile } from "node:fs/promises";
|
|
2
|
-
import { existsSync } from "node:fs";
|
|
3
|
-
import { isAbsolute, join, relative } from "node:path";
|
|
4
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
-
import {
|
|
6
|
-
type PreflightAssessment,
|
|
7
|
-
type PreflightLogEntry,
|
|
8
|
-
type PreflightRun,
|
|
9
|
-
type ProposedTask,
|
|
10
|
-
type Relation,
|
|
11
|
-
type Request,
|
|
12
|
-
type MaterializeResult,
|
|
13
|
-
type Task,
|
|
14
|
-
type Evidence,
|
|
15
|
-
type FixedAttachment,
|
|
16
|
-
type InputMatch,
|
|
17
|
-
type PreflightPulse,
|
|
18
|
-
} from "../../shared/types.ts";
|
|
19
|
-
import { normalizeTaskId, REQUEST_ID } from "../../shared/refs.ts";
|
|
20
|
-
import { nowIso, writeFileAtomic } from "../store/fsutil.ts";
|
|
21
|
-
import { ConflictError, NotFoundError } from "../store/collection.ts";
|
|
22
|
-
import type { Workspace } from "../store/workspace.ts";
|
|
23
|
-
import { supersedeCandidates } from "../supersede.ts";
|
|
24
|
-
import { redact } from "../redact.ts";
|
|
25
|
-
import { renderCarryover, selectCarryover } from "./carryover.ts";
|
|
26
|
-
import type { PreflightEngine, PreflightJob } from "./engine.ts";
|
|
27
|
-
import { refScope, type ResolvedRef } from "../repoRefs.ts";
|
|
28
|
-
import { checkRepoTarget, planWorkstreams, workstreamPatch } from "../workTargets.ts";
|
|
29
|
-
import { hideConfigPath } from "../userConfig.ts";
|
|
30
|
-
import { extractXlsx, XlsxError } from "./xlsx.ts";
|
|
31
|
-
import { applyUiShortage, IMAGE_TYPES, loadUiMaterials, readUiImage, UI_DIR, UiMaterialError } from "./uiMaterials.ts";
|
|
32
|
-
import { compareInput, normalizeInput, renderRequestSnapshot, runInput, StaleInputError } from "./input.ts";
|
|
33
|
-
import { changedLabel } from "../../shared/preflightInput.ts";
|
|
34
|
-
import { PREFLIGHT_CANCELLED } from "../../shared/directTask.ts";
|
|
35
|
-
|
|
36
|
-
/** 始められない理由をそのまま失敗にするエンジン(run の記録とログに残すため) */
|
|
37
|
-
const failing = (name: PreflightEngine["name"], message: string): PreflightEngine => ({
|
|
38
|
-
name,
|
|
39
|
-
status: async () => ({ name, ok: false, detail: message }),
|
|
40
|
-
run: async () => Promise.reject(new Error(message)),
|
|
41
|
-
});
|
|
42
|
-
|
|
43
|
-
/** 同じ要望の Preflight が実行中(エンジンを使えないのとは別) */
|
|
44
|
-
export class PreflightBusyError extends Error {}
|
|
45
|
-
|
|
46
|
-
/** タスク案の題が、編集を始めたあとに外で変わった(409 code: rev_conflict。current に今の案) */
|
|
47
|
-
export class DraftConflictError extends Error {
|
|
48
|
-
constructor(readonly current: ProposedTask) {
|
|
49
|
-
super(`${current.key} の題が他で変わりました(今の題: ${current.title})`);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/** pulse の問い合わせの ID の形が違う(400) */
|
|
54
|
-
export class PulseInputError extends Error {}
|
|
55
|
-
|
|
56
|
-
export class PreflightService {
|
|
57
|
-
private active = new Map<string, { run: PreflightRun; abort: AbortController; done: Promise<void> }>();
|
|
58
|
-
|
|
59
|
-
/** 最後に分かった既定のエンジン */
|
|
60
|
-
private lastDefault: PreflightEngine["name"];
|
|
61
|
-
|
|
62
|
-
/**
|
|
63
|
-
* defaultEngine: 決まった名前か、読むたびに今の既定を返す関数(serve: 個人設定の preflight.engine を Preflight を始めるたびに読む)
|
|
64
|
-
*/
|
|
65
|
-
constructor(
|
|
66
|
-
private ws: Workspace,
|
|
67
|
-
private engines: Partial<Record<PreflightEngine["name"], PreflightEngine>>,
|
|
68
|
-
defaultEngine: PreflightEngine["name"] | { load: () => Promise<PreflightEngine["name"]>; initial: PreflightEngine["name"] },
|
|
69
|
-
) {
|
|
70
|
-
if (typeof defaultEngine === "string") {
|
|
71
|
-
this.lastDefault = defaultEngine;
|
|
72
|
-
this.loadDefault = async () => defaultEngine;
|
|
73
|
-
} else {
|
|
74
|
-
this.lastDefault = defaultEngine.initial;
|
|
75
|
-
this.loadDefault = defaultEngine.load;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
private loadDefault: () => Promise<PreflightEngine["name"]>;
|
|
80
|
-
|
|
81
|
-
/** 既定のエンジン(最後に読めた値。画面の表示用) */
|
|
82
|
-
get defaultEngine(): PreflightEngine["name"] {
|
|
83
|
-
return this.lastDefault;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** 今の既定のエンジン。読めなければ SettingsError など */
|
|
87
|
-
private async currentDefault(): Promise<PreflightEngine["name"]> {
|
|
88
|
-
this.lastDefault = await this.loadDefault();
|
|
89
|
-
return this.lastDefault;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
/** 既定のエンジンが使えるか(個人設定を読み直す。読めなければ直す場所を出す) */
|
|
93
|
-
async engineStatus() {
|
|
94
|
-
let name: PreflightEngine["name"];
|
|
95
|
-
try {
|
|
96
|
-
name = await this.currentDefault();
|
|
97
|
-
} catch (e) {
|
|
98
|
-
return { name: this.lastDefault, ok: false, detail: `個人設定を読めないので Preflight を始められません: ${(e as Error).message}` };
|
|
99
|
-
}
|
|
100
|
-
const e = this.engines[name];
|
|
101
|
-
return e ? e.status() : { name, ok: false, detail: "エンジンがありません" };
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
availableEngines() {
|
|
105
|
-
return Object.keys(this.engines) as PreflightEngine["name"][];
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
async list(requestId: string) {
|
|
109
|
-
return this.ws.preflight.list(requestId);
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
async get(requestId: string, runId: string) {
|
|
113
|
-
return this.active.get(runId)?.run ?? (await this.ws.preflight.get(requestId, runId));
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
/** 次の Preflight に引き継ぐもの(画面・CLI で実行前に見せる) */
|
|
117
|
-
carryover(requestId: string) {
|
|
118
|
-
this.ws.requests.require(requestId);
|
|
119
|
-
return selectCarryover(this.ws, requestId);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
/** Preflight へのメモを書き足す */
|
|
123
|
-
async addNote(requestId: string, body: string, actor?: string) {
|
|
124
|
-
this.ws.requests.require(requestId);
|
|
125
|
-
const note = await this.ws.notes.add(requestId, body, actor);
|
|
126
|
-
this.ws.emit({ type: "changed", kind: "note", request: requestId });
|
|
127
|
-
return note;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
async start(requestId: string, opts: { engine?: PreflightEngine["name"]; actor?: string } = {}): Promise<PreflightRun> {
|
|
131
|
-
// 評価対象はディスクから読み直して固定する(監視していない外部の編集も取り込む)。この後に変わっても、この run は固定した内容で評価する
|
|
132
|
-
await this.ws.requests.reload(requestId);
|
|
133
|
-
const current = this.ws.requests.require(requestId);
|
|
134
|
-
const input = normalizeInput(current);
|
|
135
|
-
const request: Request = { ...current, ...input };
|
|
136
|
-
if ([...this.active.values()].some((a) => a.run.requestId === requestId)) {
|
|
137
|
-
throw new PreflightBusyError(`${requestId} の preflight は実行中です`);
|
|
138
|
-
}
|
|
139
|
-
// 既定のエンジンは始めるたびに個人設定から決める。読めなければ、この run を設定のエラーとして失敗にする
|
|
140
|
-
// (古い設定や Mock に落とさない。serve とほかの操作は続ける)
|
|
141
|
-
let engine: PreflightEngine | undefined;
|
|
142
|
-
if (opts.engine) engine = this.engines[opts.engine];
|
|
143
|
-
else {
|
|
144
|
-
try {
|
|
145
|
-
engine = this.engines[await this.currentDefault()];
|
|
146
|
-
} catch (e) {
|
|
147
|
-
const message = `個人設定を読めないので Preflight を始めません(Docker は起動していません): ${hideConfigPath(e)}`;
|
|
148
|
-
engine = failing(this.lastDefault, message);
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
if (!engine) throw new Error(`engine ${opts.engine} は利用できません`);
|
|
152
|
-
// 始めるときの設定に決める(この run の間は個人設定が変わっても使い続ける)
|
|
153
|
-
if (engine.snapshot) {
|
|
154
|
-
const from = engine;
|
|
155
|
-
engine = await from.snapshot!().catch((e: Error) => failing(from.name, e.message));
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
const stamp = nowIso().replace(/[-:]/g, "").replace("T", "-").slice(0, 15);
|
|
159
|
-
const id = `PF-${stamp}-${randomBytes(2).toString("hex")}`;
|
|
160
|
-
// 前回の結果とその後のメモ。開始の時点で選んで固定する(実行中に足されたメモは次回に回る)
|
|
161
|
-
const carry = await selectCarryover(this.ws, requestId);
|
|
162
|
-
const carryover = renderCarryover(carry);
|
|
163
|
-
// 読む参照先は始めるときに決める(読めないものは理由を記録に残す。このマシンのパスは残さない)
|
|
164
|
-
const refs = this.ws.refs();
|
|
165
|
-
const run: PreflightRun = {
|
|
166
|
-
id,
|
|
167
|
-
requestId,
|
|
168
|
-
engine: engine.name,
|
|
169
|
-
status: "running",
|
|
170
|
-
startedAt: nowIso(),
|
|
171
|
-
startedBy: opts.actor,
|
|
172
|
-
previous: carry.previous?.id,
|
|
173
|
-
notes: carry.notes.length ? carry.notes.map((n) => n.id) : undefined,
|
|
174
|
-
log: [],
|
|
175
|
-
drafts: [],
|
|
176
|
-
scope: refs.map(refScope),
|
|
177
|
-
ui: { status: "generating", targets: [], items: [], problems: [] },
|
|
178
|
-
input,
|
|
179
|
-
};
|
|
180
|
-
const runDir = this.ws.preflight.runDir(requestId, id);
|
|
181
|
-
// 添付は始める時点のものを run の中にコピーして固定する。途中で変わったら始めない(原本は残るので、そのまま再試行できる)
|
|
182
|
-
try {
|
|
183
|
-
const fixed = await this.ws.attachments.snapshot(requestId, runDir);
|
|
184
|
-
if (fixed.length) run.attachments = fixed;
|
|
185
|
-
} catch (e) {
|
|
186
|
-
await rm(runDir, { recursive: true, force: true });
|
|
187
|
-
throw e;
|
|
188
|
-
}
|
|
189
|
-
await this.ws.preflight.save(run);
|
|
190
|
-
if (carryover) await writeFileAtomic(join(runDir, "carryover.md"), carryover);
|
|
191
|
-
const carried = carryover ? { text: carryover, previous: carry.previous, notes: carry.notes } : undefined;
|
|
192
|
-
if (carry.previous) this.log(run, { kind: "info", text: `前回 ${carry.previous.id} の結果を引き継ぎます` });
|
|
193
|
-
if (carry.previous && carry.requestChange) {
|
|
194
|
-
const m = carry.requestChange.match;
|
|
195
|
-
this.log(run, {
|
|
196
|
-
kind: "info",
|
|
197
|
-
text: m.status === "changed"
|
|
198
|
-
? `前回の評価のあとで要望の${changedLabel(m.changed)}が変わりました。今の内容を基準に評価し、変わったことを資料として渡します`
|
|
199
|
-
: `前回が何を評価したか確かめられません(${m.reason ?? "不明"})。今の内容を基準に評価します`,
|
|
200
|
-
});
|
|
201
|
-
}
|
|
202
|
-
else if (carry.previousSkipped) this.log(run, { kind: "info", text: `前回の結果は引き継ぎません(${carry.previousSkipped})` });
|
|
203
|
-
if (carry.notes.length) this.log(run, { kind: "info", text: `メモ ${carry.notes.length} 件を渡します: ${carry.notes.map((n) => n.id).join(", ")}` });
|
|
204
|
-
if (run.attachments) this.log(run, { kind: "info", text: `添付 ${run.attachments.length} 件を固定して渡します: ${run.attachments.map((a) => `${a.id}(${a.name})`).join(", ")}` });
|
|
205
|
-
for (const n of carry.invalidNotes) this.log(run, { kind: "error", text: `読めないメモを除きました: ${n.file}(${n.error})` });
|
|
206
|
-
for (const s of run.scope ?? []) if (s.status !== "ok") this.log(run, { kind: "info", text: `見ていない参照先: ${s.name}(${s.reason})` });
|
|
207
|
-
if (refs.length && !refs.some((r) => r.status === "ok")) {
|
|
208
|
-
this.log(run, { kind: "info", text: "読める参照先がありません。要望と P3 のデータだけで評価します(コードは確かめられません)" });
|
|
209
|
-
}
|
|
210
|
-
// 要望のスナップショットと文脈をファイルとして残す(後から「何を根拠に判断したか」を辿れる)
|
|
211
|
-
await writeFileAtomic(join(runDir, "request.md"), renderRequestSnapshot(request.id, input));
|
|
212
|
-
// ステータスを動かすのはタスク化する前の要望だけ。進行中・完了の要望で再評価しても状態は変えない
|
|
213
|
-
const before = request.status;
|
|
214
|
-
const early = before === "draft" || before === "preflight" || before === "reviewed";
|
|
215
|
-
await this.ws.requests.update(requestId, early ? { status: "preflight", lastPreflight: id } : { lastPreflight: id }, { actor: opts.actor });
|
|
216
|
-
this.ws.emit({ type: "changed", kind: "request", request: requestId });
|
|
217
|
-
|
|
218
|
-
const abort = new AbortController();
|
|
219
|
-
const after = (ok: boolean) => (early ? (ok ? "reviewed" : before === "reviewed" ? "reviewed" : "draft") : before);
|
|
220
|
-
const done = this.execute(engine, run, request, runDir, carried, abort.signal, after, refs);
|
|
221
|
-
this.active.set(id, { run, abort, done });
|
|
222
|
-
return run;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
/** 実行中の run の完了を待つ(CLI 用)。完了後の run を返す */
|
|
226
|
-
async wait(requestId: string, runId: string): Promise<PreflightRun | undefined> {
|
|
227
|
-
await this.active.get(runId)?.done;
|
|
228
|
-
return this.ws.preflight.get(requestId, runId);
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
cancel(runId: string) {
|
|
232
|
-
this.active.get(runId)?.abort.abort();
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
/** 実行中の run の数 */
|
|
236
|
-
running(): number {
|
|
237
|
-
return this.active.size;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/** 実行中の run が全部終わるまで待つ(cancel: 先に全部を取り消す)。serve を止める・登録から外れたプロジェクトを閉じる前に */
|
|
241
|
-
async settle(opts: { cancel?: boolean } = {}): Promise<void> {
|
|
242
|
-
const jobs = [...this.active.values()];
|
|
243
|
-
if (opts.cancel) for (const j of jobs) j.abort.abort();
|
|
244
|
-
await Promise.allSettled(jobs.map((j) => j.done));
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
private log(run: PreflightRun, e: Omit<PreflightLogEntry, "at">) {
|
|
248
|
-
// トークンらしいもの(Codex のエラーが一部を見せるキーなど)は残さない
|
|
249
|
-
const entry = { ...e, text: redact(e.text), at: nowIso() };
|
|
250
|
-
run.log.push(entry);
|
|
251
|
-
this.ws.emit({ type: "preflight-log", runId: run.id, entry });
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
/** 共有の記録に出すパス: 参照先の中なら <参照先>:<パス>、データのフォルダの中なら data:<パス>(このマシンのパスは出さない) */
|
|
255
|
-
private shownPath(p: string, refs: ResolvedRef[]): string {
|
|
256
|
-
const inside = (dir: string) => {
|
|
257
|
-
const rel = relative(dir, p);
|
|
258
|
-
return rel.startsWith("..") || isAbsolute(rel) ? undefined : rel;
|
|
259
|
-
};
|
|
260
|
-
for (const r of refs) {
|
|
261
|
-
const rel = r.local ? inside(r.local) : undefined;
|
|
262
|
-
if (rel !== undefined) return `${r.name}:${rel}`;
|
|
263
|
-
}
|
|
264
|
-
const data = inside(this.ws.dataDir);
|
|
265
|
-
if (data !== undefined) return `data:${data}`;
|
|
266
|
-
return p.startsWith("/workspace") ? p : "(参照先の外)";
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
private async execute(
|
|
270
|
-
engine: PreflightEngine,
|
|
271
|
-
run: PreflightRun,
|
|
272
|
-
request: Request,
|
|
273
|
-
runDir: string,
|
|
274
|
-
carryover: PreflightJob["carryover"],
|
|
275
|
-
signal: AbortSignal,
|
|
276
|
-
after: (ok: boolean) => Request["status"],
|
|
277
|
-
refs: ResolvedRef[],
|
|
278
|
-
) {
|
|
279
|
-
try {
|
|
280
|
-
await this.extractAttachments(run, runDir);
|
|
281
|
-
const outcome = await engine.run(
|
|
282
|
-
{
|
|
283
|
-
project: this.ws.project,
|
|
284
|
-
// 始めたときに固定した要望(実行中に本文が変わっても、request.md・run.input と同じものを渡す)
|
|
285
|
-
request,
|
|
286
|
-
refs,
|
|
287
|
-
dataDir: this.ws.dataDir,
|
|
288
|
-
runDir,
|
|
289
|
-
carryover,
|
|
290
|
-
attachments: run.attachments ?? [],
|
|
291
|
-
},
|
|
292
|
-
(e) => this.log(run, e),
|
|
293
|
-
signal,
|
|
294
|
-
);
|
|
295
|
-
// 書いてよい範囲の外が変更されていないか確かめる
|
|
296
|
-
const stray = outcome.changed.filter((p) => !p.startsWith(`${runDir}/`));
|
|
297
|
-
for (const p of stray) this.log(run, { kind: "error", text: `想定外の変更: ${this.shownPath(p, refs)}(確認して必要なら元に戻してください)` });
|
|
298
|
-
|
|
299
|
-
run.assessment = parseAssessment(await readFile(join(runDir, "assessment.json"), "utf8"), refs);
|
|
300
|
-
run.drafts = await this.ws.preflight.loadDrafts(run.requestId, run.id);
|
|
301
|
-
// 画面資料: 確かめて取り込む。不正なものは除いて理由を残す(評価は消さない)。必要な画面イメージが足りなければ go を clarify に
|
|
302
|
-
run.ui = applyUiShortage(run.assessment, await loadUiMaterials(runDir, run.id, run.drafts.map((d) => d.key)));
|
|
303
|
-
for (const p of run.ui.problems) this.log(run, { kind: "error", text: `画面資料を取り込めません: ${p}` });
|
|
304
|
-
if (run.ui.status === "missing") this.log(run, { kind: "info", text: `画面資料が足りません: ${run.ui.reason}` });
|
|
305
|
-
run.ui = withCurrent(run.ui, run);
|
|
306
|
-
if (run.ui.verdictAdjusted) this.log(run, { kind: "info", text: "必要な画面イメージが足りないので、判定を go から clarify にしました" });
|
|
307
|
-
run.status = "completed";
|
|
308
|
-
} catch (e) {
|
|
309
|
-
run.status = "failed";
|
|
310
|
-
run.ui = withCurrent({ status: "missing", reason: "評価が終わらなかったので、画面資料を取り込んでいません", targets: [], items: [], problems: [] }, run);
|
|
311
|
-
// 取消はエンジンによらず同じ言い方で残す(失敗とは分けて扱う。shared/directTask.ts)
|
|
312
|
-
run.error = signal.aborted ? PREFLIGHT_CANCELLED : redact((e as Error).message);
|
|
313
|
-
this.log(run, { kind: "error", text: run.error });
|
|
314
|
-
} finally {
|
|
315
|
-
run.finishedAt = nowIso();
|
|
316
|
-
await this.ws.preflight.save(run);
|
|
317
|
-
// 評価中にした要望だけ、終わったら評価済み(失敗なら元)へ戻す。実行中に人や AI が変えたステータス
|
|
318
|
-
// (進行中に戻した・完了済にしたなど)や、評価中にしていない要望(進行中・対応済など)は上書きしない
|
|
319
|
-
const status = after(run.status === "completed");
|
|
320
|
-
if (this.ws.requests.get(run.requestId)?.status === "preflight" && status !== "preflight") {
|
|
321
|
-
await this.ws.requests.update(run.requestId, { status });
|
|
322
|
-
}
|
|
323
|
-
// 保存が終わってから実行中の一覧から外す(先に外すと wait() が保存前のファイルを読む)
|
|
324
|
-
this.active.delete(run.id);
|
|
325
|
-
this.ws.emit({ type: "preflight-status", runId: run.id, status: run.status });
|
|
326
|
-
this.ws.emit({ type: "changed", kind: "request", request: run.requestId });
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
/**
|
|
331
|
-
* 最新の Preflight(lastPreflight)と、指定した run の今の状態。要望と run.json をディスクから読むだけで、読み込んだ内容
|
|
332
|
-
* (キャッシュ)・ファイル・rev は変えない。監視が届かなくても、外(CLI など)で始めた run とその進み・終わりを画面が見つけるため。
|
|
333
|
-
* ID の形が違えば使い方の誤り(パスは受け取らない)
|
|
334
|
-
*/
|
|
335
|
-
async pulse(requestId: string, runId?: string): Promise<PreflightPulse> {
|
|
336
|
-
if (!REQUEST_ID.test(requestId)) throw new PulseInputError(`要望 ID の形ではありません: ${requestId}`);
|
|
337
|
-
if (runId !== undefined && !/^PF-[\w-]+$/.test(runId)) throw new PulseInputError(`run の ID の形ではありません: ${runId}`);
|
|
338
|
-
const run = runId ? await this.ws.preflight.pulse(requestId, runId) : undefined;
|
|
339
|
-
const read = await this.ws.requests.peek(requestId);
|
|
340
|
-
if (!("item" in read)) return { requestId, state: "missing" in read ? "gone" : "broken", latest: null, ...(run ? { run } : {}) };
|
|
341
|
-
const last = read.item.lastPreflight;
|
|
342
|
-
const latest = last ? (last === runId ? run! : await this.ws.preflight.pulse(requestId, last)) : null;
|
|
343
|
-
return { requestId, state: "ok", latest, ...(run ? { run } : {}) };
|
|
344
|
-
}
|
|
345
|
-
|
|
346
|
-
/**
|
|
347
|
-
* 画面資料の画像(要望 / run / 資料 ID で決める。パスは受け取らない)。取り込んだときと同じ確かめ方をもう一度してから返す。
|
|
348
|
-
* 原稿(HTML)は返さない
|
|
349
|
-
*/
|
|
350
|
-
async uiImage(requestId: string, runId: string, materialId: string): Promise<{ data: Buffer; type: string; item: NonNullable<PreflightRun["ui"]>["items"][number] }> {
|
|
351
|
-
if (!/^PF-[\w-]+$/.test(runId)) throw new NotFoundError(runId);
|
|
352
|
-
this.ws.requests.require(requestId);
|
|
353
|
-
const run = await this.get(requestId, runId);
|
|
354
|
-
const item = run?.ui?.items.find((x) => x.id === materialId);
|
|
355
|
-
if (!run || !item) throw new NotFoundError(`${requestId}/${runId}/${materialId}`);
|
|
356
|
-
try {
|
|
357
|
-
const { data, info } = await readUiImage(join(this.ws.preflight.runDir(requestId, runId), UI_DIR), item.file);
|
|
358
|
-
return { data, type: IMAGE_TYPES[info.format], item };
|
|
359
|
-
} catch (e) {
|
|
360
|
-
if (e instanceof UiMaterialError) throw new NotFoundError(`${materialId}(${e.message})`);
|
|
361
|
-
throw e;
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
/** 要望の添付を足す(CLI と API で同じ確かめ方) */
|
|
366
|
-
async addAttachment(requestId: string, input: { data: Buffer; name: string; description?: string; source?: string }, actor?: string) {
|
|
367
|
-
this.ws.requests.require(requestId);
|
|
368
|
-
const a = await this.ws.attachments.add(requestId, input, actor);
|
|
369
|
-
this.ws.emit({ type: "changed", kind: "attachment", request: requestId });
|
|
370
|
-
return a;
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
async removeAttachment(requestId: string, id: string) {
|
|
374
|
-
this.ws.requests.require(requestId);
|
|
375
|
-
await this.ws.attachments.remove(requestId, id);
|
|
376
|
-
this.ws.emit({ type: "changed", kind: "attachment", request: requestId });
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
/** run に固定した添付の原本(その run の資料。後で添付を消しても変わらない) */
|
|
380
|
-
async fixedAttachment(requestId: string, runId: string, id: string): Promise<{ meta: FixedAttachment; data: Buffer }> {
|
|
381
|
-
if (!/^PF-[\w-]+$/.test(runId)) throw new NotFoundError(runId);
|
|
382
|
-
this.ws.requests.require(requestId);
|
|
383
|
-
const run = await this.get(requestId, runId);
|
|
384
|
-
const meta = run?.attachments?.find((a) => a.id === id);
|
|
385
|
-
if (!meta) throw new NotFoundError(`${requestId}/${runId}/${id}`);
|
|
386
|
-
const file = join(this.ws.preflight.runDir(requestId, runId), meta.path);
|
|
387
|
-
const st = await lstat(file).catch(() => undefined);
|
|
388
|
-
const data = st?.isFile() ? await readFile(file) : undefined;
|
|
389
|
-
if (!data || data.length !== meta.bytes || createHash("sha256").update(data).digest("hex") !== meta.sha256) {
|
|
390
|
-
throw new NotFoundError(`${id}(run に固定した原本が無いか、変わっています)`);
|
|
391
|
-
}
|
|
392
|
-
return { meta, data };
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
/** 固定した xlsx から、セルの文字と標準の埋め込み画像を取り出して run の中に置く(読めなくても評価は続ける) */
|
|
396
|
-
private async extractAttachments(run: PreflightRun, runDir: string) {
|
|
397
|
-
const xlsx = (run.attachments ?? []).filter((a) => a.format === "xlsx" && !a.extract);
|
|
398
|
-
for (const a of xlsx) {
|
|
399
|
-
try {
|
|
400
|
-
const x = extractXlsx(await readFile(join(runDir, a.path)), `${a.name}(${a.id})`);
|
|
401
|
-
const text = `attachments/${a.id}.md`;
|
|
402
|
-
await writeFileAtomic(join(runDir, text), x.text);
|
|
403
|
-
const images = [];
|
|
404
|
-
for (const [i, img] of x.images.entries()) {
|
|
405
|
-
const file = `spec/${a.id}-${i + 1}.${img.format === "png" ? "png" : "jpg"}`;
|
|
406
|
-
await mkdir(join(runDir, UI_DIR, "spec"), { recursive: true });
|
|
407
|
-
await writeFile(join(runDir, UI_DIR, file), img.data);
|
|
408
|
-
images.push({ id: `${a.id}-${i + 1}`, file, sheet: img.sheet, anchor: img.anchor, format: img.format, width: img.width, height: img.height, bytes: img.data.length });
|
|
409
|
-
}
|
|
410
|
-
a.extract = { text, sheets: x.sheets, cells: x.cells, unknownCells: x.unknownCells, images, truncated: x.truncated, unsupported: x.unsupported };
|
|
411
|
-
this.log(run, {
|
|
412
|
-
kind: "info",
|
|
413
|
-
text: `${a.name}: シート ${x.sheets}・セル ${x.cells}・画像 ${images.length} を取り出しました${x.truncated.length ? `(打ち切り ${x.truncated.length})` : ""}${x.unsupported.length ? `(扱っていないもの ${x.unsupported.length})` : ""}`,
|
|
414
|
-
});
|
|
415
|
-
} catch (e) {
|
|
416
|
-
const error = e instanceof XlsxError ? e.message : `読めません: ${(e as Error).message}`;
|
|
417
|
-
a.extract = { sheets: 0, cells: 0, unknownCells: 0, images: [], truncated: [], unsupported: [], error };
|
|
418
|
-
this.log(run, { kind: "error", text: `${a.name} の中身を取り出せません(未読として渡します): ${error}` });
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
if (xlsx.length) await this.ws.preflight.save(run);
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
/** run に固定した xlsx から取り出した内容(Markdown) */
|
|
425
|
-
async fixedExtract(requestId: string, runId: string, id: string): Promise<string> {
|
|
426
|
-
const { meta } = await this.fixedAttachment(requestId, runId, id);
|
|
427
|
-
const rel = meta.extract?.text;
|
|
428
|
-
if (!rel || rel !== `attachments/${meta.id}.md`) throw new NotFoundError(`${id} の取り出した内容`);
|
|
429
|
-
const file = join(this.ws.preflight.runDir(requestId, runId), rel);
|
|
430
|
-
const st = await lstat(file).catch(() => undefined);
|
|
431
|
-
if (!st?.isFile()) throw new NotFoundError(`${id} の取り出した内容`);
|
|
432
|
-
return readFile(file, "utf8");
|
|
433
|
-
}
|
|
434
|
-
|
|
435
|
-
/**
|
|
436
|
-
* タスク案を直す(案のファイルを読み直してから書く)。opts.expectedTitle: 編集を始めたときの題。今の題と違えば(外で
|
|
437
|
-
* 変わった)DraftConflictError で書かない。画面から題を変えるときは必ず渡す。CLI・内部の呼び出しは渡さなくてよい
|
|
438
|
-
* (その場合は確かめない)。期待値はファイルに書かない。読んでから書くまでの間に外のプロセスが書くことまでは防げない
|
|
439
|
-
*/
|
|
440
|
-
async updateDraft(requestId: string, runId: string, key: string, patch: Partial<ProposedTask>, opts: { expectedTitle?: string } = {}) {
|
|
441
|
-
const run = await this.ws.preflight.get(requestId, runId);
|
|
442
|
-
const draft = run?.drafts.find((d) => d.key === key);
|
|
443
|
-
if (!run || !draft) throw new Error(`${runId}/${key} not found`);
|
|
444
|
-
if (opts.expectedTitle !== undefined && draft.title !== opts.expectedTitle) throw new DraftConflictError(draft);
|
|
445
|
-
// 作業先は作業先にできる参照先だけ(変える前に断る)
|
|
446
|
-
if ("repo" in patch) checkRepoTarget(this.ws, patch.repo);
|
|
447
|
-
const next = { ...draft, ...patch, key };
|
|
448
|
-
await this.ws.preflight.saveDraft(requestId, runId, next);
|
|
449
|
-
return next;
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
/**
|
|
453
|
-
* run の評価対象と今の要望が同じか。fresh: 要望をディスクから読み直してから比べる(タスク化の直前など)。
|
|
454
|
-
* 既定はメモリ上の要望(serve は変更を監視して取り込む)
|
|
455
|
-
*/
|
|
456
|
-
async inputMatch(requestId: string, run: PreflightRun, opts: { fresh?: boolean } = {}): Promise<InputMatch> {
|
|
457
|
-
if (opts.fresh) await this.ws.requests.reload(requestId);
|
|
458
|
-
const request = this.ws.requests.require(requestId);
|
|
459
|
-
return compareInput(await runInput(run, this.ws.preflight.runDir(requestId, run.id)), request);
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
/** run に今の要望との比較(inputMatch)を添える(画面・CLI・API の表示用。run.json には書かない) */
|
|
463
|
-
async withInputMatch(requestId: string, run: PreflightRun): Promise<PreflightRun & { inputMatch: InputMatch }> {
|
|
464
|
-
return { ...run, inputMatch: await this.inputMatch(requestId, run) };
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
/** タスク化の前に見せるもの: 採用する案と、置き換えられる既存タスク、評価対象が今の要望と同じか(ファイルは変えない) */
|
|
468
|
-
async previewMaterialize(requestId: string, runId: string) {
|
|
469
|
-
const run = await this.ws.preflight.get(requestId, runId);
|
|
470
|
-
if (!run) throw new NotFoundError(runId);
|
|
471
|
-
return {
|
|
472
|
-
include: run.drafts.filter((d) => d.include).map((d) => d.key),
|
|
473
|
-
candidates: supersedeCandidates(this.ws, run),
|
|
474
|
-
materialized: run.materialized ?? [],
|
|
475
|
-
inputMatch: await this.inputMatch(requestId, run, { fresh: true }),
|
|
476
|
-
};
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
/**
|
|
480
|
-
* タスク化: 採用されたタスク案を、要望のフォルダの tasks/T00x.md として書き出し、関係を張る。
|
|
481
|
-
* - 同じ run 内の dependsOn → depends_on(要望の中なので相対参照 T00x)
|
|
482
|
-
* - 案が持つ既存項目への関係 → 存在するものだけ(origin: preflight)。置き換え(supersedes)もここで各タスクに残る
|
|
483
|
-
* - 案の supersedes → 同じ要望の今あるタスクへの supersedes(置き換え)
|
|
484
|
-
* - archive: 置き換えられるタスク(previewMaterialize の候補)のうちアーカイブするもの。既定はどれも残す。
|
|
485
|
-
* 確定の時点で候補を読み直し、候補でない・rev が変わったものがあれば何も変えずに失敗する
|
|
486
|
-
*
|
|
487
|
-
* 古いタスクを先に外さないよう、新しいタスクと関係を保存してからアーカイブする。途中経過は run.json の
|
|
488
|
-
* materialization に残し、途中で失敗したら同じ呼び出しでやり直せる(作った案は作り直さず、アーカイブも重ねない)。
|
|
489
|
-
*
|
|
490
|
-
* 評価対象(タイトル・本文)が今の要望と違う・確かめられない run からはタスク化しない(StaleInputError。やり直しも同じ)。
|
|
491
|
-
* 直前に要望をディスクから読み直して比べ、断るときは何も書かない
|
|
492
|
-
*/
|
|
493
|
-
async materialize(
|
|
494
|
-
requestId: string,
|
|
495
|
-
runId: string,
|
|
496
|
-
actor = "preflight",
|
|
497
|
-
opts: { archive?: { id: string; rev?: number }[] } = {},
|
|
498
|
-
): Promise<MaterializeResult> {
|
|
499
|
-
const run = await this.ws.preflight.get(requestId, runId);
|
|
500
|
-
if (!run || run.status !== "completed") throw new Error("完了した preflight のみタスク化できます");
|
|
501
|
-
const resuming = run.materialization && !run.materialization.done;
|
|
502
|
-
if (!resuming && run.materialized?.length) throw new Error(`既にタスク化済みです: ${run.materialized.join(", ")}`);
|
|
503
|
-
const match = await this.inputMatch(requestId, run, { fresh: true });
|
|
504
|
-
if (match.status !== "same") throw new StaleInputError(requestId, runId, match);
|
|
505
|
-
const request = this.ws.requests.require(requestId);
|
|
506
|
-
const tasks = this.ws.tasksOf(requestId);
|
|
507
|
-
const drafts = resuming ? run.drafts.filter((d) => d.key in run.materialization!.created || d.include) : run.drafts.filter((d) => d.include);
|
|
508
|
-
if (!drafts.length) throw new Error("採用したタスク案がありません");
|
|
509
|
-
|
|
510
|
-
// 作業先: 手で直した案も、変える前に確かめる。割り当てるブランチもここで決めて run に残す(やり直しでも同じ)
|
|
511
|
-
for (const d of drafts) checkRepoTarget(this.ws, d.repo);
|
|
512
|
-
const draftRepo = (d: ProposedTask) => d.repo ?? null;
|
|
513
|
-
const plan =
|
|
514
|
-
resuming && run.materialization!.workstreams
|
|
515
|
-
? run.materialization!.workstreams
|
|
516
|
-
: planWorkstreams(
|
|
517
|
-
this.ws,
|
|
518
|
-
requestId,
|
|
519
|
-
drafts.map(draftRepo).filter((r): r is string => !!r),
|
|
520
|
-
);
|
|
521
|
-
|
|
522
|
-
const candidates = supersedeCandidates(this.ws, run);
|
|
523
|
-
if (!resuming) {
|
|
524
|
-
const chosen: string[] = [];
|
|
525
|
-
for (const sel of opts.archive ?? []) {
|
|
526
|
-
const id = normalizeTaskId(sel.id) ?? sel.id;
|
|
527
|
-
const c = candidates.find((x) => x.id === id);
|
|
528
|
-
if (!c) throw new Error(`${id} は置き換えられるタスクの候補ではありません(もう一度確認してください)`);
|
|
529
|
-
if (sel.rev !== undefined && sel.rev !== c.rev) throw new ConflictError(`${requestId}/${id}`, sel.rev, c.rev);
|
|
530
|
-
if (!chosen.includes(id)) chosen.push(id);
|
|
531
|
-
}
|
|
532
|
-
run.materialization = { created: {}, archive: chosen, archived: [], done: false, workstreams: plan };
|
|
533
|
-
await this.ws.preflight.save(run);
|
|
534
|
-
}
|
|
535
|
-
const state = run.materialization!;
|
|
536
|
-
|
|
537
|
-
const keyToId = new Map<string, string>();
|
|
538
|
-
const created: Task[] = [];
|
|
539
|
-
// 置き換えは、同じ要望に今あるタスクだけ(Codex が書いた T3 / 3 も T003 にそろえる)
|
|
540
|
-
const supersedes = (d: ProposedTask): Relation[] =>
|
|
541
|
-
[...new Set(d.supersedes.map((x) => normalizeTaskId(x) ?? x))]
|
|
542
|
-
.filter((id) => tasks.get(id))
|
|
543
|
-
.map((target) => ({ type: "supersedes" as const, target, origin: "preflight" as const }));
|
|
544
|
-
|
|
545
|
-
for (const d of drafts) {
|
|
546
|
-
const marker = `> preflight: ${runId} / ${d.key}`;
|
|
547
|
-
// やり直しでは、前回作ったタスク(本文の印で分かる)を使う
|
|
548
|
-
const made = tasks.get(state.created[d.key] ?? "") ?? tasks.list().find((t) => t.body.includes(marker));
|
|
549
|
-
const t =
|
|
550
|
-
made ??
|
|
551
|
-
(await tasks.create(
|
|
552
|
-
{
|
|
553
|
-
title: d.title,
|
|
554
|
-
status: "todo",
|
|
555
|
-
repo: draftRepo(d),
|
|
556
|
-
labels: [],
|
|
557
|
-
areas: d.areas,
|
|
558
|
-
outputs: [],
|
|
559
|
-
relations: supersedes(d),
|
|
560
|
-
body: `${d.description}\n\n${marker}`,
|
|
561
|
-
},
|
|
562
|
-
actor,
|
|
563
|
-
));
|
|
564
|
-
if (state.created[d.key] !== t.id) {
|
|
565
|
-
state.created[d.key] = t.id;
|
|
566
|
-
await this.ws.preflight.save(run);
|
|
567
|
-
}
|
|
568
|
-
keyToId.set(d.key, t.id);
|
|
569
|
-
created.push(t);
|
|
570
|
-
}
|
|
571
|
-
// 依存は全タスクの ID が決まってから張る
|
|
572
|
-
for (const d of drafts) {
|
|
573
|
-
const id = keyToId.get(d.key)!;
|
|
574
|
-
const cur = tasks.require(id);
|
|
575
|
-
const deps: Relation[] = d.dependsOn
|
|
576
|
-
.map((k) => keyToId.get(k))
|
|
577
|
-
.filter((t): t is string => !!t && !cur.relations.some((r) => r.type === "depends_on" && r.target === t))
|
|
578
|
-
.map((target) => ({ type: "depends_on", target, origin: "preflight" }));
|
|
579
|
-
if (deps.length) {
|
|
580
|
-
const t = await tasks.update(id, { relations: [...cur.relations, ...deps] }, { actor });
|
|
581
|
-
created[created.findIndex((c) => c.id === id)] = t;
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
await this.ws.requests.update(
|
|
586
|
-
requestId,
|
|
587
|
-
{
|
|
588
|
-
status: "active",
|
|
589
|
-
areas: [...new Set([...request.areas, ...(run.assessment?.areas ?? [])])],
|
|
590
|
-
// 採用した案の作業先の分だけブランチを割り当てる(既にあるものは変えない。作業先なしは割り当てない)
|
|
591
|
-
...workstreamPatch(this.ws, requestId, plan),
|
|
592
|
-
},
|
|
593
|
-
{ actor },
|
|
594
|
-
);
|
|
595
|
-
run.materialized = created.map((t) => t.id);
|
|
596
|
-
await this.ws.preflight.save(run);
|
|
597
|
-
|
|
598
|
-
// 新しいタスクと関係を保存してから、選んだ置き換えられるタスクをアーカイブする
|
|
599
|
-
for (const id of state.archive) {
|
|
600
|
-
if (state.archived.includes(id)) continue;
|
|
601
|
-
if (tasks.get(id)) await tasks.archive(id);
|
|
602
|
-
state.archived.push(id);
|
|
603
|
-
await this.ws.preflight.save(run);
|
|
604
|
-
}
|
|
605
|
-
state.done = true;
|
|
606
|
-
await this.ws.preflight.save(run);
|
|
607
|
-
|
|
608
|
-
this.ws.emit({ type: "changed", kind: "task", request: requestId });
|
|
609
|
-
this.ws.emit({ type: "changed", kind: "request", request: requestId });
|
|
610
|
-
return { tasks: created, archived: state.archived, kept: candidates.filter((c) => !state.archive.includes(c.id)) };
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
/** 固定した添付の画像を、現状(添付)の画面資料として足す(対象のタスク案は無し) */
|
|
615
|
-
function withCurrent(ui: NonNullable<PreflightRun["ui"]>, run: PreflightRun): NonNullable<PreflightRun["ui"]> {
|
|
616
|
-
const current = (run.attachments ?? [])
|
|
617
|
-
.filter((a) => a.format !== "xlsx" && a.path.startsWith(`${UI_DIR}/`))
|
|
618
|
-
.map((a) => ({
|
|
619
|
-
id: a.id,
|
|
620
|
-
kind: "current" as const,
|
|
621
|
-
file: a.path.slice(UI_DIR.length + 1),
|
|
622
|
-
format: a.format as "png" | "jpeg",
|
|
623
|
-
width: a.width ?? 0,
|
|
624
|
-
height: a.height ?? 0,
|
|
625
|
-
bytes: a.bytes,
|
|
626
|
-
title: a.description ?? a.name,
|
|
627
|
-
source: `添付 ${a.name}${a.source ? `(${a.source})` : ""}`,
|
|
628
|
-
drafts: [],
|
|
629
|
-
assumptions: [],
|
|
630
|
-
run: run.id,
|
|
631
|
-
}));
|
|
632
|
-
const spec = (run.attachments ?? []).flatMap((a) =>
|
|
633
|
-
(a.extract?.images ?? []).map((img) => ({
|
|
634
|
-
id: img.id,
|
|
635
|
-
kind: "spec" as const,
|
|
636
|
-
file: img.file,
|
|
637
|
-
format: img.format,
|
|
638
|
-
width: img.width,
|
|
639
|
-
height: img.height,
|
|
640
|
-
bytes: img.bytes,
|
|
641
|
-
title: `${a.name} のシート「${img.sheet}」${img.anchor} の画像`,
|
|
642
|
-
source: `添付 ${a.name} / シート「${img.sheet}」${img.anchor}`,
|
|
643
|
-
drafts: [],
|
|
644
|
-
assumptions: [],
|
|
645
|
-
run: run.id,
|
|
646
|
-
})),
|
|
647
|
-
);
|
|
648
|
-
const added = [...current, ...spec];
|
|
649
|
-
return added.length ? { ...ui, items: [...ui.items.filter((m) => m.kind === "proposal"), ...added] } : ui;
|
|
650
|
-
}
|
|
651
|
-
|
|
652
|
-
function clampScore(v: unknown) {
|
|
653
|
-
const n = Number(v);
|
|
654
|
-
return Number.isFinite(n) ? Math.max(0, Math.min(100, Math.round(n))) : 0;
|
|
655
|
-
}
|
|
656
|
-
|
|
657
|
-
const strs = (v: unknown) => (Array.isArray(v) ? v.map(String) : []);
|
|
658
|
-
|
|
659
|
-
/** LLM の出力は形が揺れるので、厳密に弾かず正規化する */
|
|
660
|
-
/**
|
|
661
|
-
* evidence を取り込む。verified は、読めた参照先・その中の相対パス・あるファイルを指すときだけ認める
|
|
662
|
-
* (refs を渡したとき。ほかは assumed に直して理由を note に書く)。項目は消さない
|
|
663
|
-
*/
|
|
664
|
-
export function parseEvidence(v: unknown, refs?: readonly ResolvedRef[]): Evidence[] | undefined {
|
|
665
|
-
if (!Array.isArray(v)) return undefined;
|
|
666
|
-
const text = (x: unknown) => (typeof x === "string" && x.trim() ? x.trim() : undefined);
|
|
667
|
-
return v
|
|
668
|
-
.filter((e): e is Record<string, unknown> => !!e && typeof e === "object")
|
|
669
|
-
.map((e) => {
|
|
670
|
-
const ev: Evidence = { claim: text(e.claim) ?? "(判断の説明がありません)", kind: e.kind === "verified" ? "verified" : "assumed" };
|
|
671
|
-
for (const k of ["repo", "file", "location", "commit"] as const) if (text(e[k])) ev[k] = text(e[k]);
|
|
672
|
-
if (ev.kind !== "verified" || !refs) return ev;
|
|
673
|
-
const problem = verifiedProblem(ev, refs);
|
|
674
|
-
return problem ? { ...ev, kind: "assumed" as const, note: problem } : ev;
|
|
675
|
-
});
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
function verifiedProblem(ev: Evidence, refs: readonly ResolvedRef[]): string | undefined {
|
|
679
|
-
if (!ev.repo || !ev.file) return "参照先とファイルが書かれていないので、確かめた根拠として扱いません";
|
|
680
|
-
const ref = refs.find((r) => r.name === ev.repo);
|
|
681
|
-
if (!ref) return `参照先「${ev.repo}」は登録されていません`;
|
|
682
|
-
if (ref.status !== "ok" || !ref.local) return `参照先 ${ev.repo} はこの評価で見ていません`;
|
|
683
|
-
const file = ev.file.replace(/^(\.\/)+/, "");
|
|
684
|
-
if (file.startsWith("/") || file.split("/").includes("..")) return "参照先の中の相対パスではありません";
|
|
685
|
-
if (!existsSync(join(ref.local, file))) return `${ev.repo}:${file} がありません`;
|
|
686
|
-
return undefined;
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
export function parseAssessment(text: string, refs?: readonly ResolvedRef[]): PreflightAssessment {
|
|
690
|
-
let a: Record<string, any>;
|
|
691
|
-
try {
|
|
692
|
-
a = JSON.parse(text);
|
|
693
|
-
} catch (e) {
|
|
694
|
-
throw new Error(`assessment.json が JSON として読めません: ${(e as Error).message}`);
|
|
695
|
-
}
|
|
696
|
-
const verdict = ["go", "clarify", "no_go"].includes(a.verdict) ? a.verdict : "clarify";
|
|
697
|
-
return {
|
|
698
|
-
summary: String(a.summary ?? ""),
|
|
699
|
-
verdict,
|
|
700
|
-
validity: { score: clampScore(a.validity?.score), reasons: strs(a.validity?.reasons) },
|
|
701
|
-
feasibility: { score: clampScore(a.feasibility?.score), reasons: strs(a.feasibility?.reasons) },
|
|
702
|
-
risks: strs(a.risks),
|
|
703
|
-
questions: strs(a.questions),
|
|
704
|
-
areas: strs(a.areas),
|
|
705
|
-
...(Array.isArray(a.evidence) ? { evidence: parseEvidence(a.evidence, refs) } : {}),
|
|
706
|
-
};
|
|
707
|
-
}
|