@tamai/hub-cli 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.
@@ -0,0 +1,22 @@
1
+ import { requireSinglePositional, usageError } from "../lib/args.mjs";
2
+ import { postChunks } from "../lib/api.mjs";
3
+ import { printTaskResult } from "../lib/format.mjs";
4
+ import { splitNote } from "../lib/records.mjs";
5
+
6
+ export const taskReportCommand = {
7
+ name: "report",
8
+ options: { allowed: ["note"] },
9
+ async run({ options, positional, dependencies, api }) {
10
+ const id = requireSinglePositional(positional, "タスクID");
11
+ if (!options.note?.trim()) throw usageError("--noteを指定してください");
12
+ const results = await postChunks(
13
+ splitNote(options.note),
14
+ (chunk) => api(`/api/tasks/${encodeURIComponent(id)}/report`, {
15
+ method: "POST",
16
+ body: JSON.stringify({ note: chunk }),
17
+ }),
18
+ "報告",
19
+ );
20
+ printTaskResult(results.at(-1), options.json, dependencies.stdout, "task");
21
+ },
22
+ };
@@ -0,0 +1,12 @@
1
+ import { requireSinglePositional } from "../lib/args.mjs";
2
+ import { printTaskResult } from "../lib/format.mjs";
3
+
4
+ export const taskShowCommand = {
5
+ name: "show",
6
+ options: {},
7
+ async run({ options, positional, dependencies, api }) {
8
+ const id = requireSinglePositional(positional, "タスクID");
9
+ const payload = await api(`/api/tasks/${encodeURIComponent(id)}`);
10
+ printTaskResult(payload, options.json, dependencies.stdout, "show");
11
+ },
12
+ };
package/lib/api.mjs ADDED
@@ -0,0 +1,220 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ import { DEFAULT_BASE_URL, cliError } from "./args.mjs";
6
+
7
+ export class ApiError extends Error {
8
+ constructor(status, payload) {
9
+ super(`hub API returned ${status}`);
10
+ this.status = status;
11
+ this.payload = payload;
12
+ }
13
+ }
14
+
15
+ export function isConflictError(error) {
16
+ return error instanceof ApiError && error.payload?.error?.code === "conflict";
17
+ }
18
+
19
+ export function defaultEnvFilePath(homedir = os.homedir()) {
20
+ return path.join(homedir, ".config", "tamai", "hub-tasks.env");
21
+ }
22
+
23
+ export function parseEnvFile(text) {
24
+ const values = {};
25
+ for (const rawLine of String(text).split("\n")) {
26
+ const line = rawLine.trim();
27
+ if (line === "" || line.startsWith("#")) continue;
28
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
29
+ if (!match) continue;
30
+ const raw = match[2].trim();
31
+ const quoted = /^(['"])([\s\S]*)\1\s*(?:#.*)?$/.exec(raw);
32
+ values[match[1]] = quoted === null ? raw.replace(/\s+#.*$/, "").trim() : quoted[2];
33
+ }
34
+ return values;
35
+ }
36
+
37
+ export async function configFromEnv(env, readFileImpl = readFile) {
38
+ let clientId = env.TASKS_CLIENT_ID;
39
+ let clientSecret = env.TASKS_CLIENT_SECRET;
40
+ let baseUrl = env.TASKS_BASE_URL;
41
+ let actor = env.HUB_ACTOR?.trim();
42
+
43
+ const envFile = env.TASKS_ENV_FILE || defaultEnvFilePath();
44
+ if (!clientId || !clientSecret) {
45
+ try {
46
+ const fromFile = parseEnvFile(await readFileImpl(envFile, "utf8"));
47
+ clientId ||= fromFile.TASKS_CLIENT_ID;
48
+ clientSecret ||= fromFile.TASKS_CLIENT_SECRET;
49
+ baseUrl ||= fromFile.TASKS_BASE_URL;
50
+ actor ||= fromFile.HUB_ACTOR?.trim();
51
+ } catch {
52
+ // 読めない場合は下の未設定エラーで期待パスを案内する。
53
+ }
54
+ }
55
+
56
+ if (!clientId || !clientSecret) {
57
+ throw cliError(
58
+ "TASKS_CLIENT_ID と TASKS_CLIENT_SECRET を設定してください。\n"
59
+ + `認証ファイル ${envFile} があれば自動で読み込みます。\n`
60
+ + "手動で設定する場合: set -a && source ~/.config/tamai/hub-tasks.env && set +a",
61
+ );
62
+ }
63
+ assertCredentialFormat("TASKS_CLIENT_ID", clientId);
64
+ assertCredentialFormat("TASKS_CLIENT_SECRET", clientSecret);
65
+ return {
66
+ baseUrl: (baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, ""),
67
+ clientId,
68
+ clientSecret,
69
+ ...(actor ? { actor } : {}),
70
+ };
71
+ }
72
+
73
+ export function createHubApi(config, fetchImpl) {
74
+ const baseUrl = config.baseUrl.replace(/\/+$/, "");
75
+ return async function request(requestPath, init = {}) {
76
+ const headers = new Headers(init.headers);
77
+ headers.set("Accept", "application/json");
78
+ if (config.clientId && config.clientSecret) {
79
+ headers.set("CF-Access-Client-Id", config.clientId);
80
+ headers.set("CF-Access-Client-Secret", config.clientSecret);
81
+ }
82
+ if (config.actor) headers.set("X-Hub-Actor", config.actor);
83
+ if (init.body !== undefined) headers.set("Content-Type", "application/json");
84
+
85
+ const response = await fetchImpl(`${baseUrl}${requestPath}`, { ...init, headers });
86
+ const text = await response.text();
87
+ let payload = null;
88
+ if (text !== "") {
89
+ try {
90
+ payload = JSON.parse(text);
91
+ } catch {
92
+ throw cliError(`APIからJSONではない応答を受信しました (${response.status})`);
93
+ }
94
+ }
95
+ if (!response.ok) throw new ApiError(response.status, payload);
96
+ return payload;
97
+ };
98
+ }
99
+
100
+ /** 秘匿した値の置き換え先。JSON文字列の中に置いても壊れない文字だけで作る。 */
101
+ export const REDACTED = "[redacted]";
102
+
103
+ /**
104
+ * 認証値として受理する最短の長さ。
105
+ *
106
+ * Cloudflare Access の service token は Client ID が **32桁hex + `.access`**、
107
+ * Client Secret が **64桁hex**(旧)または **`cfast_` 始まり**(新)で、いずれも32文字以上ある。
108
+ * 短い値はそもそも正規の service token ではない。
109
+ */
110
+ export const MIN_CREDENTIAL_LENGTH = 32;
111
+
112
+ /**
113
+ * 認証値の形式を **API を呼ぶ前に**検査する(codex1 再レビュー Medium 1)。
114
+ *
115
+ * `redactSecrets` は出力全体に対する**部分文字列の置換**である。`id` や `"` のような短い値を
116
+ * 受理すると、秘密でないJSONのキー・値・記号までもが `[redacted]` へ変わり、
117
+ * `"` に至っては `--json` の stdout がJSONとしてparseできなくなる。
118
+ *
119
+ * **短い値をマスクの対象から外して漏らすのではなく、設定そのものを拒否する。**
120
+ * 正規の service token は下限を余裕で超えるので、実運用で弾かれるのは打ち間違いか
121
+ * 取り違えた値だけである。
122
+ *
123
+ * **値そのものはエラー文へ含めない。** 形式の誤りを知らせるのに値は要らない。
124
+ */
125
+ export function assertCredentialFormat(name, value) {
126
+ if (typeof value !== "string" || value.length < MIN_CREDENTIAL_LENGTH || /\s/.test(value)) {
127
+ throw cliError(
128
+ `${name} の形式が不正です(Cloudflare Access の service token ではありません)。\n`
129
+ + `${MIN_CREDENTIAL_LENGTH}文字以上で、空白を含まない値を設定してください`
130
+ + "(Client IDは32桁hex + .access、Client Secretは64桁hexまたは cfast_ 始まり)。\n"
131
+ + "値そのものはここへ出さないので、認証ファイルの中身を直接確かめてください。",
132
+ );
133
+ }
134
+ return value;
135
+ }
136
+
137
+ /**
138
+ * 設定済みの認証値を出力文字列から消す(codex1 High 2)。
139
+ *
140
+ * ヘッダへ載せた値がAPI応答・例外messageへ反射して返ることがあり、CLIはそれを
141
+ * stderr(エラー整形)と `--json` のstdoutへそのまま流していた。値が1度でも出力へ落ちると
142
+ * エージェントのtranscriptと端末のログへ機械的に積み上がる。
143
+ *
144
+ * **`runCli` が stdout / stderr を包む出口1か所でだけ呼ぶ。** 各コマンドに散らすと、
145
+ * 新しい出力を足したときに通し忘れる。configが決まる前(help / version / 認証未設定)は
146
+ * 消すものが無いので素通りする。
147
+ *
148
+ * 保証するのは「**設定済みの値がそのままの綴りで出ない**」ことだけである。
149
+ * 値が部分的に変形して返る場合(切り詰め・再エンコード等)は対象外。
150
+ *
151
+ * **これは構文を解さない文字列置換である。** JSONを組み立て直しているわけではないので、
152
+ * 値が短ければ正当なキー・値・記号にも一致してしまう。それが起きないことは
153
+ * `assertCredentialFormat` が入口で短い値を拒否することで担保する(両方でひとつの性質)。
154
+ */
155
+ export function redactSecrets(text, config) {
156
+ const source = String(text);
157
+ if (config === null || config === undefined) return source;
158
+
159
+ const patterns = [];
160
+ for (const value of [config.clientSecret, config.clientId]) {
161
+ if (typeof value !== "string" || value === "") continue;
162
+ patterns.push(value);
163
+ // `JSON.stringify` を通ると `"` `\` 改行はエスケープされる。JSON出力側の綴りも消す。
164
+ const escaped = JSON.stringify(value).slice(1, -1);
165
+ if (escaped !== value) patterns.push(escaped);
166
+ }
167
+ if (patterns.length === 0) return source;
168
+
169
+ // 長いものから消す。片方が他方の部分文字列でも取りこぼさない
170
+ patterns.sort((a, b) => b.length - a.length);
171
+ let out = source;
172
+ for (const pattern of patterns) out = out.split(pattern).join(REDACTED);
173
+ return out;
174
+ }
175
+
176
+ export function describeFailure(error) {
177
+ if (error instanceof ApiError) return `${error.status} ${JSON.stringify(error.payload)}`;
178
+ return error instanceof Error ? error.message : String(error);
179
+ }
180
+
181
+ export function formatFailure(error, payload) {
182
+ const message = typeof payload?.error?.message === "string" && payload.error.message !== ""
183
+ ? payload.error.message
184
+ : (error instanceof Error ? error.message : String(error));
185
+ const [first, ...rest] = message.split("\n");
186
+ const origin = error instanceof ApiError
187
+ ? ` (HTTP ${error.status}${typeof payload?.error?.code === "string" ? ` ${payload.error.code}` : ""})`
188
+ : "";
189
+ const lines = [`error: ${first}${origin}`, ...rest];
190
+ if (typeof error?.usage === "string" && error.usage !== "") lines.push(`使い方: ${error.usage}`);
191
+ return lines.join("\n");
192
+ }
193
+
194
+ export function withGuidance(error, guidance) {
195
+ if (error instanceof ApiError) {
196
+ const current = error.payload?.error ?? {};
197
+ return new ApiError(error.status, {
198
+ ...error.payload,
199
+ error: { ...current, message: `${current.message ?? `hub API returned ${error.status}`}\n${guidance}` },
200
+ });
201
+ }
202
+ return cliError(`${describeFailure(error)}\n${guidance}`);
203
+ }
204
+
205
+ export async function postChunks(chunks, send, label) {
206
+ const results = [];
207
+ for (let index = 0; index < chunks.length; index += 1) {
208
+ try {
209
+ results.push(await send(chunks[index]));
210
+ } catch (error) {
211
+ if (chunks.length === 1) throw error;
212
+ throw withGuidance(
213
+ error,
214
+ `${label}は${chunks.length}件中${index}件まで送信済みです(${index + 1}件目で失敗)。`
215
+ + "送信済みの分は取り消せないため、残りの本文だけを送り直してください",
216
+ );
217
+ }
218
+ }
219
+ return results;
220
+ }
package/lib/args.mjs ADDED
@@ -0,0 +1,167 @@
1
+ /** プロジェクトの区分。共有範囲のvisibility(private|team)とは別の軸。 */
2
+ export const PROJECT_KINDS = ["work", "private"];
3
+
4
+ export const DEFAULT_BASE_URL = "https://dash.tamaitakamasa.com";
5
+
6
+ export const TASK_USAGE = `使い方:
7
+ hub task claim <id> --owner <name> [--json]
8
+ hub task next --owner <name> [--json]
9
+ hub task show <id> [--json]
10
+ hub task report <id> --note <text> [--json]
11
+ hub task note <id> (--note <text> | --note-file <path>) [--json]
12
+ hub task add <title> [--project <name>] [--force] [--due <YYYY-MM-DD>] [--body-file <path>] [--json]
13
+ hub task new <title> [--project <name>] [--due <YYYY-MM-DD>] [--body-file <path>]
14
+ [--repo-card [<dir>]] [--slug <slug>] [--force] [--json]
15
+ hub task list [--status <s>] [--project <name>] [--owner <name>] [--q <text>] [--json]
16
+ hub task audit [--json]
17
+
18
+ hub task new は「D1へ起票 → repoに記録の雛形を作成 → context_ref で紐付け」を1コマンドで行う。
19
+ 記録には status / owner / priority を書かない(状態の正本はD1だけ)。
20
+ --repo-card はリポジトリ相対のディレクトリのみ。context_ref にはリポジトリルート相対のパスが入る。
21
+ hub task audit は done のタスクの context_ref を git と突き合わせ、記録が未コミット・
22
+ 未pushのまま done になっていないかを見る(「doneなのに本番に無い」の検出)。
23
+ -- 以降はすべて位置引数になる。-- で始まるタイトルは hub task new --project hub -- "--で始まる題" の順で渡す。
24
+ オプションは --name=value の形でも書ける。値が -- で始まるとき(例 --note='--- 見出し')はこの形で渡す。
25
+ report / note の長文は約2000字ごとに分割して送る。途中で失敗すると「n件中m件まで送信済み」と出る。
26
+ `;
27
+
28
+ export const PROJECT_USAGE = `使い方:
29
+ hub project list [--kind work|private] [--json]
30
+ hub project show <slug> [--json]
31
+ hub project create <slug> --name <text> [--kind work|private] [--repo <text>] [--json]
32
+ hub project update <slug> [--name <text>] [--repo <text>] [--slug <new-slug>]
33
+ [--kind work|private]
34
+ [--add-link "<ラベル>=<URL>"]... [--remove-link "<ラベル>"]...
35
+ [--clear-links] [--json]
36
+ hub project move <slug> (--after <slug> | --top) [--json]
37
+ hub project sync-registry [--json]
38
+
39
+ create はslugを自動生成しない。既存に倣ってkebabの英字で指定する(例 pc-setup)。
40
+ move はピン留めしたプロジェクトの並び替え。--top で先頭、--after で指定slugの直後。
41
+ update の --repo に空文字(--repo "")を渡すとrepoをクリアする。
42
+ --add-link は最初の = でラベルとURLに分ける(URL側の = や ?a=1&b=2 はそのまま)。
43
+ 追加は末尾へ・繰り返し指定可。--remove-link はラベル完全一致(該当なし・複数該当はエラー)。
44
+ --add-link は既存と同じラベルを拒否する(張り替えは同じコマンドで --remove-link と併用する)。
45
+ --clear-links は全消し(--add-link / --remove-link と同時指定不可)。
46
+ --kind は仕事/プライベートの区分(既定 work)。共有範囲のvisibilityとは別。
47
+ list は既定で全件出す(--kind を付けたときだけ絞る)。
48
+ オプションは --name=value の形でも書ける(値が -- で始まるときはこの形で渡す)。
49
+ `;
50
+
51
+ export const USAGE = `使い方:
52
+ hub task <verb> ... タスク操作(new / add / claim / next / show / report / note / list)
53
+ hub task help
54
+ hub project <verb> ... プロジェクト操作(list / show / create / update / move / sync-registry)
55
+ hub project help
56
+ hub --version 入っているCLIの版を出す(hub version も同じ)
57
+
58
+ 環境変数:
59
+ TASKS_CLIENT_ID / TASKS_CLIENT_SECRET
60
+ Cloudflare Accessのservice token。
61
+ **CLIは設定済みの認証値を出力から秘匿する**(stdout / stderr / エラー文)。
62
+ 値そのものがAPI応答や例外に含まれて返ってきた場合も [redacted] に置き換える。
63
+ 形式はAPI呼び出し前に検査する(32文字未満・空白を含む値は弾く。値はエラー文へ出さない)。
64
+ TASKS_BASE_URL(既定 ${DEFAULT_BASE_URL})
65
+ 接続先。変えるときだけ指定する。
66
+ HUB_ACTOR
67
+ 操作の名乗り(例 codex1 / opus3)。X-Hub-Actorとして送り、看板の監査eventに残る。
68
+ **service tokenを共有するので、設定を忘れると別人の操作として記録される。**
69
+ TASKS_ENV_FILE(既定 ~/.config/tamai/hub-tasks.env)
70
+ 認証情報がprocess envに無いときに読むファイル。TASKS_BASE_URLとHUB_ACTORもここから読む。
71
+
72
+ hub task new --repo-card の出力先は**cwd基準**である(gitリポジトリの中で実行する)。
73
+ 例: repo直下なら docs/records/、dash/ で実行すると dash/docs/records/ に書く。
74
+ 解決した出力先は起票前にstderrへ1行出る。確認待ちや自動停止は行わない。
75
+
76
+ done化(検収)はCLIから行えない。人間がdashで行う。
77
+ `;
78
+
79
+ export function cliError(message) {
80
+ const error = new Error(message);
81
+ error.code = "cli_error";
82
+ return error;
83
+ }
84
+
85
+ export function usageError(message) {
86
+ const error = cliError(message);
87
+ error.usage = true;
88
+ return error;
89
+ }
90
+
91
+ export function usageLineFor(group, verb) {
92
+ const usage = group === "task" ? TASK_USAGE : PROJECT_USAGE;
93
+ const lines = usage.split("\n");
94
+ const prefix = ` hub ${group} ${verb}`;
95
+ const start = lines.findIndex((line) => line === prefix || line.startsWith(`${prefix} `));
96
+ if (start === -1) return "";
97
+ const picked = [lines[start].trim()];
98
+ for (let index = start + 1; index < lines.length; index += 1) {
99
+ if (!/^ {3,}\S/.test(lines[index])) break;
100
+ picked.push(lines[index].trim());
101
+ }
102
+ return picked.join("\n ");
103
+ }
104
+
105
+ export function parseArgs(args, allowedOptions, optionalValue = [], booleanOptions = [], repeatableOptions = []) {
106
+ const options = { json: false };
107
+ const flags = {};
108
+ const positional = [];
109
+ for (const name of repeatableOptions) options[name] = [];
110
+
111
+ for (let index = 0; index < args.length; index += 1) {
112
+ const token = args[index];
113
+ if (token === "--") {
114
+ positional.push(...args.slice(index + 1));
115
+ break;
116
+ }
117
+ if (!token.startsWith("--")) {
118
+ positional.push(token);
119
+ continue;
120
+ }
121
+
122
+ const at = token.indexOf("=");
123
+ const name = at === -1 ? token.slice(2) : token.slice(2, at);
124
+ const inlineValue = at === -1 ? undefined : token.slice(at + 1);
125
+ if (name !== "json" && !allowedOptions.includes(name)) {
126
+ throw usageError(`未対応のオプションです: --${name}`);
127
+ }
128
+ if (name === "json" || booleanOptions.includes(name)) {
129
+ if (inlineValue !== undefined) throw usageError(`--${name} は値を取りません`);
130
+ if (name === "json") options.json = true;
131
+ else flags[name] = true;
132
+ continue;
133
+ }
134
+ flags[name] = true;
135
+ let value = inlineValue;
136
+ if (value === undefined) {
137
+ const next = args[index + 1];
138
+ if (next === undefined || next.startsWith("--")) {
139
+ if (optionalValue.includes(name)) continue;
140
+ throw usageError(`--${name} の値が必要です。値が -- で始まるときは --${name}=<値> の形で渡してください`);
141
+ }
142
+ value = next;
143
+ index += 1;
144
+ }
145
+ if (repeatableOptions.includes(name)) options[name].push(value);
146
+ else options[name] = value;
147
+ }
148
+
149
+ return { options, positional, flags };
150
+ }
151
+
152
+ export function parseCommandArgs(args, spec = {}) {
153
+ return parseArgs(
154
+ args,
155
+ spec.allowed ?? [],
156
+ spec.optionalValue ?? [],
157
+ spec.boolean ?? [],
158
+ spec.repeatable ?? [],
159
+ );
160
+ }
161
+
162
+ export function requireSinglePositional(positional, label) {
163
+ if (positional.length !== 1 || positional[0].trim() === "") {
164
+ throw usageError(`${label}を1つ指定してください`);
165
+ }
166
+ return positional[0];
167
+ }
package/lib/cli.mjs ADDED
@@ -0,0 +1,195 @@
1
+ // hub CLI の本体(タスク52 / 指示書v4「CLIが唯一の実装」・記録147で `tools/hub.mjs` から移設)。
2
+ // エージェント・人間の双方がhubを操作する唯一の道具。スキルやMCPを足す場合も
3
+ // ここを呼ぶだけの薄いラッパにし、ロジックを二重に持たないこと。
4
+ //
5
+ // hub task <verb> ... タスク操作(旧 tools/task.mjs と同機能)
6
+ // hub project <verb> ... プロジェクト操作(読み取り + 作成・更新 + registry生成)
7
+ //
8
+ // 全サブコマンドが `--json` を受け付け、付けると生のAPI応答をそのまま出力する。
9
+ //
10
+ // **ここに自動実行判定(`import.meta.url === pathToFileURL(process.argv[1])`)は置かない。**
11
+ // あの比較は `npm i -g` が張る symlink 経由だと偽になり、CLIが何も出さずexit 0で終わる
12
+ // (Astra High 1・実測: 実体パス447 byte / symlink 0 byte)。入口は `bin/hub.mjs` 専用にして、
13
+ // 比較そのものを無くしてある。このファイルはライブラリとしてだけ読まれる。
14
+
15
+ import { mkdir, readdir, readFile, stat, writeFile } from "node:fs/promises";
16
+
17
+ import {
18
+ ApiError,
19
+ configFromEnv,
20
+ createHubApi,
21
+ formatFailure,
22
+ redactSecrets,
23
+ } from "./api.mjs";
24
+ import {
25
+ PROJECT_USAGE,
26
+ TASK_USAGE,
27
+ USAGE,
28
+ cliError,
29
+ parseCommandArgs,
30
+ usageLineFor,
31
+ } from "./args.mjs";
32
+ import { projectCreateCommand } from "../commands/project-create.mjs";
33
+ import { projectListCommand } from "../commands/project-list.mjs";
34
+ import { projectMoveCommand } from "../commands/project-move.mjs";
35
+ import { projectShowCommand } from "../commands/project-show.mjs";
36
+ import { projectSyncRegistryCommand } from "../commands/project-sync-registry.mjs";
37
+ import { projectUpdateCommand } from "../commands/project-update.mjs";
38
+ import { taskAddCommand } from "../commands/task-add.mjs";
39
+ import { taskAuditCommand } from "../commands/task-audit.mjs";
40
+ import { taskClaimCommand } from "../commands/task-claim.mjs";
41
+ import { taskListCommand } from "../commands/task-list.mjs";
42
+ import { taskNewCommand } from "../commands/task-new.mjs";
43
+ import { taskNextCommand } from "../commands/task-next.mjs";
44
+ import { taskNoteCommand } from "../commands/task-note.mjs";
45
+ import { taskReportCommand } from "../commands/task-report.mjs";
46
+ import { taskShowCommand } from "../commands/task-show.mjs";
47
+ import { defaultRunGit } from "./git.mjs";
48
+
49
+ export { configFromEnv, createHubApi } from "./api.mjs";
50
+ export { defaultEnvFilePath, parseEnvFile } from "./api.mjs";
51
+ export { projectLines, toRegistryYaml } from "./format.mjs";
52
+ export { auditDoneTasks, formatAuditReport, parseGitStatusPaths, readGitState } from "./git.mjs";
53
+ export {
54
+ DEFAULT_RECORD_DIR,
55
+ NOTE_CHUNK_LIMIT,
56
+ findRepoRoot,
57
+ nextRecordNumber,
58
+ recordTemplate,
59
+ slugify,
60
+ splitNote,
61
+ } from "./records.mjs";
62
+
63
+
64
+ const commandMap = (commands) => new Map(commands.map((command) => [command.name, command]));
65
+
66
+ const COMMAND_GROUPS = {
67
+ task: {
68
+ usage: TASK_USAGE,
69
+ commands: commandMap([
70
+ taskAddCommand,
71
+ taskAuditCommand,
72
+ taskClaimCommand,
73
+ taskListCommand,
74
+ taskNewCommand,
75
+ taskNextCommand,
76
+ taskNoteCommand,
77
+ taskReportCommand,
78
+ taskShowCommand,
79
+ ]),
80
+ },
81
+ project: {
82
+ usage: PROJECT_USAGE,
83
+ commands: commandMap([
84
+ projectCreateCommand,
85
+ projectListCommand,
86
+ projectMoveCommand,
87
+ projectShowCommand,
88
+ projectSyncRegistryCommand,
89
+ projectUpdateCommand,
90
+ ]),
91
+ },
92
+ };
93
+
94
+ /**
95
+ * 配布されている版(`packages/hub-cli/package.json` の `version`)。
96
+ *
97
+ * **`import.meta.url` 基準で読む。** cwd 基準にすると `npm i -g` した bin をどこから
98
+ * 呼ぶかで値が変わる(=どの hub が入っているのか確かめる道具にならない)。
99
+ * スキル側は「`command not found` なら `npm i -g`」だけでは古い CLI が残る場合を扱えないので、
100
+ * 対応版の確認はこの値で行う(Astra B-4-4)。
101
+ */
102
+ export async function packageVersion(readFileImpl = readFile) {
103
+ const raw = await readFileImpl(new URL("../package.json", import.meta.url), "utf8");
104
+ const parsed = JSON.parse(raw);
105
+ if (typeof parsed.version !== "string" || parsed.version === "") {
106
+ throw cliError("package.json に version がありません");
107
+ }
108
+ return parsed.version;
109
+ }
110
+
111
+ async function execute(argv, dependencies, onConfig) {
112
+ const [group, ...rest] = argv;
113
+ if (group === undefined || group === "help" || group === "--help" || group === "-h") {
114
+ dependencies.stdout.write(USAGE);
115
+ return;
116
+ }
117
+
118
+ // 版の確認は認証情報なしで通す(help と同じ扱い)。
119
+ if (group === "version" || group === "--version" || group === "-V") {
120
+ // 読むのはパッケージ自身のメタデータなので、利用者向けの readFileImpl 注入は通さない。
121
+ dependencies.stdout.write(`${await packageVersion()}\n`);
122
+ return;
123
+ }
124
+
125
+ const groupDefinition = COMMAND_GROUPS[group];
126
+ if (groupDefinition === undefined) {
127
+ throw cliError(`未対応のサブコマンドです: ${group}\n${USAGE.trimEnd()}`);
128
+ }
129
+
130
+ // helpだけは認証情報なしでも読めるようにする
131
+ if (rest.length === 0 || rest[0] === "help" || rest[0] === "--help" || rest[0] === "-h") {
132
+ dependencies.stdout.write(groupDefinition.usage);
133
+ return;
134
+ }
135
+
136
+ // config が決まった時点で秘匿の対象を出口へ知らせる。これより前の出力(help / version /
137
+ // 認証未設定の案内)は消すものが無い。
138
+ const config = await configFromEnv(dependencies.env, dependencies.readFileImpl);
139
+ onConfig(config);
140
+ const api = createHubApi(config, dependencies.fetchImpl);
141
+ try {
142
+ const [name, ...args] = rest;
143
+ const command = groupDefinition.commands.get(name);
144
+ if (command === undefined) {
145
+ throw cliError(`未対応の動詞です: ${name}\n${groupDefinition.usage.trimEnd()}`);
146
+ }
147
+ await command.run({
148
+ ...parseCommandArgs(args, command.options),
149
+ dependencies,
150
+ api,
151
+ });
152
+ } catch (error) {
153
+ // 使い方の誤りには該当コマンドの行を添える。動詞が分かるのはここだけ
154
+ if (error?.usage === true) error.usage = usageLineFor(group, rest[0]);
155
+ throw error;
156
+ }
157
+ }
158
+
159
+ export async function runCli(argv, overrides = {}) {
160
+ // **秘密を消す出口はここ1か所だけ**(codex1 High 2)。
161
+ // API応答や例外messageへ反射して返ってきた認証値が、stderr のエラー整形にも
162
+ // `--json` の stdout にも出ないようにする。コマンド側に散らすと通し忘れるので、
163
+ // stdout / stderr を包んで「書くもの全部」を通す。
164
+ const redaction = { config: null };
165
+ const guarded = (stream) => ({
166
+ write: (text) => stream.write(redactSecrets(text, redaction.config)),
167
+ });
168
+
169
+ const dependencies = {
170
+ env: overrides.env ?? process.env,
171
+ fetchImpl: overrides.fetchImpl ?? globalThis.fetch,
172
+ readFileImpl: overrides.readFileImpl ?? readFile,
173
+ writeFileImpl: overrides.writeFileImpl ?? writeFile,
174
+ readdirImpl: overrides.readdirImpl ?? readdir,
175
+ mkdirImpl: overrides.mkdirImpl ?? mkdir,
176
+ statImpl: overrides.statImpl ?? stat,
177
+ cwd: overrides.cwd ?? (() => process.cwd()),
178
+ runGitImpl: overrides.runGitImpl ?? defaultRunGit,
179
+ stdout: guarded(overrides.stdout ?? process.stdout),
180
+ stderr: guarded(overrides.stderr ?? process.stderr),
181
+ };
182
+
183
+ try {
184
+ await execute(argv, dependencies, (config) => { redaction.config = config; });
185
+ return 0;
186
+ } catch (error) {
187
+ const payload = error instanceof ApiError
188
+ ? error.payload
189
+ : { error: { code: error?.code ?? "cli_error", message: error instanceof Error ? error.message : String(error) } };
190
+ // 1行目は人間可読の `error: ...`、続けてこれまでどおりのJSON(エラー形は変えない)。
191
+ // stdout は `--json` のデータ専用なので汚さない(警告と同じ扱い)
192
+ dependencies.stderr.write(`${formatFailure(error, payload)}\n${JSON.stringify(payload, null, 2)}\n`);
193
+ return 1;
194
+ }
195
+ }