@phren/cli 0.3.28 → 0.3.31

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.
Files changed (65) hide show
  1. package/dist/bridge/agent-hooks.d.ts +5 -55
  2. package/dist/bridge/agent-hooks.js +22 -155
  3. package/dist/bridge/codex-servers.d.ts +12 -0
  4. package/dist/bridge/codex-servers.js +35 -3
  5. package/dist/bridge/codex-thread-origin.d.ts +12 -0
  6. package/dist/bridge/codex-thread-origin.js +31 -0
  7. package/dist/bridge/hand-off-queue.d.ts +16 -0
  8. package/dist/bridge/hand-off-queue.js +62 -19
  9. package/dist/bridge/hook-main.js +12 -2
  10. package/dist/bridge/prompt-deliveries.d.ts +99 -0
  11. package/dist/bridge/prompt-deliveries.js +327 -0
  12. package/dist/bridge/prompt-once.d.ts +2 -0
  13. package/dist/bridge/prompt-once.js +2 -0
  14. package/dist/bridge/resources.d.ts +21 -0
  15. package/dist/bridge/resources.js +58 -2
  16. package/dist/bridge/server-launch.js +2 -1
  17. package/dist/bridge/server-pane-routes.js +72 -34
  18. package/dist/bridge/server-routes.d.ts +1 -0
  19. package/dist/bridge/server-routes.js +34 -3
  20. package/dist/bridge/server-stream.js +4 -2
  21. package/dist/bridge/server.js +12 -3
  22. package/dist/bridge/simulators.d.ts +3 -1
  23. package/dist/bridge/simulators.js +40 -5
  24. package/dist/bridge/sudo.d.ts +1 -1
  25. package/dist/bridge/sudo.js +51 -17
  26. package/dist/bridge/task-routes.d.ts +282 -0
  27. package/dist/bridge/task-routes.js +162 -0
  28. package/dist/bridge/uploads.d.ts +4 -0
  29. package/dist/bridge/uploads.js +15 -0
  30. package/dist/bridge-hook.mjs +18218 -15566
  31. package/dist/cli/namespaces-store.js +32 -1
  32. package/dist/cli/namespaces-tasks.d.ts +1 -0
  33. package/dist/cli/namespaces-tasks.js +55 -4
  34. package/dist/cli/ops.d.ts +2 -1
  35. package/dist/cli/ops.js +20 -4
  36. package/dist/cli-registry.js +5 -4
  37. package/dist/data/task-contract.d.ts +75 -0
  38. package/dist/data/task-contract.js +161 -0
  39. package/dist/data/task-format.d.ts +20 -0
  40. package/dist/data/task-format.js +55 -0
  41. package/dist/data/task-metadata.d.ts +10 -0
  42. package/dist/data/task-metadata.js +24 -0
  43. package/dist/data/task-store-directory.d.ts +21 -0
  44. package/dist/data/task-store-directory.js +37 -0
  45. package/dist/data/tasks.d.ts +38 -2
  46. package/dist/data/tasks.js +221 -28
  47. package/dist/generated/memory-ui-graph.browser.js +328 -333
  48. package/dist/init/setup.js +2 -2
  49. package/dist/memory-ui-graph.runtime.js +328 -333
  50. package/dist/modules/registry.js +3 -3
  51. package/dist/shell/input.js +49 -4
  52. package/dist/shell/state-store.d.ts +1 -0
  53. package/dist/shell/state-store.js +2 -0
  54. package/dist/shell/view.js +19 -3
  55. package/dist/store-registry.d.ts +12 -1
  56. package/dist/store-registry.js +52 -4
  57. package/dist/sync/task-claim.d.ts +1 -0
  58. package/dist/sync/task-claim.js +8 -1
  59. package/dist/sync/task-merge.d.ts +0 -9
  60. package/dist/sync/task-merge.js +48 -1
  61. package/dist/tools/tasks.js +31 -18
  62. package/dist/ui/page.js +1 -0
  63. package/dist/ui/scripts.js +64 -5
  64. package/dist/ui/server.js +18 -0
  65. package/package.json +8 -8
@@ -0,0 +1,37 @@
1
+ import * as path from "node:path";
2
+ import { execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ import { readTaskStoreEntries, registeredStoreIdentity, getStoreProjectDirs } from "../store-registry.js";
5
+ import { githubStoreRepository } from "../bridge/memory-store.js";
6
+ const exec = promisify(execFile);
7
+ /** Local attachment roles/subscriptions authorize access; only the target's
8
+ * synced primary ID identifies a task store on another machine. */
9
+ export function taskStores(base) {
10
+ return readTaskStoreEntries(base).map(store => ({ ...store,
11
+ taskStoreId: store.available === false ? undefined : registeredStoreIdentity(store.path),
12
+ }));
13
+ }
14
+ export function taskStoreProjects(store) {
15
+ if (store.available === false)
16
+ return [];
17
+ try {
18
+ return getStoreProjectDirs(store).map(dir => path.basename(dir))
19
+ .filter(project => /^[A-Za-z0-9][A-Za-z0-9_-]{0,99}$/.test(project)).sort();
20
+ }
21
+ catch {
22
+ return [];
23
+ }
24
+ }
25
+ export function taskStoreHasProject(store, project) {
26
+ return taskStoreProjects(store).includes(project);
27
+ }
28
+ /** The directory never snapshots Git or returns its stderr/remote/path. Only
29
+ * bounded, read-only Git queries and the existing credential-stripping parser. */
30
+ export async function taskStoreRepositoryIdentity(store) {
31
+ const git = async (args) => exec("git", ["-C", store, ...args], {
32
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_OPTIONAL_LOCKS: "0" }, timeout: 5000, maxBuffer: 8192,
33
+ }).then(result => result.stdout.trim(), () => "");
34
+ const [remote, branch] = await Promise.all([git(["config", "--get", "remote.origin.url"]), git(["symbolic-ref", "--quiet", "--short", "HEAD"])]);
35
+ const repository = githubStoreRepository(remote);
36
+ return repository && branch && !/[\x00-\x1f\x7f]/.test(branch) ? { repository, branch } : undefined;
37
+ }
@@ -1,4 +1,5 @@
1
1
  import { type PhrenResult } from "../shared.js";
2
+ import { type TaskDependency, type TaskResponsibility, type TaskChange } from "./task-contract.js";
2
3
  export type TaskSection = "Active" | "Queue" | "Done";
3
4
  export { TASK_FILE_ALIASES, TASKS_FILENAME, isTaskFileName } from "../filenames.js";
4
5
  export interface TaskItem {
@@ -6,6 +7,8 @@ export interface TaskItem {
6
7
  id: string;
7
8
  /** Content-addressed stable ID embedded in the file as `<!-- bid:HASH -->`. Survives reordering and completions. */
8
9
  stableId?: string;
10
+ /** More than one bid comment on a record cannot identify one task safely. */
11
+ identityAmbiguous?: boolean;
9
12
  section: TaskSection;
10
13
  line: string;
11
14
  checked: boolean;
@@ -24,6 +27,17 @@ export interface TaskItem {
24
27
  childFindings?: string[];
25
28
  speculative?: boolean;
26
29
  parentFinding?: string;
30
+ /** Independent of Queue/Active/Done; absent legacy value means agent. */
31
+ responsibility?: TaskResponsibility;
32
+ dependencies?: TaskDependency[];
33
+ history?: TaskChange[];
34
+ /** Unknown/invalid contract content is retained and fails closed for selection. */
35
+ taskContractRaw?: string;
36
+ taskContractRecords?: string[];
37
+ /** Exact opaque Task continuations, including whitespace and duplicates. */
38
+ taskContractLines?: string[];
39
+ /** Preserve future continuations instead of hiding any later Task records. */
40
+ opaqueContinuationLines?: string[];
27
41
  }
28
42
  /**
29
43
  * A conductor's claim on a task, written under it in tasks.md as
@@ -37,6 +51,8 @@ export interface TaskClaim {
37
51
  session?: string;
38
52
  }
39
53
  export interface TaskDoc {
54
+ /** Digest of the exact bytes read, shared by every entry in this document. */
55
+ revision?: string;
40
56
  project: string;
41
57
  title: string;
42
58
  items: Record<TaskSection, TaskItem[]>;
@@ -67,10 +83,17 @@ export declare function stripBid(text: string): {
67
83
  export declare function applyGravity(items: TaskItem[]): TaskItem[];
68
84
  export declare function canonicalTaskFilePath(phrenPath: string, project: string): string | null;
69
85
  export declare function resolveTaskFilePath(phrenPath: string, project: string): string | null;
86
+ export declare function parseTaskContent(project: string, taskPath: string, content: string): TaskDoc;
70
87
  export declare function readTasks(phrenPath: string, project: string): PhrenResult<TaskDoc>;
71
88
  export declare function readTasksAcrossProjects(phrenPath: string, profile?: string): TaskDoc[];
72
89
  export declare function resolveTaskItem(phrenPath: string, project: string, match: string): PhrenResult<TaskItem>;
90
+ /** Validate raw input before normalization can hide a newline or identity. */
91
+ export declare function validTaskTitle(value: unknown): value is string;
73
92
  export interface AddTaskOptions {
93
+ /** Atomic metadata creation, with a caller-retained identity for uncertain replies. */
94
+ stableId?: string;
95
+ responsibility?: TaskResponsibility;
96
+ graphRoot?: string;
74
97
  createdAt?: string;
75
98
  sessionId?: string;
76
99
  scope?: string;
@@ -101,7 +124,19 @@ export declare function updateTask(phrenPath: string, project: string, match: st
101
124
  github_issue?: number | string;
102
125
  github_url?: string;
103
126
  unlink_github?: boolean;
104
- }): PhrenResult<string>;
127
+ responsibility?: TaskResponsibility;
128
+ dependencies?: TaskDependency[];
129
+ }, graphRoot?: string, expectedRevision?: string): PhrenResult<string>;
130
+ /** Reserve exactly the saved task before external launch work. The durable claim
131
+ * survives errors/restarts: a retry must not silently start a second worker.
132
+ * The returned snapshot is the only source of the worker's prompt. */
133
+ export declare function reserveTaskLaunch(phrenPath: string, project: string, stableId: string, expectedRevision: string, computer: string, graphRoot?: string): PhrenResult<{
134
+ identity: TaskDependency;
135
+ revision: string;
136
+ text: string;
137
+ context?: string;
138
+ launchId: string;
139
+ }>;
105
140
  export declare function pinTask(phrenPath: string, project: string, match: string): PhrenResult<string>;
106
141
  export declare function unpinTask(phrenPath: string, project: string, match: string): PhrenResult<string>;
107
142
  export declare function reorderTask(phrenPath: string, project: string, match: string, targetRank: number): PhrenResult<string>;
@@ -119,8 +154,9 @@ export declare function claimTask(phrenPath: string, project: string, match: str
119
154
  release?: boolean;
120
155
  force?: boolean;
121
156
  now?: number;
157
+ graphRoot?: string;
122
158
  }): PhrenResult<TaskItem>;
123
- export declare function workNextTask(phrenPath: string, project: string): PhrenResult<string>;
159
+ export declare function workNextTask(phrenPath: string, project: string, graphRoot?: string): PhrenResult<string>;
124
160
  export declare function tidyDoneTasks(phrenPath: string, project: string, keep?: number, dryRun?: boolean): PhrenResult<string>;
125
161
  export declare function taskMarkdown(doc: TaskDoc): string;
126
162
  export declare function linkTaskIssue(phrenPath: string, project: string, match: string, link: {
@@ -1,14 +1,17 @@
1
+ import { parseTaskMetadata } from "./task-metadata.js";
2
+ import { taskFormatStatus, taskFormatMigrationHint } from "./task-format.js";
1
3
  import { moduleEnabled } from "../modules/runtime.js";
2
4
  import { disabledHint } from "../modules/registry.js";
3
5
  import * as fs from "fs";
4
6
  import * as path from "path";
5
- import { randomBytes, randomUUID } from "crypto";
7
+ import { createHash, randomBytes, randomUUID } from "crypto";
6
8
  import { phrenErr, PhrenError, phrenOk, forwardErr, getProjectDirs, } from "../shared.js";
7
9
  import { validateTaskFormat } from "../shared/content.js";
8
10
  import { withSafeLock, ensureProject } from "../shared/data-utils.js";
9
11
  import { getNonPrimaryStores, getStoreProjectDirs } from "../store-registry.js";
10
12
  import { storeAwareProjectPath } from "../store-routing.js";
11
13
  import { TASKS_FILENAME } from "../filenames.js";
14
+ import { taskIdentity, taskReadiness, validateTaskDependencies, withTaskGraphLock } from "./task-contract.js";
12
15
  import { recordTaskWrite } from "./task-receipts.js";
13
16
  const ACTIVE_HEADINGS = new Set(["active", "in progress", "in-progress", "current", "wip"]);
14
17
  const QUEUE_HEADINGS = new Set(["queue", "queued", "task", "todo", "upcoming", "next"]);
@@ -81,6 +84,11 @@ function formatGitHubIssueReference(item) {
81
84
  return item.githubUrl;
82
85
  }
83
86
  function parseContinuation(lines, idx) {
87
+ let contract;
88
+ let taskContractRaw;
89
+ const taskContractRecords = [];
90
+ const taskContractLines = [];
91
+ const opaqueContinuationLines = [];
84
92
  let context;
85
93
  let claim;
86
94
  let githubIssue;
@@ -95,6 +103,12 @@ function parseContinuation(lines, idx) {
95
103
  linesToSkip++;
96
104
  continue;
97
105
  }
106
+ if (trimmed.startsWith("Task:")) {
107
+ taskContractRecords.push(trimmed.slice(5).trim());
108
+ taskContractLines.push(raw);
109
+ linesToSkip++;
110
+ continue;
111
+ }
98
112
  if (trimmed.startsWith("Context:")) {
99
113
  context = trimmed.slice("Context:".length).trim();
100
114
  linesToSkip++;
@@ -113,9 +127,20 @@ function parseContinuation(lines, idx) {
113
127
  linesToSkip++;
114
128
  continue;
115
129
  }
116
- break;
130
+ opaqueContinuationLines.push(raw);
131
+ linesToSkip++;
117
132
  }
118
- return { context, githubIssue, githubUrl, claim, linesToSkip };
133
+ if (taskContractRecords.length === 1) {
134
+ contract = parseTaskMetadata(taskContractRecords[0]);
135
+ if (!contract)
136
+ taskContractRaw = taskContractRecords[0];
137
+ }
138
+ else if (taskContractRecords.length > 1)
139
+ taskContractRaw = taskContractRecords[0];
140
+ return { context, githubIssue, githubUrl, claim, contract, taskContractRaw,
141
+ ...(taskContractRaw !== undefined ? { taskContractLines } : {}),
142
+ ...(taskContractRecords.length > 1 ? { taskContractRecords } : {}),
143
+ ...(opaqueContinuationLines.length ? { opaqueContinuationLines } : {}), linesToSkip };
119
144
  }
120
145
  /** Pattern that matches the task metadata comment embedded in task item lines.
121
146
  * Format: <!-- bid:HASH [rank:N] [lastActivity:ISO] -->
@@ -208,7 +233,7 @@ function normalizeTaskItemLine(item) {
208
233
  const speculativePart = item.speculative ? " speculative" : "";
209
234
  return `${prefix}${text} <!-- bid:${bid}${rankPart}${activityPart}${createdPart}${sessionPart}${scopePart}${findingsPart}${parentFindingPart}${speculativePart} -->`;
210
235
  }
211
- function parseTaskContent(project, taskPath, content) {
236
+ export function parseTaskContent(project, taskPath, content) {
212
237
  const lines = content.split("\n");
213
238
  const title = lines[0]?.trim() || `# ${project} tasks`;
214
239
  const items = {
@@ -247,6 +272,7 @@ function parseTaskContent(project, taskPath, content) {
247
272
  items[section].push({
248
273
  id: `${sectionPrefix}${sectionCounters[section]}`,
249
274
  stableId: bid,
275
+ identityAmbiguous: [...line.matchAll(/<!--\s*bid:([a-f0-9]{8})\b[^>]*-->/g)].length > 1 || undefined,
250
276
  section,
251
277
  line: cleanBody,
252
278
  checked: parsed.checked || section === "Done",
@@ -264,6 +290,13 @@ function parseTaskContent(project, taskPath, content) {
264
290
  githubIssue: continuation.githubIssue,
265
291
  githubUrl: continuation.githubUrl,
266
292
  claim: continuation.claim,
293
+ responsibility: continuation.contract?.responsibility,
294
+ dependencies: continuation.contract?.dependencies,
295
+ history: continuation.contract?.history,
296
+ taskContractRaw: continuation.taskContractRaw,
297
+ taskContractRecords: continuation.taskContractRecords,
298
+ taskContractLines: continuation.taskContractLines,
299
+ opaqueContinuationLines: continuation.opaqueContinuationLines,
267
300
  });
268
301
  i += continuation.linesToSkip;
269
302
  }
@@ -276,6 +309,7 @@ function parseTaskContent(project, taskPath, content) {
276
309
  title,
277
310
  path: taskPath,
278
311
  items,
312
+ revision: createHash("sha256").update(content).digest("hex"),
279
313
  issues: validateTaskFormat(content),
280
314
  };
281
315
  }
@@ -285,6 +319,14 @@ function renderTask(doc) {
285
319
  out.push(`## ${section}`, "");
286
320
  for (const item of doc.items[section]) {
287
321
  out.push(normalizeTaskItemLine(item));
322
+ if (item.taskContractLines?.length)
323
+ out.push(...item.taskContractLines);
324
+ else if (item.taskContractRecords?.length)
325
+ out.push(...item.taskContractRecords.map(raw => ` Task: ${raw}`));
326
+ else if (item.taskContractRaw !== undefined)
327
+ out.push(` Task: ${item.taskContractRaw}`);
328
+ else if (item.responsibility !== undefined || item.dependencies?.length || item.history?.length)
329
+ out.push(` Task: ${JSON.stringify({ version: 1, responsibility: item.responsibility ?? "agent", dependencies: item.dependencies ?? [], history: item.history ?? [] })}`);
288
330
  if (item.context)
289
331
  out.push(` Context: ${item.context}`);
290
332
  const githubRef = formatGitHubIssueReference(item);
@@ -292,6 +334,8 @@ function renderTask(doc) {
292
334
  out.push(` GitHub: ${githubRef}`);
293
335
  if (item.claim)
294
336
  out.push(` ${formatClaim(item.claim)}`);
337
+ if (item.opaqueContinuationLines?.length)
338
+ out.push(...item.opaqueContinuationLines);
295
339
  }
296
340
  out.push("");
297
341
  }
@@ -301,20 +345,33 @@ function findItemByMatch(doc, match) {
301
345
  const needle = match.trim().toLowerCase();
302
346
  if (!needle)
303
347
  return { error: `${PhrenError.EMPTY_INPUT}: Please provide the item text or ID to match against.`, errorCode: PhrenError.EMPTY_INPUT };
348
+ const unique = (matched) => {
349
+ const item = doc.items[matched.section][matched.index];
350
+ const duplicates = item.stableId && TASK_SECTIONS.flatMap(section => doc.items[section]).filter(other => other.stableId === item.stableId).length > 1;
351
+ return item.identityAmbiguous || duplicates
352
+ ? { error: "Stable task identity is ambiguous; repair the conflicting records before editing.", errorCode: PhrenError.AMBIGUOUS_MATCH }
353
+ : { match: matched };
354
+ };
304
355
  // 1a) Stable ID match (bid:XXXX or just the 8-char hex).
305
356
  const bidNeedle = needle.replace(/^bid:/, "");
306
357
  if (/^[a-f0-9]{8}$/.test(bidNeedle)) {
307
- for (const section of TASK_SECTIONS) {
308
- const idx = doc.items[section].findIndex((item) => item.stableId === bidNeedle);
309
- if (idx !== -1)
310
- return { match: { section, index: idx } };
311
- }
358
+ const stableMatches = [];
359
+ for (const section of TASK_SECTIONS)
360
+ doc.items[section].forEach((item, index) => {
361
+ if (item.stableId === bidNeedle)
362
+ stableMatches.push({ section, index });
363
+ });
364
+ if (stableMatches.length === 1)
365
+ return unique(stableMatches[0]);
366
+ if (stableMatches.length > 1)
367
+ return { error: "Stable task ID is duplicated; repair the conflicting records before editing.", errorCode: PhrenError.AMBIGUOUS_MATCH };
368
+ return { error: `No task with stable ID ${bidNeedle}.`, errorCode: PhrenError.NOT_FOUND };
312
369
  }
313
370
  // 1b) Positional ID match (A1, Q2, D3).
314
371
  for (const section of TASK_SECTIONS) {
315
372
  const idx = doc.items[section].findIndex((item) => item.id.toLowerCase() === needle);
316
373
  if (idx !== -1)
317
- return { match: { section, index: idx } };
374
+ return unique({ section, index: idx });
318
375
  }
319
376
  // 2) Exact line match.
320
377
  const exact = [];
@@ -325,7 +382,7 @@ function findItemByMatch(doc, match) {
325
382
  });
326
383
  }
327
384
  if (exact.length === 1)
328
- return { match: exact[0] };
385
+ return unique(exact[0]);
329
386
  if (exact.length > 1) {
330
387
  return { error: `${PhrenError.AMBIGUOUS_MATCH}: "${match}" is ambiguous (${exact.length} exact matches). Use item ID.`, errorCode: PhrenError.AMBIGUOUS_MATCH };
331
388
  }
@@ -338,7 +395,7 @@ function findItemByMatch(doc, match) {
338
395
  });
339
396
  }
340
397
  if (partial.length === 1)
341
- return { match: partial[0] };
398
+ return unique(partial[0]);
342
399
  if (partial.length > 1) {
343
400
  return { error: `${PhrenError.AMBIGUOUS_MATCH}: "${match}" is ambiguous (${partial.length} partial matches). Use item ID.`, errorCode: PhrenError.AMBIGUOUS_MATCH };
344
401
  }
@@ -370,6 +427,7 @@ export function readTasks(phrenPath, project) {
370
427
  return phrenOk({
371
428
  project,
372
429
  title: `# ${project} tasks`,
430
+ revision: createHash("sha256").update("").digest("hex"),
373
431
  path: taskPath,
374
432
  issues: [],
375
433
  items: { Active: [], Queue: [], Done: [] },
@@ -427,7 +485,14 @@ export function resolveTaskItem(phrenPath, project, match) {
427
485
  return taskItemNotFound(project, match);
428
486
  return phrenOk(parsed.data.items[found.match.section][found.match.index]);
429
487
  }
488
+ /** Validate raw input before normalization can hide a newline or identity. */
489
+ export function validTaskTitle(value) {
490
+ return typeof value === "string" && !!value.trim() && !/[\x00-\x1f\x7f]|<!--\s*bid:/i.test(value);
491
+ }
492
+ const invalidTaskTitle = "Task text must be one nonempty line without control characters or embedded task identities.";
430
493
  export function addTask(phrenPath, project, item, opts) {
494
+ if (!validTaskTitle(item))
495
+ return phrenErr(invalidTaskTitle, PhrenError.VALIDATION_ERROR);
431
496
  const bPath = canonicalTaskFilePath(phrenPath, project);
432
497
  if (!bPath)
433
498
  return phrenErr(`Project name "${project}" is not valid. Use lowercase letters, numbers, and hyphens (e.g. "my-project").`, PhrenError.INVALID_PROJECT_NAME);
@@ -436,16 +501,45 @@ export function addTask(phrenPath, project, item, opts) {
436
501
  const preCheck = ensureProject(phrenPath, project);
437
502
  if (!preCheck.ok)
438
503
  return forwardErr(preCheck);
439
- return withSafeLock(bPath, () => {
504
+ const create = () => withSafeLock(bPath, () => {
440
505
  const parsed = readTasks(phrenPath, project);
441
506
  if (!parsed.ok)
442
507
  return forwardErr(parsed);
443
508
  const line = item.replace(/^-\s*/, "").trim();
509
+ if (!line)
510
+ return phrenErr(invalidTaskTitle, PhrenError.VALIDATION_ERROR);
511
+ if (opts?.responsibility !== undefined) {
512
+ if (!taskFormatStatus(phrenPath).enabled)
513
+ return phrenErr(taskFormatMigrationHint, PhrenError.VALIDATION_ERROR);
514
+ if (!["human", "agent"].includes(opts.responsibility) || !opts.stableId || !/^[a-f0-9]{8}$/.test(opts.stableId))
515
+ return phrenErr("Atomic creation requires a valid responsibility and stable ID.", PhrenError.VALIDATION_ERROR);
516
+ if (!line || /[\r\n]/.test(line) || /<!--\s*bid:/i.test(line))
517
+ return phrenErr("Task title must be one nonempty line.", PhrenError.VALIDATION_ERROR);
518
+ const existing = [...parsed.data.items.Active, ...parsed.data.items.Queue, ...parsed.data.items.Done].filter(task => task.stableId === opts.stableId);
519
+ if (existing.length) {
520
+ const task = existing[0];
521
+ if (existing.length === 1 && !task.identityAmbiguous && task.taskContractRaw === undefined && task.line === line && task.responsibility === opts.responsibility)
522
+ return phrenOk(task);
523
+ return phrenErr("This creation identity already exists with different task content. Refresh before continuing; no task was created.", PhrenError.VALIDATION_ERROR);
524
+ }
525
+ const archive = path.join(phrenPath, ".config", "task-archive", `${project}.md`);
526
+ try {
527
+ if (new RegExp(`<!--\\s*bid:${opts.stableId}(?=\\s|-->)`, "i").test(fs.readFileSync(archive, "utf8")))
528
+ return phrenErr("This creation identity is already archived. Refresh before continuing; no task was created.", PhrenError.VALIDATION_ERROR);
529
+ }
530
+ catch (error) {
531
+ if (error.code !== "ENOENT")
532
+ throw error;
533
+ }
534
+ }
535
+ else if (opts?.stableId !== undefined)
536
+ return phrenErr("A supplied creation identity requires explicit responsibility.", PhrenError.VALIDATION_ERROR);
444
537
  const newItem = {
445
538
  id: `Q${parsed.data.items.Queue.length + 1}`,
446
- stableId: newBid(),
539
+ stableId: opts?.stableId ?? newBid(),
447
540
  section: "Queue",
448
541
  line,
542
+ ...(opts?.responsibility !== undefined ? { responsibility: opts.responsibility, dependencies: [], history: [{ at: new Date().toISOString(), change: `created as ${opts.responsibility}` }] } : {}),
449
543
  checked: false,
450
544
  priority: normalizePriority(line),
451
545
  createdAt: opts?.createdAt ?? new Date().toISOString(),
@@ -458,6 +552,7 @@ export function addTask(phrenPath, project, item, opts) {
458
552
  writeTaskDoc(parsed.data);
459
553
  return phrenOk(newItem);
460
554
  });
555
+ return opts?.responsibility !== undefined ? withTaskGraphLock(opts.graphRoot ?? phrenPath, create) : create();
461
556
  }
462
557
  export function addTasks(phrenPath, project, items, opts) {
463
558
  const bPath = canonicalTaskFilePath(phrenPath, project);
@@ -473,6 +568,10 @@ export function addTasks(phrenPath, project, items, opts) {
473
568
  const added = [];
474
569
  const errors = [];
475
570
  for (const item of items) {
571
+ if (!validTaskTitle(item)) {
572
+ errors.push(item);
573
+ continue;
574
+ }
476
575
  const line = item.replace(/^-\s*/, "").trim();
477
576
  if (!line) {
478
577
  errors.push(item);
@@ -490,7 +589,8 @@ export function addTasks(phrenPath, project, items, opts) {
490
589
  });
491
590
  added.push(line);
492
591
  }
493
- writeTaskDoc(parsed.data);
592
+ if (added.length)
593
+ writeTaskDoc(parsed.data);
494
594
  return phrenOk({ added, errors });
495
595
  });
496
596
  }
@@ -516,6 +616,8 @@ export function completeTasks(phrenPath, project, matches) {
516
616
  const [item] = parsed.data.items[found.match.section].splice(found.match.index, 1);
517
617
  item.section = "Done";
518
618
  item.checked = true;
619
+ if (item.history !== undefined)
620
+ item.history.push({ at: new Date().toISOString(), change: `completed${item.claim ? `; released claim by ${item.claim.computer}` : ""}` });
519
621
  item.claim = undefined;
520
622
  parsed.data.items.Done.unshift(item);
521
623
  completed.push(item.line);
@@ -543,6 +645,8 @@ export function completeTask(phrenPath, project, match) {
543
645
  const [item] = parsed.data.items[found.match.section].splice(found.match.index, 1);
544
646
  item.section = "Done";
545
647
  item.checked = true;
648
+ if (item.history !== undefined)
649
+ item.history.push({ at: new Date().toISOString(), change: `completed${item.claim ? `; released claim by ${item.claim.computer}` : ""}` });
546
650
  item.claim = undefined;
547
651
  parsed.data.items.Done.unshift(item);
548
652
  writeTaskDoc(parsed.data);
@@ -596,32 +700,69 @@ export function removeTasks(phrenPath, project, matches) {
596
700
  return phrenOk({ removed, errors });
597
701
  });
598
702
  }
599
- export function updateTask(phrenPath, project, match, updates) {
703
+ export function updateTask(phrenPath, project, match, updates, graphRoot = phrenPath, expectedRevision) {
600
704
  const bPath = canonicalTaskFilePath(phrenPath, project);
601
705
  if (!bPath)
602
706
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
603
707
  const preCheck = ensureProject(phrenPath, project);
604
708
  if (!preCheck.ok)
605
709
  return forwardErr(preCheck);
606
- return withSafeLock(bPath, () => {
710
+ return withTaskGraphLock(graphRoot, () => withSafeLock(bPath, () => {
607
711
  const parsed = readTasks(phrenPath, project);
608
712
  if (!parsed.ok)
609
713
  return forwardErr(parsed);
714
+ if (expectedRevision !== undefined && parsed.data.revision !== expectedRevision) {
715
+ return phrenErr("Task revision changed; refresh and review your draft before saving.", PhrenError.VALIDATION_ERROR);
716
+ }
610
717
  const found = findItemByMatch(parsed.data, match);
611
718
  if (found.error)
612
719
  return phrenErr(found.error, found.errorCode ?? PhrenError.AMBIGUOUS_MATCH);
613
720
  if (!found.match)
614
721
  return taskItemNotFound(project, match);
615
722
  const item = parsed.data.items[found.match.section][found.match.index];
723
+ if (expectedRevision !== undefined && (!taskFormatStatus(phrenPath).enabled
724
+ || !taskIdentity(graphRoot, parsed.data, item) || item.taskContractRaw !== undefined || item.taskContractRecords !== undefined)) {
725
+ return phrenErr("Task metadata is disabled, unsupported or ambiguous; preserve your draft.", PhrenError.VALIDATION_ERROR);
726
+ }
616
727
  const changes = [];
728
+ if (updates.responsibility !== undefined || updates.dependencies !== undefined) {
729
+ const storeRoot = path.dirname(path.dirname(parsed.data.path));
730
+ if (!taskFormatStatus(storeRoot).enabled)
731
+ return phrenErr(taskFormatMigrationHint, PhrenError.VALIDATION_ERROR);
732
+ if (item.taskContractRaw !== undefined)
733
+ return phrenErr("Task metadata is invalid or from a newer version; preserve it and repair before editing responsibility/dependencies.", PhrenError.VALIDATION_ERROR);
734
+ if (updates.responsibility !== undefined && !["human", "agent"].includes(updates.responsibility))
735
+ return phrenErr("Responsibility must be human or agent.", PhrenError.VALIDATION_ERROR);
736
+ item.stableId ??= newBid();
737
+ if (updates.dependencies !== undefined) {
738
+ const error = validateTaskDependencies(graphRoot, parsed.data, item, updates.dependencies);
739
+ if (error)
740
+ return phrenErr(error, PhrenError.VALIDATION_ERROR);
741
+ item.dependencies = updates.dependencies;
742
+ changes.push("dependencies updated");
743
+ }
744
+ if (updates.responsibility !== undefined && updates.responsibility !== (item.responsibility ?? "agent")) {
745
+ changes.push(`responsibility ${(item.responsibility ?? "agent")} -> ${updates.responsibility}`);
746
+ item.responsibility = updates.responsibility;
747
+ if (updates.responsibility === "human" && item.claim) {
748
+ changes.push(`released claim by ${item.claim.computer} at ${item.claim.at}`);
749
+ item.claim = undefined;
750
+ }
751
+ }
752
+ }
617
753
  if (updates.text !== undefined) {
754
+ if (typeof updates.text === "string" && !updates.text.trim())
755
+ return phrenErr("Task text cannot be empty.", PhrenError.EMPTY_INPUT);
756
+ if (!validTaskTitle(updates.text))
757
+ return phrenErr(invalidTaskTitle, PhrenError.VALIDATION_ERROR);
618
758
  const nextText = updates.text.trim();
619
759
  if (!nextText)
620
760
  return phrenErr("Task text cannot be empty.", PhrenError.EMPTY_INPUT);
761
+ const previousText = item.line;
621
762
  item.line = nextText;
622
763
  item.priority = normalizePriority(nextText);
623
764
  item.pinned = detectPinned(nextText) || undefined;
624
- changes.push("text updated");
765
+ changes.push(`text updated from ${JSON.stringify(previousText)}`);
625
766
  }
626
767
  if (updates.priority) {
627
768
  const priority = updates.priority.toLowerCase();
@@ -632,7 +773,9 @@ export function updateTask(phrenPath, project, match, updates) {
632
773
  changes.push(`priority -> ${priority}`);
633
774
  }
634
775
  }
635
- if (updates.context) {
776
+ if (updates.context !== undefined && (updates.context !== "" || updates.replace_context)) {
777
+ if (typeof updates.context !== "string" || /[\x00-\x1f\x7f]/.test(updates.context))
778
+ return phrenErr("Task context must be one line without control characters.", PhrenError.VALIDATION_ERROR);
636
779
  if (updates.replace_context || !item.context)
637
780
  item.context = updates.context;
638
781
  // Agents sometimes send the existing context with their new note. Do
@@ -677,12 +820,53 @@ export function updateTask(phrenPath, project, match, updates) {
677
820
  item.section = section;
678
821
  item.checked = section === "Done";
679
822
  parsed.data.items[section].unshift(item);
680
- changes.push(`moved to ${section}`);
823
+ changes.push(`moved ${found.match.section} -> ${section}`);
681
824
  }
682
825
  }
826
+ if (changes.length && (item.responsibility !== undefined || item.dependencies !== undefined || item.history !== undefined))
827
+ item.history = [...(item.history ?? []), { at: new Date().toISOString(), change: changes.join(", ") }];
683
828
  writeTaskDoc(parsed.data);
684
829
  return phrenOk(`Updated item in ${project}: ${changes.join(", ") || "no changes"}`);
685
- });
830
+ }));
831
+ }
832
+ /** Reserve exactly the saved task before external launch work. The durable claim
833
+ * survives errors/restarts: a retry must not silently start a second worker.
834
+ * The returned snapshot is the only source of the worker's prompt. */
835
+ export function reserveTaskLaunch(phrenPath, project, stableId, expectedRevision, computer, graphRoot = phrenPath) {
836
+ const file = canonicalTaskFilePath(phrenPath, project);
837
+ if (!file || !/^[a-f0-9]{8}$/.test(stableId) || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,252}$/.test(computer)) {
838
+ return phrenErr("Invalid task launch identity.", PhrenError.VALIDATION_ERROR);
839
+ }
840
+ return withTaskGraphLock(graphRoot, () => withSafeLock(file, () => {
841
+ const parsed = readTasks(phrenPath, project);
842
+ if (!parsed.ok)
843
+ return forwardErr(parsed);
844
+ if (parsed.data.revision !== expectedRevision)
845
+ return phrenErr("Task revision changed; refresh before starting.", PhrenError.VALIDATION_ERROR);
846
+ const found = findItemByMatch(parsed.data, `bid:${stableId}`);
847
+ if (found.error || !found.match)
848
+ return phrenErr(found.error ?? "Task is missing.", PhrenError.VALIDATION_ERROR);
849
+ const item = parsed.data.items[found.match.section][found.match.index];
850
+ const identity = taskIdentity(graphRoot, parsed.data, item);
851
+ if (!identity || !taskFormatStatus(phrenPath).enabled || item.taskContractRaw !== undefined || item.taskContractRecords !== undefined
852
+ || item.checked || item.section === "Done" || taskReadiness(graphRoot, parsed.data, item).readiness !== "ready") {
853
+ return phrenErr("Task is not eligible for agent launch. Refresh responsibility and prerequisites.", PhrenError.VALIDATION_ERROR);
854
+ }
855
+ if (item.claim)
856
+ return phrenErr("Task already has a claim. Review the existing worker before explicitly releasing it.", PhrenError.VALIDATION_ERROR);
857
+ if (!validTaskTitle(item.line) || (item.context && /[\x00-\x1f\x7f]/.test(item.context))
858
+ || item.line.length + (item.context?.length ?? 0) > 30000)
859
+ return phrenErr("Task text/context cannot be carried safely in a launch brief.", PhrenError.VALIDATION_ERROR);
860
+ const launchId = randomUUID(), at = new Date().toISOString();
861
+ item.claim = { computer, at, session: `task-launch:${launchId}` };
862
+ item.responsibility ??= "agent";
863
+ item.history = [...(item.history ?? []), { at, change: `reserved task launch ${launchId}` }];
864
+ parsed.data.items[found.match.section].splice(found.match.index, 1);
865
+ item.section = "Active";
866
+ parsed.data.items.Active.unshift(item);
867
+ writeTaskDoc(parsed.data);
868
+ return phrenOk({ identity, revision: expectedRevision, text: item.line, context: item.context, launchId });
869
+ }));
686
870
  }
687
871
  export function pinTask(phrenPath, project, match) {
688
872
  const bPath = canonicalTaskFilePath(phrenPath, project);
@@ -843,7 +1027,7 @@ export function claimTask(phrenPath, project, match, claim, opts = {}) {
843
1027
  const preCheck = ensureProject(phrenPath, project);
844
1028
  if (!preCheck.ok)
845
1029
  return forwardErr(preCheck);
846
- return withSafeLock(bPath, () => {
1030
+ return withTaskGraphLock(opts.graphRoot ?? phrenPath, () => withSafeLock(bPath, () => {
847
1031
  const parsed = readTasks(phrenPath, project);
848
1032
  if (!parsed.ok)
849
1033
  return forwardErr(parsed);
@@ -853,6 +1037,8 @@ export function claimTask(phrenPath, project, match, claim, opts = {}) {
853
1037
  if (!found.match)
854
1038
  return taskItemNotFound(project, match);
855
1039
  const item = parsed.data.items[found.match.section][found.match.index];
1040
+ if (!opts.release && taskReadiness(opts.graphRoot ?? phrenPath, parsed.data, item).readiness !== "ready")
1041
+ return phrenErr("This task awaits a human or prerequisite task.", PhrenError.VALIDATION_ERROR);
856
1042
  if (item.section === "Done")
857
1043
  return phrenErr(`This task is already done: ${item.line}`, PhrenError.VALIDATION_ERROR);
858
1044
  const held = item.claim && item.claim.computer !== claim.computer ? item.claim : undefined;
@@ -862,6 +1048,8 @@ export function claimTask(phrenPath, project, match, claim, opts = {}) {
862
1048
  return phrenErr(`${held.computer} claimed this task at ${held.at}${stale ? "; the claim is over a day old, so force can take it over" : ""}.`, PhrenError.PERMISSION_DENIED);
863
1049
  }
864
1050
  }
1051
+ if (item.history !== undefined)
1052
+ item.history.push({ at: new Date().toISOString(), change: opts.release ? `released claim by ${claim.computer}` : `claimed by ${claim.computer}` });
865
1053
  if (opts.release) {
866
1054
  if (!item.claim)
867
1055
  return phrenErr(`This task is not claimed: ${item.line}`, PhrenError.VALIDATION_ERROR);
@@ -881,16 +1069,16 @@ export function claimTask(phrenPath, project, match, claim, opts = {}) {
881
1069
  }
882
1070
  writeTaskDoc(parsed.data);
883
1071
  return phrenOk(item);
884
- });
1072
+ }));
885
1073
  }
886
- export function workNextTask(phrenPath, project) {
1074
+ export function workNextTask(phrenPath, project, graphRoot = phrenPath) {
887
1075
  const bPath = canonicalTaskFilePath(phrenPath, project);
888
1076
  if (!bPath)
889
1077
  return phrenErr(`Project name "${project}" is not valid.`, PhrenError.INVALID_PROJECT_NAME);
890
1078
  const preCheck = ensureProject(phrenPath, project);
891
1079
  if (!preCheck.ok)
892
1080
  return forwardErr(preCheck);
893
- return withSafeLock(bPath, () => {
1081
+ return withTaskGraphLock(graphRoot, () => withSafeLock(bPath, () => {
894
1082
  const parsed = readTasks(phrenPath, project);
895
1083
  if (!parsed.ok)
896
1084
  return forwardErr(parsed);
@@ -903,13 +1091,18 @@ export function workNextTask(phrenPath, project) {
903
1091
  const pb = priorityOrder[b.priority ?? ""] ?? 3;
904
1092
  return pa - pb;
905
1093
  });
906
- const item = parsed.data.items.Queue.shift();
1094
+ const nextIndex = parsed.data.items.Queue.findIndex(item => taskReadiness(graphRoot, parsed.data, item).readiness === "ready");
1095
+ if (nextIndex < 0)
1096
+ return phrenErr("No ready agent tasks; queued tasks await a human or prerequisite task.", PhrenError.NOT_FOUND);
1097
+ const [item] = parsed.data.items.Queue.splice(nextIndex, 1);
1098
+ if (item.history !== undefined)
1099
+ item.history.push({ at: new Date().toISOString(), change: "moved Queue -> Active by next" });
907
1100
  item.section = "Active";
908
1101
  item.checked = false;
909
1102
  parsed.data.items.Active.push(item);
910
1103
  writeTaskDoc(parsed.data);
911
1104
  return phrenOk(`Moved next queue item to Active in ${project}: ${item.line}`);
912
- });
1105
+ }));
913
1106
  }
914
1107
  export function tidyDoneTasks(phrenPath, project, keep = 30, dryRun) {
915
1108
  const bPath = canonicalTaskFilePath(phrenPath, project);
@@ -936,7 +1129,7 @@ export function tidyDoneTasks(phrenPath, project, keep = 30, dryRun) {
936
1129
  const archiveFile = taskArchivePath(path.dirname(path.dirname(bPath)), project);
937
1130
  fs.mkdirSync(path.dirname(archiveFile), { recursive: true });
938
1131
  const stamp = new Date().toISOString();
939
- const lines = archived.map((item) => `- [x] ${item.line}${item.context ? `\n Context: ${item.context}` : ""}`);
1132
+ const lines = archived.map((item) => renderTask({ ...parsed.data, items: { Active: [], Queue: [], Done: [item] } }).split("## Done\n\n")[1].trimEnd());
940
1133
  const block = `## ${stamp}\n\n${lines.join("\n")}\n\n`;
941
1134
  const prior = fs.existsSync(archiveFile) ? fs.readFileSync(archiveFile, "utf8") : `# ${project} tasks archive\n\n`;
942
1135
  const tmpPath = `${archiveFile}.tmp-${randomUUID()}`;