@quolu/lattice 0.114.4 → 0.116.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.
@@ -9,6 +9,7 @@ import { renamePublishedFile, syncPublishedFile } from './fs-publish.mjs';
9
9
  import { normalizeCheckoutEol } from './todo-store-view.mjs';
10
10
  import { memoByFileIdentity } from './todo-version-memo.mjs';
11
11
  import { TODO_VERSION_COMPACT_FILE, readVersionCompact } from './todo-version-compact.mjs';
12
+ import { publishDerivedPlanCache, readDerivedPlanCache } from './todo-store.mjs';
12
13
 
13
14
  import {
14
15
  TODO_LIMITS,
@@ -338,50 +339,83 @@ function noteProjectionEntry(event, supersededBy) {
338
339
  };
339
340
  }
340
341
 
341
- function migrationIndex(migrations) {
342
+ /**
343
+ * One migration's entries that change a task, `[from, to | null]` (null: removed). A migration lists every task of its
344
+ * predecessor (the writer refuses an incomplete one: predecessor_task_migration_incomplete), so an entry that keeps the id
345
+ * says nothing and is left out; this is what keeps the lineage small on a plan with thousands of tasks and versions.
346
+ */
347
+ function changedTaskMoves(taskMigration, planVersion) {
348
+ const seen = new Set();
349
+ const moves = [];
350
+ for (const entry of taskMigration) {
351
+ const to = entry?.to_task_id === 'removed' ? null : entry?.to_task_id;
352
+ if (!isTodoIdentifier(entry?.from_task_id) || !(to === null || isTodoIdentifier(to)) || seen.has(entry.from_task_id)) {
353
+ fail('NOTE_PROJECTION_INVALID', 'note_task_migration_invalid', { plan_version: planVersion });
354
+ }
355
+ seen.add(entry.from_task_id);
356
+ if (to !== entry.from_task_id) moves.push([entry.from_task_id, to]);
357
+ }
358
+ return moves;
359
+ }
360
+
361
+ /**
362
+ * w2-impl: where a note's origin (plan version, task) ends up at the head, without walking every later version per note.
363
+ * `versions` runs from the oldest version to the head along the predecessor chain; `moves` are `[index, from, to | null]`:
364
+ * the migration from versions[index] to versions[index + 1] renamed or removed `from`, in ascending index order.
365
+ */
366
+ class NoteLineage {
367
+ constructor(versions, moves) {
368
+ this.versions = versions;
369
+ this.positions = new Map(versions.map((version, index) => [version, index]));
370
+ this.moves = new Map();
371
+ for (const [index, from, to] of moves) {
372
+ if (!this.moves.has(from)) this.moves.set(from, []);
373
+ this.moves.get(from).push([index, to]);
374
+ }
375
+ }
376
+
377
+ /** The head task id that `taskId` of `version` became (callers check it is still in the plan), or null: removed, or a version off the chain. */
378
+ resolve(version, taskId) {
379
+ let index = this.positions.get(version);
380
+ if (index === undefined) return null;
381
+ for (let task = taskId; ;) {
382
+ // shortcut: linear in the task's own moves (a few), upgrade if one task is renamed thousands of times
383
+ const move = this.moves.get(task)?.find(([at]) => at >= index);
384
+ if (move === undefined) return task;
385
+ if (move[1] === null) return null;
386
+ [index, task] = [move[0] + 1, move[1]];
387
+ }
388
+ }
389
+ }
390
+
391
+ /** The lineage of a hand-made migration list (the pure projector's input): its chain ending at `head`; versions off that chain resolve to null. */
392
+ function lineageFromMigrations(migrations, head) {
342
393
  if (!Array.isArray(migrations)) throw new TypeError('todo note migrations must be an array');
343
- const index = new Map();
394
+ const byTo = new Map();
395
+ const froms = new Set();
344
396
  for (const migration of migrations) {
345
397
  if (!exactRecord(migration, ['from_plan_version', 'to_plan_version', 'task_migration'])
346
398
  || !isTodoIdentifier(migration.from_plan_version)
347
399
  || !isTodoIdentifier(migration.to_plan_version)
348
400
  || migration.from_plan_version === migration.to_plan_version
349
401
  || !Array.isArray(migration.task_migration)
350
- || index.has(migration.from_plan_version)) {
402
+ || froms.has(migration.from_plan_version) || byTo.has(migration.to_plan_version)) {
351
403
  fail('NOTE_PROJECTION_INVALID', 'note_migration_history_invalid');
352
404
  }
353
- const taskMap = new Map();
354
- for (const entry of migration.task_migration) {
355
- if (!exactRecord(entry, ['from_task_id', 'to_task_id'])
356
- || !isTodoIdentifier(entry.from_task_id)
357
- || !(entry.to_task_id === null || isTodoIdentifier(entry.to_task_id))
358
- || taskMap.has(entry.from_task_id)) {
359
- fail('NOTE_PROJECTION_INVALID', 'note_task_migration_invalid');
360
- }
361
- taskMap.set(entry.from_task_id, entry.to_task_id === 'removed' ? null : entry.to_task_id);
362
- }
363
- index.set(migration.from_plan_version, {
364
- toPlanVersion: migration.to_plan_version, taskMap,
365
- });
405
+ froms.add(migration.from_plan_version);
406
+ byTo.set(migration.to_plan_version, { from: migration.from_plan_version,
407
+ moves: changedTaskMoves(migration.task_migration, migration.to_plan_version) });
366
408
  }
367
- return index;
368
- }
369
-
370
- function resolveNoteTarget(event, { currentPlanVersion, currentTaskIds, migrations }) {
371
- let version = event.plan_version;
372
- let taskId = event.task_id;
373
- const seen = new Set();
374
- while (version !== currentPlanVersion) {
375
- if (seen.has(version)) fail('NOTE_PROJECTION_INVALID', 'note_migration_cycle');
376
- seen.add(version);
377
- const step = migrations.get(version);
378
- if (step === undefined) return { kind: 'archived' };
379
- const nextTaskId = step.taskMap.get(taskId);
380
- if (nextTaskId === undefined || nextTaskId === null) return { kind: 'archived' };
381
- version = step.toPlanVersion;
382
- taskId = nextTaskId;
409
+ const versions = [head];
410
+ const steps = [];
411
+ for (let version = head; byTo.has(version);) {
412
+ const step = byTo.get(version);
413
+ if (versions.includes(step.from)) fail('NOTE_PROJECTION_INVALID', 'note_migration_cycle');
414
+ versions.unshift(step.from);
415
+ steps.unshift(step.moves);
416
+ version = step.from;
383
417
  }
384
- return currentTaskIds.has(taskId) ? { kind: 'active', taskId } : { kind: 'archived' };
418
+ return new NoteLineage(versions, steps.flatMap((moves, index) => moves.map(([from, to]) => [index, from, to])));
385
419
  }
386
420
 
387
421
  /**
@@ -401,7 +435,8 @@ export function projectTodoNoteContext(options = {}) {
401
435
  throw new TypeError('todo note projection options invalid');
402
436
  }
403
437
  const currentTaskIds = new Set(options.currentTaskIds);
404
- const migrations = migrationIndex(options.migrations);
438
+ const lineage = options.migrations instanceof NoteLineage
439
+ ? options.migrations : lineageFromMigrations(options.migrations, options.currentPlanVersion);
405
440
  // 訂正はscopeを跨げないので、supersedeの追跡もchainごとに閉じる。
406
441
  const supersededBy = new Map();
407
442
  for (const event of [...options.events, ...options.planEvents]) {
@@ -418,11 +453,9 @@ export function projectTodoNoteContext(options = {}) {
418
453
  const planSequence = sequenceOf(options.planEvents);
419
454
  for (const event of options.events) {
420
455
  const entry = noteProjectionEntry(event, supersededBy.get(event.event_digest));
421
- const target = resolveNoteTarget(event, {
422
- currentPlanVersion: options.currentPlanVersion, currentTaskIds, migrations,
423
- });
424
- if (target.kind === 'archived') archived.push(entry);
425
- else if (target.taskId === options.currentTaskId) taskCurrent.push(entry);
456
+ const target = lineage.resolve(event.plan_version, event.task_id);
457
+ if (target === null || !currentTaskIds.has(target)) archived.push(entry);
458
+ else if (target === options.currentTaskId) taskCurrent.push(entry);
426
459
  }
427
460
  // plan noteは特定のtaskに属さないので、task migrationで宛先を失うことがない。全taskの
428
461
  // contextへ載せる——工程レベルの義務は「次に着手する誰か」へ届くべきもので、誰が着手するかは
@@ -498,80 +531,125 @@ async function readCanonicalJson(ref, { missing = false } = {}) {
498
531
  return value;
499
532
  }
500
533
 
501
- async function readNoteMigrations(repoRoot, planKey, eventVersions) {
502
- const base = path.resolve(repoRoot, '.lattice/todo/plans', planKey);
503
- let entries;
504
- try { entries = await readdir(base, { withFileTypes: true }); }
505
- catch (error) {
506
- if (error?.code === 'ENOENT' && eventVersions.size === 0) return [];
507
- fail('NOTE_PROJECTION_INVALID', 'note_plan_history_unreadable', { plan_key: planKey });
508
- }
509
- const versions = new Set();
510
- const migrations = [];
511
- for (const entry of entries) {
512
- if (!entry.isDirectory() || !isTodoIdentifier(entry.name)) {
513
- fail('NOTE_PROJECTION_INVALID', 'note_plan_history_inventory_invalid', { plan_key: planKey });
514
- }
515
- const versionRoot = path.join(base, entry.name);
516
- const planPath = path.join(versionRoot, 'plan.json');
517
- const revisionPath = path.join(versionRoot, 'revision.json');
518
- const compactPath = path.join(versionRoot, TODO_VERSION_COMPACT_FILE);
519
- // perf-store: validated once per process while the files are unchanged (todo-version-memo).
520
- const version = await memoByFileIdentity([planPath, revisionPath, compactPath], async () => {
521
- // b10: a superseded version keeps compact.json.gz (its revision, minus the plan it repeats) instead of plan.json/revision.json.
522
- const compact = await readVersionCompact(versionRoot, undefined, { verify: false }).catch(() => fail('NOTE_PROJECTION_INVALID',
523
- 'note_historical_plan_invalid', { plan_version: entry.name }));
524
- if (compact !== null) {
525
- if (compact.plan_key !== planKey || compact.plan_version !== entry.name) {
526
- fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: entry.name });
527
- }
528
- const migration = compact.revision?.task_migration;
529
- if (compact.revision === null) return { migration: null };
530
- if (compact.predecessor_plan_version === null || !Array.isArray(migration)) {
531
- fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: entry.name });
532
- }
533
- return { migration: { from_plan_version: compact.predecessor_plan_version, to_plan_version: entry.name,
534
- task_migration: migration.map(({ from_task_id: fromTaskId, to_task_id: toTaskId }) => ({
535
- from_task_id: fromTaskId, to_task_id: toTaskId })) } };
536
- }
537
- // A revision directory is published before manifest activation. A crash during
538
- // that window can leave an unreferenced directory containing only a journal
539
- // stub. It is not a historical plan until its canonical plan artifact exists.
540
- // Do not make that unreachable residue poison note projection; if a note event
541
- // names this version, the origin-version check below still fails closed.
542
- const plan = await readCanonicalJson(planPath, { missing: true });
543
- if (plan === null) return null;
544
- if (!validateTodoPlan(plan) || plan.plan_key !== planKey || plan.plan_version !== entry.name) {
545
- fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: entry.name });
534
+ /**
535
+ * One retained version as the lineage needs it: `{predecessor, moves}` (its predecessor's version name, null for the first
536
+ * version, and `changedTaskMoves` of the migration into it), or null when the version does not exist.
537
+ */
538
+ function readVersionMigration(base, name, planKey) {
539
+ const versionRoot = path.join(base, name);
540
+ const planPath = path.join(versionRoot, 'plan.json');
541
+ const revisionPath = path.join(versionRoot, 'revision.json');
542
+ const compactPath = path.join(versionRoot, TODO_VERSION_COMPACT_FILE);
543
+ // perf-store: validated once per process while the files are unchanged (todo-version-memo). w2: the memo holds only the
544
+ // moves, not the whole 3,321-entry task_migration (that array times 4,204 versions was the 1.6 GB).
545
+ return memoByFileIdentity([planPath, revisionPath, compactPath], async () => {
546
+ const record = (predecessor, taskMigration) => {
547
+ if (predecessor === name) fail('NOTE_PROJECTION_INVALID', 'note_migration_history_invalid');
548
+ return { predecessor, moves: changedTaskMoves(taskMigration, name) };
549
+ };
550
+ // b10: a superseded version keeps compact.json.gz (its revision, minus the plan it repeats) instead of plan.json/revision.json.
551
+ const compact = await readVersionCompact(versionRoot, undefined, { verify: false }).catch(() => fail('NOTE_PROJECTION_INVALID',
552
+ 'note_historical_plan_invalid', { plan_version: name }));
553
+ if (compact !== null) {
554
+ if (compact.plan_key !== planKey || compact.plan_version !== name) {
555
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: name });
546
556
  }
547
- const revision = await readCanonicalJson(revisionPath, { missing: true });
548
- if (revision === null) return { migration: null };
549
- if (!(validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
550
- || revision.plan_key !== planKey || revision.predecessor?.plan_version === undefined
551
- || !Array.isArray(revision.task_migration)) {
552
- fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: entry.name });
557
+ if (compact.revision === null) return { predecessor: null, moves: [] };
558
+ if (compact.predecessor_plan_version === null || !Array.isArray(compact.revision?.task_migration)) {
559
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: name });
553
560
  }
554
- return { migration: {
555
- from_plan_version: revision.predecessor.plan_version,
556
- to_plan_version: entry.name,
557
- task_migration: revision.task_migration.map(({ from_task_id: fromTaskId, to_task_id: toTaskId }) => ({
558
- from_task_id: fromTaskId, to_task_id: toTaskId,
559
- })),
560
- } };
561
+ return record(compact.predecessor_plan_version, compact.revision.task_migration);
562
+ }
563
+ // A revision directory is published before manifest activation. A crash during
564
+ // that window can leave an unreferenced directory containing only a journal
565
+ // stub. It is not a historical plan until its canonical plan artifact exists.
566
+ // Do not make that unreachable residue poison note projection; if a note event
567
+ // names this version, the origin-version check below still fails closed.
568
+ const plan = await readCanonicalJson(planPath, { missing: true });
569
+ if (plan === null) return null;
570
+ if (!validateTodoPlan(plan) || plan.plan_key !== planKey || plan.plan_version !== name) {
571
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_plan_invalid', { plan_version: name });
572
+ }
573
+ const revision = await readCanonicalJson(revisionPath, { missing: true });
574
+ if (revision === null) return { predecessor: null, moves: [] };
575
+ if (!(validateTodoRevision(revision) || validatePhaseTodoRevision(revision))
576
+ || revision.plan_key !== planKey || revision.predecessor?.plan_version === undefined
577
+ || !Array.isArray(revision.task_migration)) {
578
+ fail('NOTE_PROJECTION_INVALID', 'note_historical_revision_invalid', { plan_version: name });
579
+ }
580
+ return record(revision.predecessor.plan_version, revision.task_migration);
581
+ });
582
+ }
583
+
584
+ const LINEAGE_CACHE_DIRECTORY = '.lattice/generated/store-note-lineage';
585
+ const LINEAGE_CACHE_SCHEMA = 'lattice.todo_note_lineage_cache.v1';
586
+ // shortcut: a shorter chain reads in well under 0.1 s, so an ordinary `todo start` on a small plan leaves no file in a user's git tree; upgrade if a short chain gets slow
587
+ const LINEAGE_CACHE_MIN_VERSIONS = 32;
588
+
589
+ /** The cached `{versions, moves}` of a plan's lineage up to some head, or null for any miss (absent, unreadable, wrong plan, bad digest, bad shape). */
590
+ async function readLineageCache(root, planKey) {
591
+ const body = await readDerivedPlanCache(root, LINEAGE_CACHE_DIRECTORY, LINEAGE_CACHE_SCHEMA, planKey);
592
+ if (body === null || !Array.isArray(body.versions) || body.versions.length === 0
593
+ || !body.versions.every(isTodoIdentifier) || new Set(body.versions).size !== body.versions.length
594
+ || !Array.isArray(body.moves) || !body.moves.every((move, at) => Array.isArray(move) && move.length === 3
595
+ && Number.isInteger(move[0]) && move[0] >= 0 && move[0] < body.versions.length - 1
596
+ && (at === 0 || move[0] >= body.moves[at - 1][0])
597
+ && isTodoIdentifier(move[1]) && (move[2] === null || isTodoIdentifier(move[2])))) return null;
598
+ return body;
599
+ }
600
+
601
+ /**
602
+ * w2-impl: the lineage of `headVersion`, from the head back along its predecessors. Derived cache
603
+ * `.lattice/generated/store-note-lineage/<plan_key>.json` (best effort, never truth: any miss reads the chain; a failed write
604
+ * never fails the read; written only for a chain of at least LINEAGE_CACHE_MIN_VERSIONS versions): a cached head equal
605
+ * to this one costs no version read, a head some revisions later reads only the versions after the cached head. Only a chain
606
+ * that reaches the first version (or the cached head, itself rooted) is cached, so a version directory that is missing for a
607
+ * while can never leave a short lineage behind. Versions off the head's chain
608
+ * (unpublished residue) are not read; a note naming a version that does not exist at all is still refused.
609
+ */
610
+ async function readNoteLineage(repoRoot, planKey, headVersion, eventVersions) {
611
+ const base = path.resolve(repoRoot, '.lattice/todo/plans', planKey);
612
+ const lineage = await memoByFileIdentity([path.join(base, headVersion, 'plan.json')], async () => {
613
+ const cached = await readLineageCache(repoRoot, planKey);
614
+ const stop = cached?.versions.at(-1) ?? null;
615
+ if (stop === headVersion) return new NoteLineage(cached.versions, cached.moves);
616
+ const fresh = []; // newest first
617
+ for (let name = headVersion, seen = new Set(); name !== null && name !== stop;) {
618
+ if (seen.has(name)) fail('NOTE_PROJECTION_INVALID', 'note_migration_cycle');
619
+ seen.add(name);
620
+ const record = await readVersionMigration(base, name, planKey);
621
+ if (record === null) break;
622
+ fresh.push({ name, ...record });
623
+ name = record.predecessor;
624
+ }
625
+ fresh.reverse();
626
+ const extends_ = stop !== null && fresh[0]?.predecessor === stop;
627
+ const rooted = extends_ || fresh[0]?.predecessor === null;
628
+ const versions = [...(extends_ ? cached.versions : []), ...fresh.map(({ name }) => name)];
629
+ const moves = extends_ ? [...cached.moves] : [];
630
+ fresh.forEach(({ moves: changed }, at) => {
631
+ const index = (extends_ ? cached.versions.length : 0) + at - 1; // the migration into this version
632
+ if (index >= 0) for (const [from, to] of changed) moves.push([index, from, to]);
561
633
  });
562
- if (version === null) continue;
563
- versions.add(entry.name);
564
- // The memoized migration is only read (migrationIndex copies it into its own Map), so it is shared, not cloned.
565
- if (version.migration !== null) migrations.push(version.migration);
566
- }
567
- if ([...eventVersions].some((version) => !versions.has(version))) {
568
- fail('NOTE_PROJECTION_INVALID', 'note_origin_plan_version_unknown');
634
+ if (rooted && fresh.length > 0 && versions.length >= LINEAGE_CACHE_MIN_VERSIONS) {
635
+ await publishDerivedPlanCache(repoRoot, LINEAGE_CACHE_DIRECTORY, { schema: LINEAGE_CACHE_SCHEMA, plan_key: planKey,
636
+ versions, moves }).catch(() => {});
637
+ }
638
+ return new NoteLineage(versions, moves);
639
+ }, 'note-lineage');
640
+ for (const version of eventVersions) {
641
+ if (!lineage.positions.has(version) && await readVersionMigration(base, version, planKey) === null) {
642
+ fail('NOTE_PROJECTION_INVALID', 'note_origin_plan_version_unknown');
643
+ }
569
644
  }
570
- return migrations;
645
+ return lineage;
571
646
  }
572
647
 
573
- /** active store memberと歴史revisionから、通常供給用contextを一回で読む。 */
574
- export async function readTodoNoteContext(options = {}) {
648
+ /**
649
+ * active store memberと歴史revisionから、1 taskのnote contextの素材を一回で読む。`project(extra)`がcontextを作る。
650
+ * `extra`は読んだ後に積んだtask note(appendNoteが今書いたもの)で、素材を読み直さずに入れる。
651
+ */
652
+ export async function readTodoNoteSource(options = {}) {
575
653
  if (!exactRecord(options, ['repoRoot', 'store', 'planKey', 'taskId'])
576
654
  || !isTodoIdentifier(options.planKey) || !isTodoIdentifier(options.taskId)
577
655
  || options.store === null || typeof options.store !== 'object') {
@@ -590,18 +668,22 @@ export async function readTodoNoteContext(options = {}) {
590
668
  });
591
669
  const chain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey });
592
670
  const planChain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey, scope: 'plan' });
593
- const migrations = await readNoteMigrations(repoRoot, options.planKey,
671
+ const lineage = await readNoteLineage(repoRoot, options.planKey, member.plan.plan_version,
594
672
  new Set(chain.events.map(({ plan_version: version }) => version)));
595
- return projectTodoNoteContext({
673
+ return { project: (extra = []) => projectTodoNoteContext({
596
674
  projectId: member.plan.project_id,
597
675
  planKey: options.planKey,
598
676
  currentPlanVersion: member.plan.plan_version,
599
677
  currentTaskId: task.task_id,
600
678
  currentTaskIds: member.plan.tasks.map(({ task_id: taskId }) => taskId),
601
- events: chain.events,
679
+ events: [...chain.events, ...extra],
602
680
  planEvents: planChain.events,
603
- migrations,
604
- });
681
+ migrations: lineage,
682
+ }) };
683
+ }
684
+
685
+ export async function readTodoNoteContext(options = {}) {
686
+ return (await readTodoNoteSource(options)).project();
605
687
  }
606
688
 
607
689
  /**
@@ -676,7 +758,7 @@ export async function readTodoNoteContextsForPlan(options = {}) {
676
758
  });
677
759
  const chain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey });
678
760
  const planChain = await readTodoNoteEvents({ repoRoot, planKey: options.planKey, scope: 'plan' });
679
- const migrations = await readNoteMigrations(repoRoot, options.planKey,
761
+ const migrations = await readNoteLineage(repoRoot, options.planKey, member.plan.plan_version,
680
762
  new Set(chain.events.map(({ plan_version: version }) => version)));
681
763
  const currentTaskIds = member.plan.tasks.map(({ task_id: taskId }) => taskId);
682
764
  const projected = member.plan.tasks.map((task) => projectTodoNoteContext({
@@ -54,7 +54,7 @@ export function createTodoReadiness(store) {
54
54
  }
55
55
  // xchart: predecessors on other charts, as their chart reports them (`withTodoExternalTasks`); never phase-gated.
56
56
  for (const entry of store.external_tasks ?? []) {
57
- nodes.set(taskKey(entry), { status: entry.status, task_id: entry.task_id, finished: entry.finished === true,
57
+ nodes.set(taskKey(entry), { status: entry.status, task_id: entry.task_id, finished: entry.finished === true || entry.missing === true,
58
58
  schema: null, plan_key: entry.plan_key, project_id: entry.project_id, phase_id: null, reason: entry.reason });
59
59
  }
60
60
  // An external edge whose state was not loaded waits (fail closed), named `chart_not_read`.
@@ -229,15 +229,11 @@ function blockingConnection({ kind, ref, reason, since, state_reason: stateReaso
229
229
  return { kind, ref, reason, since, ...(stateReason === undefined ? {} : { state_reason: stateReason }) };
230
230
  }
231
231
  /** The read-contract `connections` of one task (他条件に接続 open and settled, plus 優先接続 when `store.priority_waits` is loaded), for `todo show` and the CLI (call withTodoExternalTasks first). */
232
- export function listTodoConnections(store, planKey, taskId, { includeRemoved = false } = {}) {
232
+ export function listTodoConnections(store, planKey, taskId) {
233
233
  const member = store.members.find(({ plan }) => plan.plan_key === planKey);
234
234
  if (member === undefined) return [];
235
- const listed = createTodoReadiness(store).allConnections(`${member.plan.project_id}\0${planKey}\0${taskId}`);
236
- if (!includeRemoved) return listed;
237
- // A removed entry is history; a retry of remove needs it to answer `unchanged` rather than not-found.
238
- const removed = projectTodoScheduleConnections(member.plan_scoped?.events).filter((entry) => entry.state === 'removed'
239
- && entry.task_id === taskId).map(({ task_id: _task, actor: _actor, provenance: _provenance, ended: _ended, ...shown }) => shown);
240
- return [...listed, ...removed];
235
+ // A removed schedule entry is listed as `gone`, so a retry of remove answers `unchanged` rather than not-found.
236
+ return createTodoReadiness(store).allConnections(`${member.plan.project_id}\0${planKey}\0${taskId}`);
241
237
  }
242
238
  function byRef(left, right) {
243
239
  return refId(left) < refId(right) ? -1 : refId(left) > refId(right) ? 1 : 0;
@@ -1,5 +1,5 @@
1
1
  /* Pure projections shared by Store and Plan; no I/O or lifecycle mutation. */
2
- import { canonicalizeTodoArtifact } from './todo-contracts.mjs';
2
+ import { canonicalizeTodoArtifact, digestTodoArtifact } from './todo-contracts.mjs';
3
3
 
4
4
  /**
5
5
  * u03 A6: undo a Git autocrlf checkout of canonical LF bytes in memory. Only a pure
@@ -77,10 +77,10 @@ export function projectTodoCrossPlanDependencies(members) {
77
77
  }
78
78
 
79
79
  /**
80
- * A member's journal as the host reads it: `{first: {at, agent}|null, last_at, tasks: [{task_id, changed_at, started: {at, agent}|null}]}`
81
- * (`started` = the last `start`; only tasks with an event). One loop for the compact read and the closed history.
80
+ * A member's journal as the host reads it: `{first: {at, agent}|null, last_at, tasks: [{task_id, changed_at, started: {at, agent}|null, added: {at, agent}|null}]}`
81
+ * (`started` = the last `start`; a task with an event or an add record; `added` = who added it and when, from `added`). One loop for the compact read and the closed history.
82
82
  */
83
- function journalActivity(events) {
83
+ function journalActivity(events, added = new Map()) {
84
84
  const tasks = new Map();
85
85
  let first = null;
86
86
  let last = null;
@@ -88,11 +88,16 @@ function journalActivity(events) {
88
88
  if (first === null || event.recorded_at < first.recorded_at) first = event;
89
89
  if (last === null || event.recorded_at > last) last = event.recorded_at;
90
90
  if (event.task_id === undefined || event.task_id === null) continue;
91
- const entry = tasks.get(event.task_id) ?? { task_id: event.task_id, changed_at: event.recorded_at, started: null };
91
+ const entry = tasks.get(event.task_id) ?? { task_id: event.task_id, changed_at: event.recorded_at, started: null,
92
+ added: added.get(event.task_id) ?? null };
92
93
  if (event.recorded_at > entry.changed_at) entry.changed_at = event.recorded_at;
93
94
  if (event.kind === 'start') entry.started = { at: event.recorded_at, agent: event.actor?.agent ?? null };
94
95
  tasks.set(event.task_id, entry);
95
96
  }
97
+ // n3: an add is a plan revision, not a journal event, so a task with an add record and no event still gets an entry.
98
+ for (const [taskId, record] of added) {
99
+ if (!tasks.has(taskId)) tasks.set(taskId, { task_id: taskId, changed_at: record.at, started: null, added: record });
100
+ }
96
101
  return { first: first === null ? null : { at: first.recorded_at, agent: first.actor?.agent ?? null },
97
102
  last_at: last, tasks: [...tasks.values()] };
98
103
  }
@@ -104,13 +109,13 @@ function journalActivity(events) {
104
109
  * `[{event_digest, from, to}]` of the member's plan-scoped chain (a removal in any member's chain drops it).
105
110
  * A member with neither (the unverified raw read) is returned as it is.
106
111
  */
107
- export function compactDisplayStore(store) {
112
+ export function compactDisplayStore(store, { addedByPlan = new Map() } = {}) {
108
113
  const removed = new Set(store.members.flatMap((member) => (member.plan_scoped?.events ?? [])
109
114
  .filter((event) => event.kind === 'cross_plan_dependency_removed').map((event) => event.payload.target_event_digest)));
110
115
  return { ...store, members: store.members.map(({ journal, plan_scoped: planScoped, ...member }) => {
111
116
  if (journal === undefined && planScoped === undefined) return member;
112
117
  return { ...member,
113
- activity: journalActivity(journal?.events ?? []),
118
+ activity: journalActivity(journal?.events ?? [], addedByPlan.get(member.plan?.plan_key) ?? new Map()),
114
119
  cross_plan_dependencies: (planScoped?.events ?? [])
115
120
  .filter((event) => event.kind === 'cross_plan_dependency' && !removed.has(event.event_digest))
116
121
  .map((event) => ({ event_digest: event.event_digest, from: event.payload.from, to: event.payload.to })) };
@@ -241,6 +246,30 @@ export function projectTodoScheduleConnections(events) {
241
246
  });
242
247
  }
243
248
 
249
+ /**
250
+ * n2 (Snow White, dfd-connect.md "JSON contract"): the digest of a target task's content as its chart reads it now, over
251
+ * `{title, done_condition, lane, split: {children, function_split}}`: `children` = the sorted ids of the plan's tasks whose
252
+ * `parent_task_id` is the target (what `todo split` extracts), `function_split` = the plan task's mark or null.
253
+ * Design memo, notes, evidence and status are not part of it. `tasks` is the target plan's `tasks`.
254
+ */
255
+ export function todoTaskContentDigest(task, tasks = []) {
256
+ const children = tasks.filter(({ parent_task_id: parent }) => parent === task.task_id).map(({ task_id: id }) => id).sort();
257
+ return digestTodoArtifact({ title: task.title ?? null, done_condition: task.done_condition ?? null, lane: task.lane ?? null,
258
+ split: { children, function_split: task.function_split ?? null } });
259
+ }
260
+
261
+ /**
262
+ * n2: one judgment of a task 接続 from its target's state `{status, missing?, reason?}` (undefined = the chart was not read):
263
+ * done settles; retired and missing are gone; anything else waits (open), naming why when the target could not be read.
264
+ */
265
+ export function judgeTaskConnection(source) {
266
+ if (source?.status === 'done') return { state: 'settled', state_reason: 'target_done' };
267
+ if (source?.status === 'retired') return { state: 'gone', state_reason: 'target_retired' };
268
+ if (source?.missing === true) return { state: 'gone', state_reason: 'target_missing' };
269
+ const unread = source === undefined || source.status === null || source.status === undefined;
270
+ return unread ? { state: 'open', state_reason: source?.reason ?? 'chart_not_read' } : { state: 'open' };
271
+ }
272
+
244
273
  const connectionTaskKey = (projectId, planKey, taskId) => `${projectId}\0${planKey}\0${taskId}`;
245
274
  export { connectionTaskKey as todoConnectionTaskKey };
246
275
 
@@ -257,22 +286,27 @@ export function projectTodoConnections(members, externalTasks = []) {
257
286
  for (const member of members) {
258
287
  const { plan } = member;
259
288
  for (const entry of projectTodoScheduleConnections(member.plan_scoped?.events)) {
260
- if (entry.state === 'removed') continue;
261
289
  const { task_id: taskId, actor: _actor, provenance: _provenance, ended: _ended, ...shown } = entry;
262
- push(connectionTaskKey(plan.project_id, plan.plan_key, taskId), shown);
290
+ // n2: a removed schedule is listed as gone (a reader tells it from "never connected"); a settled one keeps its history.
291
+ push(connectionTaskKey(plan.project_id, plan.plan_key, taskId), entry.state === 'removed'
292
+ ? { ...shown, state: 'gone', state_reason: 'schedule_removed' }
293
+ : entry.state === 'settled' ? { ...shown, state_reason: 'schedule_resolved' } : shown);
263
294
  }
264
295
  }
265
296
  for (const dependency of projectTodoCrossPlanDependencies(members)) {
266
297
  if (dependency.from.project_id === dependency.to.project_id) continue;
267
298
  const { from, to } = dependency;
268
299
  const source = external.get(connectionTaskKey(from.project_id, from.plan_key, from.task_id));
269
- const settled = source?.finished === true;
300
+ // n2: waits only while the target exists and is not done; retired and missing targets are gone, not settled.
301
+ const { state, state_reason: stateReason } = judgeTaskConnection(source);
302
+ const { kind: changedKind, event_digest: changedDigest, recorded_at: changedAt } = source?.trigger ?? {};
270
303
  push(connectionTaskKey(to.project_id, to.plan_key, to.task_id), {
271
304
  kind: 'task', ref: `${from.project_id}/${from.plan_key}/${from.task_id}`,
272
- state: settled ? 'settled' : 'open', reason: dependency.reason, since: dependency.connected_at,
305
+ state, reason: dependency.reason, since: dependency.connected_at,
273
306
  event_digest: dependency.event_digest,
274
- ...(!settled && (source === undefined || source.status === null || source.status === undefined)
275
- ? { state_reason: source?.reason ?? 'chart_not_read' } : {}) });
307
+ ...(stateReason === undefined ? {} : { state_reason: stateReason }),
308
+ target_content_digest: source?.content_digest ?? null,
309
+ ...(changedDigest === undefined ? {} : { changed: { kind: changedKind, event_digest: changedDigest, recorded_at: changedAt } }) });
276
310
  }
277
311
  for (const [key, entries] of byTask) {
278
312
  byTask.set(key, entries.sort((left, right) => (left.since + left.event_digest < right.since + right.event_digest ? -1 : 1)));