@infodb/p3 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +56 -2
- package/bin/p3.mjs +18 -0
- package/dist/web/apple-touch-icon.png +0 -0
- package/dist/web/assets/Outputs-Ni3pNuGU.js +1 -0
- package/dist/web/assets/RequestStatus-K8TZwpur.js +1 -0
- package/dist/web/assets/TagInput-BICKVH2x.js +1 -0
- package/dist/web/assets/TaskDrawer-BkDIstIN.js +3 -0
- package/dist/web/assets/_requestId-B5O_ytaq.js +1 -0
- package/dist/web/assets/_requestId-C66puEMO.js +30 -0
- package/dist/web/assets/action-CMjATXqv.js +1 -0
- package/dist/web/assets/board-CbfDjkls.js +1 -0
- package/dist/web/assets/copy-B1ZbihKL.js +2 -0
- package/dist/web/assets/done-CPQbCFHg.js +1 -0
- package/dist/web/assets/draft-dT3gLDIt.js +1 -0
- package/dist/web/assets/format-DuK6P1hb.js +1 -0
- package/dist/web/assets/index-BUcs2J6N.js +12 -0
- package/dist/web/assets/index-C3DkqwJ9.css +2 -0
- package/dist/web/assets/link-_s8ndNKS.js +1 -0
- package/dist/web/assets/new-T60RB7de.js +1 -0
- package/dist/web/assets/preload-helper-dXqN7N-I.js +1 -0
- package/dist/web/assets/release-notes-DxrPhDbt.js +3 -0
- package/dist/web/assets/requestData-D8ZiSZss.js +1 -0
- package/dist/web/assets/rolldown-runtime-hePW80VL.js +1 -0
- package/dist/web/assets/routes-D9ZxXoLk.js +2 -0
- package/dist/web/assets/search-CJ8MBKTz.js +1 -0
- package/dist/web/assets/settings-DsHVyqzJ.js +1 -0
- package/dist/web/assets/supersede-CLXlhCq0.js +1 -0
- package/dist/web/assets/ui-Cvke4y4X.js +1 -0
- package/dist/web/favicon.ico +0 -0
- package/dist/web/favicon.svg +12 -0
- package/dist/web/index.html +23 -0
- package/docs/architecture.md +588 -0
- package/docs/chatgpt-sign-in.md +163 -0
- package/docs/development.md +194 -0
- package/docs/how-to-use.md +524 -0
- package/docs/installation.md +275 -0
- package/docs/publishing.md +65 -0
- package/package.json +86 -3
- package/skills/p3/SKILL.md +95 -0
- package/src/cli/args.ts +179 -0
- package/src/cli/chatgpt.ts +74 -0
- package/src/cli/codex.ts +28 -0
- package/src/cli/format.ts +9 -0
- package/src/cli/help.ts +99 -0
- package/src/cli/main.ts +267 -0
- package/src/cli/output.ts +99 -0
- package/src/cli/preflightCommands.ts +237 -0
- package/src/cli/project.ts +501 -0
- package/src/cli/readOnly.ts +36 -0
- package/src/cli/releaseNotesCommands.ts +139 -0
- package/src/cli/render.ts +60 -0
- package/src/cli/requestCommands.ts +170 -0
- package/src/cli/showView.ts +110 -0
- package/src/cli/taskCommands.ts +167 -0
- package/src/cli/userConfig.ts +58 -0
- package/src/core/chatgpt.ts +33 -0
- package/src/core/context.ts +57 -0
- package/src/core/machineSettings.ts +207 -0
- package/src/core/machineSettingsEdit.ts +156 -0
- package/src/core/ops.ts +114 -0
- package/src/core/preflight/carryover.ts +133 -0
- package/src/core/preflight/codexEngine.ts +702 -0
- package/src/core/preflight/codexImage.ts +98 -0
- package/src/core/preflight/diagnose.ts +124 -0
- package/src/core/preflight/engine.ts +92 -0
- package/src/core/preflight/input.ts +65 -0
- package/src/core/preflight/launch.ts +86 -0
- package/src/core/preflight/launcher.mjs +75 -0
- package/src/core/preflight/mock-ui.html +24 -0
- package/src/core/preflight/mock-ui.png +0 -0
- package/src/core/preflight/mockEngine.ts +145 -0
- package/src/core/preflight/render-image/Dockerfile +23 -0
- package/src/core/preflight/render-image/render.mjs +53 -0
- package/src/core/preflight/render.ts +336 -0
- package/src/core/preflight/service.ts +690 -0
- package/src/core/preflight/uiMaterials.ts +272 -0
- package/src/core/preflight/uiRender.ts +84 -0
- package/src/core/preflight/wireframe.ts +69 -0
- package/src/core/preflight/xlsx.ts +328 -0
- package/src/core/redact.ts +31 -0
- package/src/core/releaseNotes/generate.ts +271 -0
- package/src/core/releaseNotes/material.ts +114 -0
- package/src/core/releaseNotes/mockSummarizer.ts +28 -0
- package/src/core/releaseNotes/service.ts +106 -0
- package/src/core/releaseNotes/store.ts +216 -0
- package/src/core/repoAdmin.ts +81 -0
- package/src/core/repoRefs.ts +90 -0
- package/src/core/requestOps.ts +140 -0
- package/src/core/requestStatus.ts +58 -0
- package/src/core/store/attachments.ts +228 -0
- package/src/core/store/collection.ts +282 -0
- package/src/core/store/frontmatter.ts +22 -0
- package/src/core/store/fsutil.ts +90 -0
- package/src/core/store/locate.ts +181 -0
- package/src/core/store/normalize.ts +155 -0
- package/src/core/store/noteStore.ts +56 -0
- package/src/core/store/preflightStore.ts +136 -0
- package/src/core/store/projectFile.ts +101 -0
- package/src/core/store/workspace.ts +328 -0
- package/src/core/supersede.ts +74 -0
- package/src/core/userConfig.ts +180 -0
- package/src/core/userTheme.ts +22 -0
- package/src/core/workTargets.ts +120 -0
- package/src/server/api/chatgptRoutes.ts +48 -0
- package/src/server/api/local.ts +33 -0
- package/src/server/api/manifest.ts +119 -0
- package/src/server/api/releaseNoteRoutes.ts +78 -0
- package/src/server/api/repoRoutes.ts +67 -0
- package/src/server/api/routes.ts +374 -0
- package/src/server/api/userThemeRoutes.ts +62 -0
- package/src/server/server.ts +49 -0
- package/src/shared/dates.ts +12 -0
- package/src/shared/preflightInput.ts +27 -0
- package/src/shared/refs.ts +55 -0
- package/src/shared/repos.ts +113 -0
- package/src/shared/scopeView.ts +48 -0
- package/src/shared/tags.ts +27 -0
- package/src/shared/types.ts +700 -0
- package/src/shared/workTarget.ts +44 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { THEMES } from "../shared/types.ts";
|
|
2
|
+
import { describeSettings, parseSettingChange, SETTING_KEY_LIST, SettingsInputError, writeMachineSettings, type SettingChange } from "../core/machineSettingsEdit.ts";
|
|
3
|
+
import { loadUserConfig, UserConfigError, userConfigPath } from "../core/userConfig.ts";
|
|
4
|
+
import { readTheme, ThemeInputError, writeTheme } from "../core/userTheme.ts";
|
|
5
|
+
import { UsageError } from "./project.ts";
|
|
6
|
+
|
|
7
|
+
const USAGE = [
|
|
8
|
+
"p3 user-config 個人設定の値と出どころ(環境変数 / 個人設定 / 既定)",
|
|
9
|
+
`p3 user-config set キー=値 ... ui.theme=${THEMES.join("|")} / ${SETTING_KEY_LIST.filter((k) => k !== "codex.pathMap").join(" ")}(キー= で消す)`,
|
|
10
|
+
"p3 user-config set codex.pathMap+=<このマシンのパス>=<Docker デーモンから見たパス> パスの対応を足す",
|
|
11
|
+
"p3 user-config set codex.pathMap-=<このマシンのパス> パスの対応を外す(codex.pathMap= で全部)",
|
|
12
|
+
].join("\n");
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* p3 user-config [set ...]。個人設定(このマシン・この人)のうち、画面のテーマとマシンごとの設定(codex / preflight / serve)を
|
|
16
|
+
* 見せ・変える。プロジェクトの登録は p3 project、プロジェクトの設定は p3 config。プロジェクトを決める前に動く。
|
|
17
|
+
*/
|
|
18
|
+
export async function userConfigCommand(args: string[], env: Record<string, string | undefined> = process.env): Promise<{ data: unknown; text: string }> {
|
|
19
|
+
const [sub, ...pairs] = args;
|
|
20
|
+
const path = userConfigPath();
|
|
21
|
+
if (sub === undefined || sub === "ls" || sub === "show") {
|
|
22
|
+
const theme = await readTheme(path);
|
|
23
|
+
const user = await loadUserConfig(path).catch((e) => {
|
|
24
|
+
if (e instanceof UserConfigError) throw new UsageError(e.message);
|
|
25
|
+
throw e;
|
|
26
|
+
});
|
|
27
|
+
const { rows, error } = describeSettings(user, env);
|
|
28
|
+
const width = Math.max(...rows.map((r) => r.key.length), "ui.theme".length) + 2;
|
|
29
|
+
const text = [
|
|
30
|
+
`${"ui.theme".padEnd(width)}${theme}`,
|
|
31
|
+
...rows.map((r) => `${r.key.padEnd(width)}${r.value}${r.from === "既定" ? " (既定)" : r.from === "環境変数" ? ` (環境変数 ${r.env})` : ""}`),
|
|
32
|
+
...(error ? ["", `読めない値があります: ${error}`] : []),
|
|
33
|
+
"",
|
|
34
|
+
`ファイル: ${path}`,
|
|
35
|
+
"変えるとき: p3 user-config set キー=値(例: p3 user-config set codex.pathMap+=/workspaces=/home/me/workspaces)",
|
|
36
|
+
].join("\n");
|
|
37
|
+
return { data: { ui: { theme }, settings: rows, ...(error ? { error } : {}), path }, text };
|
|
38
|
+
}
|
|
39
|
+
if (sub !== "set" || !pairs.length) throw new UsageError(USAGE);
|
|
40
|
+
|
|
41
|
+
let theme: string | undefined;
|
|
42
|
+
const changes: SettingChange[] = [];
|
|
43
|
+
try {
|
|
44
|
+
for (const pair of pairs) {
|
|
45
|
+
if (pair === "ui.theme" || pair.startsWith("ui.theme=")) theme = pair.slice("ui.theme=".length);
|
|
46
|
+
else changes.push(parseSettingChange(pair));
|
|
47
|
+
}
|
|
48
|
+
// 読めない値があれば何も書かない(テーマも書く前に確かめる)
|
|
49
|
+
if (theme !== undefined && !(THEMES as readonly string[]).includes(theme)) throw new ThemeInputError(`ui.theme は ${THEMES.join(" / ")} のどれか: ${theme}`);
|
|
50
|
+
if (changes.length) await writeMachineSettings(changes, path);
|
|
51
|
+
if (theme !== undefined) await writeTheme(theme, path);
|
|
52
|
+
} catch (e) {
|
|
53
|
+
if (e instanceof SettingsInputError || e instanceof ThemeInputError || e instanceof UserConfigError) throw new UsageError(e.message);
|
|
54
|
+
throw e;
|
|
55
|
+
}
|
|
56
|
+
const keys = pairs.map((p) => p.replace(/^(codex\.pathMap[+-]?)=.*$/s, "$1").replace(/=.*$/s, ""));
|
|
57
|
+
return { data: { changed: keys, path }, text: `個人設定を変えました: ${keys.join(", ")}(${path})\n効いている値は p3 user-config で確かめられます` };
|
|
58
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { dirname, join } from "node:path";
|
|
2
|
+
import { ChatGptAccount, OAuthError, type OAuthDeps } from "@infodb/chatgpt-plan";
|
|
3
|
+
import { userConfigPath } from "./userConfig.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* ChatGPT(Sign in with ChatGPT のプラン利用)との接続。サインイン・トークンの保存と更新・解除は
|
|
7
|
+
* @infodb/chatgpt-plan(llmcs の chatgpt-plan-ts)が行い、ここには P3 の決まりだけを置く。設計: docs/chatgpt-sign-in.md
|
|
8
|
+
*
|
|
9
|
+
* ~/.config/infodb-p3/chatgpt.json 0600。秘密(トークン)を含む。個人設定(config.yaml)とは別のファイル
|
|
10
|
+
* ~/.config/infodb-p3/chatgpt.lock トークンの更新の排他(CLI・serve・並行する Preflight で1つずつ)
|
|
11
|
+
*/
|
|
12
|
+
export { ChatGptAccount, ChatGptAuthError, OAuthError, type ChatGptStatus } from "@infodb/chatgpt-plan";
|
|
13
|
+
|
|
14
|
+
/** アプリの名前。初回の登録の agent_name_hint と、app-server の initialize の clientInfo.name をそろえる */
|
|
15
|
+
export const APP_NAME = "infodb_p3";
|
|
16
|
+
|
|
17
|
+
/** Codex に渡す access token の残りの長さ(1 ターンの途中で切れないように、部品の既定の 5 分より長く取る) */
|
|
18
|
+
export const CODEX_TOKEN_MIN_VALID_MS = 35 * 60_000;
|
|
19
|
+
|
|
20
|
+
export const connectionPath = () => join(dirname(userConfigPath()), "chatgpt.json");
|
|
21
|
+
|
|
22
|
+
/** P3 の接続(CLI と serve で同じファイルを使う)。file と deps はテストで差し替える */
|
|
23
|
+
export function chatgptAccount(file = connectionPath(), deps?: OAuthDeps): ChatGptAccount {
|
|
24
|
+
return new ChatGptAccount({ file, appName: APP_NAME, appLabel: "P3", ...(deps ? { deps } : {}) });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** サインインの失敗を CLI で次にすることが分かる文言にする(部品の文言は呼び方が P3 のものではない) */
|
|
28
|
+
export function signInFailure(e: unknown): Error {
|
|
29
|
+
if (e instanceof OAuthError && e.code === "account_mismatch") {
|
|
30
|
+
return new Error(`${e.message.replace(/(登録ごと消す: .*)$/, "")}(p3 chatgpt logout --forget で登録ごと解除してから、サインインし直してください)`);
|
|
31
|
+
}
|
|
32
|
+
return e instanceof Error ? e : new Error(String(e));
|
|
33
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { fileURLToPath } from "node:url";
|
|
2
|
+
import { chatgptAccount, type ChatGptAccount } from "./chatgpt.ts";
|
|
3
|
+
import { CodexWorkspaceEngine, codexConfig } from "./preflight/codexEngine.ts";
|
|
4
|
+
import { fixedSettings, machineSettingsSource, type MachineSettings, type SettingsSource } from "./machineSettings.ts";
|
|
5
|
+
import type { PreflightEngine } from "./preflight/engine.ts";
|
|
6
|
+
import { MockEngine } from "./preflight/mockEngine.ts";
|
|
7
|
+
import { PreflightService } from "./preflight/service.ts";
|
|
8
|
+
import { checkDataDir } from "./store/locate.ts";
|
|
9
|
+
import { Workspace } from "./store/workspace.ts";
|
|
10
|
+
import { ReleaseGenerator } from "./releaseNotes/generate.ts";
|
|
11
|
+
import { MockSummarizer } from "./releaseNotes/mockSummarizer.ts";
|
|
12
|
+
|
|
13
|
+
/** p3 本体(パッケージ)のルート */
|
|
14
|
+
export const P3_ROOT = fileURLToPath(new URL("../../", import.meta.url));
|
|
15
|
+
|
|
16
|
+
export interface P3Context {
|
|
17
|
+
ws: Workspace;
|
|
18
|
+
preflight: PreflightService;
|
|
19
|
+
/** リリースノートの要約の生成(Codex の接続を Preflight と共有する) */
|
|
20
|
+
releaseGenerator: ReleaseGenerator;
|
|
21
|
+
/** ChatGPT の接続(このマシン。サインインの待ち受けを Codex エンジンと共有する) */
|
|
22
|
+
chatgpt?: ChatGptAccount;
|
|
23
|
+
/** 個人設定に登録したプロジェクト名(参照先のこのマシンのパスを書くため。登録していなければ無い) */
|
|
24
|
+
projectName?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* サーバと CLI が共有する組み立て。どちらもデータのフォルダのファイルを直接読み書きする。
|
|
29
|
+
* repos: 参照先の名前 → このマシンのパス(個人設定)
|
|
30
|
+
* settings: マシンごとの設定(環境変数と個人設定から。.env は読まない)。省くと個人設定から、Preflight を始めるたび・
|
|
31
|
+
* エンジンの状態を見るたびに読み直す(serve を起動し直さずに効く)。MachineSettings を渡すとその値に決める(テストなど)。
|
|
32
|
+
* プロジェクト(データのフォルダ)側には置かない: 認証情報をプロジェクトの git に入れないため
|
|
33
|
+
*/
|
|
34
|
+
export async function openProject(
|
|
35
|
+
dataDir: string,
|
|
36
|
+
opts: { repos?: Record<string, string>; settings?: MachineSettings | SettingsSource; projectName?: string } = {},
|
|
37
|
+
): Promise<P3Context> {
|
|
38
|
+
// データのフォルダと project.yaml が無ければ、空のプロジェクトとして開かずに止める(何も作らない)
|
|
39
|
+
await checkDataDir(dataDir, opts.projectName);
|
|
40
|
+
const source = !opts.settings ? machineSettingsSource() : "get" in opts.settings ? opts.settings : fixedSettings(opts.settings);
|
|
41
|
+
// 初めの値(画面の表示の既定エンジン)。読めなくても開ける(Preflight を始めるときに設定のエラーとして知らせる)
|
|
42
|
+
const initial = await source.get().catch(() => undefined);
|
|
43
|
+
const ws = new Workspace(dataDir, opts.repos);
|
|
44
|
+
await ws.load();
|
|
45
|
+
// 既定は Codex(ChatGPT プランか旧来の auth.json。どちらも無ければ使えない理由と次にすることを出す)。
|
|
46
|
+
// Mock は preflight.engine: mock(P3_PREFLIGHT_ENGINE=mock)か --engine mock で明示したときだけ(認証の失敗を Mock の成功に見せない)
|
|
47
|
+
const chatgpt = chatgptAccount();
|
|
48
|
+
const codex = new CodexWorkspaceEngine({ load: async () => codexConfig(await source.get()), account: chatgpt });
|
|
49
|
+
const engines: Partial<Record<PreflightEngine["name"], PreflightEngine>> = { codex, mock: new MockEngine() };
|
|
50
|
+
const preflight = new PreflightService(ws, engines, {
|
|
51
|
+
initial: initial?.preflight.engine ?? "codex",
|
|
52
|
+
load: async () => (await source.get()).preflight.engine,
|
|
53
|
+
});
|
|
54
|
+
// 要約の生成も Preflight と同じ接続と既定のエンジン(preflight.engine)を使う
|
|
55
|
+
const releaseGenerator = new ReleaseGenerator(ws, { codex, mock: new MockSummarizer() }, { engine: async () => (await source.get()).preflight.engine });
|
|
56
|
+
return { ws, preflight, releaseGenerator, chatgpt, projectName: opts.projectName };
|
|
57
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { isAbsolute } from "node:path";
|
|
2
|
+
import { loadUserSettings, userConfigPath, UserConfigError, type UserConfig } from "./userConfig.ts";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* マシンごとの設定(Codex の認証・パスの対応・Preflight の既定エンジン・serve の待ち受け)。
|
|
6
|
+
*
|
|
7
|
+
* 決め方(項目ごと): CLI の明示(--port / --host / --engine)→ 環境変数(P3_*)→ 個人設定(config.yaml)→ 既定値。
|
|
8
|
+
* - 環境変数を空(P3_CODEX_MODEL=)にすると、個人設定の値を使わずに既定値に戻す(解除)
|
|
9
|
+
* - 読めない値は黙って捨てず、どこの何を直せばよいかをエラーにする
|
|
10
|
+
*
|
|
11
|
+
* 個人設定(~/.config/infodb-p3/config.yaml)の書き方:
|
|
12
|
+
*
|
|
13
|
+
* codex:
|
|
14
|
+
* auth: auto # auto(ChatGPT に接続していれば ChatGPT、無ければ旧来)/ legacy(旧来の auth.json を使う)
|
|
15
|
+
* authVolume: codex-state # 旧来: auth.json を入れた Docker ボリューム
|
|
16
|
+
* authFile: /home/me/.codex/auth.json # 旧来: ホストの auth.json(authVolume とどちらか)
|
|
17
|
+
* pathMap: # このマシンのパス → Docker デーモンから見たパス(DevContainer のとき)
|
|
18
|
+
* /workspaces: /home/me/workspaces
|
|
19
|
+
* model: gpt-5.5
|
|
20
|
+
* effort: medium
|
|
21
|
+
* ensureImage: true # false で、Preflight の前のイメージの作り直し(1日ごと)を止める
|
|
22
|
+
* preflight:
|
|
23
|
+
* engine: codex # codex / mock
|
|
24
|
+
* serve:
|
|
25
|
+
* host: 0.0.0.0
|
|
26
|
+
* port: 4310
|
|
27
|
+
*
|
|
28
|
+
* ChatGPT のトークンはここに置かない(chatgpt.json。所有者だけが読める権限)。
|
|
29
|
+
* P3_ACTOR・P3_REQUEST は操作ごとの指定なので、環境変数(と --actor / --req)だけで決める。
|
|
30
|
+
*/
|
|
31
|
+
export interface MachineSettings {
|
|
32
|
+
codex: {
|
|
33
|
+
auth: CodexAuthChoice;
|
|
34
|
+
authVolume?: string;
|
|
35
|
+
authFile?: string;
|
|
36
|
+
pathMap: [string, string][];
|
|
37
|
+
model?: string;
|
|
38
|
+
effort?: string;
|
|
39
|
+
ensureImage: boolean;
|
|
40
|
+
};
|
|
41
|
+
preflight: { engine: EngineChoice };
|
|
42
|
+
serve: { host: string; port: number };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type CodexAuthChoice = "auto" | "legacy";
|
|
46
|
+
export type EngineChoice = "codex" | "mock";
|
|
47
|
+
|
|
48
|
+
/** 環境変数と個人設定の対応(docs/installation.md の「設定の決まり」の表と同じ) */
|
|
49
|
+
export const SETTING_KEYS = {
|
|
50
|
+
"codex.auth": "P3_CODEX_AUTH",
|
|
51
|
+
"codex.authVolume": "P3_CODEX_AUTH_VOLUME",
|
|
52
|
+
"codex.authFile": "P3_CODEX_AUTH_FILE",
|
|
53
|
+
"codex.pathMap": "P3_CODEX_PATH_MAP",
|
|
54
|
+
"codex.model": "P3_CODEX_MODEL",
|
|
55
|
+
"codex.effort": "P3_CODEX_EFFORT",
|
|
56
|
+
"codex.ensureImage": "P3_CODEX_ENSURE_IMAGE",
|
|
57
|
+
"preflight.engine": "P3_PREFLIGHT_ENGINE",
|
|
58
|
+
"serve.host": "P3_HOST",
|
|
59
|
+
"serve.port": "P3_PORT",
|
|
60
|
+
} as const;
|
|
61
|
+
type Key = keyof typeof SETTING_KEYS;
|
|
62
|
+
|
|
63
|
+
export const DEFAULT_SETTINGS: MachineSettings = {
|
|
64
|
+
codex: { auth: "auto", pathMap: [], ensureImage: true },
|
|
65
|
+
preflight: { engine: "codex" },
|
|
66
|
+
serve: { host: "0.0.0.0", port: 4310 },
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
/** 設定の値が読めない(CLI は使い方の誤りと同じく終了コード 1)。configPath: 読んだ個人設定のファイル(共有の記録から外すため) */
|
|
70
|
+
export class SettingsError extends Error {
|
|
71
|
+
configPath?: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface SettingsOverrides {
|
|
75
|
+
host?: string;
|
|
76
|
+
port?: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
type Env = Record<string, string | undefined>;
|
|
80
|
+
|
|
81
|
+
/** どこから来た値か(エラーの案内に使う) */
|
|
82
|
+
type Raw = { value: unknown; from: string } | { value: undefined; from: "default" };
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* マシンごとの設定を、呼ぶたびに読み直す(serve を起動し直さずに、個人設定の変更を次の Preflight から効かせる)。
|
|
86
|
+
* 読めなければ SettingsError(直すファイルと項目を添える)。CLI の明示(--port / --host)は起動のときの値のまま渡す
|
|
87
|
+
*/
|
|
88
|
+
export interface SettingsSource {
|
|
89
|
+
get(): Promise<MachineSettings>;
|
|
90
|
+
/** 個人設定のファイル(案内に出す) */
|
|
91
|
+
path: string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function machineSettingsSource(opts: { path?: string; env?: Env; cli?: SettingsOverrides } = {}): SettingsSource {
|
|
95
|
+
const path = opts.path ?? userConfigPath();
|
|
96
|
+
return {
|
|
97
|
+
path,
|
|
98
|
+
async get() {
|
|
99
|
+
try {
|
|
100
|
+
return resolveMachineSettings(await loadUserSettings(path), opts.env ?? process.env, opts.cli ?? {});
|
|
101
|
+
} catch (e) {
|
|
102
|
+
const err =
|
|
103
|
+
e instanceof UserConfigError
|
|
104
|
+
? new SettingsError(e.message)
|
|
105
|
+
: e instanceof SettingsError && e.message.includes("個人設定")
|
|
106
|
+
? new SettingsError(`${e.message}(${path})`)
|
|
107
|
+
: e;
|
|
108
|
+
if (err instanceof SettingsError) err.configPath = path;
|
|
109
|
+
throw err;
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** 決まった設定(テストや、起動のときに一度だけ決めたいとき) */
|
|
116
|
+
export const fixedSettings = (settings: MachineSettings, path = userConfigPath()): SettingsSource => ({ path, get: async () => settings });
|
|
117
|
+
|
|
118
|
+
export function resolveMachineSettings(user: Pick<UserConfig, "settings">, env: Env = process.env, cli: SettingsOverrides = {}): MachineSettings {
|
|
119
|
+
const pick = (key: Key, flag?: string): Raw => {
|
|
120
|
+
if (flag !== undefined) return { value: flag, from: `--${key.split(".")[1]}` };
|
|
121
|
+
const name = SETTING_KEYS[key];
|
|
122
|
+
const e = env[name];
|
|
123
|
+
if (e !== undefined) return e === "" ? { value: undefined, from: "default" } : { value: e, from: `環境変数 ${name}` };
|
|
124
|
+
const [section, field] = key.split(".") as [keyof UserConfig["settings"], string];
|
|
125
|
+
const v = user.settings[section]?.[field];
|
|
126
|
+
return v === undefined || v === null || v === "" ? { value: undefined, from: "default" } : { value: v, from: `個人設定 ${key}` };
|
|
127
|
+
};
|
|
128
|
+
const text = (key: Key): string | undefined => {
|
|
129
|
+
const r = pick(key);
|
|
130
|
+
if (r.value === undefined) return undefined;
|
|
131
|
+
if (typeof r.value !== "string" && typeof r.value !== "number") throw new SettingsError(`${r.from} は文字列で指定してください`);
|
|
132
|
+
return String(r.value);
|
|
133
|
+
};
|
|
134
|
+
const oneOf = <T extends string>(key: Key, choices: readonly T[], def: T): T => {
|
|
135
|
+
const v = text(key);
|
|
136
|
+
if (v === undefined) return def;
|
|
137
|
+
if (!(choices as readonly string[]).includes(v)) throw new SettingsError(`${pick(key).from} が読めません: ${v}(${choices.join(" / ")})`);
|
|
138
|
+
return v as T;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const ensure = pick("codex.ensureImage");
|
|
142
|
+
const port = pick("serve.port", cli.port);
|
|
143
|
+
const host = pick("serve.host", cli.host);
|
|
144
|
+
return {
|
|
145
|
+
codex: {
|
|
146
|
+
auth: oneOf("codex.auth", ["auto", "legacy"] as const, DEFAULT_SETTINGS.codex.auth),
|
|
147
|
+
authVolume: text("codex.authVolume"),
|
|
148
|
+
authFile: text("codex.authFile"),
|
|
149
|
+
pathMap: parsePathMap(pick("codex.pathMap")),
|
|
150
|
+
model: text("codex.model"),
|
|
151
|
+
effort: text("codex.effort"),
|
|
152
|
+
ensureImage: ensure.value === undefined ? DEFAULT_SETTINGS.codex.ensureImage : parseBool(ensure),
|
|
153
|
+
},
|
|
154
|
+
preflight: { engine: oneOf("preflight.engine", ["codex", "mock"] as const, DEFAULT_SETTINGS.preflight.engine) },
|
|
155
|
+
serve: {
|
|
156
|
+
host: host.value === undefined ? DEFAULT_SETTINGS.serve.host : String(host.value),
|
|
157
|
+
port: port.value === undefined ? DEFAULT_SETTINGS.serve.port : parsePort(port),
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function parseBool(r: Raw): boolean {
|
|
163
|
+
if (typeof r.value === "boolean") return r.value;
|
|
164
|
+
const v = String(r.value).toLowerCase();
|
|
165
|
+
if (["1", "true", "yes", "on"].includes(v)) return true;
|
|
166
|
+
if (["0", "false", "no", "off"].includes(v)) return false;
|
|
167
|
+
throw new SettingsError(`${r.from} が読めません: ${String(r.value)}(true / false。環境変数なら 1 / 0 も可)`);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function parsePort(r: Raw): number {
|
|
171
|
+
const n = Number(r.value);
|
|
172
|
+
if (!Number.isInteger(n) || n < 1 || n > 65535) throw new SettingsError(`${r.from} が読めません: ${String(r.value)}(1〜65535 のポート番号)`);
|
|
173
|
+
return n;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const PATH_MAP_HINT =
|
|
177
|
+
"個人設定は p3 user-config set codex.pathMap+=<このマシンのパス>=<Docker デーモンから見たパス> で1件ずつ。環境変数は <このマシンのパス>=<Docker デーモンから見たパス> をカンマ区切りで。例: /workspaces=/home/me/workspaces";
|
|
178
|
+
|
|
179
|
+
/** "ローカル=ホスト,..."(環境変数)か { ローカル: ホスト }(個人設定)。どちらも絶対パス */
|
|
180
|
+
function parsePathMap(r: Raw): [string, string][] {
|
|
181
|
+
if (r.value === undefined) return [];
|
|
182
|
+
let pairs: [string, string][];
|
|
183
|
+
if (typeof r.value === "string") {
|
|
184
|
+
pairs = r.value
|
|
185
|
+
.split(",")
|
|
186
|
+
.map((s) => s.trim())
|
|
187
|
+
.filter(Boolean)
|
|
188
|
+
.map((s) => {
|
|
189
|
+
const at = s.indexOf("=");
|
|
190
|
+
if (at < 0) throw new SettingsError(`${r.from} の「${s}」が読めません(${PATH_MAP_HINT})`);
|
|
191
|
+
return [s.slice(0, at).trim(), s.slice(at + 1).trim()];
|
|
192
|
+
});
|
|
193
|
+
} else if (typeof r.value === "object" && !Array.isArray(r.value)) {
|
|
194
|
+
pairs = Object.entries(r.value as Record<string, unknown>).map(([k, v]) => {
|
|
195
|
+
if (typeof v !== "string") throw new SettingsError(`${r.from} の「${k}」の値はパスの文字列で指定してください`);
|
|
196
|
+
return [k, v];
|
|
197
|
+
});
|
|
198
|
+
} else {
|
|
199
|
+
throw new SettingsError(`${r.from} は「このマシンのパス: Docker デーモンから見たパス」の対応で指定してください`);
|
|
200
|
+
}
|
|
201
|
+
for (const [local, host] of pairs) {
|
|
202
|
+
if (!isAbsolute(local) || !host || !(isAbsolute(host) || /^[A-Za-z]:[\\/]/.test(host))) {
|
|
203
|
+
throw new SettingsError(`${r.from} の「${local}=${host}」が読めません。どちらも絶対パスにしてください(${PATH_MAP_HINT})`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return pairs;
|
|
207
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import YAML from "yaml";
|
|
2
|
+
import { DEFAULT_SETTINGS, resolveMachineSettings, SETTING_KEYS, SettingsError, type MachineSettings } from "./machineSettings.ts";
|
|
3
|
+
import { normalizeUserConfig, updateUserConfig, userConfigPath, type UserConfig } from "./userConfig.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 個人設定のマシンごとの設定(codex / preflight / serve)を変える(p3 user-config set)。
|
|
7
|
+
*
|
|
8
|
+
* キー=値 その項目を書く(ensureImage は true / false、port は数で書く)
|
|
9
|
+
* キー= その項目を消す(既定値に戻す)
|
|
10
|
+
* codex.pathMap+=A=B パスの対応を1件足す(同じ A があれば置き換える)
|
|
11
|
+
* codex.pathMap-=A パスの対応を1件外す
|
|
12
|
+
* codex.pathMap= パスの対応を全部外す
|
|
13
|
+
*
|
|
14
|
+
* 書いた後の内容を読むときと同じ規則(resolveMachineSettings)で確かめ、読めなければ書かない。
|
|
15
|
+
* コメントとほかの項目は残す。
|
|
16
|
+
*/
|
|
17
|
+
export class SettingsInputError extends Error {}
|
|
18
|
+
|
|
19
|
+
export type SettingKey = keyof typeof SETTING_KEYS;
|
|
20
|
+
export const SETTING_KEY_LIST = Object.keys(SETTING_KEYS) as SettingKey[];
|
|
21
|
+
|
|
22
|
+
export type SettingChange =
|
|
23
|
+
| { kind: "set"; key: SettingKey; value: string }
|
|
24
|
+
| { kind: "unset"; key: SettingKey }
|
|
25
|
+
| { kind: "mapAdd"; local: string; host: string }
|
|
26
|
+
| { kind: "mapRemove"; local: string };
|
|
27
|
+
|
|
28
|
+
const isKey = (k: string): k is SettingKey => (SETTING_KEY_LIST as string[]).includes(k);
|
|
29
|
+
|
|
30
|
+
/** 「キー=値」「codex.pathMap+=A=B」「codex.pathMap-=A」を読む */
|
|
31
|
+
export function parseSettingChange(pair: string): SettingChange {
|
|
32
|
+
const add = pair.match(/^codex\.pathMap\+=(.*)$/s);
|
|
33
|
+
if (add) {
|
|
34
|
+
const at = add[1].indexOf("=");
|
|
35
|
+
if (at < 1) throw new SettingsInputError(`「${pair}」が読めません。codex.pathMap+=<このマシンのパス>=<Docker デーモンから見たパス>(例: codex.pathMap+=/workspaces=/home/me/workspaces)`);
|
|
36
|
+
return { kind: "mapAdd", local: add[1].slice(0, at).trim(), host: add[1].slice(at + 1).trim() };
|
|
37
|
+
}
|
|
38
|
+
const remove = pair.match(/^codex\.pathMap-=(.*)$/s);
|
|
39
|
+
if (remove) {
|
|
40
|
+
if (!remove[1].trim()) throw new SettingsInputError("codex.pathMap-=<このマシンのパス> で外す対応を指定してください");
|
|
41
|
+
return { kind: "mapRemove", local: remove[1].trim() };
|
|
42
|
+
}
|
|
43
|
+
const eq = pair.indexOf("=");
|
|
44
|
+
const key = eq > 0 ? pair.slice(0, eq) : pair;
|
|
45
|
+
if (!isKey(key)) throw new SettingsInputError(`変更できるキー: ui.theme ${SETTING_KEY_LIST.join(" ")}`);
|
|
46
|
+
if (eq < 0) throw new SettingsInputError(`${key}=<値> で指定してください(${key}= で消す)`);
|
|
47
|
+
const value = pair.slice(eq + 1).trim();
|
|
48
|
+
if (key === "codex.pathMap" && value) {
|
|
49
|
+
throw new SettingsInputError("パスの対応は1件ずつ codex.pathMap+=<このマシンのパス>=<Docker デーモンから見たパス> で足し、codex.pathMap-=<このマシンのパス> で外してください(codex.pathMap= で全部外す)");
|
|
50
|
+
}
|
|
51
|
+
return value ? { kind: "set", key, value } : { kind: "unset", key };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** YAML に書く形(読むときと同じ型にそろえる) */
|
|
55
|
+
function typed(key: SettingKey, value: string): unknown {
|
|
56
|
+
if (key === "codex.ensureImage") {
|
|
57
|
+
const v = value.toLowerCase();
|
|
58
|
+
if (["true", "1", "yes", "on"].includes(v)) return true;
|
|
59
|
+
if (["false", "0", "no", "off"].includes(v)) return false;
|
|
60
|
+
throw new SettingsInputError(`codex.ensureImage は true か false: ${value}`);
|
|
61
|
+
}
|
|
62
|
+
if (key === "serve.port") {
|
|
63
|
+
const n = Number(value);
|
|
64
|
+
if (!Number.isInteger(n) || n < 1 || n > 65535) throw new SettingsInputError(`serve.port は 1〜65535 のポート番号: ${value}`);
|
|
65
|
+
return n;
|
|
66
|
+
}
|
|
67
|
+
return value;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function ensureMap(doc: YAML.Document, path: string[]) {
|
|
71
|
+
for (let i = 1; i <= path.length; i++) {
|
|
72
|
+
const at = path.slice(0, i);
|
|
73
|
+
if (!YAML.isMap(doc.getIn(at))) doc.setIn(at, doc.createNode({}));
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 空になった項目(codex: {} など)を消す */
|
|
78
|
+
function dropEmpty(doc: YAML.Document, path: string[]) {
|
|
79
|
+
for (let i = path.length; i >= 1; i--) {
|
|
80
|
+
const node = doc.getIn(path.slice(0, i));
|
|
81
|
+
if (YAML.isMap(node) && !node.items.length) doc.deleteIn(path.slice(0, i));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function applySettingChange(doc: YAML.Document, c: SettingChange) {
|
|
86
|
+
if (c.kind === "mapAdd") {
|
|
87
|
+
ensureMap(doc, ["codex", "pathMap"]);
|
|
88
|
+
doc.setIn(["codex", "pathMap", c.local], c.host);
|
|
89
|
+
} else if (c.kind === "mapRemove") {
|
|
90
|
+
if (!doc.hasIn(["codex", "pathMap", c.local])) throw new SettingsInputError(`codex.pathMap に「${c.local}」の対応はありません`);
|
|
91
|
+
doc.deleteIn(["codex", "pathMap", c.local]);
|
|
92
|
+
dropEmpty(doc, ["codex", "pathMap"]);
|
|
93
|
+
} else {
|
|
94
|
+
const path = c.key.split(".");
|
|
95
|
+
if (c.kind === "unset") {
|
|
96
|
+
doc.deleteIn(path);
|
|
97
|
+
dropEmpty(doc, path.slice(0, -1));
|
|
98
|
+
} else {
|
|
99
|
+
ensureMap(doc, path.slice(0, -1));
|
|
100
|
+
doc.setIn(path, typed(c.key, c.value));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 変更をまとめて書く。どれか1つでも読めなければ何も書かない。書いた後の個人設定の値を返す */
|
|
106
|
+
export async function writeMachineSettings(changes: SettingChange[], path = userConfigPath()): Promise<MachineSettings> {
|
|
107
|
+
return updateUserConfig((doc) => {
|
|
108
|
+
for (const c of changes) applySettingChange(doc, c);
|
|
109
|
+
try {
|
|
110
|
+
// 環境変数は見ずに、個人設定に書いた値だけで確かめる
|
|
111
|
+
return resolveMachineSettings(normalizeUserConfig(doc.toJS() ?? {}), {});
|
|
112
|
+
} catch (e) {
|
|
113
|
+
if (e instanceof SettingsError) throw new SettingsInputError(`${e.message}(書いていません)`);
|
|
114
|
+
throw e;
|
|
115
|
+
}
|
|
116
|
+
}, path);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface SettingRow {
|
|
120
|
+
key: SettingKey;
|
|
121
|
+
/** 効いている値(表示用の文字列) */
|
|
122
|
+
value: string;
|
|
123
|
+
/** どこから来たか */
|
|
124
|
+
from: "環境変数" | "個人設定" | "既定";
|
|
125
|
+
env: string;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const show = (v: unknown): string => (v === undefined ? "(なし)" : typeof v === "object" ? JSON.stringify(v) : String(v));
|
|
129
|
+
|
|
130
|
+
/** 項目ごとの効いている値と出どころ。読めない値があれば error に理由(行は書かれたままの値で出す) */
|
|
131
|
+
export function describeSettings(user: Pick<UserConfig, "settings">, env: Record<string, string | undefined>): { rows: SettingRow[]; resolved?: MachineSettings; error?: string } {
|
|
132
|
+
let resolved: MachineSettings | undefined;
|
|
133
|
+
let error: string | undefined;
|
|
134
|
+
try {
|
|
135
|
+
resolved = resolveMachineSettings(user, env);
|
|
136
|
+
} catch (e) {
|
|
137
|
+
error = (e as Error).message;
|
|
138
|
+
}
|
|
139
|
+
const rows = SETTING_KEY_LIST.map((key): SettingRow => {
|
|
140
|
+
const name = SETTING_KEYS[key];
|
|
141
|
+
const [section, field] = key.split(".") as [keyof UserConfig["settings"], string];
|
|
142
|
+
const written = user.settings[section]?.[field];
|
|
143
|
+
// 空の環境変数は個人設定を使わずに既定値に戻す(resolveMachineSettings と同じ)
|
|
144
|
+
const from: SettingRow["from"] =
|
|
145
|
+
env[name] !== undefined ? (env[name] === "" ? "既定" : "環境変数") : written !== undefined && written !== null && written !== "" ? "個人設定" : "既定";
|
|
146
|
+
const effective = resolved ? (resolved as unknown as Record<string, Record<string, unknown>>)[section][field] : from === "環境変数" ? env[name] : written;
|
|
147
|
+
const def = (DEFAULT_SETTINGS as unknown as Record<string, Record<string, unknown>>)[section][field];
|
|
148
|
+
let value: string;
|
|
149
|
+
if (key === "codex.pathMap") {
|
|
150
|
+
const pairs = (Array.isArray(effective) ? effective : []) as [string, string][];
|
|
151
|
+
value = pairs.length ? pairs.map(([l, h]) => `${l} → ${h}`).join(", ") : resolved ? "(なし)" : show(effective);
|
|
152
|
+
} else value = show(effective ?? def);
|
|
153
|
+
return { key, value, from, env: name };
|
|
154
|
+
});
|
|
155
|
+
return { rows, resolved, error };
|
|
156
|
+
}
|
package/src/core/ops.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { normalizeTaskId } from "../shared/refs.ts";
|
|
2
|
+
import { type RequestProgress, type Task, TASK_STATUSES, type TaskStatus } from "../shared/types.ts";
|
|
3
|
+
import type { P3Context } from "./context.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* API と CLI で共通の読み取り(一覧・参照の解き方・進捗)。変更の手順は requestOps.ts。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export interface TaskFilter {
|
|
10
|
+
/** 要望(無ければ全要望) */
|
|
11
|
+
request?: string;
|
|
12
|
+
status?: string[];
|
|
13
|
+
area?: string;
|
|
14
|
+
q?: string;
|
|
15
|
+
/** 作業先(参照先の名前。none は作業先なし) */
|
|
16
|
+
repo?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function listTasks({ ws }: P3Context, f: TaskFilter = {}): Task[] {
|
|
20
|
+
let tasks = f.request ? ws.tasksOf(f.request).list() : ws.allTasks();
|
|
21
|
+
if (f.status?.length) tasks = tasks.filter((t) => f.status!.includes(t.status));
|
|
22
|
+
if (f.area) tasks = tasks.filter((t) => t.areas.some((a) => a.startsWith(f.area!)));
|
|
23
|
+
// 作業先で絞る(none は作業先なし)
|
|
24
|
+
if (f.repo !== undefined) tasks = tasks.filter((t) => (t.repo ?? null) === (f.repo === "none" ? null : f.repo));
|
|
25
|
+
if (f.q) {
|
|
26
|
+
const q = f.q.toLowerCase();
|
|
27
|
+
tasks = tasks.filter((t) => `${t.ref} ${t.title} ${t.body}`.toLowerCase().includes(q));
|
|
28
|
+
}
|
|
29
|
+
return tasks;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 要望の ID を短い書き方からも解く: 完全な ID、乱数部分(k7m3x)、ID の先頭・末尾の一部(一意なときだけ)。
|
|
34
|
+
*/
|
|
35
|
+
export function resolveRequestId({ ws }: P3Context, raw: string): string | undefined {
|
|
36
|
+
const s = raw.trim().toLowerCase();
|
|
37
|
+
if (!s) return undefined;
|
|
38
|
+
if (ws.requests.get(s)) return s;
|
|
39
|
+
if (s.length < 3) return undefined;
|
|
40
|
+
const hits = ws.requests.list().filter((r) => r.id.startsWith(s) || r.id.endsWith(s));
|
|
41
|
+
return hits.length === 1 ? hits[0].id : undefined;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 参照を絶対参照に解く。存在しなければ undefined。
|
|
46
|
+
* "<要望>/T3" "<要望>" — 要望は短い書き方でもよい
|
|
47
|
+
* "T3" / "3" — current(今の要望)の中のタスク
|
|
48
|
+
*/
|
|
49
|
+
export function resolveRef(ctx: P3Context, raw: string, current?: string): string | undefined {
|
|
50
|
+
const s = raw.trim();
|
|
51
|
+
const [head, tail] = s.split("/", 2);
|
|
52
|
+
if (tail !== undefined) {
|
|
53
|
+
const rid = resolveRequestId(ctx, head);
|
|
54
|
+
const tid = normalizeTaskId(tail);
|
|
55
|
+
return rid && tid && ctx.ws.tasksOf(rid).get(tid) ? `${rid}/${tid}` : undefined;
|
|
56
|
+
}
|
|
57
|
+
const tid = normalizeTaskId(s);
|
|
58
|
+
if (tid && current) return ctx.ws.tasksOf(current).get(tid) ? `${current}/${tid}` : undefined;
|
|
59
|
+
return resolveRequestId(ctx, s);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface ResolveResult {
|
|
63
|
+
match: string | null;
|
|
64
|
+
candidates: { ref: string; title: string; score: number; reasons: string[] }[];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** 参照・タイトル・自然文から対象を特定する。参照の一致 → タイトル部分一致 → 内容類似 */
|
|
68
|
+
export function resolve(ctx: P3Context, q: string, current?: string): ResolveResult {
|
|
69
|
+
const query = q.trim();
|
|
70
|
+
const exact = query ? resolveRef(ctx, query, current) : undefined;
|
|
71
|
+
if (exact) return { match: exact, candidates: [{ ref: exact, title: titleOf(ctx, exact), score: 1, reasons: ["参照が一致"] }] };
|
|
72
|
+
const items = [
|
|
73
|
+
...ctx.ws.requests.list().map((r) => ({ ref: r.id, title: r.title, request: r.id })),
|
|
74
|
+
...ctx.ws.allTasks().map((t) => ({ ref: t.ref, title: t.title, request: t.request })),
|
|
75
|
+
];
|
|
76
|
+
const byTitle = items
|
|
77
|
+
.filter((t) => query && t.title.toLowerCase().includes(query.toLowerCase()))
|
|
78
|
+
// 今の要望の中のものを先に
|
|
79
|
+
.sort((a, b) => Number(b.request === current) - Number(a.request === current))
|
|
80
|
+
.map((t) => ({ ref: t.ref, title: t.title, score: 0.9, reasons: ["タイトルに含む"] }));
|
|
81
|
+
const candidates = byTitle.slice(0, 8);
|
|
82
|
+
return { match: candidates.length === 1 ? candidates[0].ref : null, candidates };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function titleOf({ ws }: P3Context, ref: string): string {
|
|
86
|
+
return ws.task(ref)?.title ?? ws.requests.get(ref)?.title ?? "?";
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 要望ごとの進捗。進捗の画面と `p3 progress` で使う。
|
|
91
|
+
* 並び: 最終更新(要望自身と、アーカイブしていないタスクの updatedAt の最大)の新しい順。同じ日時なら要望 ID の順。
|
|
92
|
+
*/
|
|
93
|
+
export function progress(ctx: P3Context): RequestProgress[] {
|
|
94
|
+
return ctx.ws.requests
|
|
95
|
+
.list()
|
|
96
|
+
.map((request) => {
|
|
97
|
+
const tasks = ctx.ws.tasksOf(request.id).list();
|
|
98
|
+
const counts = Object.fromEntries(TASK_STATUSES.map((s) => [s, 0])) as Record<TaskStatus, number>;
|
|
99
|
+
for (const t of tasks) counts[t.status]++;
|
|
100
|
+
const done = tasks.filter((t) => t.status === "done");
|
|
101
|
+
return {
|
|
102
|
+
request,
|
|
103
|
+
tasks: tasks.map(({ id, ref, title, status, createdAt, startedAt, doneAt, checkedAt }) => ({ id, ref, title, status, createdAt, startedAt, doneAt, checkedAt })),
|
|
104
|
+
counts,
|
|
105
|
+
total: tasks.length,
|
|
106
|
+
done: done.length,
|
|
107
|
+
updatedAt: [request.updatedAt, ...tasks.map((t) => t.updatedAt)].sort().at(-1)!,
|
|
108
|
+
};
|
|
109
|
+
})
|
|
110
|
+
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || byId(a.request.id, b.request.id));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** ID の順(数を含む部分は数として比べる: T2 < T10) */
|
|
114
|
+
const byId = (a: string, b: string) => a.localeCompare(b, undefined, { numeric: true });
|