kankaku 1.4.0 → 1.4.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kankaku",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
4
4
  "description": "Terminal app that shows today's kankaku work across every project on disk",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -38,9 +38,9 @@
38
38
  },
39
39
  "dependencies": {
40
40
  "ink": "^7.1.1",
41
- "kankaku-pi": "^1.4.0",
42
- "kankaku-claude": "^1.4.0",
43
- "kankaku-hub": "^0.3.0",
41
+ "kankaku-claude": "^1.4.2",
42
+ "kankaku-hub": "^0.5.1",
43
+ "kankaku-pi": "^1.4.2",
44
44
  "react": "^19.3.0"
45
45
  },
46
46
  "devDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kankaku-pi",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
4
4
  "description": "pi extension that records agent work time per prompt, excluding waits for the user, with subagent linkage and task/session views",
5
5
  "license": "MIT",
6
6
  "author": "soyunninja",
@@ -32,6 +32,16 @@ function isCatalogSnapshot(value: unknown): value is CatalogSnapshot {
32
32
  );
33
33
  }
34
34
 
35
+ export class CatalogAdoptionFailure extends Error {
36
+ readonly reason: "snapshot-unavailable" | "persistence";
37
+
38
+ constructor(reason: "snapshot-unavailable" | "persistence") {
39
+ super(reason === "persistence" ? "Catalog cache persistence failed" : "Catalog snapshot unavailable");
40
+ this.name = "CatalogAdoptionFailure";
41
+ this.reason = reason;
42
+ }
43
+ }
44
+
35
45
  export interface CachedCatalogDeps {
36
46
  /** Absolute path to the cache file, e.g. `~/.kankaku/catalog.json`. */
37
47
  filePath: string;
@@ -61,6 +71,7 @@ export class CachedCatalog implements Catalog {
61
71
  private readonly deps: CachedCatalogDeps;
62
72
  private memo: CatalogSnapshot | undefined;
63
73
  private memoized = false;
74
+ private pendingAdoptions = new Set<Map<string, HubTask>>();
64
75
 
65
76
  constructor(deps: CachedCatalogDeps) {
66
77
  this.deps = deps;
@@ -74,6 +85,23 @@ export class CachedCatalog implements Catalog {
74
85
  return this.memo;
75
86
  }
76
87
 
88
+ /** Adopt a POST response without relying on an eventually-consistent list refresh. */
89
+ adoptTask(task: HubTask): void {
90
+ const snapshot = this.read();
91
+ if (!snapshot) throw new CatalogAdoptionFailure("snapshot-unavailable");
92
+ const adopted = { ...snapshot, tasks: [...(snapshot.tasks ?? []).filter((item) => item.id !== task.id), task] };
93
+ // The parsed POST response is the freshest known task even when atomic
94
+ // persistence fails. Publish it to this process and in-flight refreshes
95
+ // before writing so session target resolution can still validate the link.
96
+ this.memo = adopted;
97
+ for (const pending of this.pendingAdoptions) pending.set(task.id, task);
98
+ try {
99
+ this.writeDisk(adopted, true);
100
+ } catch {
101
+ throw new CatalogAdoptionFailure("persistence");
102
+ }
103
+ }
104
+
77
105
  isStale(): boolean {
78
106
  const snapshot = this.read();
79
107
  if (!snapshot) return true;
@@ -82,6 +110,8 @@ export class CachedCatalog implements Catalog {
82
110
  }
83
111
 
84
112
  async refresh(signal?: AbortSignal): Promise<CatalogSnapshot | undefined> {
113
+ const adopted = new Map<string, HubTask>();
114
+ this.pendingAdoptions.add(adopted);
85
115
  try {
86
116
  const { clients, projects, tasks } = await this.deps.fetchCatalog(signal);
87
117
  const snapshot: CatalogSnapshot = {
@@ -89,7 +119,7 @@ export class CachedCatalog implements Catalog {
89
119
  url: this.deps.url,
90
120
  clients,
91
121
  projects,
92
- ...(tasks !== undefined ? { tasks } : {}),
122
+ ...(tasks !== undefined || adopted.size > 0 ? { tasks: [...(tasks ?? []).filter((task) => !adopted.has(task.id)), ...adopted.values()] } : {}),
93
123
  };
94
124
  this.writeDisk(snapshot);
95
125
  this.memo = snapshot;
@@ -97,6 +127,8 @@ export class CachedCatalog implements Catalog {
97
127
  return snapshot;
98
128
  } catch {
99
129
  return undefined;
130
+ } finally {
131
+ this.pendingAdoptions.delete(adopted);
100
132
  }
101
133
  }
102
134
 
@@ -112,7 +144,7 @@ export class CachedCatalog implements Catalog {
112
144
  }
113
145
  }
114
146
 
115
- private writeDisk(snapshot: CatalogSnapshot): void {
147
+ private writeDisk(snapshot: CatalogSnapshot, required = false): void {
116
148
  try {
117
149
  // This cache lives under `~/.kankaku` (machine-wide, not a project's
118
150
  // own KANKAKU_DIR) — but `~/.kankaku` itself is never mode-tightened
@@ -139,7 +171,8 @@ export class CachedCatalog implements Catalog {
139
171
  // Owner-only: this file names every client/project the machine's user has touched.
140
172
  writeFileSync(tmp, JSON.stringify(snapshot), { mode: OWNER_FILE_MODE });
141
173
  renameSync(tmp, this.deps.filePath);
142
- } catch {
174
+ } catch (error) {
175
+ if (required) throw error;
143
176
  // Best-effort cache write: a failure here must not fail the refresh
144
177
  // itself, since the in-memory snapshot is still usable this process.
145
178
  }
@@ -194,7 +194,7 @@ const COMMAND_TOKENS = ["all", "tasks", "sessions", "client", "clients", "export
194
194
  /** Only offered when the hub is configured, so completions are unchanged for users without one. */
195
195
  const HUB_COMMAND_TOKENS = ["target", "task", "projects", "catalog", "sync", "backfill"];
196
196
  const TARGET_TOKENS = ["pick", "clear"];
197
- const TASK_TOKENS = ["pick", "clear"];
197
+ const TASK_TOKENS = ["pick", "clear", "new"];
198
198
  const CATALOG_TOKENS = ["refresh"];
199
199
  const SYNC_TOKENS = ["all", "status"];
200
200
 
@@ -480,7 +480,7 @@ export function registerKankakuCommand(pi: ExtensionAPI, deps: KankakuCommandDep
480
480
  }
481
481
 
482
482
  /**
483
- * Handle `/kankaku task [pick|clear]`; `rest` excludes the leading `task`
483
+ * Handle `/kankaku task [pick|clear|new <title> [--ref <externalRef>]]`; `rest` excludes the leading `task`
484
484
  * token. Default (no args) is `pick`. `pickTask`/`clearTask`
485
485
  * (`session-target.ts`) notify their own outcome directly, so this only
486
486
  * dispatches and refreshes the idle status line.
@@ -505,6 +505,19 @@ export function registerKankakuCommand(pi: ExtensionAPI, deps: KankakuCommandDep
505
505
  return;
506
506
  }
507
507
 
508
+ if (rest[0] === "new") {
509
+ const refIndex = rest.indexOf("--ref");
510
+ const title = rest.slice(1, refIndex === -1 ? undefined : refIndex).join(" ").trim();
511
+ const externalRef = refIndex === -1 ? undefined : rest[refIndex + 1]?.trim();
512
+ if (!title || (refIndex !== -1 && (!externalRef || refIndex !== rest.length - 2))) {
513
+ notifyError(ctx, new Error("usage: /kankaku task new <title> [--ref <externalRef>]"));
514
+ return;
515
+ }
516
+ await sessionTarget.newTask(pi, ctx, title, externalRef);
517
+ deps.refreshIdleStatus(ctx);
518
+ return;
519
+ }
520
+
508
521
  notifyError(ctx, new Error(`unknown task subcommand: ${rest.join(" ")}`));
509
522
  }
510
523
 
@@ -598,7 +611,8 @@ export function registerKankakuCommand(pi: ExtensionAPI, deps: KankakuCommandDep
598
611
  "When a hub (PocketBase) is configured: 'target' to show the effective client/project and its source, " +
599
612
  "'target pick' to run the picker again, 'target clear' to clear the session target, " +
600
613
  "'task' (or 'task pick') to link this session to an open/doing hub task of the effective project, " +
601
- "'task clear' to drop the link, " +
614
+ "'task clear' to drop the link, 'task new <title> [--ref <externalRef>]' to create and link an open task; " +
615
+ "the visual task picker also offers creation, " +
602
616
  "'catalog refresh' to force a catalog refresh, 'projects' for per-project totals today ('projects all' for every day), " +
603
617
  "'sync' to push pending tasks to the hub ('sync all' for a full re-evaluation, 'sync status' for the watermark/pending count/last error), " +
604
618
  "'backfill' to run a full sync and report how many tasks went to Sin determinar, grouped by their old label. " +
@@ -23,6 +23,24 @@ interface TaskRecord extends PocketBaseRecord {
23
23
  external_ref?: string;
24
24
  }
25
25
 
26
+ export interface CreateHubTaskInput {
27
+ title: string;
28
+ projectId: string;
29
+ externalRef?: string;
30
+ }
31
+
32
+ /** Explicit user-driven creation; never called from hook paths. */
33
+ export async function createHubTask(client: PocketBaseClient, input: CreateHubTaskInput, signal?: AbortSignal): Promise<HubTask> {
34
+ const record: unknown = await client.request("POST", "/api/collections/tasks/records", {
35
+ title: input.title,
36
+ project: input.projectId,
37
+ status: "open",
38
+ ...(input.externalRef !== undefined ? { external_ref: input.externalRef } : {}),
39
+ }, signal);
40
+ assertCreatedTaskRecord(record, input.projectId);
41
+ return mapTask(record);
42
+ }
43
+
26
44
  const TASK_STATUSES = new Set(["open", "doing", "done"]);
27
45
 
28
46
  function mapClient(record: ClientRecord): Client {
@@ -47,6 +65,21 @@ function mapProject(record: ProjectRecord): Project {
47
65
  }
48
66
 
49
67
  /** `open` on any unrecognised or missing status, rather than dropping the task. */
68
+ function assertCreatedTaskRecord(record: unknown, projectId: string): asserts record is TaskRecord {
69
+ if (!record || typeof record !== "object" || Array.isArray(record)) {
70
+ throw new Error("Hub returned an invalid task creation response");
71
+ }
72
+ const candidate = record as Record<string, unknown>;
73
+ if (
74
+ typeof candidate["id"] !== "string" || candidate["id"].trim() === "" ||
75
+ typeof candidate["title"] !== "string" || candidate["title"].trim() === "" ||
76
+ candidate["project"] !== projectId ||
77
+ typeof candidate["status"] !== "string" || !TASK_STATUSES.has(candidate["status"])
78
+ ) {
79
+ throw new Error("Hub returned an invalid task creation response");
80
+ }
81
+ }
82
+
50
83
  function mapTaskStatus(status: string | undefined): HubTask["status"] {
51
84
  return status !== undefined && TASK_STATUSES.has(status) ? (status as HubTask["status"]) : "open";
52
85
  }
@@ -3,6 +3,8 @@ import { formatWorkTargetLabel, resolveWorkTarget, resolveWorkTargetSource } fro
3
3
  import type { WorkTarget, WorkTargetCandidate, WorkTargetSessionOverride, WorkTargetSourceName } from "../domain/work-target.ts";
4
4
  import type { WorkRole } from "../domain/work-record.ts";
5
5
  import type { Catalog, CatalogSnapshot } from "../ports/catalog.ts";
6
+ import type { TaskCreator } from "./target-picker.ts";
7
+ import { formatTaskCreationFailure, TaskCreationFailure } from "./task-creation.ts";
6
8
  import { pickHubTask, pickTarget } from "./target-picker.ts";
7
9
 
8
10
  /** Persisted as a `kankaku-target` custom session entry so the session-level target survives a reload. */
@@ -14,8 +16,7 @@ export interface KankakuTargetEntryData {
14
16
  /**
15
17
  * A hub task picked for this session (`/kankaku task pick`). Session-only:
16
18
  * never written to the project's `.kankaku/config.json`, and dropped by
17
- * any target change (`pick`/`setExplicit`/`clear`/`ensurePicked`'s
18
- * silent resolution) since those all build a fresh candidate without it.
19
+ * target changes unless a new task is selected in the target picker.
19
20
  */
20
21
  hubTaskId?: string;
21
22
  }
@@ -25,6 +26,8 @@ export const TARGET_ENTRY_TYPE = "kankaku-target";
25
26
  export interface SessionTargetDeps {
26
27
  role: WorkRole;
27
28
  catalog: Catalog;
29
+ /** Creates and adopts the returned task before linking it. */
30
+ createTask?: TaskCreator;
28
31
  /** Lazily reads `clientId`/`projectId` from `<kankaku dir>/config.json`. */
29
32
  resolveProjectConfigIds: () => WorkTargetCandidate | undefined;
30
33
  /** Persist `clientId`/`projectId` into `<kankaku dir>/config.json`, merging existing keys. */
@@ -81,6 +84,8 @@ export interface SessionTarget {
81
84
  pickTask(pi: ExtensionAPI, ctx: ExtensionContext): Promise<void>;
82
85
  /** `/kankaku task clear`: drops the linked hub task, keeping the rest of the session target. A no-op when none is linked. */
83
86
  clearTask(pi: ExtensionAPI): void;
87
+ /** Create through the shared creator and link only in the current session. */
88
+ newTask(pi: ExtensionAPI, ctx: ExtensionContext, title: string, externalRef?: string): Promise<void>;
84
89
  /**
85
90
  * Set the linked hub task directly, bypassing the picker — the panel's
86
91
  * target screen (`adapters/panel/screens/target.ts`) uses this once the
@@ -291,7 +296,7 @@ export function createSessionTarget(deps: SessionTargetDeps): SessionTarget {
291
296
  }
292
297
 
293
298
  async function runPicker(pi: ExtensionAPI, ctx: ExtensionContext, snapshot: CatalogSnapshot): Promise<void> {
294
- const result = await pickTarget(ctx, snapshot);
299
+ const result = await pickTarget(ctx, snapshot, deps.createTask);
295
300
 
296
301
  if (result.kind === "skipped") {
297
302
  sessionOverride = "skipped";
@@ -299,13 +304,17 @@ export function createSessionTarget(deps: SessionTargetDeps): SessionTarget {
299
304
  return;
300
305
  }
301
306
 
302
- const ids = candidateFrom(result.target);
307
+ const projectIds = candidateFrom(result.target);
308
+ const ids: WorkTargetCandidate = {
309
+ ...projectIds,
310
+ ...(result.target.hubTaskId !== undefined ? { hubTaskId: result.target.hubTaskId } : {}),
311
+ };
303
312
  sessionOverride = ids;
304
313
  pi.appendEntry<KankakuTargetEntryData>(TARGET_ENTRY_TYPE, entryDataFrom(ids));
305
314
 
306
315
  const remember = await ctx.ui.confirm("kankaku", `Remember ${formatWorkTargetLabel(result.target)} for this repository?`);
307
316
  if (remember) {
308
- deps.persistProjectConfig(ids);
317
+ deps.persistProjectConfig(projectIds);
309
318
  }
310
319
  }
311
320
 
@@ -390,7 +399,7 @@ export function createSessionTarget(deps: SessionTargetDeps): SessionTarget {
390
399
  }
391
400
 
392
401
  const tasks = deps.catalog.read()?.tasks ?? [];
393
- const result = await pickHubTask(ctx, tasks, target.projectId);
402
+ const result = await pickHubTask(ctx, tasks, target.projectId, deps.createTask);
394
403
 
395
404
  if (result.kind === "empty") {
396
405
  ctx.ui.notify(`kankaku: No open tasks for ${target.projectName ?? target.projectId} in the hub`, "warning");
@@ -404,6 +413,27 @@ export function createSessionTarget(deps: SessionTargetDeps): SessionTarget {
404
413
  if (updated) ctx.ui.notify(`kankaku: task set to ${formatWorkTargetLabel(updated)}`);
405
414
  }
406
415
 
416
+ async function newTask(pi: ExtensionAPI, ctx: ExtensionContext, title: string, externalRef?: string): Promise<void> {
417
+ if (deps.role !== "orchestrator" || !ctx.hasUI) return;
418
+ const target = effectiveTarget();
419
+ if (!target || target.projectId === undefined) {
420
+ ctx.ui.notify("kankaku: Pick a client and project first (/kankaku target pick)", "warning");
421
+ return;
422
+ }
423
+ if (!deps.createTask) throw new Error("task creation is not configured");
424
+ try {
425
+ const task = await deps.createTask(target.projectId, title, externalRef);
426
+ setTask(pi, task.id);
427
+ ctx.ui.notify(`kankaku: created and linked: ${task.title}`);
428
+ } catch (error) {
429
+ if (error instanceof TaskCreationFailure && error.kind === "cache-persistence" && error.task) {
430
+ setTask(pi, error.task.id);
431
+ }
432
+ const warning = error instanceof TaskCreationFailure && (error.kind === "cache-persistence" || error.kind === "catalog-unavailable");
433
+ ctx.ui.notify(formatTaskCreationFailure(error), warning ? "warning" : "error");
434
+ }
435
+ }
436
+
407
437
  function clearTask(pi: ExtensionAPI): void {
408
438
  if (sessionOverride === undefined || sessionOverride === "skipped") return;
409
439
  if (sessionOverride.hubTaskId === undefined) return;
@@ -420,6 +450,7 @@ export function createSessionTarget(deps: SessionTargetDeps): SessionTarget {
420
450
  clear,
421
451
  pickTask,
422
452
  clearTask,
453
+ newTask,
423
454
  setTask,
424
455
  rememberTarget,
425
456
  effectiveTarget,
@@ -1,12 +1,16 @@
1
1
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { Client, HubTask, Project, WorkTarget } from "../domain/work-target.ts";
3
+ import { formatTaskCreationFailure, TaskCreationFailure } from "./task-creation.ts";
3
4
 
4
5
  const SKIP_OPTION = "— skip —";
5
6
  const NO_PROJECT_OPTION = "(no project)";
7
+ const CREATE_OPTION = "+ create task +";
8
+ export type TaskCreator = (projectId: string, title: string, externalRef?: string) => Promise<HubTask>;
6
9
 
7
10
  export interface PickerCatalog {
8
11
  clients: Client[];
9
12
  projects: Project[];
13
+ tasks?: HubTask[];
10
14
  }
11
15
 
12
16
  export type PickResult = { kind: "picked"; target: WorkTarget } | { kind: "skipped" };
@@ -36,14 +40,15 @@ function labelOptions<T extends { name: string; code?: string }>(items: T[]): La
36
40
  }
37
41
 
38
42
  /**
39
- * Run the client/project picker (`ctx.ui.select`) against an already-loaded
43
+ * Run the client/project/task picker (`ctx.ui.select`) against an already-loaded
40
44
  * catalog snapshot. Pure UI interaction: no network, no persistence — the
41
45
  * caller (`session-target.ts`) decides what to do with the result.
42
46
  *
43
- * Declining at either step — choosing "— skip —" or dismissing the dialog
47
+ * Declining at either client/project step — choosing "— skip —" or dismissing the dialog
44
48
  * (`undefined`) — cancels the whole pick, not just that step.
49
+ * Skipping the optional task step keeps the selected client/project.
45
50
  */
46
- export async function pickTarget(ctx: ExtensionContext, catalog: PickerCatalog): Promise<PickResult> {
51
+ export async function pickTarget(ctx: ExtensionContext, catalog: PickerCatalog, createTask?: TaskCreator): Promise<PickResult> {
47
52
  const pickableClients = catalog.clients.filter((client) => client.active && !client.unassigned);
48
53
  const clientOptions = labelOptions(pickableClients);
49
54
 
@@ -78,6 +83,14 @@ export async function pickTarget(ctx: ExtensionContext, catalog: PickerCatalog):
78
83
  : {}),
79
84
  };
80
85
 
86
+ if (project) {
87
+ const taskResult = await pickHubTask(ctx, catalog.tasks ?? [], project.id, createTask);
88
+ if (taskResult.kind === "picked") {
89
+ target.hubTaskId = taskResult.task.id;
90
+ target.hubTaskTitle = taskResult.task.title;
91
+ }
92
+ }
93
+
81
94
  return { kind: "picked", target };
82
95
  }
83
96
 
@@ -112,13 +125,33 @@ function labelTaskOptions(tasks: HubTask[]): LabeledOption<HubTask>[] {
112
125
  * has no open/doing task, so the caller can tell "nothing to pick from"
113
126
  * apart from "the user skipped".
114
127
  */
115
- export async function pickHubTask(ctx: ExtensionContext, tasks: HubTask[], projectId: string): Promise<PickHubTaskResult> {
128
+ export async function pickHubTask(ctx: ExtensionContext, tasks: HubTask[], projectId: string, createTask?: TaskCreator): Promise<PickHubTaskResult> {
116
129
  const pickable = tasks.filter((task) => task.status !== "done" && task.projectId === projectId);
117
- if (pickable.length === 0) return { kind: "empty" };
130
+ if (pickable.length === 0 && !createTask) return { kind: "empty" };
118
131
 
119
132
  const taskOptions = labelTaskOptions(pickable);
120
- const choice = await ctx.ui.select("kankaku — task", [...taskOptions.map((option) => option.label), SKIP_OPTION]);
133
+ const labels = taskOptions.map((option) => option.label);
134
+ let createOption = CREATE_OPTION;
135
+ for (let suffix = 2; labels.includes(createOption); suffix++) {
136
+ createOption = `${CREATE_OPTION} (${suffix})`;
137
+ }
138
+ const choice = await ctx.ui.select("kankaku — task", [...labels, ...(createTask ? [createOption] : []), SKIP_OPTION]);
121
139
  if (choice === undefined || choice === SKIP_OPTION) return { kind: "skipped" };
140
+ if (choice === createOption && createTask) {
141
+ const title = (await ctx.ui.input("kankaku — task title"))?.trim();
142
+ if (!title) return { kind: "skipped" };
143
+ const externalRef = (await ctx.ui.input("kankaku — external reference (optional)"))?.trim();
144
+ try {
145
+ return { kind: "picked", task: await createTask(projectId, title, externalRef || undefined) };
146
+ } catch (error) {
147
+ if (error instanceof TaskCreationFailure && error.kind === "cache-persistence" && error.task) {
148
+ ctx.ui.notify(formatTaskCreationFailure(error), "warning");
149
+ return { kind: "picked", task: error.task };
150
+ }
151
+ ctx.ui.notify(formatTaskCreationFailure(error), error instanceof TaskCreationFailure && error.kind === "catalog-unavailable" ? "warning" : "error");
152
+ return { kind: "skipped" };
153
+ }
154
+ }
122
155
 
123
156
  const task = taskOptions.find((option) => option.label === choice)?.item;
124
157
  if (!task) return { kind: "skipped" };
@@ -0,0 +1,68 @@
1
+ import type { HubTask } from "../domain/work-target.ts";
2
+ import type { TaskCreator } from "./target-picker.ts";
3
+ import { CatalogAdoptionFailure } from "./cached-catalog.ts";
4
+ import { PocketBaseError } from "./pocketbase-client.ts";
5
+
6
+ export class TaskCreationFailure extends Error {
7
+ readonly kind: "request" | "cache-persistence" | "catalog-unavailable";
8
+ readonly task: HubTask | undefined;
9
+ readonly source: unknown;
10
+
11
+ constructor(kind: "request" | "cache-persistence" | "catalog-unavailable", task?: HubTask, source?: unknown) {
12
+ super(kind === "request" ? "Task creation request failed" : "Task was created but could not be adopted locally");
13
+ this.name = "TaskCreationFailure";
14
+ this.kind = kind;
15
+ this.task = task;
16
+ this.source = source;
17
+ }
18
+ }
19
+
20
+ /** Compose the remote POST and local cache adoption without hiding known remote success. */
21
+ export function createTaskCreator(createRemote: TaskCreator, adopt: (task: HubTask) => void): TaskCreator {
22
+ return async (projectId, title, externalRef) => {
23
+ let task: HubTask;
24
+ try {
25
+ task = await createRemote(projectId, title, externalRef);
26
+ } catch (error) {
27
+ throw new TaskCreationFailure("request", undefined, error);
28
+ }
29
+ try {
30
+ adopt(task);
31
+ } catch (error) {
32
+ const kind = error instanceof CatalogAdoptionFailure && error.reason === "persistence" ? "cache-persistence" : "catalog-unavailable";
33
+ throw new TaskCreationFailure(kind, task);
34
+ }
35
+ return task;
36
+ };
37
+ }
38
+
39
+ /** A bounded user-facing diagnostic; arbitrary exception text is never included. */
40
+ export function formatTaskCreationFailure(error: unknown): string {
41
+ if (error instanceof TaskCreationFailure && error.kind === "cache-persistence") {
42
+ return "kankaku: task created in the hub, but local catalog cache persistence failed; the task is linked to this session. The in-memory catalog remains available until restart.";
43
+ }
44
+ if (error instanceof TaskCreationFailure && error.kind === "catalog-unavailable") {
45
+ return "kankaku: task created in the hub, but no local catalog snapshot was available to validate a session link. Refresh the catalog, then link the existing task; do not create it again.";
46
+ }
47
+
48
+ const source = error instanceof TaskCreationFailure ? error.source : error;
49
+ let kind: string | undefined;
50
+ let status: number | undefined;
51
+ if (source instanceof PocketBaseError) {
52
+ try {
53
+ const candidateKind: unknown = source.kind;
54
+ const candidateStatus: unknown = source.status;
55
+ if (candidateKind === "network" || candidateKind === "timeout" || candidateKind === "http" || candidateKind === "auth") {
56
+ kind = candidateKind;
57
+ }
58
+ if (typeof candidateStatus === "number" && Number.isInteger(candidateStatus) && candidateStatus >= 100 && candidateStatus <= 599) {
59
+ status = candidateStatus;
60
+ }
61
+ } catch {
62
+ // Malformed typed errors fall back to a generic diagnostic.
63
+ }
64
+ }
65
+ const detail = [kind, status !== undefined ? String(status) : undefined].filter(Boolean).join(" ");
66
+ const uncertain = kind === undefined || kind === "network" || kind === "timeout";
67
+ return `kankaku: task creation was not confirmed${detail ? ` (${detail})` : ""}; ${uncertain ? "the outcome is uncertain; " : ""}check the hub before retrying.`;
68
+ }
@@ -11,8 +11,9 @@ import { LazyProjectClientSource, LazyProjectTargetSource } from "./adapters/pro
11
11
  import { LazyExportWriter } from "./adapters/export-writer.ts";
12
12
  import { resolveHubCredentials, safeHomeDir } from "./adapters/hub-credentials.ts";
13
13
  import { PocketBaseClient } from "./adapters/pocketbase-client.ts";
14
- import { createPocketBaseCatalogFetcher } from "./adapters/pocketbase-catalog.ts";
14
+ import { createHubTask, createPocketBaseCatalogFetcher } from "./adapters/pocketbase-catalog.ts";
15
15
  import { CachedCatalog } from "./adapters/cached-catalog.ts";
16
+ import { createTaskCreator } from "./adapters/task-creation.ts";
16
17
  import { createSessionTarget } from "./adapters/session-target.ts";
17
18
  import { resolveKankakuDir, resolveWritableTarget } from "./adapters/kankaku-dir.ts";
18
19
  import { SyncStateStore } from "./adapters/sync-state-store.ts";
@@ -212,7 +213,7 @@ export default function kankaku(pi: ExtensionAPI): void {
212
213
  // when no home directory is available so an env-only hub configuration
213
214
  // still works without one (the cache just does not survive a reboot).
214
215
  const homeDirForCache = safeHomeDir(homedir) ?? tmpdir();
215
- catalog = new CachedCatalog({
216
+ const cachedCatalog = new CachedCatalog({
216
217
  // Machine-wide cache: several projects on the same machine share one
217
218
  // catalog fetch, and it survives across projects.
218
219
  filePath: join(homeDirForCache, ".kankaku", "catalog.json"),
@@ -221,10 +222,15 @@ export default function kankaku(pi: ExtensionAPI): void {
221
222
  fetchCatalog: createPocketBaseCatalogFetcher(client),
222
223
  });
223
224
 
225
+ catalog = cachedCatalog;
224
226
  const projectTarget = new LazyProjectTargetSource(config.dir);
225
227
  sessionTarget = createSessionTarget({
226
228
  role,
227
229
  catalog,
230
+ createTask: createTaskCreator(
231
+ (projectId, title, externalRef) => createHubTask(client, { projectId, title, ...(externalRef ? { externalRef } : {}) }),
232
+ (task) => cachedCatalog.adoptTask(task),
233
+ ),
228
234
  resolveProjectConfigIds: () => projectTarget.read(),
229
235
  persistProjectConfig: (ids) => projectTarget.write(ids),
230
236
  });