@quolu/lattice 0.107.0 → 0.108.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.ja.md CHANGED
@@ -304,7 +304,7 @@ lattice todo start --plan <key> --task <id> --override-reason <reason>
304
304
  ```
305
305
 
306
306
  記録があるのに対象工程が未宣言・失効でも`todo start`は止まらず、`advisory.guidance`で知らせます。
307
- `independence compile`は`next_ready`がwitnessに無いとき`INDEPENDENCE_READY_UNDECLARED`で拒否します。
307
+ `independence compile`は宣言済みの行だけでcompileします。witnessに無いreadyの工程は、その工程だけが未知になります。
308
308
  remainingのA工程は同じwitnessへ含めます。競合の同時起動は助言のままです。
309
309
 
310
310
  `--serial-confirmed`と`--serialization-reviewed`は古い手順の互換として受理しますが、
package/README.md CHANGED
@@ -235,8 +235,8 @@ parallel set. Starting one of them does not require `--parallel-frontier` or
235
235
  `--override-reason`. Those flags record intent; they are not gates.
236
236
  `--serial-confirmed` and `--serialization-reviewed` are accepted only for compatibility.
237
237
  If an independence record exists but the task is undeclared or stale, `todo start`
238
- still starts and reports it in `advisory.guidance`. `independence compile` fails with
239
- `INDEPENDENCE_READY_UNDECLARED` when `next_ready` is missing from the witness.
238
+ still starts and reports it in `advisory.guidance`. `independence compile` compiles the declared
239
+ rows; a ready task missing from the witness is unknown for itself only.
240
240
 
241
241
  ```bash
242
242
  lattice todo start --plan <key> --task <id>
package/bin/lattice.mjs CHANGED
@@ -176,6 +176,9 @@ if (help !== null) {
176
176
  try {
177
177
  process.exitCode = await runPlanRevise({ cwd: process.cwd(), inputRef: flags.input, planKey: flags.plan,
178
178
  dryRun: flags['dry-run'] === true, stdout: process.stdout, env: process.env });
179
+ if (process.exitCode === 0 && flags['dry-run'] !== true) {
180
+ await (await import('../src/todo-cli.mjs')).carryIndependenceAfterRevision({ cwd: process.cwd() });
181
+ }
179
182
  } catch (error) {
180
183
  process.exitCode = projectCliFailure(process.stderr, error, { command: 'revise', flags });
181
184
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.107.0",
3
+ "version": "0.108.0",
4
4
  "description": "Schedulability compiler for multi-agent development: observe real code boundaries, refactor the conflicting seam, recompile the plan for parallel execution",
5
5
  "author": {
6
6
  "name": "Quo / クオ at kitepon.dev",
package/src/cli-help.mjs CHANGED
@@ -174,7 +174,7 @@ Write commands:
174
174
  independence witness scaffold --schema --json # 下書き(lattice.todo_witness_draft.v2)のJSON Schema
175
175
  independence witness scaffold --plan <key> --input <draft> # 下書きとfresh観測から宣言を書き出す
176
176
  independence witness declare --plan <key> --task <id> [--owns <path>[,<path>...]] [--reads ...] [--writes ...]
177
- # 1件のtaskの行だけを宣言する(a40)。readyが全部宣言済みならcompileまで行い、未宣言はwaiting_forに返す
177
+ # 1件のtaskの行だけを宣言する(a40)。宣言済みの行でcompileまで行い、未宣言のreadyはwaiting_forに返す
178
178
  structure input --plan <key> --input <file> --dry-run --json
179
179
  # plan identity・topology・unfinished task coverage・baseline祖先を無変更で検査する
180
180
  structure input --plan <key> --input <file>
@@ -434,10 +434,12 @@ export function evidenceFromCollectedOutcomes(options = {}) {
434
434
  * 入力shape違反はTypeErrorでfail closed。
435
435
  */
436
436
  export function compileRuntimePlanV1(options = {}) {
437
- if (!exactRecord(options, ['request', 'sensorEvidence', 'planRef', 'planEpoch', 'predecessorRefs'])) {
437
+ const { omitWavesOverLimit, ...required } = options;
438
+ if (!exactRecord(required, ['request', 'sensorEvidence', 'planRef', 'planEpoch', 'predecessorRefs'])
439
+ || (omitWavesOverLimit !== undefined && typeof omitWavesOverLimit !== 'boolean')) {
438
440
  fail('compileRuntimePlanV1 optionsがexact shapeでない');
439
441
  }
440
- const { request, sensorEvidence, planRef, planEpoch, predecessorRefs } = options;
442
+ const { request, sensorEvidence, planRef, planEpoch, predecessorRefs } = required;
441
443
  if (!validateRunRequest(request)) fail('run_request.v1がcontractを満たさない');
442
444
  if (!identifier(planRef)) fail('planRefがidentifierではない');
443
445
  if (!Number.isSafeInteger(planEpoch) || planEpoch < 0) fail('planEpochが不正');
@@ -808,7 +810,7 @@ export function compileRuntimePlanV1(options = {}) {
808
810
  };
809
811
 
810
812
  const bundle = compileBoundaryObservationV2(observationSet);
811
- const compiled = compileSchedulabilityGraphV2(bundle.graph);
813
+ const compiled = compileSchedulabilityGraphV2(bundle.graph, omitWavesOverLimit === true ? { omitWavesOverLimit: true } : {});
812
814
 
813
815
  if (compiled.outcome === 'unsupported' && compiled.code === 'NODE_LIMIT_EXCEEDED') {
814
816
  return nonDispatchable('NODE_LIMIT_EXCEEDED', { todo_count: todoIds.length });
@@ -843,11 +845,13 @@ export function compileRuntimePlanV1(options = {}) {
843
845
  }
844
846
  if (compiled.outcome !== 'compiled') fail(`未知のcompiler outcome: ${compiled.outcome}`);
845
847
 
846
- // producer非依存の独立verifierと必ず一致すること(成功条件5)。
847
- const verified = verifySchedulabilityPlanV2(bundle.graph, compiled.plan);
848
- if (verified.outcome !== 'verified'
849
- || verified.minimum_feasible_waves !== compiled.plan.minimum_feasible_waves) {
850
- fail(`producerとverifierの結果が一致しない: ${JSON.stringify(verified)}`);
848
+ // producer非依存の独立verifierと必ず一致すること(成功条件5)。g5: wave planを省いた(plan: null)時は検証する対象が無い。
849
+ if (compiled.plan !== null) {
850
+ const verified = verifySchedulabilityPlanV2(bundle.graph, compiled.plan);
851
+ if (verified.outcome !== 'verified'
852
+ || verified.minimum_feasible_waves !== compiled.plan.minimum_feasible_waves) {
853
+ fail(`producerとverifierの結果が一致しない: ${JSON.stringify(verified)}`);
854
+ }
851
855
  }
852
856
 
853
857
  // boundary_manifest.v2をTODOごとに構成する。
@@ -890,6 +894,14 @@ export function compileRuntimePlanV1(options = {}) {
890
894
  manifests[todoId] = manifest;
891
895
  }
892
896
 
897
+ // g5: no wave plan (over the exact-search limit) means no runtime plan either: its claim is `exact_minimum`.
898
+ if (compiled.plan === null) {
899
+ return {
900
+ outcome: 'dispatchable', plan: null, manifests, schedule: null, pairwise_verdicts: compiled.pairwise_verdicts,
901
+ graph: bundle.graph, resources: bundle.resources, graph_digest: bundle.graph_digest,
902
+ };
903
+ }
904
+
893
905
  const plan = {
894
906
  schema: 'lattice.runtime_plan.v1',
895
907
  plan_ref: planRef,
@@ -48,14 +48,16 @@ function assertArray(value, label) {
48
48
  }
49
49
 
50
50
  function normalizeOptions(options) {
51
- if (!exactRecord(options, []) && !exactRecord(options, ['maxSearchStates'])) {
51
+ const keys = Object.keys(options).sort();
52
+ if (!exactRecord(options, keys) || !keys.every((key) => ['maxSearchStates', 'omitWavesOverLimit'].includes(key))
53
+ || (options.omitWavesOverLimit !== undefined && typeof options.omitWavesOverLimit !== 'boolean')) {
52
54
  fail('options shapeが不正');
53
55
  }
54
56
  const maxSearchStates = options.maxSearchStates ?? DEFAULT_MAX_SEARCH_STATES;
55
57
  if (!Number.isSafeInteger(maxSearchStates) || maxSearchStates < 0) {
56
58
  fail('maxSearchStatesがnon-negative safe integerではない');
57
59
  }
58
- return { maxSearchStates };
60
+ return { maxSearchStates, omitWavesOverLimit: options.omitWavesOverLimit === true };
59
61
  }
60
62
 
61
63
  function assertAcyclic(todos, precedences) {
@@ -270,14 +272,18 @@ function pairwiseVerdicts(graph) {
270
272
  */
271
273
  export function compileSchedulabilityGraphV2(normalizedGraph, options = {}) {
272
274
  const graph = normalizeGraph(normalizedGraph);
273
- const { maxSearchStates } = normalizeOptions(options);
275
+ const { maxSearchStates, omitWavesOverLimit } = normalizeOptions(options);
274
276
 
275
- if (graph.todos.length > MAX_TODOS) {
277
+ const overLimit = graph.todos.length > MAX_TODOS;
278
+ if (overLimit && !omitWavesOverLimit) {
276
279
  return { outcome: 'unsupported', code: 'NODE_LIMIT_EXCEEDED' };
277
280
  }
278
281
  if (graph.unknowns.length > 0) {
279
282
  return { outcome: 'unknown', code: 'BOUNDARY_UNKNOWN', unknowns: graph.unknowns };
280
283
  }
284
+ // g5: the exact minimum-wave search stops at MAX_TODOS. A caller that only needs the verdicts (independence) opts in to
285
+ // `plan: null` above it: the pairwise verdicts do not depend on the search, and no minimum is claimed.
286
+ if (overLimit) return { outcome: 'compiled', pairwise_verdicts: pairwiseVerdicts(graph), plan: null };
281
287
  if (maxSearchStates === 0) {
282
288
  return { outcome: 'unsupported', code: 'SEARCH_BUDGET_EXHAUSTED' };
283
289
  }
package/src/todo-cli.mjs CHANGED
@@ -3482,25 +3482,7 @@ async function independenceCompile({ repoRoot, planKey, inputRef }) {
3482
3482
  { task_ids: absentFromPlan },
3483
3483
  );
3484
3484
  }
3485
- const readyIds = projectTodoStatus(storeForReady, TODO_STATUS_DISPATCH_ONLY).next_ready
3486
- .filter((task) => task.plan_key === planKey)
3487
- .map((task) => task.task_id);
3488
- const declared = new Set(declaredIds);
3489
- const missingReady = readyIds.filter((taskId) => !declared.has(taskId)).sort();
3490
- if (missingReady.length > 0) {
3491
- throw new TodoStoreError(
3492
- 'INDEPENDENCE_READY_UNDECLARED',
3493
- 'ready_tasks_missing_from_witness',
3494
- undefined,
3495
- {
3496
- plan_key: planKey,
3497
- missing_task_ids: missingReady,
3498
- // a35: compiling the same set again cannot add them; the template keeps what is declared.
3499
- next_action: `Declare ${missingReady.join(', ')} in the witness set. ${witnessRoute(planKey)}`
3500
- + ' The template keeps the declarations already recorded, so only the new tasks need filling.',
3501
- },
3502
- );
3503
- }
3485
+ // g4: a ready task nobody declared is `witness_missing` for itself only (projectIndependenceFrontier), so it no longer stops the compile.
3504
3486
  const observation = await collectTodoIndependenceAuthoritativeObservation({ repoRoot, witnessSet });
3505
3487
  const baseSha = observation.head_sha;
3506
3488
  const store = storeForReady;
@@ -3592,6 +3574,33 @@ async function independenceWitnessMigrate({ repoRoot, planKey }) {
3592
3574
  return result;
3593
3575
  }
3594
3576
 
3577
+ /**
3578
+ * g4: the independence artifact is keyed to the plan version, so a revision (todo add, predecessor, plan revise ...) leaves the
3579
+ * new version without a record and an enforced plan refuses every start. After a revision, move the recorded declarations to the
3580
+ * new version and recompile over them: unchanged tasks keep their verdicts, a new undeclared task is `witness_missing` for itself
3581
+ * only. Best effort: the revision is already recorded, so a failure is one warning with the way out, never an error.
3582
+ */
3583
+ export async function carryIndependenceAfterRevision({ cwd }) {
3584
+ let planKey = null;
3585
+ try {
3586
+ const repoRoot = resolveRepoRoot(cwd);
3587
+ const store = await readTodoStore({ repoRoot });
3588
+ for (const member of store.members) {
3589
+ planKey = member.plan.plan_key;
3590
+ if (!['witness', 'enforced'].includes(member.coordination?.mode) || !headResolves(repoRoot)) continue;
3591
+ const artifact = await readTodoIndependenceArtifact({ repoRoot, store, planKey });
3592
+ if (artifact !== null && !isTodoIndependenceLegacyMarker(artifact)) continue;
3593
+ if (await readTodoWitnessSet({ repoRoot, planKey }) === null) continue;
3594
+ if (Array.isArray(member.revision?.task_migration)) await independenceWitnessMigrate({ repoRoot, planKey });
3595
+ await independenceCompile({ repoRoot, planKey, inputRef: todoWitnessRef(planKey) });
3596
+ }
3597
+ } catch (error) {
3598
+ process.emitWarning(`independence record not carried to the new plan version${planKey === null ? '' : ` of ${planKey}`}`
3599
+ + ` (${error?.detail?.reason ?? error?.message ?? error}): declare a task again, or run \`lattice todo independence witness migrate --plan <key>\``
3600
+ + ' and then compile', { code: 'LATTICE_INDEPENDENCE_NOT_CARRIED' });
3601
+ }
3602
+ }
3603
+
3595
3604
  async function independence({ repoRoot, requestedPlanKey }) {
3596
3605
  const store = await readTodoStore({ repoRoot });
3597
3606
  if (requestedPlanKey !== null
@@ -3920,7 +3929,7 @@ function declaredStartHint(store, member, state) {
3920
3929
 
3921
3930
  /**
3922
3931
  * a40: one task's witness row, declared by its member. Rows nobody declared stay out (an empty row
3923
- * would claim "touches nothing"); compile runs once every ready task is declared.
3932
+ * would claim "touches nothing"); compile runs on the declared rows (g4), `waiting_for` names the ready tasks still undeclared.
3924
3933
  */
3925
3934
  async function witnessDeclare({ repoRoot, env, planKey, flags }) {
3926
3935
  const store = await readTodoStoreForReadiness({ repoRoot, env });
@@ -3955,7 +3964,7 @@ async function witnessDeclare({ repoRoot, env, planKey, flags }) {
3955
3964
  .map(({ task_id: id }) => id).sort();
3956
3965
  // declare-without-git: a Store root with no commit cannot be observed, so the row is recorded and not compiled.
3957
3966
  const observable = headResolves(repoRoot);
3958
- const compile = waitingFor.length === 0 && observable
3967
+ const compile = observable
3959
3968
  ? await independenceCompile({ repoRoot, planKey, inputRef: scaffolded.witness_ref }) : null;
3960
3969
  const result = {
3961
3970
  schema: 'lattice.todo_witness_declare_result.v1', project_id: member.plan.project_id, plan_key: planKey,
@@ -4693,6 +4702,13 @@ function writesTodoStore(argv) {
4693
4702
  }
4694
4703
  }
4695
4704
 
4705
+ /** g4: the todo commands that write a new plan version (the plan revise command carries on its own in bin/lattice.mjs). */
4706
+ function revisesPlan(argv) {
4707
+ return ['add', 'revise', 'revise-phase', 'revise-set', 'split', 'dependency', 'predecessor'].includes(argv[0])
4708
+ && !(argv[0] === 'dependency' && !['connect', 'disconnect'].includes(argv[1]))
4709
+ && !(argv[0] === 'predecessor' && !['add', 'remove'].includes(argv[1]));
4710
+ }
4711
+
4696
4712
  /** notice-impl: the writes that can make a task startable carry `notices` ([startable notices](dfd-done-notice.md)). */
4697
4713
  function releasesTasks(argv) {
4698
4714
  const [command, second] = argv;
@@ -5619,6 +5635,7 @@ export async function runTodoCli({ argv, cwd, stdout, stderr, env = process.env,
5619
5635
  : await action(repoRoot);
5620
5636
  const result = releasesTasks(argv) ? await withNotices(repoRoot, written, before, env) : written;
5621
5637
  if (result !== null) stdout.write(`${plainVerify ? verifyVerdictLine(result) : JSON.stringify(result)}\n`);
5638
+ if (!atomicCommit && revisesPlan(argv)) await carryIndependenceAfterRevision({ cwd });
5622
5639
  return 0;
5623
5640
  } catch (error) {
5624
5641
  if (error instanceof TodoStoreError || (typeof error?.code === 'string'
@@ -1,3 +1,4 @@
1
+ import { existsSync } from 'node:fs';
1
2
  import { mkdtemp, rm } from 'node:fs/promises';
2
3
  import { tmpdir } from 'node:os';
3
4
  import path from 'node:path';
@@ -40,22 +41,46 @@ function memoryStream() {
40
41
  };
41
42
  }
42
43
 
43
- async function initializeSensor(observationRoot) {
44
+ async function runSensor(command, observationRoot) {
44
45
  const stdout = memoryStream();
45
46
  const stderr = memoryStream();
46
47
  const status = await runSensorCli({
47
- argv: ['init', observationRoot, '--json'],
48
+ argv: [command, observationRoot, '--json'],
48
49
  stdout: stdout.stream,
49
50
  stderr: stderr.stream,
50
51
  });
51
52
  if (status !== 0) {
52
53
  fail('INDEPENDENCE_OBSERVATION_SENSOR_INIT_FAILED', 'observation_sensor_init_failed', {
53
- sensor_error: stderr.read(),
54
+ sensor_command: command, sensor_error: stderr.read(),
54
55
  });
55
56
  }
56
57
  }
57
58
 
58
- /** 共有repoのdirtyな状態を観測せず、current HEADのclean worktreeでsensorを実行する。 */
59
+ /**
60
+ * a2 (ADR 0204 Observe): 作業木がHEADと同じ内容か。`.lattice/`はsensor索引とstoreが書く場所で、
61
+ * 索引の対象外なので数えない(storeがtrackedな製品repoでは書込みのたびにdirtyになるため)。
62
+ */
63
+ function isCleanAtHead(repoRoot, headSha) {
64
+ return git({ cwd: repoRoot, args: ['rev-parse', '--verify', 'HEAD^{commit}'], operation: 'resolve_head' }) === headSha
65
+ && git({
66
+ cwd: repoRoot, operation: 'status_clean_check',
67
+ args: ['status', '--porcelain', '--untracked-files=all', '--', '.', ':(exclude).lattice'],
68
+ }) === '';
69
+ }
70
+
71
+ /**
72
+ * HEADと同じ内容の作業木では、維持されている索引を増分syncして使う(無ければ最初の1回だけinit)。
73
+ * 同期の前後でcleanとHEADを確かめ、崩れていたらnull=隔離worktreeの経路へ落とす。
74
+ * 保護するもの: 未commitの状態を判定が観測しないこと。落とす先が出口で、拒否はしない。
75
+ */
76
+ async function observeMaintainedIndex({ repoRoot, headSha, witnessSet }) {
77
+ if (!isCleanAtHead(repoRoot, headSha)) return null;
78
+ await runSensor(existsSync(path.join(repoRoot, '.lattice/sensor/sensor.db')) ? 'sync' : 'init', repoRoot);
79
+ if (!isCleanAtHead(repoRoot, headSha)) return null;
80
+ return { head_sha: headSha, sensor_evidence: await collectWitnessSensorEvidence({ cwd: repoRoot, witnessSet }) };
81
+ }
82
+
83
+ /** 共有repoのdirtyな状態を観測せず、current HEADの索引(維持されたもの、無ければclean worktree)でsensorを実行する。 */
59
84
  export async function collectTodoIndependenceAuthoritativeObservation({ repoRoot, witnessSet } = {}) {
60
85
  if (typeof repoRoot !== 'string' || repoRoot.length === 0
61
86
  || witnessSet === null || typeof witnessSet !== 'object') {
@@ -65,6 +90,8 @@ export async function collectTodoIndependenceAuthoritativeObservation({ repoRoot
65
90
  const headSha = git({
66
91
  cwd: repoRoot, args: ['rev-parse', '--verify', 'HEAD^{commit}'], operation: 'resolve_head',
67
92
  });
93
+ const maintained = await observeMaintainedIndex({ repoRoot, headSha, witnessSet });
94
+ if (maintained !== null) return maintained;
68
95
  const temporaryRoot = await mkdtemp(path.join(tmpdir(), 'lattice-independence-observation-'));
69
96
  const observationRoot = path.join(temporaryRoot, 'worktree');
70
97
  let registered = false;
@@ -86,7 +113,7 @@ export async function collectTodoIndependenceAuthoritativeObservation({ repoRoot
86
113
  expected_head_sha: headSha, actual_head_sha: observedHead,
87
114
  });
88
115
  }
89
- await initializeSensor(observationRoot);
116
+ await runSensor('init', observationRoot);
90
117
  result = await collectWitnessSensorEvidence({ cwd: observationRoot, witnessSet });
91
118
  } catch (error) {
92
119
  operationError = error;
@@ -400,6 +400,7 @@ function wavePlan(value, taskIds) {
400
400
  * conflictは`conflict_resources`のresource idを参照し、kindとnormalized targetを一度だけ保持する。
401
401
  * `task_boundaries`はtask別の宣言境界で、鮮度のdiff交差判定をartifactだけで閉じるために持つ。
402
402
  * `wave_plan`はschedulability compileが`compiled`を返した時だけ持ち、unknownが残る間はnullになる。
403
+ * `outcome: compiled`で`wave_plan: null`は、exact探索の上限(MAX_TODOS)を超えたため波の計画だけを省いた記録で、verdictは全て揃う(g5)。
403
404
  * verdictに現れないペアをverified独立と読めるのは、両taskにunknownが無いときだけである。
404
405
  */
405
406
  export function validateTodoIndependence(value) {
@@ -284,6 +284,7 @@ export function compileTodoIndependence(options = {}) {
284
284
  planRef: witnessRequestId(witnessSet, plan.plan_version),
285
285
  planEpoch: 0,
286
286
  predecessorRefs: [],
287
+ omitWavesOverLimit: true,
287
288
  });
288
289
 
289
290
  if (compiled.outcome !== 'dispatchable'
@@ -316,7 +317,9 @@ export function compileTodoIndependence(options = {}) {
316
317
  conflicts: conflictProjection.conflicts,
317
318
  precedences: dispatchable ? precedencesFrom(compiled.pairwise_verdicts) : [],
318
319
  unknowns: dispatchable ? [] : unknownsFrom(compiled.detail),
319
- wave_plan: dispatchable
320
+ // g5: `outcome: compiled` with `wave_plan: null` = the exact wave search was omitted (more tasks than MAX_TODOS in the
321
+ // schedulability compiler); every verdict above is still complete. `unknown` is the other reason for null.
322
+ wave_plan: dispatchable && compiled.schedule !== null
320
323
  ? {
321
324
  waves: compiled.schedule.waves.map((wave) => ({
322
325
  task_ids: [...wave.todo_ids].sort(compareText),