@quolu/lattice 0.102.1 → 0.104.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/src/todo-cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { createTodoReadiness, retireStateConflict, validateProspectiveEvent } from './todo-readiness.mjs';
1
+ import { createTodoReadiness, listTodoConnections, retireStateConflict, validateProspectiveEvent } from './todo-readiness.mjs';
2
2
  import { cliCommandKind } from './cli-command-kind.mjs';
3
3
  import { cliFailureClass } from './cli-failure-class.mjs';
4
4
  import { ENFORCED_DONE_MESSAGE, FLAG_PLACEHOLDER, publicRefusalCode, withRefusalGuidance } from './cli-refusal-guidance.mjs';
@@ -170,7 +170,7 @@ import {
170
170
  } from './seam-proposal-contracts.mjs';
171
171
  import { compileSeamProposalArtifact, declaredConcernSymbols } from './seam-proposal.mjs';
172
172
  import { collectSensorEvidence } from './sensor-adapter.mjs';
173
- import { newTodoNotices, projectTodoNotices, waitInEffect } from './todo-notices.mjs';
173
+ import { newTodoNotices, projectTodoNotices, waitInEffect, withTodoPriorityWaits } from './todo-notices.mjs';
174
174
  import {
175
175
  externalCycle, readTodoExternalChart, readTodoExternalTasks, withTodoExternalTasks,
176
176
  } from './todo-external.mjs';
@@ -202,6 +202,7 @@ import {
202
202
  readTodoNoteEvents,
203
203
  readTodoPlanNotesForStatus,
204
204
  } from './todo-note-store.mjs';
205
+ import { dependencyNoteBody, todoAddNoteBody } from './todo-revision-note.mjs';
205
206
  import { readTodoParallelCandidatesForStatus } from './todo-parallel-candidates.mjs';
206
207
  import { commitTodoStoreMutation } from './todo-store-git-transaction.mjs';
207
208
  import { repairTodoStoreWorktreeEol } from './todo-store-worktree-eol.mjs';
@@ -313,7 +314,7 @@ const TODO_COMMAND_NAMES = Object.freeze([
313
314
  'status', 'show', 'note', 'bindings', 'display', 'independence', 'structure', 'seam-profile', 'seam-proposal',
314
315
  'verify', 'repair-eol', 'snapshot', 'gantt', 'dashboard', 'phase', 'migrate', 'start', 'block',
315
316
  'unblock', 'retire', 'done', 'reopen', 'evidence', 'split', 'revise', 'revise-phase', 'revise-set',
316
- 'retract', 'dependency', 'add', 'notice', 'wait', 'blockers',
317
+ 'retract', 'dependency', 'predecessor', 'connect', 'add', 'notice', 'wait', 'blockers',
317
318
  ]);
318
319
 
319
320
  function typedArgumentFailure(stderr, code, message, detail, context = {}) {
@@ -337,6 +338,8 @@ const DEPENDENCY_FLAG_SPEC = Object.freeze({
337
338
  known: ['from-project', 'from-plan', 'from-task', 'to-plan', 'to-task', 'reason'],
338
339
  required: ['from-plan', 'from-task', 'to-plan', 'to-task', 'reason'],
339
340
  });
341
+ const PREDECESSOR_FLAG_SPEC = Object.freeze({ known: ['plan', 'task', 'after', 'reason'], required: ['plan', 'task', 'after', 'reason'] });
342
+ const CONNECT_FLAG_SPEC = Object.freeze({ known: ['plan', 'task', 'to', 'reason'], required: ['plan', 'task', 'to', 'reason'] });
340
343
  // a18: one spec per write command is both its parser and the explanation of its refusal.
341
344
  const TODO_FLAG_SPECS = Object.freeze({
342
345
  start: Object.freeze({
@@ -356,6 +359,11 @@ const TODO_FLAG_SPECS = Object.freeze({
356
359
  required: ['plan', 'task', 'title'],
357
360
  }),
358
361
  'dependency disconnect': DEPENDENCY_FLAG_SPEC,
362
+ 'predecessor add': PREDECESSOR_FLAG_SPEC,
363
+ 'predecessor remove': PREDECESSOR_FLAG_SPEC,
364
+ 'connect condition add': CONNECT_FLAG_SPEC,
365
+ 'connect condition remove': CONNECT_FLAG_SPEC,
366
+ 'connect condition resolve': Object.freeze({ known: ['plan', 'task', 'to', 'message'], required: ['plan', 'task', 'to', 'message'] }),
359
367
  // a23: the remaining writes whose refusal pointed only at --help.
360
368
  'phase review': PHASE_REASON_FLAG_SPEC,
361
369
  'phase close-unaudited': PHASE_REASON_FLAG_SPEC,
@@ -376,6 +384,7 @@ const TODO_FLAG_SPECS = Object.freeze({
376
384
  'notice list': Object.freeze({ known: ['lane', 'include-acked', 'json'], required: [], booleans: ['include-acked', 'json'] }),
377
385
  'notice ack': Object.freeze({ known: ['lane', 'notice', 'json'], required: ['lane', 'notice'], booleans: ['json'] }),
378
386
  blockers: Object.freeze({ known: ['json'], required: [], booleans: ['json'] }),
387
+ 'connect priority': Object.freeze({ known: ['plan', 'task', 'reason', 'cancel', 'json'], required: ['plan', 'task'], booleans: ['cancel', 'json'] }),
379
388
  wait: Object.freeze({ known: ['plan', 'task', 'reason', 'cancel', 'json'], required: ['plan', 'task'], booleans: ['cancel', 'json'] }),
380
389
  'note list': Object.freeze({ known: ['plan', 'task', 'json'], required: ['plan'], booleans: ['json'] }),
381
390
  'phase status': Object.freeze({ known: ['plan', 'json'], required: ['plan'], booleans: ['json'] }),
@@ -387,10 +396,12 @@ const WITNESS_TEMPLATE_FLAG_SPEC = Object.freeze({
387
396
  // a28: command groups, their subcommands and the one a refusal shows as the example.
388
397
  const TODO_SUBCOMMANDS = Object.freeze({
389
398
  dependency: { names: ['connect', 'disconnect'], example: 'connect' },
399
+ predecessor: { names: ['add', 'remove'], example: 'add' },
400
+ connect: { names: ['condition', 'priority'], example: 'priority' },
390
401
  phase: { names: ['status', 'review', 'accept', 'reject', 'reopen', 'close-unaudited', 'baseline'], example: 'review' },
391
402
  evidence: { names: ['promote'], example: 'promote' },
392
403
  });
393
- const GROUP_COMMANDS = ['dependency', 'phase', 'evidence', 'independence', 'note', 'structure'];
404
+ const GROUP_COMMANDS = ['dependency', 'predecessor', 'connect', 'phase', 'evidence', 'independence', 'note', 'structure'];
394
405
  const IDENTIFIER_FLAGS = ['plan', 'task', 'phase', 'from-plan', 'from-task', 'to-plan', 'to-task'];
395
406
  // The shared table is FLAG_PLACEHOLDER (cli-refusal-guidance, a27).
396
407
  const placeholder = (name) => FLAG_PLACEHOLDER[name] ?? `<${name}>`;
@@ -443,6 +454,13 @@ function explainMissingSubcommand(argv) {
443
454
  + ' (every command: `lattice todo --help`).' };
444
455
  }
445
456
  const group = TODO_SUBCOMMANDS[argv[0]];
457
+ if (argv[0] === 'connect' && argv[1] === 'condition' && !['add', 'remove', 'resolve'].includes(argv[2])) {
458
+ const missing = typeof argv[2] !== 'string' || argv[2].startsWith('--');
459
+ return { pointer: missing ? '<subcommand>' : argv[2], rule: missing ? 'subcommand_missing' : 'subcommand_unknown',
460
+ available_subcommands: ['add', 'remove', 'resolve'],
461
+ next_action: 'Name one of add, remove, resolve after `lattice todo connect condition`, e.g.'
462
+ + ' `lattice todo connect condition add --plan <plan> --task <id> --to task:<project>/<plan>/<task> --reason <text>`.' };
463
+ }
446
464
  if (group === undefined || group.names.includes(argv[1])) return null;
447
465
  const missing = typeof argv[1] !== 'string' || argv[1].startsWith('--');
448
466
  const head = [argv[0], group.example];
@@ -458,6 +476,7 @@ function explainArgumentRefusal(argv) {
458
476
  const missingSubcommand = explainMissingSubcommand(argv);
459
477
  if (missingSubcommand !== null) return missingSubcommand;
460
478
  const head = argv[0] === 'independence' && argv[1] === 'witness' ? argv.slice(0, 3)
479
+ : argv[0] === 'connect' && argv[1] === 'condition' ? argv.slice(0, 3)
461
480
  : GROUP_COMMANDS.includes(argv[0]) && typeof argv[1] === 'string' && !argv[1].startsWith('--')
462
481
  ? argv.slice(0, 2) : argv.slice(0, 1);
463
482
  // a32: `scaffold --template` is a read with its own flags.
@@ -531,6 +550,14 @@ function explainArgumentRefusal(argv) {
531
550
  return { pointer: `--${name}`, rule: 'flag_missing', next_action: `Give --${name} a non-empty <text>: \`${repairedCommand(head, spec, flags)}\`.` };
532
551
  }
533
552
  }
553
+ if (argv[0] === 'connect' && argv[1] === 'condition' && parseConditionTarget(flags.to, '') === null) {
554
+ return { pointer: '--to', rule: 'target_invalid', actual: flags.to,
555
+ next_action: 'Name the 接続先 as `task:<project>/<plan>/<task>` (a task on another chart) or `schedule:<id>` (a BellTeam schedule).' };
556
+ }
557
+ if (argv[0] === 'predecessor' && typeof flags.after === 'string' && parsePredecessorTarget(flags.after, '') === null) {
558
+ return { pointer: '--after', rule: 'target_invalid', actual: flags.after,
559
+ next_action: 'Name the 前工程 as `<plan>/<task>`, a task on this chart (task ids: `lattice plan show <plan> --json`).' };
560
+ }
534
561
  if (argv[0] === 'start' && flags.rebind === true && !(typeof flags.reason === 'string' && flags.reason.length > 0)) {
535
562
  return { pointer: '--reason', rule: 'flag_missing',
536
563
  next_action: `--rebind needs --reason <text>: \`${repairedCommand(head, { ...spec, required: [...spec.required, 'reason'] }, flags)}\`.` };
@@ -1068,6 +1095,15 @@ async function mutate({
1068
1095
  return result;
1069
1096
  }
1070
1097
 
1098
+ /** ブロック is the last resort; its result says what to use first (前工程: predecessor, 接続: connect condition). */
1099
+ const BLOCK_GUIDANCE = '待っているものが自分の工程表の工程なら todo predecessor add(前工程)、それ以外で名指しや確認ができるもの(別の工程表の工程、予定表の確認)は'
1100
+ + ' todo connect condition add(他条件に接続)を使う。ブロックは最後の手段(`lattice todo unblock`で外す)。';
1101
+ function withBlockGuidance(result) {
1102
+ const guided = { ...result, next_action: BLOCK_GUIDANCE, result_digest: '' };
1103
+ guided.result_digest = todoSelfDigest(guided, 'result_digest');
1104
+ return guided;
1105
+ }
1106
+
1071
1107
  /** retract-anyone: a reopened task is unstarted again; the redo records a start (from any seat). */
1072
1108
  async function reopenTask({ repoRoot, env, planKey, taskId, payload }) {
1073
1109
  const result = await mutate({ repoRoot, env, planKey, taskId, kind: 'reopen', payload, evidenceRef: null });
@@ -1130,7 +1166,7 @@ async function unchangedTransition(store, { env, planKey, taskId, kind, dropped
1130
1166
  journal_head_digest: events.at(-1).event_digest, snapshot_digest: member.snapshot.snapshot_digest,
1131
1167
  status: state.status, advisory: null, unchanged: true,
1132
1168
  // a18: a repeated transition appends nothing, so say which given content was not recorded.
1133
- ...(notRecorded.length === 0 ? {} : {
1169
+ ...(notRecorded.length === 0 ? (kind === 'block' ? { next_action: BLOCK_GUIDANCE } : {}) : {
1134
1170
  not_recorded: notRecorded,
1135
1171
  next_action: `${planKey}/${state.task_id} ${NOT_RECORDED_NEXT[kind](`--plan ${planKey} --task ${state.task_id}`, notRecorded.join(', '))}`,
1136
1172
  }),
@@ -1412,12 +1448,25 @@ async function displayRead(repoRoot, env) {
1412
1448
  const display = await readTodoStoreForDisplay({ repoRoot });
1413
1449
  const externalTasks = display.store ? (await readTodoExternalTasks(display.store, env)).external_tasks : [];
1414
1450
  return { schema: 'lattice.todo_display_read_result.v1', ...display, external_tasks: externalTasks,
1415
- trees: display.store ? projectTodoTrees(display.store) : [] };
1451
+ trees: display.store ? projectTodoTrees(display.store) : [],
1452
+ connections: display.store ? await displayConnections(repoRoot, { ...display.store, external_tasks: externalTasks }) : [] };
1453
+ }
1454
+
1455
+ /** 接続: `[{plan_key, task_id, connections}]` for every task that has any (the one list: 他条件に接続 and 優先接続). */
1456
+ async function displayConnections(repoRoot, store) {
1457
+ // The display reads unverified members too and must not stop: an unreadable store shows no 接続.
1458
+ try {
1459
+ const full = await withTodoPriorityWaits(store, { repoRoot });
1460
+ const readiness = createTodoReadiness(full);
1461
+ return full.members.flatMap(({ plan }) => (plan.tasks ?? []).map((task) => ({ plan_key: plan.plan_key, task_id: task.task_id,
1462
+ connections: readiness.allConnections(readiness.key({ ...plan, task_id: task.task_id })) })))
1463
+ .filter(({ connections }) => connections.length > 0);
1464
+ } catch { return []; }
1416
1465
  }
1417
1466
 
1418
1467
  /** xchart: the Store plus its external predecessors' states; every readiness reader reads through this. */
1419
1468
  async function readTodoStoreForReadiness({ repoRoot, env = process.env }) {
1420
- return withTodoExternalTasks(await readTodoStore({ repoRoot }), env);
1469
+ return withTodoPriorityWaits(await withTodoExternalTasks(await readTodoStore({ repoRoot }), env), { repoRoot });
1421
1470
  }
1422
1471
 
1423
1472
  async function startTask({
@@ -1530,7 +1579,7 @@ function enforcedStartGate({ advisory, planKey, taskId, overrideReason }) {
1530
1579
  if (advisory.conflicts_with_active.length > 0 && overrideReason === null) {
1531
1580
  const active = advisory.conflicts_with_active.map(({ active_task_id: id }) => id);
1532
1581
  refuse('enforced_conflict_with_active', { conflicts_with_active: advisory.conflicts_with_active,
1533
- next_action: `${taskId} overlaps in-progress ${active.join(', ')}: wait for it with \`lattice todo dependency connect --from-plan ${planKey} --from-task ${active[0]} --to-plan ${planKey} --to-task ${taskId} --reason <text>\`,`
1582
+ next_action: `${taskId} overlaps in-progress ${active.join(', ')}: make it a 前工程 with \`lattice todo predecessor add --plan ${planKey} --task ${taskId} --after ${planKey}/${active[0]} --reason <text>\`,`
1534
1583
  + ` or start anyway with \`lattice todo start --plan ${planKey} --task ${taskId} --override-reason <text>\` (the reason is recorded).` });
1535
1584
  }
1536
1585
  }
@@ -1832,7 +1881,7 @@ async function dependencyRevision({
1832
1881
  applied = await applyPlanRevision({
1833
1882
  repoRoot, env, input: { schema: 'lattice.plan_revise_input.v1', desired },
1834
1883
  notes: [{ task_id: fromTaskId,
1835
- body: `dependency ${operation} ${fromTaskId}→${toTaskId}: ${reason}` }],
1884
+ body: dependencyNoteBody(operation, fromTaskId, toTaskId, reason) }],
1836
1885
  });
1837
1886
  } catch (error) {
1838
1887
  // a18: the new edge closes a cycle; nothing stored is inconsistent, so name the edge and the path.
@@ -1904,7 +1953,7 @@ async function addTask({ repoRoot, env, planKey, flags }) {
1904
1953
  const reason = typeof flags.reason === 'string' ? flags.reason : null;
1905
1954
  const applied = await applyPlanRevision({
1906
1955
  repoRoot, env, input: { schema: 'lattice.plan_revise_input.v1', desired },
1907
- notes: [{ task_id: taskId, body: `todo add ${taskId}${reason === null ? '' : `: ${reason}`}` }],
1956
+ notes: [{ task_id: taskId, body: todoAddNoteBody(taskId, reason) }],
1908
1957
  });
1909
1958
  const result = {
1910
1959
  schema: 'lattice.todo_task_add_result.v1', project_id: store.project_id, plan_key: planKey,
@@ -2138,6 +2187,148 @@ async function dependencyDisconnectLedger({
2138
2187
  return result;
2139
2188
  }
2140
2189
 
2190
+ /** `dependency connect|disconnect` is an alias for one minor version: each run says which of the two commands replaces it. */
2191
+ function retiredDependencyCommand(stderr, operation, flags, result) {
2192
+ const edge = `--plan ${flags['to-plan']} --task ${flags['to-task']}`;
2193
+ const use = flags['from-project'] === undefined
2194
+ ? `lattice todo predecessor ${operation} ${edge} --after ${flags['from-plan']}/${flags['from-task']} --reason <text>`
2195
+ : `lattice todo connect condition ${operation} ${edge} --to task:${flags['from-project']}/${flags['from-plan']}/${flags['from-task']} --reason <text>`;
2196
+ stderr.write(`${JSON.stringify({ schema: 'lattice.todo_command_retired.v1', command: `todo dependency ${operation === 'add' ? 'connect' : 'disconnect'}`,
2197
+ still_works_until: 'the next minor version', use })}\n`);
2198
+ return result;
2199
+ }
2200
+
2201
+ // 前工程 (`todo predecessor`) and 他条件に接続 (`todo connect condition`) are two commands with disjoint targets
2202
+ // ([connect flow](../docs/architecture/dfd-connect.md)): each refuses the other's target and names the right command.
2203
+
2204
+ /** `<plan>/<task>` (this chart); `<project>/<plan>/<task>` or a `task:`/`schedule:` target are another chart or a schedule. */
2205
+ function parsePredecessorTarget(text, projectId) {
2206
+ if (typeof text !== 'string') return null;
2207
+ if (/^schedule:/u.test(text)) return { sameChart: false };
2208
+ const parts = text.replace(/^task:/u, '').split('/');
2209
+ if (parts.length < 2 || parts.length > 3 || !parts.every(isTodoIdentifier)) return null;
2210
+ const [owner, planKey, taskId] = parts.length === 3 ? parts : [projectId, ...parts];
2211
+ return { sameChart: owner === projectId, projectId: owner, planKey, taskId };
2212
+ }
2213
+
2214
+ /** `task:<project>/<plan>/<task>` or `schedule:<id>` (id: printable ASCII, no spaces, <= 128). null when malformed (exit 2, pointer --to). */
2215
+ function parseConditionTarget(text, projectId) {
2216
+ if (typeof text !== 'string') return null;
2217
+ if (text.startsWith('schedule:')) {
2218
+ const id = text.slice('schedule:'.length);
2219
+ return /^[!-~]{1,128}$/u.test(id) ? { kind: 'schedule', id, ref: id } : null;
2220
+ }
2221
+ const parts = text.startsWith('task:') ? text.slice('task:'.length).split('/') : [];
2222
+ if (parts.length !== 3 || !parts.every(isTodoIdentifier)) return null;
2223
+ const [owner, planKey, taskId] = parts;
2224
+ return { kind: 'task', projectId: owner, planKey, taskId, ref: `${owner}/${planKey}/${taskId}`, sameChart: owner === projectId };
2225
+ }
2226
+
2227
+ async function predecessorChange({ repoRoot, env, operation, planKey, taskId, after, reason }) {
2228
+ const store = await readTodoStore({ repoRoot });
2229
+ const target = parsePredecessorTarget(after, store.project_id);
2230
+ if (target === null) {
2231
+ throw new TodoStoreError('DEPENDENCY_INVALID', 'predecessor_target_invalid', undefined, {
2232
+ after, next_action: 'Name the 前工程 as `<plan>/<task>`, a task on this chart (task ids: `lattice plan show <plan> --json`).' });
2233
+ }
2234
+ if (!target.sameChart) {
2235
+ throw new TodoStoreError('CONNECTION_INVALID', 'predecessor_target_not_same_chart', undefined, {
2236
+ after,
2237
+ next_action: `${after} is not a task on this chart, so it is a 接続, not a 前工程: \`lattice todo connect condition ${operation}`
2238
+ + ` --plan ${planKey} --task ${taskId} --to ${/^(task|schedule):/u.test(after) ? after : `task:${after}`} --reason <text>\`.`,
2239
+ });
2240
+ }
2241
+ const options = {
2242
+ repoRoot, env, fromProjectId: null, fromPlanKey: target.planKey, fromTaskId: target.taskId,
2243
+ toPlanKey: planKey, toTaskId: taskId, reason,
2244
+ };
2245
+ return operation === 'add' ? dependencyConnect(options) : dependencyDisconnect(options);
2246
+ }
2247
+
2248
+ function connectionResult(store, { operation, planKey, taskId, target, event = null, unchanged = false, reason = null, evidence = null, next_action = null }) {
2249
+ const result = {
2250
+ schema: unchanged ? 'lattice.todo_connection_unchanged_result.v1' : 'lattice.todo_connection_result.v1',
2251
+ project_id: store.project_id, operation, plan_key: planKey, task_id: taskId,
2252
+ to: { kind: target.kind, ref: target.ref },
2253
+ ...(reason === null ? {} : { reason }), ...(evidence === null ? {} : { evidence }),
2254
+ ...(event === null ? { unchanged: true } : {
2255
+ event_digest: event.event_digest, recorded_at: event.recorded_at, actor: event.actor }),
2256
+ next_action,
2257
+ result_digest: '',
2258
+ };
2259
+ result.result_digest = todoSelfDigest(result, 'result_digest');
2260
+ return result;
2261
+ }
2262
+
2263
+ /** Whether this plan's chain ever recorded a cross-chart edge to the target (a removed edge is not listed; a retried remove stays safe). */
2264
+ function everConnected(member, taskId, target) {
2265
+ return (member.plan_scoped?.events ?? []).some((event) => event.kind === 'cross_plan_dependency'
2266
+ && event.payload?.to?.task_id === taskId && event.payload?.from?.project_id === target.projectId
2267
+ && event.payload?.from?.plan_key === target.planKey && event.payload?.from?.task_id === target.taskId);
2268
+ }
2269
+
2270
+ /**
2271
+ * `todo connect condition add|remove|resolve`: a task on another chart, or a BellTeam schedule, as a 接続.
2272
+ * Every write is idempotent (a retry after an unknown outcome is safe): add of an open identical 接続, resolve of a
2273
+ * settled one and remove with nothing open answer `unchanged: true`; only a target never added is refused.
2274
+ */
2275
+ async function connectCondition({ repoRoot, env, operation, planKey, taskId, to, reason = null, message = null }) {
2276
+ const store = await readTodoStoreForReadiness({ repoRoot, env });
2277
+ const target = parseConditionTarget(to, store.project_id);
2278
+ const refuse = (code, why, detail) => new TodoStoreError(code, why, undefined, { to, ...detail });
2279
+ if (target.kind === 'task' && target.sameChart) {
2280
+ throw refuse('CONNECTION_INVALID', 'condition_target_same_chart', {
2281
+ next_action: `${target.planKey}/${target.taskId} is on this chart, so it is a 前工程, not a 接続: \`lattice todo predecessor ${operation === 'remove' ? 'remove' : 'add'}`
2282
+ + ` --plan ${planKey} --task ${taskId} --after ${target.planKey}/${target.taskId} --reason <text>\`.` });
2283
+ }
2284
+ const member = store.members.find(({ plan }) => plan.plan_key === planKey);
2285
+ if (member === undefined) throw new TodoStoreError('STORE_INCONSISTENT', 'plan_not_active', undefined, { plan_key: planKey });
2286
+ if (!member.plan.tasks.some(({ task_id: id }) => id === taskId)) {
2287
+ throw new TodoStoreError('TASK_NOT_FOUND', 'task_not_found', undefined, { requested_task_id: taskId });
2288
+ }
2289
+ const base = { operation, planKey, taskId, target };
2290
+ const addAgain = `lattice todo connect condition add --plan ${planKey} --task ${taskId} --to ${to} --reason <text>`;
2291
+ const notFound = () => refuse('CONNECTION_INVALID', 'connection_not_found', {
2292
+ next_action: `${planKey}/${taskId} has no 接続 to ${to}; add it with \`${addAgain}\` (list them with \`lattice todo show --plan ${planKey} --task ${taskId} --json\`, prerequisites.connections).` });
2293
+ if (target.kind === 'task') {
2294
+ if (operation === 'resolve') {
2295
+ throw refuse('CONNECTION_INVALID', 'condition_task_target_settles_itself', {
2296
+ next_action: `A 接続 to a task settles when ${target.ref} is done or retired; only \`schedule:<id>\` is resolved by hand.` });
2297
+ }
2298
+ const edge = { repoRoot, env, fromProjectId: target.projectId, fromPlanKey: target.planKey, fromTaskId: target.taskId,
2299
+ toPlanKey: planKey, toTaskId: taskId, reason };
2300
+ if (operation === 'add') return dependencyConnect(edge);
2301
+ try {
2302
+ return await dependencyDisconnect(edge);
2303
+ } catch (error) {
2304
+ if (error?.code !== 'DEPENDENCY_NOT_FOUND') throw error;
2305
+ if (!everConnected(member, taskId, target)) throw notFound();
2306
+ return connectionResult(store, { ...base, unchanged: true, next_action: `${to} is already removed; nothing was recorded.` });
2307
+ }
2308
+ }
2309
+ // Store is idempotent (appendTodoEvent answers `unchanged`), so no pre-check; the newest entry for this ref names the target.
2310
+ const shown = listTodoConnections(store, planKey, taskId, { includeRemoved: true })
2311
+ .filter((entry) => entry.kind === 'schedule' && entry.ref === target.id)
2312
+ .sort((left, right) => (left.since < right.since ? 1 : left.since > right.since ? -1 : 0))[0] ?? null;
2313
+ if (operation !== 'add' && shown === null) throw notFound();
2314
+ const event = {
2315
+ add: { kind: 'connection_added', payload: { task_id: taskId, to: { kind: 'schedule', id: target.id }, reason } },
2316
+ remove: { kind: 'connection_removed', payload: { target_event_digest: shown?.event_digest, reason } },
2317
+ resolve: { kind: 'connection_resolved', payload: { target_event_digest: shown?.event_digest, evidence: message } },
2318
+ }[operation];
2319
+ const recorded = await appendTodoEvent({
2320
+ validateProspectiveEvent, repoRoot, writer: createTodoStoreWriter({ caller: 'g5-authoring' }), planKey,
2321
+ event: { ...event, actor: resolveTodoActor(env) },
2322
+ });
2323
+ if (recorded.unchanged === true) {
2324
+ return connectionResult(store, { ...base, unchanged: true, next_action: `${to} is already ${{ add: 'connected', remove: 'removed', resolve: 'settled' }[operation]}; nothing was recorded.` });
2325
+ }
2326
+ return connectionResult(store, { ...base, event: recorded.event, reason, evidence: message,
2327
+ next_action: operation === 'add'
2328
+ ? `${planKey}/${taskId} cannot start until ${to} settles; the schedule's command settles it with \`lattice todo connect condition resolve\`.`
2329
+ : null });
2330
+ }
2331
+
2141
2332
  async function phaseStatus({ repoRoot, planKey }) {
2142
2333
  const store = await readTodoStore({ repoRoot });
2143
2334
  const [member] = selectMembers(store, planKey);
@@ -2789,7 +2980,8 @@ function taskPrerequisites(store, member, taskId) {
2789
2980
  const key = readiness.key({ ...member.plan, task_id: taskId });
2790
2981
  const { blocking } = readiness.prerequisites(key);
2791
2982
  return { ready: readiness.isReady(key), tasks: readiness.prerequisiteRefs(key).tasks,
2792
- blocking_tasks: blocking.blocking_tasks ?? [], blocking_phases: blocking.blocking_phases ?? [] };
2983
+ blocking_tasks: blocking.blocking_tasks ?? [], blocking_phases: blocking.blocking_phases ?? [],
2984
+ connections: readiness.allConnections(key) };
2793
2985
  }
2794
2986
 
2795
2987
  /**
@@ -4579,6 +4771,11 @@ export async function renderTodoGanttForProject({
4579
4771
  topology_digest: member.plan.topology_digest,
4580
4772
  journal_head_digest: member.journal.events.at(-1)?.event_digest ?? null,
4581
4773
  }));
4774
+ // One 接続 area per task: 他条件に接続 and 優先接続 from the single `connections` list (Store: listTodoConnections).
4775
+ const connections = store.members.flatMap(({ plan }) => plan.tasks.map(({ task_id: taskId }) => ({
4776
+ project_id: plan.project_id, plan_key: plan.plan_key, task_id: taskId,
4777
+ connections: listTodoConnections(store, plan.plan_key, taskId),
4778
+ }))).filter((entry) => entry.connections.length > 0);
4582
4779
  const metadata = {
4583
4780
  manifest_digest: store.manifest.manifest_digest,
4584
4781
  member_bindings: memberBindings,
@@ -4586,6 +4783,7 @@ export async function renderTodoGanttForProject({
4586
4783
  presentation_digest: presentation?.presentation_digest ?? null,
4587
4784
  layout_digest: digestTodoArtifact(layout),
4588
4785
  note_bindings_digest: digestTodoArtifact(notes.headBindings),
4786
+ connections_digest: digestTodoArtifact(connections),
4589
4787
  structure_projection_digest: structures?.projection_digest ?? null,
4590
4788
  renderer_version: TODO_GANTT_RENDERER_VERSION,
4591
4789
  project_display_name: identity.displayName,
@@ -4603,6 +4801,7 @@ export async function renderTodoGanttForProject({
4603
4801
  noteWarnings: notes.warnings,
4604
4802
  structurePresentation: structures,
4605
4803
  notices,
4804
+ connections,
4606
4805
  });
4607
4806
  return { store, metadata, memberBindings, rendered };
4608
4807
  }
@@ -4750,6 +4949,8 @@ function writesTodoStore(argv) {
4750
4949
  case 'seam-proposal': return ['compile', 'apply', 'land'].includes(second);
4751
4950
  case 'evidence': return second === 'promote';
4752
4951
  case 'dependency': return ['connect', 'disconnect'].includes(second);
4952
+ case 'predecessor': return ['add', 'remove'].includes(second);
4953
+ case 'connect': return second === 'condition' && ['add', 'remove', 'resolve'].includes(argv[2]);
4753
4954
  case 'phase': return second !== 'status';
4754
4955
  case 'start': case 'retract': case 'block': case 'unblock': case 'retire': case 'done':
4755
4956
  case 'reopen': case 'split': case 'revise': case 'revise-phase': case 'revise-set': case 'add':
@@ -4763,7 +4964,9 @@ function releasesTasks(argv) {
4763
4964
  const [command, second] = argv;
4764
4965
  return ['done', 'retire', 'unblock'].includes(command)
4765
4966
  || (command === 'phase' && ['accept', 'close-unaudited'].includes(second))
4766
- || (command === 'dependency' && second === 'disconnect');
4967
+ || (command === 'dependency' && second === 'disconnect')
4968
+ || (command === 'predecessor' && second === 'remove')
4969
+ || (command === 'connect' && second === 'condition' && ['remove', 'resolve'].includes(argv[2]));
4767
4970
  }
4768
4971
 
4769
4972
  /** `declared(planKey, taskId)`: whether an enforced plan's witness set records the task's row (unreadable = none). */
@@ -4933,10 +5136,10 @@ async function noticeAck({ repoRoot, env, lane, ids }) {
4933
5136
  }
4934
5137
 
4935
5138
  /**
4936
- * `todo wait` (wait-design): record that this agent stopped work and waits for T to become startable. A record, never a
4937
- * gate: an already startable or finished T is answered with a state and nothing is written.
5139
+ * `todo connect priority` (優先接続; `todo wait` is its alias for one minor version): record that this agent asks to be told the
5140
+ * moment T can start. A record, never a gate: an already startable or finished T is answered with a state and nothing is written.
4938
5141
  */
4939
- async function noticeWait({ repoRoot, env, planKey, taskId, reason, cancel }) {
5142
+ async function noticePriority({ repoRoot, env, planKey, taskId, reason, cancel }) {
4940
5143
  const view = await openNoticeView(repoRoot, env);
4941
5144
  const { store } = view;
4942
5145
  const member = store.members.find(({ plan }) => plan.plan_key === planKey);
@@ -4946,7 +5149,7 @@ async function noticeWait({ repoRoot, env, planKey, taskId, reason, cancel }) {
4946
5149
  throw new TodoStoreError('TASK_NOT_FOUND', 'task_not_found', undefined, { requested_task_id: taskId });
4947
5150
  }
4948
5151
  const { agent } = resolveTodoActor(env);
4949
- const base = { schema: 'lattice.todo_wait_result.v1', project_id: store.project_id, plan_key: planKey, task_id: taskId, agent };
5152
+ const base = { schema: 'lattice.todo_connect_priority_result.v1', project_id: store.project_id, plan_key: planKey, task_id: taskId, agent };
4950
5153
  let rest;
4951
5154
  if (cancel) {
4952
5155
  const { cancelled } = await cancelTodoNoticeWait({ repoRoot, planKey, taskId, agent });
@@ -4966,7 +5169,7 @@ async function noticeWait({ repoRoot, env, planKey, taskId, reason, cancel }) {
4966
5169
  repoRoot, planKey, taskId, agent, reason: reason ?? null, now,
4967
5170
  keep: (wait) => waitInEffect(store, { plan_key: planKey, ...wait }),
4968
5171
  });
4969
- rest = { state: 'waiting', since, reason: reason ?? null, notice: null, next_action: null };
5172
+ rest = { state: 'prioritized', since, reason: reason ?? null, notice: null, next_action: null };
4970
5173
  }
4971
5174
  }
4972
5175
  const result = { ...base, ...rest, result_digest: '' };
@@ -5371,13 +5574,22 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5371
5574
  }
5372
5575
  } else if (argv[0] === 'blockers' && matchFlagCommand(argv, ['blockers'], TODO_FLAG_SPECS.blockers) !== null) {
5373
5576
  action = (repoRoot) => blockerList({ repoRoot });
5374
- } else if (argv[0] === 'wait' && matchFlagCommand(argv, ['wait'], TODO_FLAG_SPECS.wait) !== null) {
5375
- const flags = matchFlagCommand(argv, ['wait'], TODO_FLAG_SPECS.wait);
5577
+ } else if ((argv[0] === 'connect' && argv[1] === 'priority' || argv[0] === 'wait')
5578
+ && matchFlagCommand(argv, argv[0] === 'wait' ? ['wait'] : ['connect', 'priority'], TODO_FLAG_SPECS[argv[0] === 'wait' ? 'wait' : 'connect priority']) !== null) {
5579
+ const flags = matchFlagCommand(argv, argv[0] === 'wait' ? ['wait'] : ['connect', 'priority'], TODO_FLAG_SPECS[argv[0] === 'wait' ? 'wait' : 'connect priority']);
5376
5580
  const reasonOk = flags.reason === undefined
5377
5581
  || (typeof flags.reason === 'string' && flags.reason.length > 0 && flags.reason.length <= 1024 && !/\p{Cc}/u.test(flags.reason));
5378
5582
  if (isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task) && reasonOk && !(flags.cancel === true && flags.reason !== undefined)) {
5379
- action = (repoRoot) => noticeWait({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
5380
- reason: flags.reason ?? null, cancel: flags.cancel === true });
5583
+ action = async (repoRoot) => {
5584
+ const result = await noticePriority({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
5585
+ reason: flags.reason ?? null, cancel: flags.cancel === true });
5586
+ if (argv[0] === 'wait') {
5587
+ stderr.write(`${JSON.stringify({ schema: 'lattice.todo_command_retired.v1', command: 'todo wait',
5588
+ still_works_until: 'the next minor version',
5589
+ use: `lattice todo connect priority --plan ${flags.plan} --task ${flags.task}${flags.cancel === true ? ' --cancel' : ''}` })}\n`);
5590
+ }
5591
+ return result;
5592
+ };
5381
5593
  }
5382
5594
  } else if (argv[0] === 'note' && argv[1] === 'list' && readFlags(argv, ['note', 'list']) !== null) {
5383
5595
  const flags = readFlags(argv, ['note', 'list']);
@@ -5393,20 +5605,34 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5393
5605
  repoRoot, env, planKey: flags.plan, mode: flags.set, reason: flags.reason,
5394
5606
  });
5395
5607
  }
5608
+ } else if (argv[0] === 'predecessor' && ['add', 'remove'].includes(argv[1])
5609
+ && matchFlagCommand(argv, argv.slice(0, 2), PREDECESSOR_FLAG_SPEC) !== null
5610
+ && parsePredecessorTarget(matchFlagCommand(argv, argv.slice(0, 2), PREDECESSOR_FLAG_SPEC).after, '') !== null
5611
+ && ['plan', 'task'].every((name) => isTodoIdentifier(matchFlagCommand(argv, argv.slice(0, 2), PREDECESSOR_FLAG_SPEC)[name]))) {
5612
+ const flags = matchFlagCommand(argv, argv.slice(0, 2), PREDECESSOR_FLAG_SPEC);
5613
+ action = (repoRoot) => predecessorChange({ repoRoot, env, operation: argv[1], planKey: flags.plan, taskId: flags.task,
5614
+ after: flags.after, reason: flags.reason });
5615
+ } else if (argv[0] === 'connect' && argv[1] === 'condition' && ['add', 'remove', 'resolve'].includes(argv[2])
5616
+ && parseConditionTarget(matchFlagCommand(argv, argv.slice(0, 3), TODO_FLAG_SPECS[argv.slice(0, 3).join(' ')])?.to, '') !== null
5617
+ && matchFlagCommand(argv, argv.slice(0, 3), TODO_FLAG_SPECS[argv.slice(0, 3).join(' ')]) !== null
5618
+ && ['plan', 'task'].every((name) => isTodoIdentifier(matchFlagCommand(argv, argv.slice(0, 3), TODO_FLAG_SPECS[argv.slice(0, 3).join(' ')])[name]))) {
5619
+ const flags = matchFlagCommand(argv, argv.slice(0, 3), TODO_FLAG_SPECS[argv.slice(0, 3).join(' ')]);
5620
+ action = (repoRoot) => connectCondition({ repoRoot, env, operation: argv[2], planKey: flags.plan, taskId: flags.task,
5621
+ to: flags.to, reason: flags.reason ?? null, message: flags.message ?? null });
5396
5622
  } else if (argv[0] === 'dependency' && argv[1] === 'connect'
5397
5623
  && dependencyFlags(argv) !== null) {
5398
5624
  const flags = dependencyFlags(argv);
5399
- action = (repoRoot) => dependencyConnect({
5625
+ action = async (repoRoot) => retiredDependencyCommand(stderr, 'add', flags, await dependencyConnect({
5400
5626
  repoRoot, env, fromProjectId: flags['from-project'] ?? null, fromPlanKey: flags['from-plan'], fromTaskId: flags['from-task'],
5401
5627
  toPlanKey: flags['to-plan'], toTaskId: flags['to-task'], reason: flags.reason,
5402
- });
5628
+ }));
5403
5629
  } else if (argv[0] === 'dependency' && argv[1] === 'disconnect'
5404
5630
  && dependencyFlags(argv) !== null) {
5405
5631
  const flags = dependencyFlags(argv);
5406
- action = (repoRoot) => dependencyDisconnect({
5632
+ action = async (repoRoot) => retiredDependencyCommand(stderr, 'remove', flags, await dependencyDisconnect({
5407
5633
  repoRoot, env, fromProjectId: flags['from-project'] ?? null, fromPlanKey: flags['from-plan'], fromTaskId: flags['from-task'],
5408
5634
  toPlanKey: flags['to-plan'], toTaskId: flags['to-task'], reason: flags.reason,
5409
- });
5635
+ }));
5410
5636
  } else if (argv[0] === 'independence' && argv[1] === 'compile') {
5411
5637
  const flags = matchFlagCommand(argv, ['independence', 'compile'], TODO_FLAG_SPECS['independence compile']);
5412
5638
  if (flags !== null && isTodoIdentifier(flags.plan) && isAuthoringPathToken(flags.input)) {
@@ -5670,10 +5896,10 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5670
5896
  const flags = matchFlagCommand(argv, ['block'], TODO_FLAG_SPECS.block);
5671
5897
  if (flags !== null && isTodoIdentifier(flags.plan) && isTodoIdentifier(flags.task)) {
5672
5898
  action = (repoRoot) => mutateUnlessUnchanged({ repoRoot, env, planKey: flags.plan, taskId: flags.task,
5673
- kind: 'block', dropped: reasonDropped(flags.reason), action: () => mutate({
5899
+ kind: 'block', dropped: reasonDropped(flags.reason), action: async () => withBlockGuidance(await mutate({
5674
5900
  repoRoot, env, planKey: flags.plan, taskId: flags.task,
5675
5901
  kind: 'block', payload: { reason: flags.reason }, evidenceRef: null,
5676
- }) });
5902
+ })) });
5677
5903
  }
5678
5904
  } else if (argv[0] === 'add') {
5679
5905
  const flags = matchFlagCommand(argv, ['add'], TODO_FLAG_SPECS.add);