@infodb/p3 0.9.0 → 0.10.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 +3 -2
- package/dist/web/assets/{Outputs-CQi0oba1.js → Outputs-B4Tr7JzU.js} +1 -1
- package/dist/web/assets/{RequestStatus-grC0F_SQ.js → RequestStatus-DGaoQoIa.js} +1 -1
- package/dist/web/assets/{Tabs-BJRGzidj.js → Tabs-D16MqQxu.js} +1 -1
- package/dist/web/assets/{TagInput-cIIwXAHA.js → TagInput-pSYxm4bz.js} +1 -1
- package/dist/web/assets/{TaskDrawer-CSZ7Z0JC.js → TaskDrawer-1Ev3RpRV.js} +1 -1
- package/dist/web/assets/{_requestId-Z3CBhTIL.js → _requestId-BKhn019m.js} +1 -1
- package/dist/web/assets/_requestId-Btpvuu7-.js +30 -0
- package/dist/web/assets/{appCtx-DCiGJFAe.js → appCtx-D_Iaoh2e.js} +1 -1
- package/dist/web/assets/{board-DyfGX5h0.js → board-DeHdxbN4.js} +1 -1
- package/dist/web/assets/{directTask-Dk3H5Q2B.js → directTask-C1NWDkZp.js} +1 -1
- package/dist/web/assets/{done-Bhxqy7bH.js → done-BFaHGt03.js} +1 -1
- package/dist/web/assets/{index-Bt13tvIX.js → index-CDWcKy1L.js} +3 -3
- package/dist/web/assets/{new-BRsIUNIb.js → new-ChFzBoL2.js} +1 -1
- package/dist/web/assets/{preload-helper-B40dBmwL.js → preload-helper-hSId95YD.js} +1 -1
- package/dist/web/assets/{release-notes-C3FdiM36.js → release-notes-BWNDFDkH.js} +1 -1
- package/dist/web/assets/{requestData-w6fhCYmh.js → requestData-B_320uxL.js} +1 -1
- package/dist/web/assets/{routes-QNgQHe48.js → routes-BBD464IS.js} +1 -1
- package/dist/web/assets/{settings-CoKJahEe.js → settings-D7PPrGjT.js} +1 -1
- package/dist/web/index.html +3 -3
- package/docs/architecture.md +74 -7
- package/docs/development.md +19 -9
- package/docs/how-to-use.md +51 -2
- package/docs/installation.md +26 -10
- package/docs/publishing.md +5 -1
- package/lib/cli/args.js +2 -0
- package/lib/cli/help.js +7 -2
- package/lib/cli/main.js +12 -3
- package/lib/cli/preflightCommands.js +30 -7
- package/lib/cli/project.js +31 -9
- package/lib/core/preflight/codexEngine.js +56 -12
- package/lib/core/preflight/codexImage.js +49 -19
- package/lib/core/preflight/docker.js +149 -0
- package/lib/core/preflight/owner.js +118 -0
- package/lib/core/preflight/render-image/Dockerfile +1 -1
- package/lib/core/preflight/service.js +235 -16
- package/lib/core/projectRegistry.js +2 -1
- package/lib/core/store/dataWatcher.js +122 -0
- package/lib/core/store/normalize.js +9 -1
- package/lib/core/store/preflightStore.js +20 -2
- package/lib/core/store/projectFile.js +6 -1
- package/lib/core/store/workspace.js +20 -37
- package/lib/server/api/manifest.js +10 -1
- package/lib/server/api/routes.js +18 -5
- package/lib/server/server.js +3 -1
- package/lib/shared/directTask.js +2 -2
- package/lib/shared/preflightRunner.js +18 -0
- package/package.json +2 -2
- package/skills/p3/SKILL.md +29 -17
- package/dist/web/assets/_requestId-C8WYk2kC.js +0 -30
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readFileSync, readlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir, hostname } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
let cached;
|
|
6
|
+
/** このプロセスの所有者の記録(一度だけ作る。作れなければ undefined) */
|
|
7
|
+
export function currentOwner() {
|
|
8
|
+
if (cached === undefined)
|
|
9
|
+
cached = makeOwner() ?? null;
|
|
10
|
+
return cached ?? undefined;
|
|
11
|
+
}
|
|
12
|
+
function makeOwner() {
|
|
13
|
+
const id = instanceId();
|
|
14
|
+
if (!id)
|
|
15
|
+
return undefined;
|
|
16
|
+
const linux = process.platform === "linux";
|
|
17
|
+
const start = linux ? procStart(process.pid) : undefined;
|
|
18
|
+
return {
|
|
19
|
+
instance: createHash("sha256").update(`${id}\n${hostname()}`).digest("hex").slice(0, 24),
|
|
20
|
+
...(linux ? { boot: readTrim("/proc/sys/kernel/random/boot_id"), pidNs: readNs() } : {}),
|
|
21
|
+
pid: process.pid,
|
|
22
|
+
...(start ? { start } : {}),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/** ローカルの状態のフォルダの識別子(無ければ作る)。読めない・書けなければ undefined */
|
|
26
|
+
function instanceId() {
|
|
27
|
+
const base = process.env.XDG_STATE_HOME || join(homedir(), ".local", "state");
|
|
28
|
+
const file = join(base, "infodb-p3", "instance-id");
|
|
29
|
+
try {
|
|
30
|
+
const v = readFileSync(file, "utf8").trim();
|
|
31
|
+
if (/^[0-9a-f]{32}$/.test(v))
|
|
32
|
+
return v;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// 無ければ作る
|
|
36
|
+
}
|
|
37
|
+
try {
|
|
38
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
39
|
+
const v = randomBytes(16).toString("hex");
|
|
40
|
+
// 同時に作ったときは先に書いたほうを使う(wx)
|
|
41
|
+
try {
|
|
42
|
+
writeFileSync(file, `${v}\n`, { flag: "wx", mode: 0o600 });
|
|
43
|
+
return v;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
const again = readFileSync(file, "utf8").trim();
|
|
47
|
+
return /^[0-9a-f]{32}$/.test(again) ? again : undefined;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function readTrim(path) {
|
|
55
|
+
try {
|
|
56
|
+
return readFileSync(path, "utf8").trim() || undefined;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function readNs() {
|
|
63
|
+
try {
|
|
64
|
+
return readlinkSync("/proc/self/ns/pid").replace(/^pid:\[(\d+)\]$/, "$1");
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
/** Linux の /proc/<pid>/stat の starttime(22 番目。名前に空白や括弧を含んでもよいように、最後の ")" の後ろで数える) */
|
|
71
|
+
function procStart(pid) {
|
|
72
|
+
let text;
|
|
73
|
+
try {
|
|
74
|
+
text = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
75
|
+
}
|
|
76
|
+
catch (e) {
|
|
77
|
+
return e.code === "ENOENT" ? null : undefined;
|
|
78
|
+
}
|
|
79
|
+
const fields = text.slice(text.lastIndexOf(")") + 2).split(" ");
|
|
80
|
+
return fields[19] || undefined;
|
|
81
|
+
}
|
|
82
|
+
/** 既定の読み取り: Linux は /proc、ほかはプロセスがあるかだけ(起動の時刻は確かめられない) */
|
|
83
|
+
export const systemProbe = {
|
|
84
|
+
self: currentOwner,
|
|
85
|
+
startOf(pid) {
|
|
86
|
+
if (process.platform === "linux")
|
|
87
|
+
return procStart(pid);
|
|
88
|
+
try {
|
|
89
|
+
process.kill(pid, 0);
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
catch (e) {
|
|
93
|
+
return e.code === "ESRCH" ? null : undefined;
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
/** 記録したプロセスが今も動いているか(確かめられなければ unknown。死んだと推測しない) */
|
|
98
|
+
export function ownerState(owner, probe = systemProbe) {
|
|
99
|
+
if (!owner)
|
|
100
|
+
return { state: "unknown", reason: "実行したプロセスの記録がありません(以前の版で始めた run)" };
|
|
101
|
+
const me = probe.self();
|
|
102
|
+
if (!me)
|
|
103
|
+
return { state: "unknown", reason: "このマシンの識別子を作れないので確かめられません" };
|
|
104
|
+
if (owner.instance !== me.instance)
|
|
105
|
+
return { state: "unknown", reason: "別の環境(別のマシンかコンテナ)で始めた run です" };
|
|
106
|
+
if (owner.boot && me.boot && owner.boot !== me.boot)
|
|
107
|
+
return { state: "dead", reason: "始めた後に OS が起動し直しています" };
|
|
108
|
+
if ((owner.pidNs ?? "") !== (me.pidNs ?? ""))
|
|
109
|
+
return { state: "unknown", reason: "別のプロセスの名前空間(コンテナの起動し直し・サンドボックスなど)で始めた run です" };
|
|
110
|
+
const start = probe.startOf(owner.pid);
|
|
111
|
+
if (start === null)
|
|
112
|
+
return { state: "dead", reason: `実行していたプロセス(${owner.pid})が終わっています` };
|
|
113
|
+
if (start === undefined || !owner.start)
|
|
114
|
+
return { state: "unknown", reason: "実行していたプロセスが同じものか確かめられません" };
|
|
115
|
+
if (start !== owner.start)
|
|
116
|
+
return { state: "dead", reason: `実行していたプロセス(${owner.pid})は終わり、同じ番号の別のプロセスがあります` };
|
|
117
|
+
return { state: "alive" };
|
|
118
|
+
}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
# Playwright と Chromium(headless shell)の版は固定し、日本語のフォント(Noto CJK, SIL Open Font License 1.1)を入れる。
|
|
6
6
|
# 日本語の既定と、イメージに無い日本語のフォント名は fonts-ja.conf で Noto CJK JP にする(Playwright の依存で入る
|
|
7
7
|
# 中国語の字形のフォントが先に選ばれないように)。
|
|
8
|
-
FROM node:
|
|
8
|
+
FROM node:26-bookworm-slim
|
|
9
9
|
|
|
10
10
|
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \
|
|
11
11
|
NODE_ENV=production
|
|
@@ -23,6 +23,7 @@ import { applyUiShortage, IMAGE_TYPES, loadUiMaterials, readUiImage, UI_DIR, UiM
|
|
|
23
23
|
import { compareFamily, compareInput, inputHash, normalizeInput, renderRequestSnapshot, runInput, StaleInputError } from "./input.js";
|
|
24
24
|
import { changedLabel } from "../../shared/preflightInput.js";
|
|
25
25
|
import { PREFLIGHT_CANCELLED } from "../../shared/directTask.js";
|
|
26
|
+
import { currentOwner, ownerState, systemProbe } from "./owner.js";
|
|
26
27
|
/** 始められない理由をそのまま失敗にするエンジン(run の記録とログに残すため) */
|
|
27
28
|
const failing = (name, message) => ({
|
|
28
29
|
name,
|
|
@@ -62,6 +63,7 @@ export class PreflightService {
|
|
|
62
63
|
ws;
|
|
63
64
|
engines;
|
|
64
65
|
renderOpts;
|
|
66
|
+
ownerOpts;
|
|
65
67
|
active = new Map();
|
|
66
68
|
/** 最後に分かった既定のエンジン */
|
|
67
69
|
lastDefault;
|
|
@@ -70,10 +72,13 @@ export class PreflightService {
|
|
|
70
72
|
*/
|
|
71
73
|
constructor(ws, engines, defaultEngine,
|
|
72
74
|
/** 手元のエージェントの取り込みで画面イメージを描くとき: パスの対応(codex.pathMap)と、テスト用の描画の差し替え */
|
|
73
|
-
renderOpts = { pathMap: async () => [] }
|
|
75
|
+
renderOpts = { pathMap: async () => [] },
|
|
76
|
+
/** 実行しているプロセスの判定(テストが差し替える。owner.ts) */
|
|
77
|
+
ownerOpts = {}) {
|
|
74
78
|
this.ws = ws;
|
|
75
79
|
this.engines = engines;
|
|
76
80
|
this.renderOpts = renderOpts;
|
|
81
|
+
this.ownerOpts = ownerOpts;
|
|
77
82
|
if (typeof defaultEngine === "string") {
|
|
78
83
|
this.lastDefault = defaultEngine;
|
|
79
84
|
this.loadDefault = async () => defaultEngine;
|
|
@@ -152,7 +157,17 @@ export class PreflightService {
|
|
|
152
157
|
}
|
|
153
158
|
const opened = await this.open(fixed, engine.name, opts.actor);
|
|
154
159
|
const abort = new AbortController();
|
|
155
|
-
|
|
160
|
+
// 別のプロセス(CLI・別の serve)からの中断の依頼(cancel-request.json)を見て止める
|
|
161
|
+
const watch = setInterval(() => {
|
|
162
|
+
void this.ws.preflight.cancelRequest(requestId, opened.run.id).then((r) => {
|
|
163
|
+
if (r && !abort.signal.aborted) {
|
|
164
|
+
this.log(opened.run, { kind: "info", text: `中断を頼まれたので止めます${r.by ? `(${r.by})` : ""}` });
|
|
165
|
+
abort.abort();
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
}, CANCEL_POLL_MS);
|
|
169
|
+
watch.unref();
|
|
170
|
+
const done = this.execute(engine, opened, abort.signal).finally(() => clearInterval(watch));
|
|
156
171
|
this.active.set(opened.run.id, { run: opened.run, abort, done });
|
|
157
172
|
return opened.run;
|
|
158
173
|
});
|
|
@@ -203,10 +218,108 @@ export class PreflightService {
|
|
|
203
218
|
await renderManuscripts(runDir, { pathMap: await this.renderOpts.pathMap().catch(() => []), log: (e) => this.log(run, e), render: this.renderOpts.render });
|
|
204
219
|
await this.ingest(run, runDir, refs);
|
|
205
220
|
run.status = "completed";
|
|
206
|
-
await this.
|
|
221
|
+
await this.finishLocked(run, run.local.before);
|
|
207
222
|
return { run, already: false };
|
|
208
223
|
});
|
|
209
224
|
}
|
|
225
|
+
/**
|
|
226
|
+
* run を中断する(p3 preflight --cancel --run・画面の「中止」)。最新でなくてもよい。成果物・ログ・履歴は消さない。
|
|
227
|
+
* - local: 評価を待つのをやめる(cancelLocal)
|
|
228
|
+
* - このプロセスで実行中: 止めて、終わるまで少し待つ
|
|
229
|
+
* - 実行していたプロセスが終わっていると確かめられる: その場で中断にする(T001 の回復と同じ)
|
|
230
|
+
* - ほかのプロセスで動いている: 中断を頼む(cancel-request.json。そのプロセスが見て止める)。止まるまで少し待ち、
|
|
231
|
+
* 止まらなければ requested(中断を頼んだ。まだ running)。acknowledgeStopped は断る(動いているので)
|
|
232
|
+
* - 動いているか確かめられない(以前の run・別の環境): 中断を頼んだうえで、acknowledgeStopped(人が止まっていることを確かめた)が
|
|
233
|
+
* あるときだけ中断にする。無ければ requested と、確かめて中断にする方法を返す(確かめずに中断したことにしない)
|
|
234
|
+
* 完了した run は断る(CancelRefusedError)。中断・失敗済みなら already。プロセスやコンテナを kill しない
|
|
235
|
+
*/
|
|
236
|
+
async cancelRun(requestId, runId, opts = {}) {
|
|
237
|
+
if (!/^PF-[\w-]+$/.test(runId))
|
|
238
|
+
throw new NotFoundError(`run の ID の形ではありません: ${runId}`);
|
|
239
|
+
this.ws.requests.require(requestId);
|
|
240
|
+
const found = await this.ws.preflight.get(requestId, runId);
|
|
241
|
+
if (!found)
|
|
242
|
+
throw new NotFoundError(`${requestId} に ${runId} はありません`);
|
|
243
|
+
if (found.engine === "local") {
|
|
244
|
+
if (opts.acknowledgeStopped)
|
|
245
|
+
throw new CancelRefusedError("not_needed", `${runId} は手元のエージェントの run です(--acknowledge-stopped は要りません)`);
|
|
246
|
+
const r = await this.cancelLocal(requestId, runId);
|
|
247
|
+
return { state: r.already ? "already" : "cancelled", run: r.run, message: r.already ? `${runId} は取り消し済みです` : `${runId} を取り消しました(成果物のファイルは run のフォルダに残します)` };
|
|
248
|
+
}
|
|
249
|
+
if (found.status === "completed")
|
|
250
|
+
throw new CancelRefusedError("completed", `${runId} は完了しています(中断にはしません)`);
|
|
251
|
+
if (found.status !== "running")
|
|
252
|
+
return { state: "already", run: found, message: `${runId} は既に終わっています(${found.error ?? found.status})` };
|
|
253
|
+
const waitMs = opts.waitMs ?? CANCEL_WAIT_MS;
|
|
254
|
+
const settled = async () => {
|
|
255
|
+
const until = Date.now() + waitMs;
|
|
256
|
+
for (;;) {
|
|
257
|
+
const now = await this.ws.preflight.get(requestId, runId);
|
|
258
|
+
if (now && now.status !== "running")
|
|
259
|
+
return now;
|
|
260
|
+
if (Date.now() >= until)
|
|
261
|
+
return undefined;
|
|
262
|
+
await new Promise((r) => setTimeout(r, Math.min(200, waitMs)));
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
// このプロセスで実行中
|
|
266
|
+
const mine = this.active.get(runId);
|
|
267
|
+
if (mine) {
|
|
268
|
+
if (opts.acknowledgeStopped)
|
|
269
|
+
throw new CancelRefusedError("alive", `${runId} はこの serve で実行中です(--acknowledge-stopped は使えません。そのまま中止できます)`);
|
|
270
|
+
mine.abort.abort();
|
|
271
|
+
await Promise.race([mine.done, new Promise((r) => setTimeout(r, waitMs))]);
|
|
272
|
+
const now = await settled();
|
|
273
|
+
return now ? { state: "cancelled", run: now, message: `${runId} を中止しました` } : { state: "requested", run: (await this.ws.preflight.get(requestId, runId)) ?? found, message: `${runId} を止めています(まだ終わっていません)` };
|
|
274
|
+
}
|
|
275
|
+
const owner = ownerState(found.owner, this.probe);
|
|
276
|
+
if (owner.state === "dead") {
|
|
277
|
+
await this.locked(requestId, async () => {
|
|
278
|
+
await this.ws.requests.reload(requestId);
|
|
279
|
+
await this.recoverRequest(requestId);
|
|
280
|
+
});
|
|
281
|
+
const now = (await this.ws.preflight.get(requestId, runId)) ?? found;
|
|
282
|
+
return { state: now.status === "running" ? "requested" : "cancelled", run: now, message: `${runId} を中断にしました(${owner.reason})` };
|
|
283
|
+
}
|
|
284
|
+
if (owner.state === "alive" && opts.acknowledgeStopped) {
|
|
285
|
+
throw new CancelRefusedError("alive", `${runId} は別のプロセスで動いています(--acknowledge-stopped は使えません。--cancel だけで中断を頼めます)`);
|
|
286
|
+
}
|
|
287
|
+
if (owner.state === "unknown" && opts.acknowledgeStopped) {
|
|
288
|
+
let done = false;
|
|
289
|
+
await this.locked(requestId, async () => {
|
|
290
|
+
const run = await this.ws.preflight.get(requestId, runId);
|
|
291
|
+
if (!run || run.status !== "running")
|
|
292
|
+
return;
|
|
293
|
+
await this.ws.requests.reload(requestId);
|
|
294
|
+
run.status = "failed";
|
|
295
|
+
run.error = `中断しました: 止まっていることを人が確かめました(${owner.reason})`;
|
|
296
|
+
run.interrupted = { reason: owner.reason, at: nowIso(), acknowledgedBy: opts.actor ?? "unknown" };
|
|
297
|
+
run.ui = withCurrent({ status: "missing", reason: "評価が終わらなかったので、画面資料を取り込んでいません", targets: [], items: [], problems: [] }, run);
|
|
298
|
+
this.log(run, { kind: "error", text: `${run.error}${opts.actor ? `(${opts.actor})` : ""}` });
|
|
299
|
+
await this.finishLocked(run, run.before);
|
|
300
|
+
done = true;
|
|
301
|
+
});
|
|
302
|
+
const now = (await this.ws.preflight.get(requestId, runId)) ?? found;
|
|
303
|
+
return done
|
|
304
|
+
? { state: "cancelled", run: now, message: `${runId} を中断にしました(止まっていることを確かめた記録を残しました。プロセスやコンテナは止めていません)` }
|
|
305
|
+
: { state: "already", run: now, message: `${runId} は既に終わっています` };
|
|
306
|
+
}
|
|
307
|
+
// 動いている・確かめられない: 中断を頼む(そのプロセスが見て止める)
|
|
308
|
+
await this.ws.preflight.requestCancel(requestId, runId, opts.actor);
|
|
309
|
+
this.ws.emit({ type: "changed", kind: "preflight", request: requestId });
|
|
310
|
+
const now = await settled();
|
|
311
|
+
if (now)
|
|
312
|
+
return { state: "cancelled", run: now, message: `${runId} を中止しました` };
|
|
313
|
+
const current = (await this.ws.preflight.get(requestId, runId)) ?? found;
|
|
314
|
+
return {
|
|
315
|
+
state: "requested",
|
|
316
|
+
run: current,
|
|
317
|
+
...(owner.state === "unknown" ? { acknowledgeable: true } : {}),
|
|
318
|
+
message: owner.state === "alive"
|
|
319
|
+
? `${runId} の中断を頼みました。実行しているプロセスが止めるまで running のままです`
|
|
320
|
+
: `${runId} の中断を頼みました。動いているか確かめられません(${owner.reason})。止まっていることを確かめたら、p3 preflight ${requestId} --cancel --run ${runId} --acknowledge-stopped で中断にできます(プロセスやコンテナは止めません)`,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
210
323
|
/** 手元のエージェントの評価を待つ run をやめる(取り込まない。成果物のファイルは残す)。取り消し済みなら何もしない */
|
|
211
324
|
async cancelLocal(requestId, runId) {
|
|
212
325
|
return this.locked(requestId, async () => {
|
|
@@ -219,7 +332,7 @@ export class PreflightService {
|
|
|
219
332
|
run.error = PREFLIGHT_CANCELLED;
|
|
220
333
|
run.ui = withCurrent({ status: "missing", reason: "評価が終わらなかったので、画面資料を取り込んでいません", targets: [], items: [], problems: [] }, run);
|
|
221
334
|
this.log(run, { kind: "error", text: run.error });
|
|
222
|
-
await this.
|
|
335
|
+
await this.finishLocked(run, run.local.before);
|
|
223
336
|
return { run, already: false };
|
|
224
337
|
});
|
|
225
338
|
}
|
|
@@ -243,13 +356,18 @@ export class PreflightService {
|
|
|
243
356
|
busyMessage: `${requestId} の Preflight を別の操作が変えています。少し待ってからやり直してください`,
|
|
244
357
|
});
|
|
245
358
|
}
|
|
359
|
+
get probe() {
|
|
360
|
+
return this.ownerOpts.probe ?? systemProbe;
|
|
361
|
+
}
|
|
246
362
|
/**
|
|
247
|
-
* 同じ要望の Preflight
|
|
248
|
-
*
|
|
363
|
+
* 同じ要望の Preflight が動いているか(ロックの中で呼ぶ)。先に、実行していたプロセスが終わっていると確かめられる run を中断にする
|
|
364
|
+
* (recoverRequest)。このプロセスで実行中、手元のエージェントの評価を待っている、ほかのプロセス(serve・CLI)で実行中、
|
|
365
|
+
* 動いているか確かめられない(以前の run・別の環境)なら、その理由。時間がたっただけでは始めない(生きている別のプロセスと重ねない)
|
|
249
366
|
*/
|
|
250
367
|
async busy(requestId) {
|
|
251
368
|
if ([...this.active.values()].some((a) => a.run.requestId === requestId))
|
|
252
369
|
return `${requestId} の preflight は実行中です`;
|
|
370
|
+
await this.recoverRequest(requestId);
|
|
253
371
|
const last = this.ws.requests.get(requestId)?.lastPreflight;
|
|
254
372
|
if (!last)
|
|
255
373
|
return undefined;
|
|
@@ -259,9 +377,63 @@ export class PreflightService {
|
|
|
259
377
|
if (run.engine === "local") {
|
|
260
378
|
return `${requestId} の preflight ${last} は手元のエージェントの評価を待っています(取り込む: p3 preflight ${requestId} --complete --run ${last} / やめる: p3 preflight ${requestId} --cancel --run ${last})`;
|
|
261
379
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
380
|
+
const owner = ownerState(run.owner, this.probe);
|
|
381
|
+
if (owner.state === "alive")
|
|
382
|
+
return `${requestId} の preflight ${last} が別のプロセスで実行中です(やめるなら p3 preflight ${requestId} --cancel --run ${last})`;
|
|
383
|
+
return (`${requestId} の preflight ${last} が実行中のまま残っています。動いていないと確かめられないので始めません(${owner.reason})。` +
|
|
384
|
+
`止まっていることを確かめたら p3 preflight ${requestId} --cancel --run ${last} --acknowledge-stopped で中断にでき、始め直せます`);
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* 実行していたプロセスが終わっていると確かめられる、running のまま残った run(codex / mock。最新でなくても)を中断(failed)にする。
|
|
388
|
+
* ロックの中で呼ぶ。手元のエージェントの run(local)・このプロセスで実行中の run・確かめられない run は変えない。中断にした run の ID
|
|
389
|
+
*/
|
|
390
|
+
async recoverRequest(requestId) {
|
|
391
|
+
const done = [];
|
|
392
|
+
for (const run of await this.ws.preflight.list(requestId)) {
|
|
393
|
+
if (run.status !== "running" || run.engine === "local" || this.active.has(run.id))
|
|
394
|
+
continue;
|
|
395
|
+
const owner = ownerState(run.owner, this.probe);
|
|
396
|
+
if (owner.state !== "dead")
|
|
397
|
+
continue;
|
|
398
|
+
run.status = "failed";
|
|
399
|
+
run.error = `中断しました: ${owner.reason}(serve や CLI が途中で止まった可能性があります)`;
|
|
400
|
+
run.interrupted = { reason: owner.reason, at: nowIso() };
|
|
401
|
+
run.ui = withCurrent({ status: "missing", reason: "評価が終わらなかったので、画面資料を取り込んでいません", targets: [], items: [], problems: [] }, run);
|
|
402
|
+
this.log(run, { kind: "error", text: run.error });
|
|
403
|
+
await this.finishLocked(run, run.before);
|
|
404
|
+
done.push(run.id);
|
|
405
|
+
}
|
|
406
|
+
return done;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* プロジェクトを開いたとき(serve の起動・--all-projects で開いたとき)に、全部の要望の running のまま残った run を確かめ、
|
|
410
|
+
* 実行していたプロセスが終わっていると確かめられるものを中断にする。1件の失敗で止めない(理由をログに残し、ほかは続ける)
|
|
411
|
+
*/
|
|
412
|
+
async recover(opts = {}) {
|
|
413
|
+
const log = opts.log ?? ((m) => console.error(m));
|
|
414
|
+
const recovered = [];
|
|
415
|
+
const errors = [];
|
|
416
|
+
for (const req of this.ws.requests.list()) {
|
|
417
|
+
try {
|
|
418
|
+
// ロックを取る前に、候補(running の codex / mock で、終わっていると確かめられる)があるかだけを見る
|
|
419
|
+
const runs = await this.ws.preflight.list(req.id);
|
|
420
|
+
const candidates = runs.filter((r) => r.status === "running" && r.engine !== "local" && !this.active.has(r.id) && ownerState(r.owner, this.probe).state === "dead");
|
|
421
|
+
if (!candidates.length)
|
|
422
|
+
continue;
|
|
423
|
+
recovered.push(...(await this.locked(req.id, async () => {
|
|
424
|
+
await this.ws.requests.reload(req.id);
|
|
425
|
+
return this.recoverRequest(req.id);
|
|
426
|
+
})).map((id) => `${req.id}/${id}`));
|
|
427
|
+
}
|
|
428
|
+
catch (e) {
|
|
429
|
+
const m = `[preflight] ${this.ws.dataDir}: ${req.id} の残った run を確かめられません: ${e.message}`;
|
|
430
|
+
errors.push(m);
|
|
431
|
+
log(m);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
for (const r of recovered)
|
|
435
|
+
log(`[preflight] ${this.ws.dataDir}: 実行していたプロセスが終わっていた run を中断にしました: ${r}`);
|
|
436
|
+
return { recovered, errors };
|
|
265
437
|
}
|
|
266
438
|
/** 評価対象を固定する(ディスクから読み直す)。同じ要望の Preflight が動いていれば PreflightBusyError */
|
|
267
439
|
async fix(requestId) {
|
|
@@ -308,7 +480,12 @@ export class PreflightService {
|
|
|
308
480
|
scope: refs.map(refScope),
|
|
309
481
|
ui: { status: "generating", targets: [], items: [], problems: [] },
|
|
310
482
|
input,
|
|
483
|
+
before: request.status,
|
|
311
484
|
};
|
|
485
|
+
// 実行しているプロセスの記録(codex / mock)。手元のエージェントの run はプロセスを跨いで待つので記録しない
|
|
486
|
+
const owner = engine === "local" ? undefined : currentOwner();
|
|
487
|
+
if (owner)
|
|
488
|
+
run.owner = owner;
|
|
312
489
|
const runDir = this.ws.preflight.runDir(requestId, id);
|
|
313
490
|
// 添付は始める時点のものを run の中にコピーして固定する。途中で変わったら始めない(原本は残るので、そのまま再試行できる)
|
|
314
491
|
try {
|
|
@@ -440,6 +617,18 @@ export class PreflightService {
|
|
|
440
617
|
await this.finish(run, opened.before);
|
|
441
618
|
}
|
|
442
619
|
}
|
|
620
|
+
/** 実行の終わり(execute): 要望ごとのロックの中で終える。ロックを取れなくても記録は残す(終わった状態を上書きしない規則は同じ) */
|
|
621
|
+
async finish(run, before) {
|
|
622
|
+
try {
|
|
623
|
+
await this.locked(run.requestId, () => this.finishLocked(run, before));
|
|
624
|
+
}
|
|
625
|
+
catch (e) {
|
|
626
|
+
if (!this.active.has(run.id))
|
|
627
|
+
return; // 終えた後に失敗した
|
|
628
|
+
console.error(`[preflight] ${run.requestId}/${run.id}: ロックを取れないまま終えます: ${e.message}`);
|
|
629
|
+
await this.finishLocked(run, before);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
443
632
|
/** run のフォルダの成果物(評価・案・子の案・画面資料)を取り込む。評価が読めなければ例外 */
|
|
444
633
|
async ingest(run, runDir, refs) {
|
|
445
634
|
run.assessment = parseAssessment(await readFile(join(runDir, "assessment.json"), "utf8"), refs);
|
|
@@ -464,14 +653,27 @@ export class PreflightService {
|
|
|
464
653
|
if (run.ui.verdictAdjusted)
|
|
465
654
|
this.log(run, { kind: "info", text: "必要な画面イメージが足りないので、判定を go から clarify にしました" });
|
|
466
655
|
}
|
|
467
|
-
/**
|
|
468
|
-
|
|
656
|
+
/**
|
|
657
|
+
* run を終える(ロックの中で呼ぶ): 記録を保存し、評価中にした要望を評価済み(失敗なら元)へ戻す。
|
|
658
|
+
* ファイルの run が既に終わっていれば(別のプロセスが中断にした・取り消した)、その状態を上書きしない。
|
|
659
|
+
* 要望のステータスは、その run が最新(lastPreflight)のときだけ戻す(古い run の終わりで、新しい run と要望の状態を巻き戻さない)。
|
|
660
|
+
* 始める前の状態(before)が分からない run は、要望のステータスを変えない
|
|
661
|
+
*/
|
|
662
|
+
async finishLocked(run, before) {
|
|
663
|
+
const onDisk = await this.ws.preflight.get(run.requestId, run.id);
|
|
664
|
+
if (onDisk && onDisk.status !== "running") {
|
|
665
|
+
this.active.delete(run.id);
|
|
666
|
+
this.ws.emit({ type: "preflight-status", runId: run.id, status: onDisk.status });
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
469
669
|
run.finishedAt = nowIso();
|
|
470
670
|
await this.ws.preflight.save(run);
|
|
471
671
|
// 評価中にした要望だけ、終わったら評価済み(失敗なら元)へ戻す。実行中に人や AI が変えたステータス
|
|
472
672
|
// (進行中に戻した・完了済にしたなど)や、評価中にしていない要望(進行中・対応済など)は上書きしない
|
|
473
|
-
|
|
474
|
-
|
|
673
|
+
await this.ws.requests.reload(run.requestId).catch(() => undefined);
|
|
674
|
+
const req = this.ws.requests.get(run.requestId);
|
|
675
|
+
const status = before ? statusAfter(before, run.status === "completed") : undefined;
|
|
676
|
+
if (status && req?.lastPreflight === run.id && req.status === "preflight" && status !== "preflight") {
|
|
475
677
|
await this.ws.requests.update(run.requestId, { status });
|
|
476
678
|
}
|
|
477
679
|
// 保存が終わってから実行中の一覧から外す(先に外すと wait() が保存前のファイルを読む)
|
|
@@ -628,7 +830,15 @@ export class PreflightService {
|
|
|
628
830
|
}
|
|
629
831
|
/** run に今の要望との比較(inputMatch)を添える(画面・CLI・API の表示用。run.json には書かない) */
|
|
630
832
|
async withInputMatch(requestId, run) {
|
|
631
|
-
return { ...run, inputMatch: await this.inputMatch(requestId, run) };
|
|
833
|
+
return { ...run, inputMatch: await this.inputMatch(requestId, run), ...(run.status === "running" ? { liveness: this.liveness(run) } : {}) };
|
|
834
|
+
}
|
|
835
|
+
/** running の run を実行しているプロセスの今の状態(画面の「中止」の出し分け。書かない)。local は待っている(waiting) */
|
|
836
|
+
liveness(run) {
|
|
837
|
+
if (run.engine === "local")
|
|
838
|
+
return { state: "waiting" };
|
|
839
|
+
if (this.active.has(run.id))
|
|
840
|
+
return { state: "alive" };
|
|
841
|
+
return ownerState(run.owner, this.probe);
|
|
632
842
|
}
|
|
633
843
|
/** タスク化の前に見せるもの: 採用する案と、置き換えられる既存タスク、評価対象が今の要望と同じか(ファイルは変えない) */
|
|
634
844
|
async previewMaterialize(requestId, runId) {
|
|
@@ -921,8 +1131,17 @@ export class PreflightService {
|
|
|
921
1131
|
};
|
|
922
1132
|
}
|
|
923
1133
|
}
|
|
924
|
-
/**
|
|
925
|
-
const
|
|
1134
|
+
/** 中断の依頼を見る間隔(実行しているプロセス)と、頼んだ側が止まるのを待つ時間 */
|
|
1135
|
+
const CANCEL_POLL_MS = 1_000;
|
|
1136
|
+
const CANCEL_WAIT_MS = 5_000;
|
|
1137
|
+
/** 中断できない(完了した run・動いている run への確認の操作など)。何も変えていない */
|
|
1138
|
+
export class CancelRefusedError extends Error {
|
|
1139
|
+
code;
|
|
1140
|
+
constructor(code, message) {
|
|
1141
|
+
super(message);
|
|
1142
|
+
this.code = code;
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
926
1145
|
/** ステータスを動かすのはタスク化する前の要望だけ */
|
|
927
1146
|
const isEarly = (s) => s === "draft" || s === "preflight" || s === "reviewed";
|
|
928
1147
|
/** Preflight を終えたときの要望のステータス(評価中にしたものだけ。成功なら評価済み、失敗なら元) */
|
|
@@ -57,7 +57,8 @@ export class ProjectRegistry {
|
|
|
57
57
|
e.ctx = (this.opts.open ?? openProject)(e.dir, { repos: e.repos, settings: this.opts.settings, projectName: e.name, chatgpt: this.opts.chatgpt });
|
|
58
58
|
e.ctx.then((ctx) => {
|
|
59
59
|
e.error = undefined;
|
|
60
|
-
|
|
60
|
+
ctx.ws.watch();
|
|
61
|
+
void ctx.preflight.recover().catch((err) => console.error(`[preflight] ${name}: 残った run を確かめられません: ${err.message}`));
|
|
61
62
|
// 開いている間に登録から外れた・変わった: 新しい要求には使わせず閉じる
|
|
62
63
|
if (this.entries.get(name) !== e || this.closed)
|
|
63
64
|
this.retire(ctx);
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { existsSync, watch as fsWatch } from "node:fs";
|
|
2
|
+
export const WATCH_DEFAULTS = { debounceMs: 80, retryMs: 1_000, maxRetryMs: 30_000, maxFailures: 5, stableMs: 60_000, quietMs: 60_000 };
|
|
3
|
+
export class DataWatcher {
|
|
4
|
+
dir;
|
|
5
|
+
onChange;
|
|
6
|
+
watcher;
|
|
7
|
+
pending = new Map();
|
|
8
|
+
retryTimer;
|
|
9
|
+
failures = 0;
|
|
10
|
+
startedAt = 0;
|
|
11
|
+
lastQuietLog = 0;
|
|
12
|
+
quieted = 0;
|
|
13
|
+
closed = false;
|
|
14
|
+
state = "idle";
|
|
15
|
+
o;
|
|
16
|
+
constructor(dir,
|
|
17
|
+
/** データのフォルダからの相対パスの変更 */
|
|
18
|
+
onChange, options = {}) {
|
|
19
|
+
this.dir = dir;
|
|
20
|
+
this.onChange = onChange;
|
|
21
|
+
const given = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== undefined));
|
|
22
|
+
this.o = { ...WATCH_DEFAULTS, watch: fsWatch, log: (m) => console.error(m), ...given };
|
|
23
|
+
}
|
|
24
|
+
start() {
|
|
25
|
+
if (this.closed || this.watcher)
|
|
26
|
+
return;
|
|
27
|
+
clearTimeout(this.retryTimer);
|
|
28
|
+
this.retryTimer = undefined;
|
|
29
|
+
let w;
|
|
30
|
+
try {
|
|
31
|
+
w = this.o.watch(this.dir, { recursive: true, persistent: true }, (_event, filename) => this.changed(filename));
|
|
32
|
+
}
|
|
33
|
+
catch (e) {
|
|
34
|
+
this.fail(e, "監視を始められません");
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
// 'error' は必ず聞く(聞かないと未処理のイベントとしてプロセスが落ちる)
|
|
38
|
+
w.on("error", (e) => this.onError(w, e));
|
|
39
|
+
this.watcher = w;
|
|
40
|
+
this.startedAt = Date.now();
|
|
41
|
+
this.state = "watching";
|
|
42
|
+
}
|
|
43
|
+
close() {
|
|
44
|
+
this.closed = true;
|
|
45
|
+
this.state = "closed";
|
|
46
|
+
clearTimeout(this.retryTimer);
|
|
47
|
+
this.retryTimer = undefined;
|
|
48
|
+
for (const t of this.pending.values())
|
|
49
|
+
clearTimeout(t);
|
|
50
|
+
this.pending.clear();
|
|
51
|
+
this.dropWatcher();
|
|
52
|
+
}
|
|
53
|
+
changed(filename) {
|
|
54
|
+
if (this.closed || !filename)
|
|
55
|
+
return;
|
|
56
|
+
const f = String(filename);
|
|
57
|
+
if (f.endsWith(".tmp") || f.includes(".archive"))
|
|
58
|
+
return;
|
|
59
|
+
clearTimeout(this.pending.get(f));
|
|
60
|
+
this.pending.set(f, setTimeout(() => {
|
|
61
|
+
this.pending.delete(f);
|
|
62
|
+
if (this.closed)
|
|
63
|
+
return;
|
|
64
|
+
Promise.resolve()
|
|
65
|
+
.then(() => this.onChange(f))
|
|
66
|
+
.catch((e) => this.o.log(`[watch] ${this.dir}: 変更の読み込みに失敗しました(${f})。次の変更か画面の「再読み込み」で反映します: ${message(e)}`));
|
|
67
|
+
}, this.o.debounceMs));
|
|
68
|
+
}
|
|
69
|
+
onError(w, e) {
|
|
70
|
+
if (this.closed || w !== this.watcher)
|
|
71
|
+
return;
|
|
72
|
+
// 入れ子のフォルダ・ファイルが見ている途中で消えた(データのフォルダはある): 監視は続く
|
|
73
|
+
if (code(e) === "ENOENT" && existsSync(this.dir)) {
|
|
74
|
+
const now = Date.now();
|
|
75
|
+
if (now - this.lastQuietLog >= this.o.quietMs) {
|
|
76
|
+
const more = this.quieted ? `(ほかに ${this.quieted} 件)` : "";
|
|
77
|
+
this.o.log(`[watch] ${this.dir}: 見ている途中でフォルダかファイルが消えました。監視は続けます${more}: ${message(e)}`);
|
|
78
|
+
this.lastQuietLog = now;
|
|
79
|
+
this.quieted = 0;
|
|
80
|
+
}
|
|
81
|
+
else
|
|
82
|
+
this.quieted++;
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
this.fail(e, "監視でエラーが起きました");
|
|
86
|
+
}
|
|
87
|
+
fail(e, what) {
|
|
88
|
+
this.dropWatcher();
|
|
89
|
+
if (this.closed)
|
|
90
|
+
return;
|
|
91
|
+
if (this.startedAt && Date.now() - this.startedAt >= this.o.stableMs)
|
|
92
|
+
this.failures = 0;
|
|
93
|
+
this.startedAt = 0;
|
|
94
|
+
this.failures++;
|
|
95
|
+
if (this.failures > this.o.maxFailures) {
|
|
96
|
+
this.state = "stopped";
|
|
97
|
+
this.o.log(`[watch] ${this.dir}: ${what}。続けて ${this.o.maxFailures + 1} 回失敗したので監視をやめます(serve は続きます。外での変更は画面の「再読み込み」で反映してください): ${message(e)}`);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const wait = Math.min(this.o.retryMs * 2 ** (this.failures - 1), this.o.maxRetryMs);
|
|
101
|
+
this.state = "retrying";
|
|
102
|
+
this.o.log(`[watch] ${this.dir}: ${what}。${wait} ミリ秒後に立て直します(${this.failures}/${this.o.maxFailures}): ${message(e)}`);
|
|
103
|
+
this.retryTimer = setTimeout(() => {
|
|
104
|
+
this.retryTimer = undefined;
|
|
105
|
+
this.start();
|
|
106
|
+
}, wait);
|
|
107
|
+
}
|
|
108
|
+
dropWatcher() {
|
|
109
|
+
const w = this.watcher;
|
|
110
|
+
this.watcher = undefined;
|
|
111
|
+
if (!w)
|
|
112
|
+
return;
|
|
113
|
+
try {
|
|
114
|
+
w.close();
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
// 閉じるのに失敗しても、もう使わない
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const code = (e) => (e && typeof e === "object" && "code" in e ? String(e.code) : undefined);
|
|
122
|
+
const message = (e) => (e instanceof Error ? e.message : String(e));
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { repoNameProblem } from "../../shared/repos.js";
|
|
2
|
+
import { isPreflightRunner } from "../../shared/preflightRunner.js";
|
|
2
3
|
import { isTaskStatus, RELATION_TYPES, REQUEST_STATUSES } from "../../shared/types.js";
|
|
3
4
|
const str = (v) => (v === undefined || v === null || v === "" ? undefined : String(v));
|
|
4
5
|
const num = (v) => (v === undefined || v === null || v === "" ? undefined : Number(v));
|
|
@@ -76,6 +77,13 @@ export const REQUEST_KEY_ORDER = [
|
|
|
76
77
|
"id", "title", "status", "parent", "childOrder", "splitFrom", "due", "milestone", "tags", "areas", "workstreams", "lastPreflight",
|
|
77
78
|
"rev", "createdAt", "updatedAt", "updatedBy",
|
|
78
79
|
];
|
|
80
|
+
/** preflight.runner(未設定は書かない。読めない値は invalidRunner に残し、担当を推測しない) */
|
|
81
|
+
function runnerOf(v) {
|
|
82
|
+
const raw = str(v)?.trim();
|
|
83
|
+
if (raw === undefined || raw === "")
|
|
84
|
+
return {};
|
|
85
|
+
return isPreflightRunner(raw) ? { runner: raw } : { invalidRunner: raw };
|
|
86
|
+
}
|
|
79
87
|
export function normalizeProject(d) {
|
|
80
88
|
const preflight = (d.preflight ?? {});
|
|
81
89
|
return {
|
|
@@ -88,7 +96,7 @@ export function normalizeProject(d) {
|
|
|
88
96
|
.map((m) => ({ id: String(m.id), title: str(m.title) ?? String(m.id), due: date(m.due), done: m.done === true ? true : undefined }))
|
|
89
97
|
: [],
|
|
90
98
|
branchPattern: str(d.branchPattern) ?? "req/{id}-{slug}",
|
|
91
|
-
preflight: { instructions: str(preflight.instructions) ?? "" },
|
|
99
|
+
preflight: { instructions: str(preflight.instructions) ?? "", ...runnerOf(preflight.runner) },
|
|
92
100
|
};
|
|
93
101
|
}
|
|
94
102
|
/**
|