@quolu/lattice 0.52.4 → 0.53.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +147 -147
  2. package/README.ja.md +355 -355
  3. package/README.md +258 -258
  4. package/bin/lattice-bridge-supervisor.mjs +58 -0
  5. package/bin/lattice-bridge.mjs +25 -0
  6. package/bin/lattice-hub.mjs +67 -0
  7. package/bin/lattice-mcp.mjs +0 -0
  8. package/bin/lattice-scripted-adapter.mjs +0 -0
  9. package/bin/lattice-scripted-worker.mjs +0 -0
  10. package/bin/lattice-work-order-adapter.mjs +0 -0
  11. package/bin/lattice.mjs +0 -0
  12. package/docs/bridge-setup.md +132 -132
  13. package/docs/schemas/lattice.executor_packet.v1.schema.json +57 -57
  14. package/docs/schemas/lattice.executor_receipt.v1.schema.json +66 -66
  15. package/docs/schemas/lattice.phase_todo_revision.v3.schema.json +360 -360
  16. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -56
  17. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -72
  18. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -81
  19. package/docs/schemas/lattice.plan_create_input.v4.schema.json +85 -85
  20. package/docs/schemas/lattice.run_request.v1.schema.json +238 -238
  21. package/docs/schemas/lattice.runtime_adapter_capabilities.v2.schema.json +55 -55
  22. package/docs/schemas/lattice.runtime_adapter_registration_input.v1.schema.json +78 -78
  23. package/docs/schemas/lattice.runtime_adapter_registration_input.v2.schema.json +86 -86
  24. package/docs/schemas/lattice.todo_extraction.v2.schema.json +298 -298
  25. package/docs/schemas/lattice.todo_extraction.v3.schema.json +146 -146
  26. package/docs/schemas/lattice.todo_revision.v2.schema.json +260 -260
  27. package/docs/schemas/lattice.todo_revision_set.v3.schema.json +363 -363
  28. package/package.json +103 -103
  29. package/sensor/LICENSE +21 -21
  30. package/sensor/NOTICE +19 -19
  31. package/sensor/dist/bin/lattice-sensor.js +9 -9
  32. package/sensor/dist/db/index.js +24 -24
  33. package/sensor/dist/db/migrations.js +41 -41
  34. package/sensor/dist/db/queries.js +164 -164
  35. package/sensor/dist/db/schema.sql +205 -205
  36. package/sensor/dist/directory.js +5 -5
  37. package/sensor/dist/extraction/wasm/tree-sitter-c_sharp.wasm +0 -0
  38. package/sensor/dist/extraction/wasm/tree-sitter-cfml.wasm +0 -0
  39. package/sensor/dist/extraction/wasm/tree-sitter-cfquery.wasm +0 -0
  40. package/sensor/dist/extraction/wasm/tree-sitter-cfscript.wasm +0 -0
  41. package/sensor/dist/extraction/wasm/tree-sitter-cobol.wasm +0 -0
  42. package/sensor/dist/extraction/wasm/tree-sitter-erlang.wasm +0 -0
  43. package/sensor/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  44. package/sensor/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  45. package/sensor/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  46. package/sensor/dist/extraction/wasm/tree-sitter-nix.wasm +0 -0
  47. package/sensor/dist/extraction/wasm/tree-sitter-pascal.wasm +0 -0
  48. package/sensor/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  49. package/sensor/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  50. package/sensor/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  51. package/sensor/dist/extraction/wasm/tree-sitter-vbnet.wasm +0 -0
  52. package/sensor/dist/mcp/liveness-watchdog.js +53 -53
  53. package/sensor/dist/mcp/server-instructions.js +95 -95
  54. package/sensor/package.json +56 -56
  55. package/src/bridge-cli.mjs +32 -7
  56. package/src/bridge-config.mjs +49 -6
  57. package/src/bridge-daemon.mjs +4 -1
  58. package/src/bridge-hub-heartbeat.mjs +170 -0
  59. package/src/bridge-hub-server.mjs +555 -0
  60. package/src/bridge-registrar.mjs +18 -0
  61. package/src/bridge-server.mjs +4 -1
  62. package/src/bridge-startup-folder.mjs +348 -0
  63. package/src/cli-help.mjs +4 -4
  64. package/src/todo-store.mjs +1 -1
@@ -18,79 +18,79 @@ exports.SERVER_INSTRUCTIONS_NO_ROOT_INDEX = exports.SERVER_INSTRUCTIONS = void 0
18
18
  * burn tokens. ADR 0049 / 0059 require the eight compatibility tools to remain
19
19
  * visible by default; provider identity is Lattice regardless of their names.
20
20
  */
21
- exports.SERVER_INSTRUCTIONS = `# Lattice sensor — code intelligence over an indexed knowledge graph
22
-
23
- Provider 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.
24
-
25
- Lattice sensor is a SQLite knowledge graph of every symbol, edge, and file in
26
- the workspace — pre-computed structure you would otherwise re-derive by
27
- reading files (cached intelligence: thousands of parse/trace decisions you
28
- don't pay to re-reason each run). Reads are sub-millisecond; the index lags
29
- writes by ~1s through the file watcher. Reach for it BEFORE *and* while
30
- writing or editing code — not just for questions: one call returns the
31
- verbatim source PLUS who calls it and what it affects, so you edit with the
32
- blast radius in view. More accurate context, in far fewer tokens and
33
- round-trips than reading files yourself.
34
-
35
- ## One tool: lattice_sensor_explore — use it instead of reading files
36
-
37
- There is a single tool, \`lattice_sensor_explore\`, and it is Read-equivalent. It
38
- takes either a natural-language question or a bag of symbol/file names and
39
- returns the **verbatim, line-numbered source** of the relevant symbols
40
- grouped by file — the same \`<n>\\t<line>\` shape \`Read\` gives you, safe to
41
- \`Edit\` from — PLUS the call path among them (including dynamic-dispatch hops
42
- like callbacks, React re-render, and JSX children that grep can't follow) and
43
- a blast-radius summary of what depends on them.
44
-
45
- Whether you're answering "how does X work" or implementing a change (fixing a
46
- bug, adding a feature), call \`lattice_sensor_explore\` before you Read. ONE call
47
- usually answers the whole question. Lattice sensor IS the pre-built search index —
48
- so running your own grep + read loop, or delegating the lookup to a separate
49
- file-reading sub-task/agent, repeats work lattice sensor already did and costs more
50
- for the same answer. A direct lattice sensor answer is typically one to a few
51
- calls; a grep/read exploration is dozens.
52
-
53
- ## How to query
54
-
55
- - **Almost any question — "how does X work", architecture, a bug, "what/where is X", or surveying an area** → \`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.
56
- - **"How does X reach/become Y? / the flow / the path from X to Y"** → \`lattice_sensor_explore\`, naming the symbols that span the flow (e.g. \`mutateElement renderScene\`) — it surfaces the call path among them, riding dynamic-dispatch hops, and returns their source.
57
- - **Reading or editing a file/symbol you can name** → put its name or file path in the \`lattice_sensor_explore\` query — 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.
58
- - **Need more?** Call \`lattice_sensor_explore\` again with more specific names — treat the source it returns as already Read.
59
-
60
- ## Anti-patterns
61
-
62
- - **Trust lattice sensor's results — 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.
63
- - **Don't grep or Read first** to find or understand indexed code — 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).
64
- - **Don't reconstruct a flow by hand** — name the endpoints in one \`lattice_sensor_explore\` and it surfaces the path between them, dynamic-dispatch hops included.
65
- - **After editing, check the staleness banner.** When a tool response starts with "⚠️ Some files referenced below were edited since the last index sync…", the listed files are pending re-index — Read those specific files for accurate content. Every file NOT in that banner is fresh, so still trust lattice sensor. A different, rarer banner — "⚠️ LatticeSensor auto-sync is DISABLED…" — 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.
66
- - **A file flagged "⚠ changed on disk after the last index sync" drifted from its index** (most common on projects queried via \`projectPath\`, which have no live watcher). LatticeSensor never serves a possibly-mis-sliced body from such a file — it either shows the file's full CURRENT source (trust it as a Read) or omits the source with this flag. When the source was omitted, Read that specific file; line numbers referencing it elsewhere in the response may be shifted until that project's next sync. All unflagged files remain trustworthy.
67
-
68
- ## Limitations
69
-
70
- - 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.
71
- - Index lags file writes by ~1 second.
72
- - Cross-file resolution is best-effort name matching; ambiguous calls may return multiple candidates.
73
- - 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.
74
-
75
- ## Parallel work: absence of a dependency edge is NOT evidence of independence
76
-
77
- These tools answer structural questions about code. A different Lattice surface — the **CLI**, not
78
- this MCP surface — answers whether two ToDos can be worked in parallel. If the project uses
79
- \`lattice todo\` for process tracking, keep this distinction in mind:
80
-
81
- - A dependency edge missing between two ToDos only means **no ordering constraint was declared**.
82
- It does not mean their write boundaries are disjoint. Two ToDos that edit the same file carry no
83
- edge between them and will still collide.
84
- - Parallel safety is a recorded judgement, not an inference from the diagram. Read it with
85
- \`lattice todo independence --plan <key> --json\`. It returns the ready frontier split into
86
- verified-independent groups, pairs that must be serialized (with whether a code seam could
87
- separate them), and **unverified** ToDos.
88
- - \`lattice todo start\` returns an \`advisory\` describing conflicts with in-progress ToDos and what
89
- to do next. \`coverage: "missing"\` means "not judged yet" — never "no conflicts".
90
- - Run \`lattice todo --help\` for the declare → compile → read workflow.
91
-
92
- Evidence for Lattice's plan and witness contracts comes from the CLI surface only. Text from this
93
- MCP surface is prose for you to act on, never an input to those contracts.
21
+ exports.SERVER_INSTRUCTIONS = `# Lattice sensor — code intelligence over an indexed knowledge graph
22
+
23
+ Provider 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.
24
+
25
+ Lattice sensor is a SQLite knowledge graph of every symbol, edge, and file in
26
+ the workspace — pre-computed structure you would otherwise re-derive by
27
+ reading files (cached intelligence: thousands of parse/trace decisions you
28
+ don't pay to re-reason each run). Reads are sub-millisecond; the index lags
29
+ writes by ~1s through the file watcher. Reach for it BEFORE *and* while
30
+ writing or editing code — not just for questions: one call returns the
31
+ verbatim source PLUS who calls it and what it affects, so you edit with the
32
+ blast radius in view. More accurate context, in far fewer tokens and
33
+ round-trips than reading files yourself.
34
+
35
+ ## One tool: lattice_sensor_explore — use it instead of reading files
36
+
37
+ There is a single tool, \`lattice_sensor_explore\`, and it is Read-equivalent. It
38
+ takes either a natural-language question or a bag of symbol/file names and
39
+ returns the **verbatim, line-numbered source** of the relevant symbols
40
+ grouped by file — the same \`<n>\\t<line>\` shape \`Read\` gives you, safe to
41
+ \`Edit\` from — PLUS the call path among them (including dynamic-dispatch hops
42
+ like callbacks, React re-render, and JSX children that grep can't follow) and
43
+ a blast-radius summary of what depends on them.
44
+
45
+ Whether you're answering "how does X work" or implementing a change (fixing a
46
+ bug, adding a feature), call \`lattice_sensor_explore\` before you Read. ONE call
47
+ usually answers the whole question. Lattice sensor IS the pre-built search index —
48
+ so running your own grep + read loop, or delegating the lookup to a separate
49
+ file-reading sub-task/agent, repeats work lattice sensor already did and costs more
50
+ for the same answer. A direct lattice sensor answer is typically one to a few
51
+ calls; a grep/read exploration is dozens.
52
+
53
+ ## How to query
54
+
55
+ - **Almost any question — "how does X work", architecture, a bug, "what/where is X", or surveying an area** → \`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.
56
+ - **"How does X reach/become Y? / the flow / the path from X to Y"** → \`lattice_sensor_explore\`, naming the symbols that span the flow (e.g. \`mutateElement renderScene\`) — it surfaces the call path among them, riding dynamic-dispatch hops, and returns their source.
57
+ - **Reading or editing a file/symbol you can name** → put its name or file path in the \`lattice_sensor_explore\` query — 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.
58
+ - **Need more?** Call \`lattice_sensor_explore\` again with more specific names — treat the source it returns as already Read.
59
+
60
+ ## Anti-patterns
61
+
62
+ - **Trust lattice sensor's results — 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.
63
+ - **Don't grep or Read first** to find or understand indexed code — 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).
64
+ - **Don't reconstruct a flow by hand** — name the endpoints in one \`lattice_sensor_explore\` and it surfaces the path between them, dynamic-dispatch hops included.
65
+ - **After editing, check the staleness banner.** When a tool response starts with "⚠️ Some files referenced below were edited since the last index sync…", the listed files are pending re-index — Read those specific files for accurate content. Every file NOT in that banner is fresh, so still trust lattice sensor. A different, rarer banner — "⚠️ LatticeSensor auto-sync is DISABLED…" — 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.
66
+ - **A file flagged "⚠ changed on disk after the last index sync" drifted from its index** (most common on projects queried via \`projectPath\`, which have no live watcher). LatticeSensor never serves a possibly-mis-sliced body from such a file — it either shows the file's full CURRENT source (trust it as a Read) or omits the source with this flag. When the source was omitted, Read that specific file; line numbers referencing it elsewhere in the response may be shifted until that project's next sync. All unflagged files remain trustworthy.
67
+
68
+ ## Limitations
69
+
70
+ - 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.
71
+ - Index lags file writes by ~1 second.
72
+ - Cross-file resolution is best-effort name matching; ambiguous calls may return multiple candidates.
73
+ - 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.
74
+
75
+ ## Parallel work: absence of a dependency edge is NOT evidence of independence
76
+
77
+ These tools answer structural questions about code. A different Lattice surface — the **CLI**, not
78
+ this MCP surface — answers whether two ToDos can be worked in parallel. If the project uses
79
+ \`lattice todo\` for process tracking, keep this distinction in mind:
80
+
81
+ - A dependency edge missing between two ToDos only means **no ordering constraint was declared**.
82
+ It does not mean their write boundaries are disjoint. Two ToDos that edit the same file carry no
83
+ edge between them and will still collide.
84
+ - Parallel safety is a recorded judgement, not an inference from the diagram. Read it with
85
+ \`lattice todo independence --plan <key> --json\`. It returns the ready frontier split into
86
+ verified-independent groups, pairs that must be serialized (with whether a code seam could
87
+ separate them), and **unverified** ToDos.
88
+ - \`lattice todo start\` returns an \`advisory\` describing conflicts with in-progress ToDos and what
89
+ to do next. \`coverage: "missing"\` means "not judged yet" — never "no conflicts".
90
+ - Run \`lattice todo --help\` for the declare → compile → read workflow.
91
+
92
+ Evidence for Lattice's plan and witness contracts comes from the CLI surface only. Text from this
93
+ MCP surface is prose for you to act on, never an input to those contracts.
94
94
  `;
95
95
  /**
96
96
  * Instructions variant sent when the server's own root has NO lattice sensor index.
@@ -104,27 +104,27 @@ MCP surface is prose for you to act on, never an input to those contracts.
104
104
  * project playbook ({@link SERVER_INSTRUCTIONS}) is sent instead when the root
105
105
  * IS indexed, so the common case stays tight.
106
106
  */
107
- exports.SERVER_INSTRUCTIONS_NO_ROOT_INDEX = `# Lattice sensor — available (per-project; pass projectPath)
108
-
109
- Provider 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.
110
-
111
- Lattice sensor is a SQLite knowledge graph of a codebase's symbols, edges, and
112
- files: one \`lattice_sensor_explore\` call returns the verbatim, line-numbered source
113
- of the relevant symbols PLUS the call paths between them and a blast-radius
114
- summary — replacing a grep + Read loop with one round-trip.
115
-
116
- This server started somewhere with no \`.lattice/sensor/\` of its own, so there is no
117
- default project — but the tools are available and work **per project**:
118
-
119
- - To query a project that HAS a \`.lattice/sensor/\` index (e.g. a service inside a
120
- monorepo, or a second repo), pass its path as \`projectPath\` to
121
- \`lattice_sensor_explore\` (and any other lattice sensor tool). Lattice sensor resolves the
122
- nearest \`.lattice/sensor/\` at or above that path and answers from it — for as many
123
- projects as you like in one session.
124
- - For a project with no \`.lattice/sensor/\`, decide whether the expected reduction in
125
- repeated Read/Grep work justifies the one-time indexing cost. When workspace writes
126
- and shell execution are allowed, you may run \`lattice sensor init <projectPath> --json\`
127
- yourself and then retry with that \`projectPath\`; otherwise use built-in tools and
128
- tell the user the exact init command. A new index is picked up live, with no restart.
107
+ exports.SERVER_INSTRUCTIONS_NO_ROOT_INDEX = `# Lattice sensor — available (per-project; pass projectPath)
108
+
109
+ Provider 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.
110
+
111
+ Lattice sensor is a SQLite knowledge graph of a codebase's symbols, edges, and
112
+ files: one \`lattice_sensor_explore\` call returns the verbatim, line-numbered source
113
+ of the relevant symbols PLUS the call paths between them and a blast-radius
114
+ summary — replacing a grep + Read loop with one round-trip.
115
+
116
+ This server started somewhere with no \`.lattice/sensor/\` of its own, so there is no
117
+ default project — but the tools are available and work **per project**:
118
+
119
+ - To query a project that HAS a \`.lattice/sensor/\` index (e.g. a service inside a
120
+ monorepo, or a second repo), pass its path as \`projectPath\` to
121
+ \`lattice_sensor_explore\` (and any other lattice sensor tool). Lattice sensor resolves the
122
+ nearest \`.lattice/sensor/\` at or above that path and answers from it — for as many
123
+ projects as you like in one session.
124
+ - For a project with no \`.lattice/sensor/\`, decide whether the expected reduction in
125
+ repeated Read/Grep work justifies the one-time indexing cost. When workspace writes
126
+ and shell execution are allowed, you may run \`lattice sensor init <projectPath> --json\`
127
+ yourself and then retry with that \`projectPath\`; otherwise use built-in tools and
128
+ tell the user the exact init command. A new index is picked up live, with no restart.
129
129
  `;
130
130
  //# sourceMappingURL=server-instructions.js.map
@@ -1,56 +1,56 @@
1
- {
2
- "name": "@quolu/lattice-sensor",
3
- "version": "0.7.3-lattice.1",
4
- "private": true,
5
- "description": "Lattice-owned local structural sensor.",
6
- "repository": {
7
- "type": "git",
8
- "url": "git+https://github.com/kitepon-rgb/Lattice.git"
9
- },
10
- "main": "dist/index.js",
11
- "types": "dist/index.d.ts",
12
- "files": [
13
- "dist",
14
- "README.md"
15
- ],
16
- "scripts": {
17
- "build": "npm run clean && tsc && npm run copy-assets",
18
- "copy-assets": "node -e \"const fs=require('fs');fs.mkdirSync('dist/db',{recursive:true});fs.copyFileSync('src/db/schema.sql','dist/db/schema.sql');fs.mkdirSync('dist/extraction/wasm',{recursive:true});fs.readdirSync('src/extraction/wasm').filter(f=>f.endsWith('.wasm')).forEach(f=>fs.copyFileSync('src/extraction/wasm/'+f,'dist/extraction/wasm/'+f))\"",
19
- "dev": "tsc --watch",
20
- "build:kernel": "bash scripts/build-kernel.sh",
21
- "test": "vitest run --maxWorkers=4 --minWorkers=1",
22
- "test:watch": "vitest",
23
- "test:eval": "vitest run __tests__/evaluation/",
24
- "eval": "npm run build && npx tsx __tests__/evaluation/runner.ts",
25
- "clean": "node -e \"const fs=require('fs');fs.rmSync('dist',{recursive:true,force:true})\""
26
- },
27
- "keywords": [
28
- "code-intelligence",
29
- "knowledge-graph",
30
- "static-analysis"
31
- ],
32
- "author": "",
33
- "license": "MIT",
34
- "dependencies": {
35
- "@clack/prompts": "^1.3.0",
36
- "commander": "^14.0.2",
37
- "fast-string-width": "^3.0.2",
38
- "fast-wrap-ansi": "^0.2.0",
39
- "ignore": "^7.0.5",
40
- "jsonc-parser": "^3.3.1",
41
- "picomatch": "^4.0.3",
42
- "sisteransi": "^1.0.5",
43
- "tree-sitter-wasms": "^0.1.11",
44
- "web-tree-sitter": "^0.25.3"
45
- },
46
- "devDependencies": {
47
- "@types/better-sqlite3": "^7.6.0",
48
- "@types/node": "^20.19.30",
49
- "@types/picomatch": "^4.0.2",
50
- "typescript": "^5.0.0",
51
- "vitest": "^2.1.9"
52
- },
53
- "engines": {
54
- "node": ">=20.0.0 <25.0.0 || >=26.0.0"
55
- }
56
- }
1
+ {
2
+ "name": "@quolu/lattice-sensor",
3
+ "version": "0.7.3-lattice.1",
4
+ "private": true,
5
+ "description": "Lattice-owned local structural sensor.",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/kitepon-rgb/Lattice.git"
9
+ },
10
+ "main": "dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "files": [
13
+ "dist",
14
+ "README.md"
15
+ ],
16
+ "scripts": {
17
+ "build": "npm run clean && tsc && npm run copy-assets",
18
+ "copy-assets": "node -e \"const fs=require('fs');fs.mkdirSync('dist/db',{recursive:true});fs.copyFileSync('src/db/schema.sql','dist/db/schema.sql');fs.mkdirSync('dist/extraction/wasm',{recursive:true});fs.readdirSync('src/extraction/wasm').filter(f=>f.endsWith('.wasm')).forEach(f=>fs.copyFileSync('src/extraction/wasm/'+f,'dist/extraction/wasm/'+f))\"",
19
+ "dev": "tsc --watch",
20
+ "build:kernel": "bash scripts/build-kernel.sh",
21
+ "test": "vitest run --maxWorkers=4 --minWorkers=1",
22
+ "test:watch": "vitest",
23
+ "test:eval": "vitest run __tests__/evaluation/",
24
+ "eval": "npm run build && npx tsx __tests__/evaluation/runner.ts",
25
+ "clean": "node -e \"const fs=require('fs');fs.rmSync('dist',{recursive:true,force:true})\""
26
+ },
27
+ "keywords": [
28
+ "code-intelligence",
29
+ "knowledge-graph",
30
+ "static-analysis"
31
+ ],
32
+ "author": "",
33
+ "license": "MIT",
34
+ "dependencies": {
35
+ "@clack/prompts": "^1.3.0",
36
+ "commander": "^14.0.2",
37
+ "fast-string-width": "^3.0.2",
38
+ "fast-wrap-ansi": "^0.2.0",
39
+ "ignore": "^7.0.5",
40
+ "jsonc-parser": "^3.3.1",
41
+ "picomatch": "^4.0.3",
42
+ "sisteransi": "^1.0.5",
43
+ "tree-sitter-wasms": "^0.1.11",
44
+ "web-tree-sitter": "^0.25.3"
45
+ },
46
+ "devDependencies": {
47
+ "@types/better-sqlite3": "^7.6.0",
48
+ "@types/node": "^20.19.30",
49
+ "@types/picomatch": "^4.0.2",
50
+ "typescript": "^5.0.0",
51
+ "vitest": "^2.1.9"
52
+ },
53
+ "engines": {
54
+ "node": ">=20.0.0 <25.0.0 || >=26.0.0"
55
+ }
56
+ }
@@ -17,11 +17,16 @@ import {
17
17
  disableBridgeLaunchAgent, installBridgeLaunchAgent, restoreBridgeLaunchAgent,
18
18
  snapshotBridgeLaunchAgent,
19
19
  } from './bridge-launch-agent.mjs';
20
+ import {
21
+ disableBridgeStartupFolder, installBridgeStartupFolder, restoreBridgeStartupFolder,
22
+ snapshotBridgeStartupFolder,
23
+ } from './bridge-startup-folder.mjs';
20
24
 
21
25
  // v2 adds the liveness fields. `enabled` only says the configuration is on;
22
26
  // it never said the bridge could actually be reached, which let a DHCP lease
23
27
  // change take the published surface down while status kept reporting health.
24
- const RESULT_SCHEMA = 'lattice.bridge_cli_result.v2';
28
+ // v3 adds `hub` (bh3): the terminal's registered bridge-hub, if any.
29
+ const RESULT_SCHEMA = 'lattice.bridge_cli_result.v3';
25
30
  const REACHABILITY_PROBE_TIMEOUT_MS = 750;
26
31
 
27
32
  /** TCP connect probe. Answers "is anything accepting there right now". */
@@ -65,13 +70,29 @@ async function bridgeLiveness(config, { interfaces = networkInterfaces(), probe
65
70
  };
66
71
  }
67
72
 
73
+ // The bridge's own persistence mechanism is OS-specific; everything above
74
+ // this line (config, daemon lifecycle, registrar) is not. Selecting by
75
+ // `process.platform` here — rather than requiring every caller to pick — is
76
+ // what lets `lattice bridge setup` on Windows persist via the Startup folder
77
+ // exactly the way it persists via a LaunchAgent on macOS, with no separate
78
+ // command or manual step (see bridge-startup-folder.mjs's module doc for why
79
+ // Task Scheduler's ONLOGON trigger could not be used instead).
80
+ function platformLaunchAgent() {
81
+ if (process.platform === 'win32') {
82
+ return { snapshot: snapshotBridgeStartupFolder, install: installBridgeStartupFolder,
83
+ disable: disableBridgeStartupFolder, restore: restoreBridgeStartupFolder };
84
+ }
85
+ return { snapshot: snapshotBridgeLaunchAgent, install: installBridgeLaunchAgent,
86
+ disable: disableBridgeLaunchAgent, restore: restoreBridgeLaunchAgent };
87
+ }
88
+
68
89
  function fail(stderr, code, message) {
69
90
  stderr.write(`${JSON.stringify({ schema: 'lattice.cli_error.v2', code, message })}\n`);
70
91
  return 2;
71
92
  }
72
93
 
73
94
  function parseOptions(words) {
74
- const options = { address: undefined, port: undefined, upstream: undefined, allowedHosts: [] };
95
+ const options = { address: undefined, port: undefined, upstream: undefined, hub: undefined, allowedHosts: [] };
75
96
  for (let index = 0; index < words.length; index += 1) {
76
97
  const flag = words[index];
77
98
  if (flag === '--listen') {
@@ -88,9 +109,13 @@ function parseOptions(words) {
88
109
  } else if (flag === '--upstream') {
89
110
  if (options.upstream !== undefined) throw new BridgeConfigError('USAGE', 'upstream option is ambiguous');
90
111
  options.upstream = { mode: 'url', url: words[++index] };
112
+ } else if (flag === '--hub') {
113
+ if (options.hub !== undefined) throw new BridgeConfigError('USAGE', 'duplicate --hub');
114
+ const value = words[++index];
115
+ options.hub = value === 'none' ? null : { url: value };
91
116
  } else if (flag === '--allow-host') options.allowedHosts.push(words[++index]);
92
117
  else throw new BridgeConfigError('USAGE', `unknown bridge option: ${flag}`);
93
- if ((flag === '--listen' || flag === '--port' || flag === '--upstream' || flag === '--allow-host')
118
+ if ((flag === '--listen' || flag === '--port' || flag === '--upstream' || flag === '--hub' || flag === '--allow-host')
94
119
  && words[index] === undefined) throw new BridgeConfigError('USAGE', `missing value for ${flag}`);
95
120
  }
96
121
  return options;
@@ -99,7 +124,7 @@ function parseOptions(words) {
99
124
  function result(action, config, recovery = null, liveness = null) {
100
125
  return { schema: RESULT_SCHEMA, action, configured: config !== null, enabled: config?.enabled ?? false,
101
126
  listen: config?.listen ?? null, allowed_hosts: config?.allowed_hosts ?? null,
102
- upstream: config?.upstream ?? null, updated_at: config?.updated_at ?? null, recovery,
127
+ upstream: config?.upstream ?? null, hub: config?.hub ?? null, updated_at: config?.updated_at ?? null, recovery,
103
128
  listen_state: liveness?.listen_state ?? null,
104
129
  effective_listen: liveness?.effective_listen ?? null,
105
130
  listen_candidates: liveness?.listen_candidates ?? null,
@@ -155,8 +180,7 @@ export async function collectBridgeSetupWizard({ input, output, prompts = clack
155
180
  export async function runBridgeCli({ argv, stdout, stderr, env = process.env,
156
181
  stdin = process.stdin, daemon = { ensure: ensureBridgeDaemon, requestStop: requestBridgeDaemonStop,
157
182
  stop: stopBridgeDaemon, clearStop: clearBridgeStopControl },
158
- launchAgent = { snapshot: snapshotBridgeLaunchAgent, install: installBridgeLaunchAgent,
159
- disable: disableBridgeLaunchAgent, restore: restoreBridgeLaunchAgent },
183
+ launchAgent = platformLaunchAgent(),
160
184
  prompts = clack, probe = probeBridgeListener, interfaces = networkInterfaces() } = {}) {
161
185
  if (!Array.isArray(argv)) {
162
186
  return fail(stderr, 'USAGE', 'usage: lattice bridge <setup|reconfigure|status|disable|register> [options] --json');
@@ -255,7 +279,8 @@ export async function runBridgeCli({ argv, stdout, stderr, env = process.env,
255
279
  const configured = await configureBridge({
256
280
  address: options.address ?? current?.listen.address,
257
281
  port: options.port === undefined ? (command === 'reconfigure' ? current?.listen.port ?? null : null) : options.port,
258
- upstream: options.upstream ?? current?.upstream ?? { mode: 'dashboard_descriptor' }, env,
282
+ upstream: options.upstream ?? current?.upstream ?? { mode: 'dashboard_descriptor' },
283
+ hub: options.hub === undefined ? current?.hub ?? null : options.hub, env,
259
284
  allowedHosts: options.allowedHosts.length > 0 ? options.allowedHosts
260
285
  : current?.allowed_hosts?.filter((host) => host !== current.listen.address) ?? [],
261
286
  reuseCurrentPort: options.port === undefined,
@@ -111,8 +111,32 @@ export function normalizeBridgeUpstream(upstream) {
111
111
  return Object.freeze({ mode: 'url', url: parsed.href });
112
112
  }
113
113
 
114
+ /**
115
+ * The hub this terminal heartbeats to (bh3), or null when unconfigured — most
116
+ * terminals never opt in. Unlike `upstream`, there is only one shape: an
117
+ * explicit HTTP(S) origin. There is no descriptor-derived variant because the
118
+ * hub is a separate host on the LAN, not something this terminal can discover
119
+ * from its own local state.
120
+ */
121
+ export function normalizeBridgeHubUrl(hub) {
122
+ if (hub === null) return null;
123
+ if (!exact(hub, ['url']) || typeof hub.url !== 'string') {
124
+ throw new BridgeConfigError('BRIDGE_HUB_URL_INVALID', 'bridge hub configuration is invalid');
125
+ }
126
+ let parsed;
127
+ try { parsed = new URL(hub.url); } catch {
128
+ throw new BridgeConfigError('BRIDGE_HUB_URL_INVALID', 'bridge hub URL is invalid');
129
+ }
130
+ if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username !== '' || parsed.password !== ''
131
+ || parsed.hash !== '' || parsed.search !== '') {
132
+ throw new BridgeConfigError('BRIDGE_HUB_URL_INVALID', 'bridge hub URL must be an HTTP origin');
133
+ }
134
+ parsed.pathname = parsed.pathname.endsWith('/') ? parsed.pathname : `${parsed.pathname}/`;
135
+ return Object.freeze({ url: parsed.href });
136
+ }
137
+
114
138
  export function validateBridgeConfig(value) {
115
- if (!exact(value, ['schema', 'enabled', 'listen', 'allowed_hosts', 'upstream', 'updated_at'])
139
+ if (!exact(value, ['schema', 'enabled', 'listen', 'allowed_hosts', 'upstream', 'hub', 'updated_at'])
116
140
  || value.schema !== BRIDGE_CONFIG_SCHEMA || typeof value.enabled !== 'boolean'
117
141
  || !validTimestamp(value.updated_at)) {
118
142
  throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge configuration schema is invalid');
@@ -124,12 +148,14 @@ export function validateBridgeConfig(value) {
124
148
  throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'allowed hosts are not canonical');
125
149
  }
126
150
  const upstream = normalizeBridgeUpstream(value.upstream);
151
+ const hub = normalizeBridgeHubUrl(value.hub);
127
152
  return Object.freeze({
128
153
  schema: BRIDGE_CONFIG_SCHEMA,
129
154
  enabled: value.enabled,
130
155
  listen: Object.freeze({ address: value.listen.address, port: value.listen.port }),
131
156
  allowed_hosts: allowedHosts,
132
157
  upstream,
158
+ hub,
133
159
  updated_at: value.updated_at,
134
160
  });
135
161
  }
@@ -149,7 +175,14 @@ async function readDocument(ref) {
149
175
  if (error?.code === 'ENOENT') return null;
150
176
  throw new BridgeConfigError('BRIDGE_CONFIG_UNREADABLE', 'bridge config cannot be read', undefined, error);
151
177
  }
152
- if (!stats.isFile() || stats.isSymbolicLink() || (stats.mode & 0o777) !== 0o600) {
178
+ // Windows has no POSIX permission-bit model: `fs.stat().mode` never reports
179
+ // 0600 there regardless of what `mode`/`chmod` requested at write time, so
180
+ // this check is a hard, unconditional block on every platform but darwin/
181
+ // linux — verified against a real Windows host (`BRIDGE_CONFIG_MODE_INVALID`
182
+ // on a config `configureBridge` itself had just written moments earlier).
183
+ // The other checks (regular file, not a symlink) still apply everywhere.
184
+ if (!stats.isFile() || stats.isSymbolicLink()
185
+ || (process.platform !== 'win32' && (stats.mode & 0o777) !== 0o600)) {
153
186
  throw new BridgeConfigError('BRIDGE_CONFIG_MODE_INVALID', 'bridge config must be a regular 0600 file');
154
187
  }
155
188
  let value;
@@ -175,6 +208,14 @@ async function readDocument(ref) {
175
208
  } catch (error) {
176
209
  throw new BridgeConfigError('BRIDGE_CONFIG_INVALID', 'bridge config JSON is invalid', undefined, error);
177
210
  }
211
+ // `hub` (bh3) postdates this schema's v1 tag, which never changed — an on-disk
212
+ // config written before bh3 has no `hub` key at all. Treat that absence as
213
+ // "never configured" rather than a schema violation, so a bridge that has
214
+ // been running since before hub support existed keeps reading its own
215
+ // config instead of failing closed the next time this code is deployed.
216
+ if (value !== null && typeof value === 'object' && !Array.isArray(value) && value.hub === undefined) {
217
+ value = { ...value, hub: null };
218
+ }
178
219
  return validateBridgeConfig(value);
179
220
  }
180
221
 
@@ -274,24 +315,25 @@ async function reservePort({ address, requestedPort, createCandidateServer, choo
274
315
  { address, attempts: attempted.size });
275
316
  }
276
317
 
277
- function validateMutation({ address, port, upstream, allowedHosts }) {
318
+ function validateMutation({ address, port, upstream, hub, allowedHosts }) {
278
319
  if (typeof address !== 'string' || isIP(address) === 0) {
279
320
  throw new BridgeConfigError('BRIDGE_LISTEN_INVALID', 'bridge listen address must be an IP literal');
280
321
  }
281
322
  if (port !== null && (!Number.isSafeInteger(port) || port < BRIDGE_PORT_MIN || port > BRIDGE_PORT_MAX)) {
282
323
  throw new BridgeConfigError('BRIDGE_PORT_INVALID', `bridge port must be ${BRIDGE_PORT_MIN}..${BRIDGE_PORT_MAX}`);
283
324
  }
284
- return { upstream: normalizeBridgeUpstream(upstream), allowedHosts: normalizeAllowedHosts(address, allowedHosts) };
325
+ return { upstream: normalizeBridgeUpstream(upstream), hub: normalizeBridgeHubUrl(hub),
326
+ allowedHosts: normalizeAllowedHosts(address, allowedHosts) };
285
327
  }
286
328
 
287
329
  export async function configureBridge({
288
- address, port = null, upstream = { mode: 'dashboard_descriptor' }, allowedHosts = [],
330
+ address, port = null, upstream = { mode: 'dashboard_descriptor' }, hub = null, allowedHosts = [],
289
331
  env = process.env, now = () => new Date(),
290
332
  createCandidateServer = () => createServer(),
291
333
  choosePort = () => randomInt(BRIDGE_PORT_MIN, BRIDGE_PORT_MAX + 1),
292
334
  reuseCurrentPort = true,
293
335
  } = {}) {
294
- const normalized = validateMutation({ address, port, upstream, allowedHosts });
336
+ const normalized = validateMutation({ address, port, upstream, hub, allowedHosts });
295
337
  const refs = bridgeConfigPaths(env);
296
338
  await prepareRoot(refs.root);
297
339
  return withLock(refs.lock, async () => {
@@ -312,6 +354,7 @@ export async function configureBridge({
312
354
  listen: { address, port: bindingUnchanged ? selectedPort : reservation.port },
313
355
  allowed_hosts: normalized.allowedHosts,
314
356
  upstream: normalized.upstream,
357
+ hub: normalized.hub,
315
358
  updated_at: now().toISOString(),
316
359
  });
317
360
  await atomicWrite(refs.config, config);
@@ -83,7 +83,10 @@ async function readStrictJsonOnce(ref, label) {
83
83
  let handle;
84
84
  try {
85
85
  before = await lstat(ref);
86
- if (!before.isFile() || before.isSymbolicLink() || (before.mode & 0o777) !== 0o600
86
+ // Windows has no POSIX permission-bit model see bridge-config.mjs's
87
+ // readDocument for the same guard and the real-host verification.
88
+ if (!before.isFile() || before.isSymbolicLink()
89
+ || (process.platform !== 'win32' && (before.mode & 0o777) !== 0o600)
87
90
  || before.size > CONTROL_MAX_BYTES) throw new Error(`${label} unsafe`);
88
91
  handle = await open(ref, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
89
92
  const opened = await handle.stat();