@quolu/lattice 0.12.34 → 0.14.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.
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
 
6
6
  import { readTodoStoreStable } from '../src/todo-store.mjs';
7
7
  import { projectTodoStatus } from '../src/todo-status.mjs';
8
- import { renderTodoGanttForProject } from '../src/todo-cli.mjs';
8
+ import { ganttLiveHeadDigest, renderTodoGanttForProject } from '../src/todo-cli.mjs';
9
9
  import {
10
10
  readVisibleTodoDashboardProjects,
11
11
  writeTodoDashboardDaemonDescriptor,
@@ -89,9 +89,14 @@ async function synchronize() {
89
89
  const store = await readCachedStore(entry.repo_root);
90
90
  const result = await renderTodoGanttForProject({ repoRoot: entry.repo_root,
91
91
  stable: true, displayName, readModel: store });
92
- return { html: result.rendered.html, head_digest: result.metadata.manifest_digest };
92
+ return {
93
+ html: result.rendered.html,
94
+ head_digest: await ganttLiveHeadDigest({ repoRoot: entry.repo_root, store }),
95
+ };
93
96
  },
94
- readHead: async () => (await readCachedStore(entry.repo_root)).manifest.manifest_digest,
97
+ readHead: async () => ganttLiveHeadDigest({
98
+ repoRoot: entry.repo_root, store: await readCachedStore(entry.repo_root),
99
+ }),
95
100
  });
96
101
  roots.set(entry.project_id, binding);
97
102
  }
package/bin/lattice.mjs CHANGED
@@ -14,6 +14,11 @@ if (help !== null) {
14
14
  process.stdout.write(help);
15
15
  } else if (args.length === 1 && args[0] === '--version') {
16
16
  process.stdout.write(`${packageJson.version}\n`);
17
+ } else if (args.length === 2 && args[0] === 'session-context' && args[1] === '--json') {
18
+ const { runSessionContext } = await import('../src/project-cli.mjs');
19
+ process.exitCode = await runSessionContext({
20
+ cwd: process.cwd(), stdout: process.stdout, cliVersion: packageJson.version,
21
+ });
17
22
  } else if (args.length === 2 && args[0] === 'status' && args[1] === '--json') {
18
23
  const { projectStatusFailure, runProjectStatus } = await import('../src/project-cli.mjs');
19
24
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quolu/lattice",
3
- "version": "0.12.34",
3
+ "version": "0.14.0",
4
4
  "description": "Lattice — phase-aware TODO graph compiler and conflict-aware orchestration runtime",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -60,7 +60,7 @@
60
60
  "test": "node scripts/run-product-tests.mjs",
61
61
  "test:sensor": "npm --prefix sensor test",
62
62
  "precheck": "node --check src/bridge-launch-agent.mjs",
63
- "check": "node --check bin/lattice.mjs && node --check bin/lattice-mcp.mjs && node --check bin/lattice-dashboard.mjs && node --check bin/lattice-bridge.mjs && node --check bin/lattice-scripted-adapter.mjs && node --check src/cli-stdio.mjs && node --check src/bridge-address.mjs && node --check src/bridge-registrar.mjs && node --check src/todo-gantt-layout.mjs && node --check src/todo-gantt-scope.mjs && node --check src/bridge-config.mjs && node --check src/bridge-server.mjs && node --check src/bridge-daemon.mjs && node --check src/bridge-cli.mjs && node --check src/project-cli.mjs && node --check src/sensor-cli.mjs && node --check src/sensor-runtime.mjs && node --check src/sensor-adapter.mjs && node --check src/factory-diagnostics.mjs && node --check src/runtime-errors.mjs && node --check src/runtime-contracts.mjs && node --check src/runtime-event-store.mjs && node --check src/runtime-adapter-registry.mjs && node --check src/runtime-scripted-adapter-controller.mjs && node --check src/hash-chain.mjs && node --check src/dag-chain.mjs && node --check src/todo-contracts.mjs && node --check src/todo-chain.mjs && node --check src/todo-store.mjs && node --check src/todo-migration.mjs && node --check src/todo-revision.mjs && node --check src/todo-status.mjs && node --check src/todo-cli.mjs && node --check src/todo-dashboard-registry.mjs && node --check src/todo-gantt-presentation.mjs && node --check src/todo-gantt-live.mjs && node --check src/bounded-seam.mjs && node --check src/todo-narrative-anchor.mjs && node --check src/todo-markdown-renderer.mjs && node --check src/todo-gantt-svg.mjs && node --check src/todo-gantt-html.mjs && node --check src/runtime-projection.mjs && node --check src/runtime-decision-verifier.mjs && node --check src/runtime-front-end.mjs && node --check src/runtime-cli.mjs && node --check src/rc3-dogfood-scaffold.mjs && node --check src/runtime-engine.mjs && node --check src/runtime-scripted-executor.mjs && node --check src/runtime-diff-observer.mjs && node --check src/runtime-worktree-executor.mjs && node --check src/runtime-hold-recompile.mjs && node --check src/rc3-scripted-campaign.mjs && node --check src/rc3-actual-dogfood.mjs && node --check src/rc4-stage1-dogfood.mjs && node --check research/fixtures/dispatch-record/src/dispatch-record.mjs && node --check test/research-dispatch-record.test.mjs",
63
+ "check": "node --check bin/lattice.mjs && node --check bin/lattice-mcp.mjs && node --check bin/lattice-dashboard.mjs && node --check bin/lattice-bridge.mjs && node --check bin/lattice-scripted-adapter.mjs && node --check src/cli-stdio.mjs && node --check src/bridge-address.mjs && node --check src/bridge-registrar.mjs && node --check src/todo-independence-guidance.mjs && node --check src/todo-independence.mjs && node --check src/todo-independence-contracts.mjs && node --check src/todo-gantt-layout.mjs && node --check src/todo-gantt-scope.mjs && node --check src/bridge-config.mjs && node --check src/bridge-server.mjs && node --check src/bridge-daemon.mjs && node --check src/bridge-cli.mjs && node --check src/project-cli.mjs && node --check src/sensor-cli.mjs && node --check src/sensor-runtime.mjs && node --check src/sensor-adapter.mjs && node --check src/factory-diagnostics.mjs && node --check src/runtime-errors.mjs && node --check src/runtime-contracts.mjs && node --check src/runtime-event-store.mjs && node --check src/runtime-adapter-registry.mjs && node --check src/runtime-scripted-adapter-controller.mjs && node --check src/hash-chain.mjs && node --check src/dag-chain.mjs && node --check src/todo-contracts.mjs && node --check src/todo-chain.mjs && node --check src/todo-store.mjs && node --check src/todo-migration.mjs && node --check src/todo-revision.mjs && node --check src/todo-status.mjs && node --check src/todo-cli.mjs && node --check src/todo-dashboard-registry.mjs && node --check src/todo-gantt-presentation.mjs && node --check src/todo-gantt-live.mjs && node --check src/bounded-seam.mjs && node --check src/todo-narrative-anchor.mjs && node --check src/todo-markdown-renderer.mjs && node --check src/todo-gantt-svg.mjs && node --check src/todo-gantt-html.mjs && node --check src/runtime-projection.mjs && node --check src/runtime-decision-verifier.mjs && node --check src/runtime-front-end.mjs && node --check src/runtime-cli.mjs && node --check src/rc3-dogfood-scaffold.mjs && node --check src/runtime-engine.mjs && node --check src/runtime-scripted-executor.mjs && node --check src/runtime-diff-observer.mjs && node --check src/runtime-worktree-executor.mjs && node --check src/runtime-hold-recompile.mjs && node --check src/rc3-scripted-campaign.mjs && node --check src/rc3-actual-dogfood.mjs && node --check src/rc4-stage1-dogfood.mjs && node --check research/fixtures/dispatch-record/src/dispatch-record.mjs && node --check test/research-dispatch-record.test.mjs",
64
64
  "check:project-identity": "node --check src/project-identity.mjs",
65
65
  "ci": "npm run test && npm run test:sensor && npm run check && npm run check:project-identity"
66
66
  }
@@ -15,7 +15,7 @@
15
15
  * burn tokens. ADR 0049 / 0059 require the eight compatibility tools to remain
16
16
  * visible by default; provider identity is Lattice regardless of their names.
17
17
  */
18
- export declare const SERVER_INSTRUCTIONS = "# Lattice sensor \u2014 code intelligence over an indexed knowledge graph\n\nProvider identity: lattice. The lattice_sensor_* names below are compatibility tool names served by Lattice's own bundled sensor; they do not call or require the independent Lattice sensor product.\n\nLattice sensor is a SQLite knowledge graph of every symbol, edge, and file in\nthe workspace \u2014 pre-computed structure you would otherwise re-derive by\nreading files (cached intelligence: thousands of parse/trace decisions you\ndon't pay to re-reason each run). Reads are sub-millisecond; the index lags\nwrites by ~1s through the file watcher. Reach for it BEFORE *and* while\nwriting or editing code \u2014 not just for questions: one call returns the\nverbatim source PLUS who calls it and what it affects, so you edit with the\nblast radius in view. More accurate context, in far fewer tokens and\nround-trips than reading files yourself.\n\n## One tool: lattice_sensor_explore \u2014 use it instead of reading files\n\nThere is a single tool, `lattice_sensor_explore`, and it is Read-equivalent. It\ntakes either a natural-language question or a bag of symbol/file names and\nreturns the **verbatim, line-numbered source** of the relevant symbols\ngrouped by file \u2014 the same `<n>\\t<line>` shape `Read` gives you, safe to\n`Edit` from \u2014 PLUS the call path among them (including dynamic-dispatch hops\nlike callbacks, React re-render, and JSX children that grep can't follow) and\na blast-radius summary of what depends on them.\n\nWhether you're answering \"how does X work\" or implementing a change (fixing a\nbug, adding a feature), call `lattice_sensor_explore` before you Read. ONE call\nusually answers the whole question. Lattice sensor IS the pre-built search index \u2014\nso running your own grep + read loop, or delegating the lookup to a separate\nfile-reading sub-task/agent, repeats work lattice sensor already did and costs more\nfor the same answer. A direct lattice sensor answer is typically one to a few\ncalls; a grep/read exploration is dozens.\n\n## How to query\n\n- **Almost any question \u2014 \"how does X work\", architecture, a bug, \"what/where is X\", or surveying an area** \u2192 `lattice_sensor_explore` with a natural-language question or the relevant names. ONE capped call returns the verbatim source grouped by file; most often the ONLY call you need.\n- **\"How does X reach/become Y? / the flow / the path from X to Y\"** \u2192 `lattice_sensor_explore`, naming the symbols that span the flow (e.g. `mutateElement renderScene`) \u2014 it surfaces the call path among them, riding dynamic-dispatch hops, and returns their source.\n- **Reading or editing a file/symbol you can name** \u2192 put its name or file path in the `lattice_sensor_explore` query \u2014 it returns that current line-numbered source (safe to `Edit` from) with the call path and blast radius attached, so you don't Read it separately. For an overloaded name it returns every matching definition's body in one call.\n- **Need more?** Call `lattice_sensor_explore` again with more specific names \u2014 treat the source it returns as already Read.\n\n## Anti-patterns\n\n- **Trust lattice sensor's results \u2014 don't re-verify them with grep.** They come from a full AST parse; re-checking with grep is slower, less accurate, and wastes context.\n- **Don't grep or Read first** to find or understand indexed code \u2014 ONE `lattice_sensor_explore` returns the relevant symbols' source together in a single round-trip. Reach for raw `Read`/`Grep` only to confirm a specific detail lattice sensor didn't cover, or for what lattice sensor doesn't index (configs, docs).\n- **Don't reconstruct a flow by hand** \u2014 name the endpoints in one `lattice_sensor_explore` and it surfaces the path between them, dynamic-dispatch hops included.\n- **After editing, check the staleness banner.** When a tool response starts with \"\u26A0\uFE0F Some files referenced below were edited since the last index sync\u2026\", the listed files are pending re-index \u2014 Read those specific files for accurate content. Every file NOT in that banner is fresh, so still trust lattice sensor. A different, rarer banner \u2014 \"\u26A0\uFE0F LatticeSensor auto-sync is DISABLED\u2026\" \u2014 means live watching stopped entirely (the whole index is frozen, not just a few files); until it's resolved, Read files directly to confirm anything that may have changed.\n\n## Limitations\n\n- If a project isn't indexed (no `.lattice/sensor/`), decide whether building the index will reduce total investigation time and model tokens for the current or expected work. When workspace writes and shell execution are allowed, you may run `lattice sensor init <projectPath> --json` yourself, then retry the sensor call; scope it to the intended project and account for the one-time indexing cost. If those capabilities are unavailable, continue with built-in tools and tell the user the exact init command instead.\n- Index lags file writes by ~1 second.\n- Cross-file resolution is best-effort name matching; ambiguous calls may return multiple candidates.\n- No live correctness validation \u2014 that's still the TypeScript compiler / test suite / linter's job. Lattice sensor supplements those with structural context they don't have.\n";
18
+ export declare const SERVER_INSTRUCTIONS = "# Lattice sensor \u2014 code intelligence over an indexed knowledge graph\n\nProvider identity: lattice. The lattice_sensor_* names below are compatibility tool names served by Lattice's own bundled sensor; they do not call or require the independent Lattice sensor product.\n\nLattice sensor is a SQLite knowledge graph of every symbol, edge, and file in\nthe workspace \u2014 pre-computed structure you would otherwise re-derive by\nreading files (cached intelligence: thousands of parse/trace decisions you\ndon't pay to re-reason each run). Reads are sub-millisecond; the index lags\nwrites by ~1s through the file watcher. Reach for it BEFORE *and* while\nwriting or editing code \u2014 not just for questions: one call returns the\nverbatim source PLUS who calls it and what it affects, so you edit with the\nblast radius in view. More accurate context, in far fewer tokens and\nround-trips than reading files yourself.\n\n## One tool: lattice_sensor_explore \u2014 use it instead of reading files\n\nThere is a single tool, `lattice_sensor_explore`, and it is Read-equivalent. It\ntakes either a natural-language question or a bag of symbol/file names and\nreturns the **verbatim, line-numbered source** of the relevant symbols\ngrouped by file \u2014 the same `<n>\\t<line>` shape `Read` gives you, safe to\n`Edit` from \u2014 PLUS the call path among them (including dynamic-dispatch hops\nlike callbacks, React re-render, and JSX children that grep can't follow) and\na blast-radius summary of what depends on them.\n\nWhether you're answering \"how does X work\" or implementing a change (fixing a\nbug, adding a feature), call `lattice_sensor_explore` before you Read. ONE call\nusually answers the whole question. Lattice sensor IS the pre-built search index \u2014\nso running your own grep + read loop, or delegating the lookup to a separate\nfile-reading sub-task/agent, repeats work lattice sensor already did and costs more\nfor the same answer. A direct lattice sensor answer is typically one to a few\ncalls; a grep/read exploration is dozens.\n\n## How to query\n\n- **Almost any question \u2014 \"how does X work\", architecture, a bug, \"what/where is X\", or surveying an area** \u2192 `lattice_sensor_explore` with a natural-language question or the relevant names. ONE capped call returns the verbatim source grouped by file; most often the ONLY call you need.\n- **\"How does X reach/become Y? / the flow / the path from X to Y\"** \u2192 `lattice_sensor_explore`, naming the symbols that span the flow (e.g. `mutateElement renderScene`) \u2014 it surfaces the call path among them, riding dynamic-dispatch hops, and returns their source.\n- **Reading or editing a file/symbol you can name** \u2192 put its name or file path in the `lattice_sensor_explore` query \u2014 it returns that current line-numbered source (safe to `Edit` from) with the call path and blast radius attached, so you don't Read it separately. For an overloaded name it returns every matching definition's body in one call.\n- **Need more?** Call `lattice_sensor_explore` again with more specific names \u2014 treat the source it returns as already Read.\n\n## Anti-patterns\n\n- **Trust lattice sensor's results \u2014 don't re-verify them with grep.** They come from a full AST parse; re-checking with grep is slower, less accurate, and wastes context.\n- **Don't grep or Read first** to find or understand indexed code \u2014 ONE `lattice_sensor_explore` returns the relevant symbols' source together in a single round-trip. Reach for raw `Read`/`Grep` only to confirm a specific detail lattice sensor didn't cover, or for what lattice sensor doesn't index (configs, docs).\n- **Don't reconstruct a flow by hand** \u2014 name the endpoints in one `lattice_sensor_explore` and it surfaces the path between them, dynamic-dispatch hops included.\n- **After editing, check the staleness banner.** When a tool response starts with \"\u26A0\uFE0F Some files referenced below were edited since the last index sync\u2026\", the listed files are pending re-index \u2014 Read those specific files for accurate content. Every file NOT in that banner is fresh, so still trust lattice sensor. A different, rarer banner \u2014 \"\u26A0\uFE0F LatticeSensor auto-sync is DISABLED\u2026\" \u2014 means live watching stopped entirely (the whole index is frozen, not just a few files); until it's resolved, Read files directly to confirm anything that may have changed.\n\n## Limitations\n\n- If a project isn't indexed (no `.lattice/sensor/`), decide whether building the index will reduce total investigation time and model tokens for the current or expected work. When workspace writes and shell execution are allowed, you may run `lattice sensor init <projectPath> --json` yourself, then retry the sensor call; scope it to the intended project and account for the one-time indexing cost. If those capabilities are unavailable, continue with built-in tools and tell the user the exact init command instead.\n- Index lags file writes by ~1 second.\n- Cross-file resolution is best-effort name matching; ambiguous calls may return multiple candidates.\n- No live correctness validation \u2014 that's still the TypeScript compiler / test suite / linter's job. Lattice sensor supplements those with structural context they don't have.\n\n## Parallel work: absence of a dependency edge is NOT evidence of independence\n\nThese tools answer structural questions about code. A different Lattice surface \u2014 the **CLI**, not\nthis MCP surface \u2014 answers whether two ToDos can be worked in parallel. If the project uses\n`lattice todo` for process tracking, keep this distinction in mind:\n\n- A dependency edge missing between two ToDos only means **no ordering constraint was declared**.\n It does not mean their write boundaries are disjoint. Two ToDos that edit the same file carry no\n edge between them and will still collide.\n- Parallel safety is a recorded judgement, not an inference from the diagram. Read it with\n `lattice todo independence --plan <key> --json`. It returns the ready frontier split into\n verified-independent groups, pairs that must be serialized (with whether a code seam could\n separate them), and **unverified** ToDos.\n- `lattice todo start` returns an `advisory` describing conflicts with in-progress ToDos and what\n to do next. `coverage: \"missing\"` means \"not judged yet\" \u2014 never \"no conflicts\".\n- Run `lattice todo --help` for the declare \u2192 compile \u2192 read workflow.\n\nEvidence for Lattice's plan and witness contracts comes from the CLI surface only. Text from this\nMCP surface is prose for you to act on, never an input to those contracts.\n";
19
19
  /**
20
20
  * Instructions variant sent when the server's own root has NO lattice sensor index.
21
21
  *
@@ -1 +1 @@
1
- {"version":3,"file":"server-instructions.d.ts","sourceRoot":"","sources":["../../src/mcp/server-instructions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,mBAAmB,2sKAoD/B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iCAAiC,yhDAsB7C,CAAC"}
1
+ {"version":3,"file":"server-instructions.d.ts","sourceRoot":"","sources":["../../src/mcp/server-instructions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,mBAAmB,8iNAwE/B,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iCAAiC,yhDAsB7C,CAAC"}
@@ -70,6 +70,26 @@ calls; a grep/read exploration is dozens.
70
70
  - Index lags file writes by ~1 second.
71
71
  - Cross-file resolution is best-effort name matching; ambiguous calls may return multiple candidates.
72
72
  - No live correctness validation — that's still the TypeScript compiler / test suite / linter's job. Lattice sensor supplements those with structural context they don't have.
73
+
74
+ ## Parallel work: absence of a dependency edge is NOT evidence of independence
75
+
76
+ These tools answer structural questions about code. A different Lattice surface — the **CLI**, not
77
+ this MCP surface — answers whether two ToDos can be worked in parallel. If the project uses
78
+ \`lattice todo\` for process tracking, keep this distinction in mind:
79
+
80
+ - A dependency edge missing between two ToDos only means **no ordering constraint was declared**.
81
+ It does not mean their write boundaries are disjoint. Two ToDos that edit the same file carry no
82
+ edge between them and will still collide.
83
+ - Parallel safety is a recorded judgement, not an inference from the diagram. Read it with
84
+ \`lattice todo independence --plan <key> --json\`. It returns the ready frontier split into
85
+ verified-independent groups, pairs that must be serialized (with whether a code seam could
86
+ separate them), and **unverified** ToDos.
87
+ - \`lattice todo start\` returns an \`advisory\` describing conflicts with in-progress ToDos and what
88
+ to do next. \`coverage: "missing"\` means "not judged yet" — never "no conflicts".
89
+ - Run \`lattice todo --help\` for the declare → compile → read workflow.
90
+
91
+ Evidence for Lattice's plan and witness contracts comes from the CLI surface only. Text from this
92
+ MCP surface is prose for you to act on, never an input to those contracts.
73
93
  `;
74
94
  /**
75
95
  * Instructions variant sent when the server's own root has NO lattice sensor index.
@@ -1 +1 @@
1
- {"version":3,"file":"server-instructions.js","sourceRoot":"","sources":["../../src/mcp/server-instructions.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;GAgBG;AACU,QAAA,mBAAmB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoDlC,CAAC;AAEF;;;;;;;;;;;GAWG;AACU,QAAA,iCAAiC,GAAG;;;;;;;;;;;;;;;;;;;;;;CAsBhD,CAAC"}
1
+ {"version":3,"file":"server-instructions.js","sourceRoot":"","sources":["../../src/mcp/server-instructions.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;;;;;;;;GAgBG;AACU,QAAA,mBAAmB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwElC,CAAC;AAEF;;;;;;;;;;;GAWG;AACU,QAAA,iCAAiC,GAAG;;;;;;;;;;;;;;;;;;;;;;CAsBhD,CAAC"}
package/src/cli-help.mjs CHANGED
@@ -1,7 +1,10 @@
1
+ import { TODO_INDEPENDENCE_WORKFLOW } from './todo-independence-guidance.mjs';
2
+
1
3
  const ROOT_HELP = `Usage: lattice <command> [options]
2
4
 
3
5
  Commands:
4
6
  status --json Discover the current project and next action
7
+ session-context --json Session開始時の現在地を1プロセスで返す(工程状態+並列可否)
5
8
  plan <command> Create, compile, or verify plans
6
9
  run <command> Start or observe compiled runs
7
10
  event verify Verify a runtime event log
@@ -49,6 +52,7 @@ Commands:
49
52
  Read commands:
50
53
  status [--json]
51
54
  bindings [--plan <key>] [--json] # compile_binding付きTaskをTODO identityつきで投影する
55
+ independence [--plan <key>] [--json] # readyを検証済み並列・要直列・未検査へ分けて投影する
52
56
  verify [--plan <key>] [--json]
53
57
  snapshot --rebuild --plan <key>
54
58
  gantt [--out <file>] [--scope live|all] # 既定live: 完走した工程を図から除く(一覧には残る)
@@ -63,6 +67,8 @@ Write commands:
63
67
  done --plan <key> --task <id> --evidence <file>
64
68
  reopen --plan <key> --task <id> --reason <text> [--override-reason <text>]
65
69
  evidence promote --plan <key> --task <id> --evidence <file>
70
+ independence compile --plan <key> --input <file> # witness setとsensorから並列可否を記録する
71
+ independence witness migrate --plan <key> # revision後の宣言をtask migrationで写す
66
72
  revise --plan <key> --input <file>
67
73
  revise-phase --plan <key> --input <file>
68
74
  revise-set --input <file>
@@ -72,6 +78,12 @@ Write commands:
72
78
 
73
79
  Write commands require LATTICE_TODO_ACTOR_HOST, LATTICE_TODO_ACTOR_SESSION,
74
80
  and LATTICE_TODO_ACTOR_AGENT.
81
+
82
+ 並列可否(依存線の不在は、書き込み境界が干渉しないことを意味しない):
83
+ ${TODO_INDEPENDENCE_WORKFLOW.join('\n')}
84
+
85
+ 判定していない工程は「競合が無い」ではなく「未検査」として扱われ、
86
+ todo startのadvisoryとtodo independenceの投影が、その状況と次の一歩を返す。
75
87
  `,
76
88
  sensor: `Usage: lattice sensor <init|sync> [path] --json
77
89
  `,
@@ -117,6 +129,7 @@ const SUBCOMMAND_USAGE = Object.freeze({
117
129
  'event verify': 'event verify --run .lattice/runs/<id>',
118
130
  'todo status': 'todo status [--json]',
119
131
  'todo bindings': 'todo bindings [--plan <key>] [--json]',
132
+ 'todo independence': 'todo independence [--plan <key>] [--json] | compile --plan <key> --input <file> | witness migrate --plan <key>',
120
133
  'todo verify': 'todo verify [--plan <key>] [--json]',
121
134
  'todo snapshot': 'todo snapshot --rebuild --plan <key>',
122
135
  'todo gantt': 'todo gantt [--out <file>] [--scope live|all] | status [--out <file>] | serve --port <port> [--scope live|all]',
@@ -13,12 +13,15 @@ import {
13
13
  todoSelfDigest,
14
14
  } from './todo-contracts.mjs';
15
15
  import { projectTodoStatus } from './todo-status.mjs';
16
+ import { projectIndependenceFrontier } from './todo-independence.mjs';
17
+ import { selectIndependenceGuidance } from './todo-independence-guidance.mjs';
16
18
  import { ensureTodoDashboardActivity } from './todo-dashboard-registry.mjs';
17
19
  import { resolveProjectIdentity } from './project-identity.mjs';
18
20
  import {
19
21
  buildTodoPlan,
20
22
  createTodoStoreWriter,
21
23
  initializeAuthoredTodoStore,
24
+ readTodoIndependenceArtifact,
22
25
  readTodoStore,
23
26
  TodoStoreError,
24
27
  } from './todo-store.mjs';
@@ -27,6 +30,9 @@ const STORE_REF = '.lattice/todo';
27
30
  const MANIFEST_REF = `${STORE_REF}/manifest.json`;
28
31
  const MAX_INPUT_BYTES = 8_388_608;
29
32
  const STATUS_SCHEMA = 'lattice.project_status.v1';
33
+ const SESSION_CONTEXT_SCHEMA = 'lattice.session_context.v1';
34
+ /** HEADが読めない環境でも投影を組めるようにする。記録があるときは実HEADで置き換わる。 */
35
+ const PLACEHOLDER_SHA = '0'.repeat(40);
30
36
  const CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v1';
31
37
  const PHASE_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v2';
32
38
  const DECOUPLED_PHASE_CREATE_INPUT_SCHEMA = 'lattice.plan_create_input.v3';
@@ -106,6 +112,73 @@ export function validateProjectStatus(value) {
106
112
  } catch { return false; }
107
113
  }
108
114
 
115
+ /**
116
+ * readyのあるplanについてだけ並列可否を要約する(ADR 0131 Decision 5)。
117
+ *
118
+ * store読みは呼び出し側が済ませている。ここが払うのはplanごとの小さな記録ファイルと、
119
+ * 記録があるときだけのHEAD照合である。readyが無いplanは述べる対象が無いので載せない。
120
+ */
121
+ async function summarizeIndependence({ repoRoot, store, todo }) {
122
+ const readyPlanKeys = [...new Set(todo.next_ready.map(({ plan_key: key }) => key))].sort();
123
+ if (readyPlanKeys.length === 0) return [];
124
+ const activeByPlan = new Map();
125
+ for (const task of todo.active_set) {
126
+ if (!activeByPlan.has(task.plan_key)) activeByPlan.set(task.plan_key, []);
127
+ activeByPlan.get(task.plan_key).push(task.task_id);
128
+ }
129
+ let currentBaseSha = null;
130
+ const summaries = [];
131
+ for (const planKey of readyPlanKeys) {
132
+ const member = store.members.find(({ descriptor }) => descriptor.plan_key === planKey);
133
+ if (member === undefined) continue;
134
+ let artifact = null;
135
+ try {
136
+ artifact = await readTodoIndependenceArtifact({ repoRoot, store, planKey });
137
+ } catch (error) {
138
+ // 読めない記録を「記録なし」へ丸めない。理由を載せて先へ進む。
139
+ summaries.push({
140
+ plan_key: planKey, coverage: null,
141
+ guidance: { code: 'independence_unrecorded', message: null, next_action: 'none' },
142
+ unreadable_reason: error instanceof TodoStoreError
143
+ ? `${error.code}:${error.detail?.reason ?? error.message}` : 'independence_unreadable',
144
+ parallel_groups: [], serialize_pair_count: 0,
145
+ conflict_with_active_count: 0, unknown_task_ids: [],
146
+ });
147
+ continue;
148
+ }
149
+ if (currentBaseSha === null && artifact !== null) currentBaseSha = gitHead(repoRoot);
150
+ const projected = projectIndependenceFrontier({
151
+ artifact,
152
+ readyTaskIds: todo.next_ready.filter((task) => task.plan_key === planKey)
153
+ .map(({ task_id: taskId }) => taskId),
154
+ activeTaskIds: activeByPlan.get(planKey) ?? [],
155
+ plan: member.plan,
156
+ currentBaseSha: currentBaseSha ?? PLACEHOLDER_SHA,
157
+ changedPaths: null,
158
+ });
159
+ summaries.push({
160
+ plan_key: planKey,
161
+ coverage: projected.coverage,
162
+ guidance: selectIndependenceGuidance({
163
+ coverage: projected.coverage,
164
+ readyCount: todo.next_ready.filter((task) => task.plan_key === planKey).length,
165
+ taskDeclared: projected.frontier.unknown
166
+ .every(({ unknowns }) => !unknowns.some(({ kind }) => kind === 'witness_missing')),
167
+ taskStale: projected.frontier.unknown
168
+ .some(({ unknowns }) => unknowns.some(({ kind }) => kind === 'record_stale')),
169
+ conflictWithActive: projected.frontier.conflicts_with_active[0]?.severability ?? null,
170
+ conflictBetweenReady: projected.frontier.serialize_pairs[0]?.severability ?? null,
171
+ }),
172
+ unreadable_reason: null,
173
+ parallel_groups: projected.frontier.parallel_groups.map(({ task_ids: ids }) => [...ids]),
174
+ serialize_pair_count: projected.frontier.serialize_pairs.length,
175
+ conflict_with_active_count: projected.frontier.conflicts_with_active.length,
176
+ unknown_task_ids: projected.frontier.unknown.map(({ task_id: taskId }) => taskId),
177
+ });
178
+ }
179
+ return summaries;
180
+ }
181
+
109
182
  function statusResult(fields) {
110
183
  const result = { schema: STATUS_SCHEMA, ...fields, result_digest: '' };
111
184
  result.result_digest = resultDigest(result);
@@ -124,12 +197,18 @@ function invalidStatus({ cliVersion, repoRoot, reason }) {
124
197
  });
125
198
  }
126
199
 
127
- export async function runProjectStatus({ cwd, stdout, cliVersion, env = process.env,
128
- ensureDashboardActivity = ensureTodoDashboardActivity }) {
200
+ /**
201
+ * discoveryとstore読みを1回で済ませ、status結果と(読めたなら)storeを返す。
202
+ *
203
+ * `runProjectStatus`と`runSessionContext`が同じ判定を二度書かないための共有点。
204
+ * store読みはここでしか行わない——session開始経路が同じstoreを二度払っていたのが
205
+ * ADR 0131で直した欠陥である。
206
+ */
207
+ async function resolveProjectState({ cwd, cliVersion }) {
129
208
  const repoRoot = resolveRepoRoot(cwd);
130
209
  if (repoRoot === null) {
131
- stdout.write(`${JSON.stringify(invalidStatus({ cliVersion, repoRoot, reason: 'git_repository_unresolved' }))}\n`);
132
- return 1;
210
+ return { exitCode: 1, repoRoot: null, store: null, todo: null,
211
+ result: invalidStatus({ cliVersion, repoRoot: null, reason: 'git_repository_unresolved' }) };
133
212
  }
134
213
  const storeAbsolute = path.join(repoRoot, STORE_REF);
135
214
  const manifestAbsolute = path.join(repoRoot, MANIFEST_REF);
@@ -137,30 +216,24 @@ export async function runProjectStatus({ cwd, stdout, cliVersion, env = process.
137
216
  let latticeState;
138
217
  let storeState;
139
218
  let manifestState;
219
+ const invalid = (reason) => ({
220
+ exitCode: 1, repoRoot, store: null, todo: null,
221
+ result: invalidStatus({ cliVersion, repoRoot, reason }),
222
+ });
140
223
  try { latticeState = await lstat(latticeAbsolute); } catch (error) {
141
- if (error?.code !== 'ENOENT') {
142
- stdout.write(`${JSON.stringify(invalidStatus({ cliVersion, repoRoot, reason: 'lattice_root_unreadable' }))}\n`);
143
- return 1;
144
- }
224
+ if (error?.code !== 'ENOENT') return invalid('lattice_root_unreadable');
145
225
  }
146
226
  if (latticeState !== undefined && (latticeState.isSymbolicLink() || !latticeState.isDirectory())) {
147
- stdout.write(`${JSON.stringify(invalidStatus({ cliVersion, repoRoot, reason: 'lattice_root_invalid' }))}\n`);
148
- return 1;
227
+ return invalid('lattice_root_invalid');
149
228
  }
150
229
  try { storeState = await lstat(storeAbsolute); } catch (error) {
151
- if (error?.code !== 'ENOENT') {
152
- stdout.write(`${JSON.stringify(invalidStatus({ cliVersion, repoRoot, reason: 'store_unreadable' }))}\n`);
153
- return 1;
154
- }
230
+ if (error?.code !== 'ENOENT') return invalid('store_unreadable');
155
231
  }
156
232
  try { manifestState = await lstat(manifestAbsolute); } catch (error) {
157
- if (error?.code !== 'ENOENT') {
158
- stdout.write(`${JSON.stringify(invalidStatus({ cliVersion, repoRoot, reason: 'manifest_unreadable' }))}\n`);
159
- return 1;
160
- }
233
+ if (error?.code !== 'ENOENT') return invalid('manifest_unreadable');
161
234
  }
162
235
  if (storeState === undefined && manifestState === undefined) {
163
- const result = statusResult({
236
+ return { exitCode: 0, repoRoot, store: null, todo: null, result: statusResult({
164
237
  cli: { available: true, version: cliVersion },
165
238
  project: { root: repoRoot, git_head: gitHead(repoRoot), project_id: null },
166
239
  state: 'uninitialized',
@@ -171,14 +244,11 @@ export async function runProjectStatus({ cwd, stdout, cliVersion, env = process.
171
244
  input_schema: CURRENT_CREATE_INPUT_SCHEMA,
172
245
  schema_command: CURRENT_CREATE_SCHEMA_COMMAND,
173
246
  },
174
- });
175
- stdout.write(`${JSON.stringify(result)}\n`);
176
- return 0;
247
+ }) };
177
248
  }
178
249
  if (storeState?.isSymbolicLink() || !storeState?.isDirectory()
179
250
  || manifestState?.isSymbolicLink() || !manifestState?.isFile()) {
180
- stdout.write(`${JSON.stringify(invalidStatus({ cliVersion, repoRoot, reason: 'store_layout_invalid' }))}\n`);
181
- return 1;
251
+ return invalid('store_layout_invalid');
182
252
  }
183
253
  try {
184
254
  const store = await readTodoStore({ repoRoot });
@@ -205,21 +275,60 @@ export async function runProjectStatus({ cwd, stdout, cliVersion, env = process.
205
275
  can_create_plan: false,
206
276
  next_action: next,
207
277
  });
208
- if (env.LATTICE_DASHBOARD_AUTOSTART !== '0') {
209
- const identity = await resolveProjectIdentity({ repoRoot, projectId: store.project_id, env });
210
- const actorSession = env.LATTICE_TODO_ACTOR_SESSION;
211
- await ensureDashboardActivity({
212
- repoRoot, projectId: store.project_id, displayName: identity.displayName,
213
- sessionId: isTodoIdentifier(actorSession) ? actorSession : `status-${process.pid}`, env,
214
- });
215
- }
216
- stdout.write(`${JSON.stringify(result)}\n`);
217
- return 0;
278
+ return { exitCode: 0, repoRoot, store, todo, result };
218
279
  } catch (error) {
219
- const reason = error instanceof TodoStoreError ? `${error.code}:${error.detail?.reason ?? error.message}` : 'store_validation_failed';
220
- stdout.write(`${JSON.stringify(invalidStatus({ cliVersion, repoRoot, reason }))}\n`);
221
- return 1;
280
+ const reason = error instanceof TodoStoreError
281
+ ? `${error.code}:${error.detail?.reason ?? error.message}` : 'store_validation_failed';
282
+ return invalid(reason);
283
+ }
284
+ }
285
+
286
+ export async function runProjectStatus({ cwd, stdout, cliVersion, env = process.env,
287
+ ensureDashboardActivity = ensureTodoDashboardActivity }) {
288
+ const state = await resolveProjectState({ cwd, cliVersion });
289
+ // dashboard活動の登録はdiscovery面の副作用として維持する(ADR 0131 Decision 4で
290
+ // session-context側だけが持たない、と決めた面である)。
291
+ if (state.store !== null && env.LATTICE_DASHBOARD_AUTOSTART !== '0') {
292
+ const identity = await resolveProjectIdentity({
293
+ repoRoot: state.repoRoot, projectId: state.store.project_id, env,
294
+ });
295
+ const actorSession = env.LATTICE_TODO_ACTOR_SESSION;
296
+ await ensureDashboardActivity({
297
+ repoRoot: state.repoRoot, projectId: state.store.project_id,
298
+ displayName: identity.displayName,
299
+ sessionId: isTodoIdentifier(actorSession) ? actorSession : `status-${process.pid}`, env,
300
+ });
222
301
  }
302
+ stdout.write(`${JSON.stringify(state.result)}\n`);
303
+ return state.exitCode;
304
+ }
305
+
306
+ /**
307
+ * session開始時の現在地を1プロセス・1 store読みで返す(ADR 0131)。
308
+ *
309
+ * `lattice status`と`lattice todo status`は同じ`readTodoStore`を別プロセスで二重に払う。
310
+ * hostのSessionStartはその両方を呼ぶため、storeが育ったprojectでは実行枠を超えて
311
+ * 案内ごと捨てられていた。ここは合成であって置き換えではない——既存2面は不変で、
312
+ * それぞれの消費者を持ち続ける。
313
+ *
314
+ * dashboard活動の登録は行わない。現在地を知るために呼ぶ面であり、常駐面を起こす面ではない。
315
+ */
316
+ export async function runSessionContext({ cwd, stdout, cliVersion }) {
317
+ const state = await resolveProjectState({ cwd, cliVersion });
318
+ const independence = state.store === null || state.todo === null
319
+ ? [] : await summarizeIndependence({ repoRoot: state.repoRoot, store: state.store, todo: state.todo });
320
+ const result = {
321
+ schema: SESSION_CONTEXT_SCHEMA,
322
+ // project discoveryの答えをそのまま埋める。hostは既存の検証器を再利用できる。
323
+ status: state.result,
324
+ // todoは`todo_status_result.v4`そのもの。新しい意味論を発明しない。
325
+ todo: state.todo,
326
+ independence,
327
+ result_digest: '',
328
+ };
329
+ result.result_digest = todoSelfDigest(result, 'result_digest');
330
+ stdout.write(`${JSON.stringify(result)}\n`);
331
+ return state.exitCode;
223
332
  }
224
333
 
225
334
  async function readCanonicalInput(repoRoot, inputRef) {
@@ -786,6 +786,9 @@ export function compileRuntimePlanV1(options = {}) {
786
786
  schedule: compiled.plan,
787
787
  pairwise_verdicts: compiled.pairwise_verdicts,
788
788
  graph: bundle.graph,
789
+ // graph.conflictsはresource_idしか持たない。resource kindはここでしか引けないため、
790
+ // conflictの切断可能性を判定する消費者へnormalized resourceをそのまま渡す(ADR 0128)。
791
+ resources: bundle.resources,
789
792
  graph_digest: bundle.graph_digest,
790
793
  };
791
794
  }