@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.
package/README.md ADDED
@@ -0,0 +1,145 @@
1
+ # @tamai/hub-cli
2
+
3
+ hub(tamai個人のパーソナルハブ)のタスク看板とプロジェクトを操作する CLI。
4
+ 状態の正本は hub の D1 であり、この CLI はそれを読み書きする唯一の道具である。
5
+ 依存ゼロ(`node:` のみ)。**認証は tamai の Cloudflare Access service token が要る**ので、
6
+ それを持っていない環境では何もできない。API の契約・権限・エラーの意味は
7
+ `tamaitakamasa/hub` リポジトリ側が正本で、ここには書かない。
8
+
9
+ ## インストール
10
+
11
+ ```bash
12
+ npm i -g @tamai/hub-cli
13
+ ```
14
+
15
+ `hub` コマンドが PATH に入る。**Node 22 以上**が要る。
16
+
17
+ 入っている版を確かめる:
18
+
19
+ ```bash
20
+ command -v hub
21
+ hub --version
22
+ ```
23
+
24
+ `command not found` なら入れる。**入っていても古いことがある**ので、動かないときは
25
+ `hub --version` を見てから上げる(「無ければ入れる」だけでは古い CLI を拾う)。
26
+
27
+ ## 認証
28
+
29
+ `~/.config/tamai/hub-tasks.env` に service token を置く。**発行と配布は たま**が行う。
30
+
31
+ ```
32
+ TASKS_CLIENT_ID=...
33
+ TASKS_CLIENT_SECRET=...
34
+ TASKS_BASE_URL=https://dash.tamaitakamasa.com
35
+ ```
36
+
37
+ process env に無ければ CLI がこのファイルを自動で読むので、毎回の `source` は要らない。
38
+ 別の場所に置くなら `TASKS_ENV_FILE` でパスを渡す。
39
+
40
+ **CLI は設定済みの認証値を出力から秘匿する**(stdout / stderr / エラー文のいずれも)。
41
+ CLI 自身が値を書かないだけでなく、**値そのものが API 応答や例外に含まれて返ってきた場合も
42
+ `[redacted]` に置き換える**。出すのは「どのファイルを読もうとしたか」だけである。
43
+
44
+ 秘匿は出力全体に対する文字列置換なので、**認証値の形式は API を呼ぶ前に検査する**。
45
+ 32 文字未満・空白を含む値は「形式が不正」として弾く(短い値を通すと、秘密でない JSON の
46
+ キーや値まで置き換わってしまう)。正規の service token は Client ID が 32 桁 hex + `.access`、
47
+ Client Secret が 64 桁 hex か `cfast_` 始まりで、この下限を優に超える。
48
+ エラー文に値そのものは出ないので、弾かれたら env ファイルの中身を直接確かめること。
49
+
50
+ ### HUB_ACTOR
51
+
52
+ ```bash
53
+ export HUB_ACTOR=codex1
54
+ ```
55
+
56
+ service token を複数のエージェントで共有するので、**誰の操作かはこの名乗りでしか分からない**。
57
+ `X-Hub-Actor` として送られ、看板の監査 event に残る。設定を忘れると env の既定
58
+ (`orchestrator` 等)の名義で記録され、誤帰属になる。
59
+
60
+ ## 使い方
61
+
62
+ ```bash
63
+ hub --help
64
+ hub task help
65
+ hub project help
66
+ ```
67
+
68
+ 動詞は `task` が `new` / `add` / `claim` / `next` / `show` / `report` / `note` / `list` / `audit`、
69
+ `project` が `list` / `show` / `create` / `update` / `move` / `sync-registry`。
70
+ **正確なオプションは常に `--help` を見る**(ここにも、スキルにも写経しない)。
71
+ 全動詞が `--json` を受ける。機械が読むときは必ず `--json` を使い、人向けの整形を parse しない。
72
+
73
+ `help` と `--version` は認証情報なしでも読める。
74
+
75
+ ### `--repo-card` の出力先は cwd 基準
76
+
77
+ ```bash
78
+ cd ~/ws/private/hub
79
+ hub task new '新しいタスク' --project hub --body-file brief.md --repo-card
80
+ ```
81
+
82
+ `--repo-card` は「D1 へ起票 → `docs/records/NN-slug.md` の雛形 → `context_ref` の紐付け」を
83
+ 1 コマンドで行う。**出力先は cwd 基準**である(git リポジトリの中で実行すること)。
84
+
85
+ | 実行場所 | 出力先 | `context_ref` |
86
+ | --- | --- | --- |
87
+ | repo 直下 | `docs/records/` | `docs/records/NN-slug.md` |
88
+ | repo の `dash/` | `dash/docs/records/` | `dash/docs/records/NN-slug.md` |
89
+ | 別 repo(stw-manage 等) | その repo の `docs/records/` | その repo からの相対 |
90
+
91
+ git root は探すが、出力先の基準にはしない(`context_ref` だけが git root 相対)。
92
+ これは現状の挙動で、実際そう使っている。取り違えると起票してしまってからでは戻しにくいので、
93
+ **解決した出力先を起票前に stderr へ 1 行出す**。確認待ちや自動停止は行わない。
94
+ `--repo-card <dir>` でディレクトリを明示できる(リポジトリ相対のみ。絶対パスは不可)。
95
+
96
+ ## done にしない
97
+
98
+ `done`(検収)は CLI から行えない。エージェントは `hub task report` までで、
99
+ done にするのは人間が dash で行う。done は「本番へ反映し、本番で検証まで終えた」状態を指す。
100
+
101
+ ## リリース手順
102
+
103
+ publish は GitHub Actions の **npm trusted publishing**(OIDC)で行う。`NPM_TOKEN` は置かない。
104
+
105
+ 1. `packages/hub-cli/package.json` の `version` を上げる commit を **main へ入れる**
106
+ 2. その commit で `deploy.yml` が成功していることを確かめる
107
+ 3. `hub-cli-v<version>` のタグを打って push する(例 `hub-cli-v0.1.1`)
108
+ 4. `publish hub-cli` workflow が走る。`verify` がタグと version の一致・main への取り込み・
109
+ CI の成功・テスト・`npm pack` を確かめ、`publish` が tarball を出す
110
+
111
+ タグと `package.json` の version が食い違う、prerelease(`-rc.1`)を書く、main に入っていない
112
+ commit にタグを打つ、`workflow_dispatch` の成功しかない —— これらは `verify` が止める。
113
+ タグ push とデプロイは**オーケストレーターだけ**が行う。
114
+
115
+ ### npm 側の設定(初回だけ・人が行う)
116
+
117
+ npm の trusted publisher は workflow を足しただけでは有効にならない。
118
+ npmjs.com のパッケージ設定で登録する。
119
+
120
+ | 項目 | 値 |
121
+ | --- | --- |
122
+ | Organization or user | `tamaitakamasa`(**GitHub 側の名前**。npm の scope `@tamai` とは別) |
123
+ | Repository | `hub` |
124
+ | Workflow filename | `publish-hub-cli.yml` |
125
+ | Environment | 空(environment は使わない) |
126
+
127
+ あわせて **direct publish を許可する**。direct publish は「staged publish(`npm stage publish`
128
+ で段階公開してから確定する)を経ずに `npm publish` で直接公開できる」設定のことで、
129
+ CI 以外からの publish の可否ではない。この workflow は `npm publish` を使うので、
130
+ これを許可しないと publish が通らない。CI 外の手動公開や token 利用の制限は別の設定として決める。
131
+ GitHub 側には `hub-cli-v*` タグの作成・変更・削除を release 担当に限る ruleset を張る
132
+ (workflow の検査だけを信頼境界にしない。タグ自身の workflow を書き換えれば検査は外せる)。
133
+
134
+ `hub` は private repo なので **provenance は付けない**(npm の provenance は公開 repo が前提)。
135
+
136
+ ## 配備(Mac mini)
137
+
138
+ `runner/deploy-from-macbook.sh` は `~/.local/bin/hub` を repo 直参照のラッパーとして
139
+ **毎回作り直す**。npm 版へ切り替えるときは、この script も一緒に直すこと。
140
+ 入れただけでは PATH 上で旧ラッパーが優先されたり、次の配備で書き戻されたりする。
141
+ 切り替えたら `command -v hub` と `hub --version` で実体を確かめる。
142
+
143
+ ## ライセンス
144
+
145
+ `UNLICENSED`(個人利用)。npm の scope は公開だが、利用許諾を与えるものではない。
package/bin/hub.mjs ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+
3
+ // `hub` コマンドの入口(記録147 / Astra High 1)。
4
+ //
5
+ // **ここには判定を置かない。** 旧 `tools/hub.mjs` は末尾で
6
+ // `import.meta.url === pathToFileURL(process.argv[1]).href` を比べて「直接実行か」を決めていた。
7
+ // `npm i -g` が張る symlink 経由だと `process.argv[1]` は symlink のパスのまま渡るので
8
+ // この比較が偽になり、**CLIが何も出さずに exit 0 で終わる**(実測: 実体パス447 byte / symlink 0 byte)。
9
+ // realpath で解決して比べる直し方もあるが、bin を専用ファイルにすれば比較そのものが要らない。
10
+ // 本体(`lib/cli.mjs`)はライブラリとしてだけ読まれ、実行するのはこのファイルだけである。
11
+
12
+ import { runCli } from "../lib/cli.mjs";
13
+
14
+ process.exitCode = await runCli(process.argv.slice(2));
@@ -0,0 +1,18 @@
1
+ import { PROJECT_KINDS, requireSinglePositional, usageError } from "../lib/args.mjs";
2
+ import { printProjectResult } from "../lib/format.mjs";
3
+
4
+ export const projectCreateCommand = {
5
+ name: "create",
6
+ options: { allowed: ["name", "repo", "kind"] },
7
+ async run({ options, positional, flags, dependencies, api }) {
8
+ const slug = requireSinglePositional(positional, "プロジェクトslug");
9
+ if (!flags.name || !options.name.trim()) throw usageError("--name を指定してください");
10
+ if (flags.kind && !PROJECT_KINDS.includes(options.kind)) {
11
+ throw usageError(`--kind は ${PROJECT_KINDS.join(" / ")} のいずれかです`);
12
+ }
13
+ const body = { slug, name: options.name.trim(), kind: flags.kind ? options.kind : "work" };
14
+ if (flags.repo && options.repo.trim()) body.repo = options.repo.trim();
15
+ const payload = await api("/api/projects", { method: "POST", body: JSON.stringify(body) });
16
+ printProjectResult(payload, options.json, dependencies.stdout, "create");
17
+ },
18
+ };
@@ -0,0 +1,18 @@
1
+ import { PROJECT_KINDS, usageError } from "../lib/args.mjs";
2
+ import { printProjectResult } from "../lib/format.mjs";
3
+
4
+ export const projectListCommand = {
5
+ name: "list",
6
+ options: { allowed: ["kind"] },
7
+ async run({ options, positional, flags, dependencies, api }) {
8
+ if (positional.length !== 0) throw usageError("listに位置引数は指定できません");
9
+ if (flags.kind && !PROJECT_KINDS.includes(options.kind)) {
10
+ throw usageError(`--kind は ${PROJECT_KINDS.join(" / ")} のいずれかです`);
11
+ }
12
+ const payload = await api("/api/projects");
13
+ const filtered = flags.kind
14
+ ? { ...payload, items: (payload?.items ?? []).filter((item) => (item.kind ?? "work") === options.kind) }
15
+ : payload;
16
+ printProjectResult(filtered, options.json, dependencies.stdout, "list");
17
+ },
18
+ };
@@ -0,0 +1,26 @@
1
+ import { cliError, requireSinglePositional, usageError } from "../lib/args.mjs";
2
+ import { printProjectResult } from "../lib/format.mjs";
3
+
4
+ export const projectMoveCommand = {
5
+ name: "move",
6
+ options: { allowed: ["after", "top"], boolean: ["top"] },
7
+ async run({ options, positional, flags, dependencies, api }) {
8
+ const slug = requireSinglePositional(positional, "プロジェクトslug");
9
+ if (!flags.top && !flags.after) throw usageError("--after <slug> か --top のどちらかを指定してください");
10
+ if (flags.top && flags.after) throw usageError("--after と --top は同時に指定できません");
11
+ if (flags.after && !options.after.trim()) throw usageError("--afterに空文字は指定できません");
12
+
13
+ const current = await api(`/api/projects/${encodeURIComponent(slug)}`);
14
+ if (!Number.isSafeInteger(current?.item?.version) || current.item.version < 1) {
15
+ throw cliError("API応答のversionが不正です");
16
+ }
17
+ const payload = await api(`/api/projects/${encodeURIComponent(slug)}/move`, {
18
+ method: "POST",
19
+ body: JSON.stringify({
20
+ version: current.item.version,
21
+ after_slug: flags.top ? null : options.after.trim(),
22
+ }),
23
+ });
24
+ printProjectResult(payload, options.json, dependencies.stdout, "move");
25
+ },
26
+ };
@@ -0,0 +1,12 @@
1
+ import { requireSinglePositional } from "../lib/args.mjs";
2
+ import { printProjectResult } from "../lib/format.mjs";
3
+
4
+ export const projectShowCommand = {
5
+ name: "show",
6
+ options: {},
7
+ async run({ options, positional, dependencies, api }) {
8
+ const slug = requireSinglePositional(positional, "プロジェクトslug");
9
+ const payload = await api(`/api/projects/${encodeURIComponent(slug)}`);
10
+ printProjectResult(payload, options.json, dependencies.stdout, "show");
11
+ },
12
+ };
@@ -0,0 +1,17 @@
1
+ import { usageError } from "../lib/args.mjs";
2
+ import { toRegistryYaml } from "../lib/format.mjs";
3
+
4
+ export const projectSyncRegistryCommand = {
5
+ name: "sync-registry",
6
+ options: {},
7
+ async run({ options, positional, dependencies, api }) {
8
+ if (positional.length !== 0) throw usageError("sync-registryに位置引数は指定できません");
9
+ const payload = await api("/api/projects");
10
+ const items = payload?.items ?? [];
11
+ if (options.json) {
12
+ dependencies.stdout.write(`${JSON.stringify({ items, yaml: toRegistryYaml(items) }, null, 2)}\n`);
13
+ return;
14
+ }
15
+ dependencies.stdout.write(toRegistryYaml(items));
16
+ },
17
+ };
@@ -0,0 +1,101 @@
1
+ import { PROJECT_KINDS, cliError, requireSinglePositional, usageError } from "../lib/args.mjs";
2
+ import { printProjectResult } from "../lib/format.mjs";
3
+
4
+ export const projectUpdateCommand = {
5
+ name: "update",
6
+ options: {
7
+ allowed: ["name", "repo", "slug", "kind", "add-link", "remove-link", "clear-links"],
8
+ boolean: ["clear-links"],
9
+ repeatable: ["add-link", "remove-link"],
10
+ },
11
+ async run({ options, positional, flags, dependencies, api }) {
12
+ const slug = requireSinglePositional(positional, "プロジェクトslug");
13
+ const hasLinkChange = flags["add-link"] || flags["remove-link"] || flags["clear-links"];
14
+ if (!flags.name && !flags.repo && !flags.slug && !flags.kind && !hasLinkChange) {
15
+ throw usageError("--name / --repo / --slug / --kind / --add-link / --remove-link / --clear-links のいずれかを指定してください");
16
+ }
17
+ if (flags.kind && !PROJECT_KINDS.includes(options.kind)) {
18
+ throw usageError(`--kind は ${PROJECT_KINDS.join(" / ")} のいずれかです`);
19
+ }
20
+ if (flags["clear-links"] && (flags["add-link"] || flags["remove-link"])) {
21
+ throw usageError("--clear-links と --add-link / --remove-link は同時に指定できません");
22
+ }
23
+
24
+ const addLinks = options["add-link"].map((entry) => {
25
+ const at = entry.indexOf("=");
26
+ const label = at === -1 ? "" : entry.slice(0, at).trim();
27
+ const url = at === -1 ? "" : entry.slice(at + 1).trim();
28
+ if (label === "" || url === "") {
29
+ throw cliError(`--add-link は "<ラベル>=<URL>" の形で指定してください: ${entry}`);
30
+ }
31
+ return { label, url };
32
+ });
33
+ const addedUrls = new Map();
34
+ for (const link of addLinks) {
35
+ const first = addedUrls.get(link.label);
36
+ if (first !== undefined) {
37
+ throw cliError(
38
+ `--add-link のラベルが重複しています: ${link.label}\n`
39
+ + ` 1つ目: ${first}\n 2つ目: ${link.url}`,
40
+ );
41
+ }
42
+ addedUrls.set(link.label, link.url);
43
+ }
44
+ const removeLabels = options["remove-link"].map((entry) => {
45
+ const label = entry.trim();
46
+ if (label === "") throw cliError("--remove-link に空のラベルは指定できません");
47
+ return label;
48
+ });
49
+
50
+ const current = await api(`/api/projects/${encodeURIComponent(slug)}`);
51
+ if (!Number.isSafeInteger(current?.item?.version) || current.item.version < 1) {
52
+ throw cliError("API応答のversionが不正です");
53
+ }
54
+ const body = { version: current.item.version };
55
+ if (flags.name) {
56
+ if (!options.name.trim()) throw cliError("--nameに空文字は指定できません");
57
+ body.name = options.name.trim();
58
+ }
59
+ if (flags.repo) body.repo = options.repo.trim() || null;
60
+ if (flags.slug) {
61
+ if (!options.slug.trim()) throw cliError("--slugに空文字は指定できません");
62
+ body.slug = options.slug.trim();
63
+ }
64
+ if (flags.kind) body.kind = options.kind;
65
+ if (hasLinkChange) {
66
+ const currentLinks = Array.isArray(current.item.links) ? current.item.links : [];
67
+ let links = [...currentLinks];
68
+ for (const label of removeLabels) {
69
+ const matched = links.filter((link) => link?.label === label);
70
+ if (matched.length === 0) {
71
+ const labels = links.map((link) => link?.label).filter(Boolean).join("、");
72
+ throw cliError(`該当するリンクがありません: ${label}\n現在のリンク: ${labels || "(なし)"}`);
73
+ }
74
+ if (matched.length > 1) {
75
+ throw cliError(`ラベル「${label}」のリンクが${matched.length}件あり曖昧です。--clear-links で消してから登録し直してください`);
76
+ }
77
+ links = links.filter((link) => link !== matched[0]);
78
+ }
79
+ for (const link of addLinks) {
80
+ const conflict = links.find((existing) => existing?.label === link.label);
81
+ if (conflict) {
82
+ throw cliError(
83
+ `該当ラベルは既にあります: ${conflict.label} → ${conflict.url}\n`
84
+ + `置き換えるなら同じコマンドで --remove-link 「${conflict.label}」 してから --add-link してください`,
85
+ );
86
+ }
87
+ links.push(link);
88
+ }
89
+ body.links = flags["clear-links"] ? [] : links;
90
+ }
91
+
92
+ const payload = await api(`/api/projects/${encodeURIComponent(slug)}`, {
93
+ method: "PATCH",
94
+ body: JSON.stringify(body),
95
+ });
96
+ if (typeof payload?.updated_tasks !== "number") {
97
+ throw cliError("API応答のupdated_tasksが不正です");
98
+ }
99
+ printProjectResult(payload, options.json, dependencies.stdout, "update");
100
+ },
101
+ };
@@ -0,0 +1,22 @@
1
+ import { requireSinglePositional } from "../lib/args.mjs";
2
+ import { printTaskResult } from "../lib/format.mjs";
3
+ import { resolveTaskProject } from "../lib/records.mjs";
4
+
5
+ export const taskAddCommand = {
6
+ name: "add",
7
+ options: { allowed: ["project", "due", "body-file", "force"], boolean: ["force"] },
8
+ async run({ options, positional, flags, dependencies, api }) {
9
+ const title = requireSinglePositional(positional, "タイトル");
10
+ const body = { title };
11
+ const project = await resolveTaskProject(options.project, {
12
+ force: flags.force === true,
13
+ api,
14
+ stderr: dependencies.stderr,
15
+ });
16
+ if (project) body.project = project;
17
+ if (options.due) body.due = options.due;
18
+ if (options["body-file"]) body.body = await dependencies.readFileImpl(options["body-file"], "utf8");
19
+ const payload = await api("/api/tasks", { method: "POST", body: JSON.stringify(body) });
20
+ printTaskResult(payload, options.json, dependencies.stdout, "task");
21
+ },
22
+ };
@@ -0,0 +1,42 @@
1
+ import { cliError, usageError } from "../lib/args.mjs";
2
+ import {
3
+ UNPUSHED_SKIP_REASONS,
4
+ auditDoneTasks,
5
+ formatAuditReport,
6
+ readGitState,
7
+ } from "../lib/git.mjs";
8
+ import { findRepoRoot } from "../lib/records.mjs";
9
+
10
+ export const taskAuditCommand = {
11
+ name: "audit",
12
+ options: {},
13
+ async run({ options, positional, dependencies, api }) {
14
+ if (positional.length !== 0) throw usageError("auditに位置引数は指定できません");
15
+ const root = await findRepoRoot(dependencies.cwd(), dependencies.statImpl);
16
+ if (root === null) {
17
+ throw cliError("gitリポジトリの中で実行してください(.gitが見つかりません)");
18
+ }
19
+ const payload = await api("/api/tasks?status=done&include_private=true");
20
+ const items = Array.isArray(payload?.items) ? payload.items : [];
21
+ const gitState = await readGitState(root, dependencies.runGitImpl);
22
+ if (gitState.dirty === null || gitState.tracked === null) {
23
+ dependencies.stderr.write("警告: git status / ls-files を実行できず、未コミットの検査を省きました。\n");
24
+ }
25
+ if (gitState.unpushed === null) {
26
+ dependencies.stderr.write(`警告: ${UNPUSHED_SKIP_REASONS[gitState.unpushedSkipped] ?? "理由不明で"}、未pushの検査を省きました。\n`);
27
+ }
28
+ const report = {
29
+ repo_root: root,
30
+ checks: {
31
+ uncommitted: gitState.dirty !== null && gitState.tracked !== null,
32
+ unpushed: gitState.unpushed !== null,
33
+ },
34
+ ...auditDoneTasks(items, gitState),
35
+ };
36
+ if (options.json) {
37
+ dependencies.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
38
+ return;
39
+ }
40
+ dependencies.stdout.write(formatAuditReport(report));
41
+ },
42
+ };
@@ -0,0 +1,57 @@
1
+ import { cliError, requireSinglePositional, usageError } from "../lib/args.mjs";
2
+ import { ApiError, isConflictError } from "../lib/api.mjs";
3
+ import { printTaskResult, taskLines } from "../lib/format.mjs";
4
+
5
+ export const taskClaimCommand = {
6
+ name: "claim",
7
+ options: { allowed: ["owner"] },
8
+ async run({ options, positional, dependencies, api }) {
9
+ const id = requireSinglePositional(positional, "タスクID");
10
+ if (!options.owner?.trim()) throw usageError("--ownerを指定してください");
11
+
12
+ const currentPayload = await api(`/api/tasks/${encodeURIComponent(id)}`);
13
+ let task = currentPayload?.item;
14
+ if (typeof task?.id !== "string" || typeof task.status !== "string") {
15
+ throw cliError("API応答のタスクが不正です");
16
+ }
17
+ if (task.status !== "inbox" && task.status !== "ready") {
18
+ throw cliError(`タスクをclaimできません(inboxまたはreadyのみ)\n${taskLines(task).join("\n")}`);
19
+ }
20
+
21
+ let movedFromInbox = false;
22
+ if (task.status === "inbox") {
23
+ if (!Number.isInteger(task.version)) throw cliError("API応答のversionが不正です");
24
+ const moved = await api(`/api/tasks/${encodeURIComponent(id)}/move`, {
25
+ method: "POST",
26
+ body: JSON.stringify({ status: "ready", after_id: null, version: task.version }),
27
+ });
28
+ task = moved?.item;
29
+ if (typeof task?.id !== "string" || task.status !== "ready") {
30
+ throw cliError("readyへの移動後のAPI応答が不正です");
31
+ }
32
+ movedFromInbox = true;
33
+ }
34
+
35
+ let payload;
36
+ try {
37
+ payload = await api(`/api/tasks/${encodeURIComponent(id)}/claim`, {
38
+ method: "POST",
39
+ body: JSON.stringify({ owner: options.owner.trim() }),
40
+ });
41
+ } catch (error) {
42
+ if (movedFromInbox && isConflictError(error)) {
43
+ const guidance = "inboxからreadyへは移動済みです。再実行すると直接claimされます。";
44
+ const current = error.payload?.error ?? {};
45
+ throw new ApiError(error.status, {
46
+ ...error.payload,
47
+ error: {
48
+ ...current,
49
+ message: `${current.message ?? "タスクが更新されています"}\n${guidance}`,
50
+ },
51
+ });
52
+ }
53
+ throw error;
54
+ }
55
+ printTaskResult(payload, options.json, dependencies.stdout, "task");
56
+ },
57
+ };
@@ -0,0 +1,25 @@
1
+ import { usageError } from "../lib/args.mjs";
2
+ import { printTaskResult } from "../lib/format.mjs";
3
+ import { resolveTaskProject } from "../lib/records.mjs";
4
+
5
+ export const taskListCommand = {
6
+ name: "list",
7
+ options: { allowed: ["status", "project", "owner", "q"] },
8
+ async run({ options, positional, dependencies, api }) {
9
+ if (positional.length !== 0) throw usageError("listに位置引数は指定できません");
10
+ const project = await resolveTaskProject(options.project, {
11
+ force: false,
12
+ allowUnknown: true,
13
+ api,
14
+ stderr: dependencies.stderr,
15
+ });
16
+ const query = new URLSearchParams();
17
+ if (!options.status) query.set("include_iced", "false");
18
+ for (const key of ["status", "project", "owner", "q"]) {
19
+ const value = key === "project" ? project : options[key];
20
+ if (value) query.set(key, value);
21
+ }
22
+ const payload = await api(`/api/tasks${query.size > 0 ? `?${query}` : ""}`);
23
+ printTaskResult(payload, options.json, dependencies.stdout, "list");
24
+ },
25
+ };
@@ -0,0 +1,81 @@
1
+ import { cliError, requireSinglePositional } from "../lib/args.mjs";
2
+ import { describeFailure } from "../lib/api.mjs";
3
+ import { taskLines } from "../lib/format.mjs";
4
+ import {
5
+ DEFAULT_RECORD_DIR,
6
+ resolveRecordTarget,
7
+ resolveTaskProject,
8
+ writeRepoRecord,
9
+ } from "../lib/records.mjs";
10
+
11
+ export const taskNewCommand = {
12
+ name: "new",
13
+ options: {
14
+ allowed: ["project", "due", "body-file", "repo-card", "slug", "force"],
15
+ optionalValue: ["repo-card"],
16
+ boolean: ["force"],
17
+ },
18
+ async run({ options, positional, flags, dependencies, api }) {
19
+ const title = requireSinglePositional(positional, "タイトル");
20
+ const target = flags["repo-card"]
21
+ ? await resolveRecordTarget(options["repo-card"] || DEFAULT_RECORD_DIR, dependencies)
22
+ : null;
23
+ // 出力先は cwd 基準なので、repo の別階層(例 dash/)から打つと別の docs/records/ に書く。
24
+ // 起票してしまう前に、解決した先を見せて気づけるようにする(Astra B-4-2)。
25
+ // **stderr に出す**。`--json` の stdout は機械が読むデータ専用で、警告と同じ扱いにする。
26
+ if (target !== null) {
27
+ dependencies.stderr.write(`記録の出力先: ${target.absoluteDir}\n`);
28
+ }
29
+
30
+ const body = { title };
31
+ const project = await resolveTaskProject(options.project, {
32
+ force: flags.force === true,
33
+ api,
34
+ stderr: dependencies.stderr,
35
+ });
36
+ if (project) body.project = project;
37
+ if (options.due) body.due = options.due;
38
+ if (options["body-file"]) body.body = await dependencies.readFileImpl(options["body-file"], "utf8");
39
+
40
+ const created = await api("/api/tasks", { method: "POST", body: JSON.stringify(body) });
41
+ const item = created?.item;
42
+ if (typeof item?.id !== "string") throw cliError("API応答のタスクIDが不正です");
43
+
44
+ let record = null;
45
+ if (target === null) {
46
+ dependencies.stderr.write(
47
+ `注意: --repo-card が無いため ${DEFAULT_RECORD_DIR} に記録は作られません(判断を残すタスクなら --repo-card を付ける)。\n`,
48
+ );
49
+ } else {
50
+ try {
51
+ record = await writeRepoRecord({ target, slug: options.slug, item, dependencies });
52
+ } catch (error) {
53
+ throw cliError(
54
+ `タスク ${item.id}「${item.title}」は作成済みですが、記録の生成に失敗しました: ${describeFailure(error)}`,
55
+ );
56
+ }
57
+
58
+ try {
59
+ const linked = await api(`/api/tasks/${encodeURIComponent(item.id)}`, {
60
+ method: "PATCH",
61
+ body: JSON.stringify({ version: item.version, context_ref: record.path }),
62
+ });
63
+ if (linked?.item) Object.assign(item, linked.item);
64
+ } catch (error) {
65
+ throw cliError(
66
+ `タスク ${item.id}「${item.title}」と記録 ${record.path} は作成済みですが、`
67
+ + `context_refの紐付けに失敗しました: ${describeFailure(error)}。`
68
+ + `\`hub task show ${item.id}\` で確認し、必要なら手動でcontext_refを設定してください`,
69
+ );
70
+ }
71
+ }
72
+
73
+ if (options.json) {
74
+ dependencies.stdout.write(`${JSON.stringify({ item, record }, null, 2)}\n`);
75
+ return;
76
+ }
77
+ const lines = taskLines(item);
78
+ if (record) lines.push("", `record: ${record.path}`);
79
+ dependencies.stdout.write(`${lines.join("\n")}\n`);
80
+ },
81
+ };
@@ -0,0 +1,23 @@
1
+ import { cliError, usageError } from "../lib/args.mjs";
2
+ import { printTaskResult } from "../lib/format.mjs";
3
+
4
+ export const taskNextCommand = {
5
+ name: "next",
6
+ options: { allowed: ["owner"] },
7
+ async run({ options, positional, dependencies, api }) {
8
+ if (positional.length !== 0) throw usageError("nextに位置引数は指定できません");
9
+ if (!options.owner?.trim()) throw usageError("--ownerを指定してください");
10
+ const ready = await api("/api/tasks?status=ready");
11
+ const task = ready?.items?.[0];
12
+ if (!task) {
13
+ printTaskResult({ item: null }, options.json, dependencies.stdout, "next-empty");
14
+ return;
15
+ }
16
+ if (typeof task.id !== "string") throw cliError("API応答のタスクIDが不正です");
17
+ const payload = await api(`/api/tasks/${encodeURIComponent(task.id)}/claim`, {
18
+ method: "POST",
19
+ body: JSON.stringify({ owner: options.owner.trim() }),
20
+ });
21
+ printTaskResult(payload, options.json, dependencies.stdout, "task");
22
+ },
23
+ };
@@ -0,0 +1,33 @@
1
+ import { requireSinglePositional, usageError } from "../lib/args.mjs";
2
+ import { postChunks } from "../lib/api.mjs";
3
+ import { splitNote } from "../lib/records.mjs";
4
+
5
+ export const taskNoteCommand = {
6
+ name: "note",
7
+ options: { allowed: ["note", "note-file"] },
8
+ async run({ options, positional, dependencies, api }) {
9
+ const id = requireSinglePositional(positional, "タスクID");
10
+ if (options.note && options["note-file"]) throw usageError("--note と --note-file は同時に指定できません");
11
+ const source = options["note-file"]
12
+ ? await dependencies.readFileImpl(options["note-file"], "utf8")
13
+ : options.note;
14
+ if (!source?.trim()) throw usageError("--note か --note-file を指定してください");
15
+
16
+ const events = await postChunks(
17
+ splitNote(source),
18
+ async (chunk) => {
19
+ const payload = await api(`/api/tasks/${encodeURIComponent(id)}/events`, {
20
+ method: "POST",
21
+ body: JSON.stringify({ kind: "note", note: chunk }),
22
+ });
23
+ return payload?.event ?? null;
24
+ },
25
+ "note",
26
+ );
27
+ if (options.json) {
28
+ dependencies.stdout.write(`${JSON.stringify({ events }, null, 2)}\n`);
29
+ return;
30
+ }
31
+ dependencies.stdout.write(`noteを${events.length}件のイベントとして追加しました。\n`);
32
+ },
33
+ };