@coloopx/colocad 0.1.0-alpha.6 → 0.1.0-alpha.8

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 (60) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +14 -3
  3. package/README.zh-CN.md +13 -3
  4. package/ROADMAP.md +125 -0
  5. package/ROADMAP.zh-CN.md +91 -0
  6. package/bin/colocad.mjs +17 -9
  7. package/docs/README.md +13 -2
  8. package/docs/README.zh-CN.md +12 -3
  9. package/docs/agent-modeling-handbook.md +12 -4
  10. package/docs/agent-modeling-handbook.zh-CN.md +21 -4
  11. package/docs/api.md +9 -6
  12. package/docs/best-practices.md +80 -3
  13. package/docs/best-practices.zh-CN.md +63 -0
  14. package/docs/cadquery-comparison.md +105 -0
  15. package/docs/cadquery-comparison.zh-CN.md +53 -0
  16. package/docs/cadquery-coverage.json +762 -0
  17. package/docs/engineering-queries.md +124 -0
  18. package/docs/engineering-queries.zh-CN.md +76 -0
  19. package/docs/getting-started.md +1 -1
  20. package/docs/integrations/claude-code.md +1 -1
  21. package/docs/integrations/codex.md +1 -1
  22. package/docs/integrations/overview.md +3 -1
  23. package/docs/integrations/pi.md +17 -4
  24. package/docs/integrations/verification.md +7 -1
  25. package/docs/troubleshooting.md +13 -1
  26. package/examples/integrations/README.md +11 -2
  27. package/examples/integrations/compact-tools.mjs +1 -1
  28. package/kernel/dist/client.d.ts +5 -2
  29. package/kernel/dist/client.js +35 -7
  30. package/kernel/dist/generated.d.ts +297 -4
  31. package/kernel/dist/process.d.ts +1 -1
  32. package/kernel/dist/process.js +3 -3
  33. package/kernel/dist/query-generated.d.ts +181 -0
  34. package/kernel/dist/query-generated.js +1 -0
  35. package/kernel/dist/tools.d.ts +35 -0
  36. package/kernel/dist/tools.js +11 -2
  37. package/kernel/dist/types.d.ts +9 -0
  38. package/kernel/native/darwin-arm64/agent-cad +2 -2
  39. package/kernel/native/darwin-arm64/manifest.json +2 -2
  40. package/kernel/native/linux-arm64/agent-cad +2 -2
  41. package/kernel/native/linux-arm64/manifest.json +2 -2
  42. package/kernel/native/linux-x64/agent-cad +2 -2
  43. package/kernel/native/linux-x64/manifest.json +2 -2
  44. package/kernel/release.json +4 -4
  45. package/kernel/schemas/model.schema.json +1752 -135
  46. package/kernel/schemas/query.schema.json +1150 -0
  47. package/package.json +8 -2
  48. package/skills/colocad/SKILL.md +1 -0
  49. package/skills/colocad/references/modeling-loop.md +15 -1
  50. package/skills/colocad/references/prompt-patterns.md +27 -1
  51. package/skills/colocad/references/quick-build.md +2 -0
  52. package/skills/colocad/references/tool-contracts.md +14 -2
  53. package/skills/colocad/references/tuning.md +5 -1
  54. package/src/build.mjs +3 -2
  55. package/src/index.d.mts +2 -1
  56. package/src/session.d.mts +5 -3
  57. package/src/session.mjs +26 -10
  58. package/viewer/dist/index.js +179 -179
  59. package/viewer/dist/standalone.js +179 -179
  60. package/viewer/index.d.ts +2 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coloopx/colocad",
3
- "version": "0.1.0-alpha.6",
3
+ "version": "0.1.0-alpha.8",
4
4
  "description": "Parametric feature instructions, a local Rust B-rep kernel and an experimental SolidWorks author",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -66,9 +66,15 @@
66
66
  "examples/integrations/compact-tools.mjs",
67
67
  "examples/integrations/guided-workflow.mjs",
68
68
  "docs/*.md",
69
- "docs/integrations/*.md"
69
+ "docs/integrations/*.md",
70
+ "CHANGELOG.md",
71
+ "ROADMAP.md",
72
+ "ROADMAP.zh-CN.md",
73
+ "docs/cadquery-coverage.json"
70
74
  ],
71
75
  "scripts": {
76
+ "schema": "node scripts/schema.mjs",
77
+ "schema:check": "node scripts/schema.mjs --check",
72
78
  "test": "node --test test/*.test.mjs",
73
79
  "build:kernel": "node scripts/build-kernel.mjs",
74
80
  "prepack": "node scripts/check-release.mjs",
@@ -9,6 +9,7 @@ Choose the references needed for this task:
9
9
 
10
10
  - **A dimensioned part or common structure:** [quick-build](references/quick-build.md) has editable stock, plate, sleeve, angle and housing examples. Start with the controlling section or stock and add only required features.
11
11
  - **Drawings or a real product:** [materials](references/materials.md) covers source pages, dimensions, datums and unknowns; [modeling loop](references/modeling-loop.md) covers whole-product interfaces, features, edits and verification.
12
+ - **Measure or replace an assembly part:** [modeling loop](references/modeling-loop.md#geometry-driven-assembly-with-exact-queries) covers query revisions, semantic datums/interfaces, replacement and fit checks. Read the installed query schema; alpha.7 exposes this through `cad_query`.
12
13
  - **A harness/tool adapter:** [tool contracts](references/tool-contracts.md) explains actual tool names, state, compact feedback and errors.
13
14
  - **Task/prompt guidance:** [prompt patterns](references/prompt-patterns.md) gives short task, interpretation, repair and handoff examples. Adapt them to the user's scope.
14
15
  - **Failures, quality or performance tuning:** [tuning](references/tuning.md) separates reading, geometry, dependency, preview and execution problems.
@@ -13,6 +13,20 @@ Read for assemblies, drawing reconstruction or edits whose dependencies matter.
13
13
 
14
14
  This is an adaptive loop, not a mandatory approval gate between every feature. Use fewer milestones for a simple part. For a long product, keep checkpoints that explain both shape construction and assembly.
15
15
 
16
+ ## Geometry-driven assembly with exact queries
17
+
18
+ Use this path when installation geometry must be measured or a part replaced. Check installed capabilities; alpha.7 provides `cad_query`.
19
+
20
+ Exact grid snapshots require alpha.8 or later: alpha.7 had a nested seam UV-line serialization defect. Upgrade the package and matching native if `BSplineCurve::make_nurb` status 1001 appears on this path; changing preview precision does not repair it. Use the normal grid/query workflow after upgrading.
21
+
22
+ - Build exact query artifacts with `queryable`, or declare `Model.datums`/`Model.interfaces`, which enable them. Keep the accepted `query_revision_id`, target definition/occurrence, coordinate space and tolerance with the observation.
23
+ - Narrow the mounting plane before its openings and group. Inspect complete/partial coverage, cardinality and symmetric alternatives. A normal-only selection can include a blind-hole bottom; a position-sensitive recipe can use an earlier named plane with `planar_coplanar_with`.
24
+ - Persist supported semantic recipes in datums/interfaces, not snapshot refs or face indices. A symmetric group needs design intent or a measured orientation datum for an oriented mate. Let named attachments drive the existing mate solver.
25
+ - Require all-hole compatibility and relevant exact pair checks. Boundary distance is unsigned; inspect relationship and overlap before calling it clearance. Unsupported/partial evidence cannot certify fit or absence.
26
+ - After an edit/replacement, re-query the new revision and rerun required checks. Missing, ambiguous or incompatible geometry is a retained failure. Never rewrite an old ref's revision to make it appear current. Resume from accepted source after failure/interruption.
27
+
28
+ For a replacement workflow, challenge the same recipe with compatible and incompatible sources. Do not add a new part template or hardcoded face mapping for each input. Use only the pose/pair checks required by the task; report their discrete scope.
29
+
16
30
  ## Match evidence to the claim
17
31
 
18
32
  | Claim | A useful check |
@@ -28,6 +42,6 @@ Negative material checks matter: verify that a supposed opening is empty and adj
28
42
 
29
43
  ## State that survives a long session
30
44
 
31
- Keep source IDs and coordinate conventions, accepted model path/hash, exposed parameters, interface checks, latest receipt, unresolved assumptions, and the next targeted test. Reload the current accepted source after a failure or context reset. In `ModelingSession`, recorded `cad_edit` takes only `{parameters}` and uses that accepted source.
45
+ Keep source IDs and coordinate conventions, accepted model path/hash, exposed parameters, semantic datum/interface recipes, latest receipt and `query_revision_id`, target/space/tolerance, coverage/ambiguity, passed checks, unresolved assumptions, and the next targeted test. Reload the current accepted source after a failure or context reset. In `ModelingSession`, recorded `cad_edit` takes only `{parameters}` and uses that accepted source.
32
46
 
33
47
  The KK60 example illustrates this process. Enlarging the manufacturer's section corrected the screw axis to 23 mm; the real helical B-rep exposed an internal STEP budget defect; independent material probes and rail/carriage checks established specific geometry claims. Its undisclosed nut recirculation remains unmodeled. Do not reuse its assumed internal dimensions as a universal actuator design.
@@ -58,12 +58,38 @@ read back STEP when available. Distinguish untested pairs and unknown internals
58
58
  from passed checks; do not use appearance alone as evidence of fit.
59
59
  ```
60
60
 
61
+ ## Replace a component using measured installation geometry
62
+
63
+ ```text
64
+ Use the installed exact-query API to fit this replacement STEP to the accepted assembly.
65
+ The task supplies required mounting geometry, tolerances and pairs/poses to check.
66
+ Query the accepted revision in the stated coordinate space. Select the support plane
67
+ before its openings/groups; report partial coverage, extra holes and ambiguity.
68
+ Preserve geometric selection recipes as named datums/interfaces, then solve mates
69
+ and check all required hole correspondences plus exact pair relationships/clearance.
70
+ Rebuild after replacement and query the NEW revision. Retain incompatible attempts;
71
+ do not patch face numbers or invent orientation to force success. Return editable
72
+ source, measured deviations, accepted STEP and session, with CLI review artifacts.
73
+ ```
74
+
75
+ ## Repair a stale or incomplete observation
76
+
77
+ ```text
78
+ The supplied receipt identifies a stale revision, ambiguous selection or partial query.
79
+ Reload the latest accepted source/artifact and read its current query_revision_id.
80
+ For stale observations, rerun the semantic query; never relabel an old topology ref.
81
+ For ambiguity, inspect candidates and refine the geometric criterion or orientation
82
+ using available design evidence. For partial coverage, identify unsupported geometry
83
+ and which required claim remains unverified. Keep errors and accepted state intact.
84
+ ```
85
+
61
86
  ## Handoff after a long run
62
87
 
63
88
  ```text
64
89
  Persist: product/configuration; source identifiers; units and datums; accepted
65
90
  model path/hash; session path/latest step; parameters and dependency decisions;
66
- passed checks with values; failed attempts; unresolved assumptions; next targeted
91
+ semantic datum/interface recipes; current query revision and target/space/tolerance;
92
+ coverage/ambiguity; passed checks with values; failed attempts; unresolved assumptions; next targeted
67
93
  check. Keep large meshes and receipts as file references rather than inline text.
68
94
  ```
69
95
 
@@ -10,6 +10,8 @@ node "$skill/scripts/build.mjs" "$skill/assets/plate-grid.json" ./plate-v1 \
10
10
 
11
11
  Each invocation takes a new output directory. Edit the saved `model.json` to add features or pass it back to the helper with another `--set` to change an existing dimension. Overrides are saved in the built model. Only request a preview when you need to inspect it.
12
12
 
13
+ Exact grid snapshots require alpha.8 or later: alpha.7 had a nested seam UV-line serialization defect. Upgrade the package and matching native if `BSplineCurve::make_nurb` status 1001 appears on this path; changing preview precision does not repair it. Use the normal grid/query workflow after upgrading.
14
+
13
15
  | Shape or structure | Shortest construction in this skill | Datum and acceptance check |
14
16
  |---|---|---|
15
17
  | Block, pin, ball or taper | Use one feature from [block](../assets/block.json), [pin](../assets/pin.json), [ball](../assets/ball.json) or [taper](../assets/taper.json). For example, pass `pin.json` with `--set diameter=8 --set length=40` for a Ø8 × 40 mm pin. | Box origin is the lower corner. A cylinder or cone starts at its base center and grows along +Z. Check the outer envelope. |
@@ -4,7 +4,7 @@ The existing harness owns inference, permissions, output locations and artifact
4
4
 
5
5
  ## Expose tools at the useful level
6
6
 
7
- Start with the five tools used by the executable Pi adapter; enable sketch solving or STEP inspection when that workflow needs them. Keep the SDK's schema and `$defs` intact instead of rewriting an approximate subset.
7
+ The executable Pi adapter exposes five core tools and capability-gates `cad_query` as a sixth. Enable sketch solving or STEP inspection when that workflow needs them. Keep the SDK's schema and `$defs` intact instead of rewriting an approximate subset.
8
8
 
9
9
  | Existing tool | Meaning | Important boundary |
10
10
  | --- | --- | --- |
@@ -13,10 +13,11 @@ Start with the five tools used by the executable Pi adapter; enable sketch solvi
13
13
  | `cad_build` | Execute an explicit model and return exact artifacts | Creates a new revision; inspect errors/degradations |
14
14
  | `cad_preview` | Produce a view, reusing eligible saved mesh | Geometry, pose or precision changes can require work |
15
15
  | `cad_edit` | Rebuild changed named parameters | Plain tools take `{model,parameters}`; recorded tools take `{parameters}` |
16
+ | `cad_query` | Observe an accepted exact snapshot: topology, datums, holes/groups/interfaces and explicit part-pair measurements | Requires the latest `query_revision_id`; preserve partial coverage and ambiguity |
16
17
  | `cad_solve_sketch` | Local sketch constraints/residuals/DOF | Local solution/rank is not proof of global uniqueness |
17
18
  | `cad_inspect_step` | Inspect a registered STEP asset and its instances | Import budgets and supported representations apply |
18
19
 
19
- The current API does not provide `image_to_cad`, an automatic drawing-dimension extractor, or a universal exact measurement tool in this tool set. Use the harness's file/image tools for evidence and an appropriate independent geometry verifier for checks. The SDK's `inspect` reads a report; it is not an arbitrary geometric query engine.
20
+ The current API does not provide `image_to_cad`, an automatic drawing-dimension extractor, or universal geometry recognition. Use the harness's file/image tools for evidence and an appropriate independent geometry verifier for checks. The SDK's `inspect` reads a report; `query` is the capability-gated exact-geometry API. It ships in alpha.7; alpha.6 predates it. Inspect installed capabilities before selecting tools.
20
21
 
21
22
  ## Keep feedback focused and inspectable
22
23
 
@@ -31,3 +32,14 @@ For a provider that expects an error flag or thrown error, map `ok:false` into t
31
32
  Use one client/session for sequential revisions of one modeling task. Separate independent tasks' output roots. A session stores accepted inputs and failed attempts; archive its directory before the sandbox expires. `preview` can reuse a checked mesh; observation-only artifacts may point to `source_artifact_directory` for the exact STEP. Avoid overlapping writes to one session.
32
33
 
33
34
  Prefer a small semantic set of SDK tools over an RPC endpoint per primitive. Repeated geometry can be generated in a program/feature graph and sent in a meaningful build. Keep enough milestones to inspect geometry creation, not just the final assembly.
35
+
36
+
37
+ ## Query and repair loop
38
+
39
+ Enable `queryable` when building, or declare persistent datums/interfaces, which require exact snapshots. Keep `query_revision_id` in compact build/edit feedback: the next query needs it. Session-bound `cad_query` uses the latest accepted artifact; after an edit, obtain new refs by rerunning semantic recipes. A failed build/query must not replace accepted source.
40
+
41
+ For installation, select the support plane, then its loops/openings, rather than all circles on the body. A normal test alone can also match a blind-hole bottom: use an earlier named plane with `planar_coplanar_with` when position matters. Symmetric groups do not establish a unique orientation; choose geometry-derived key direction or explicit design intent. A partial result is incomplete evidence, not proof that no hole/collision exists.
42
+
43
+ For clearance, query explicit occurrence pairs in assembly space. Boundary distance is unsigned; inspect the separate relationship/overlap result so a contained part with positive boundary gap cannot pass as clear. Allowed contact has a bounded supported domain, and discrete pose samples do not certify continuous travel. An ineffective required cut returns `NO_MATERIAL_REMOVED`; inspect its placement/axis instead of assuming the machining feature succeeded.
44
+
45
+ On process interruption, reopen the persisted session and resume from its accepted source. Let the SDK invalidate checkpoints whose execution-policy fingerprint differs; do not copy a cache from another build and force its metadata to match.
@@ -19,7 +19,7 @@ Change one cause at a time and retain the original acceptance target. These are
19
19
 
20
20
  Keep source interpretation/inference, CAD startup, geometry, validation, STEP export, tessellation, view rendering and video encoding separate. Time-to-STEP and time-to-preview answer different questions. A cached view cannot be compared with another tool's fresh geometry build as if they were the same task.
21
21
 
22
- For a fair build123d comparison, use the same dimensions, features, instances, precision and required artifacts. Verify both geometries independently, pin environments and define cold/warm behavior. Report repeat counts, median/tails, failures and the accounting boundary. For memory, state sampled RSS/process sum/cgroup, sampling interval and whether the plot is instantaneous or the peak-so-far; retaining a peak is a presentation choice, not the original trace.
22
+ For a fair CadQuery or build123d comparison, use the same dimensions, features, instances, precision and required artifacts. Verify both geometries independently, pin environments and define cold/warm behavior. Report repeat counts, median/tails, failures and the accounting boundary. For memory, state sampled RSS/process sum/cgroup, sampling interval and whether the plot is instantaneous or the peak-so-far; retaining a peak is a presentation choice, not the original trace.
23
23
 
24
24
  A 1 vCPU / 512 MiB CAD run establishes only that scoped run. It does not establish the memory budget of the resident agent/harness, an in-process LLM, Chromium or FFmpeg. Do not extrapolate a plate's speedup to a threaded multi-part product.
25
25
 
@@ -28,3 +28,7 @@ A 1 vCPU / 512 MiB CAD run establishes only that scoped run. It does not establi
28
28
  Hold product tasks, source packs, model/provider version, tools and budget fixed. Compare the existing skill with one changed instruction/tool response policy. Include a dimensioned part, a part needing section interpretation, an editable assembly and an ambiguous source case. Keep some tasks unseen during tuning. Measure required dimensions/features, edit preservation, fit checks, unsupported claims, correction count, inference cost and end-to-end duration.
29
29
 
30
30
  Use numerical checks and inspectable artifacts for acceptance. Scripted tool tests establish transport and geometry contracts; they do not establish that a model understood an unseen drawing. Report failed tasks and unknown evidence, and do not describe an unrun prompt ablation as an improvement result.
31
+
32
+ ## Preserve an improvement experiment
33
+
34
+ For an explicit optimization task, freeze the baseline, task split, required geometry, tolerances, verifier and resource budget before changing code or guidance. Retain the original failure and a small reproducer. Change one hypothesis, pass affected-family and frozen regressions, then challenge held-out product families. Include failures in the denominator and preserve rejected or inconclusive candidates. Do not change the evaluator/reference to make a candidate pass. A performance gain needs repeat measurements beyond noise; a skill gain needs live-agent evidence, not only scripted tests. Stop at the authorized iteration/cost budget and keep the last accepted state. Publishing is a separate authorized action, not a tool-score side effect.
package/src/build.mjs CHANGED
@@ -15,7 +15,7 @@ import { CadClient } from "../kernel/dist/index.js";
15
15
  export async function build(
16
16
  tree,
17
17
  destination,
18
- { preview = false, binary } = {},
18
+ { preview = false, queryable = false, binary } = {},
19
19
  ) {
20
20
  const plan = compileTree(tree);
21
21
  const model = kernelModel(tree);
@@ -26,7 +26,7 @@ export async function build(
26
26
  let owned = false;
27
27
  try {
28
28
  const client = new CadClient({ outputRoot: stage, binary, wallMs: 120000 });
29
- const result = await client.build(model);
29
+ const result = await client.build(model,{queryable});
30
30
  if (!result.ok)
31
31
  throw Error(result.error.code + ": " + result.error.message);
32
32
  const folder = result.data.artifact_directory;
@@ -59,6 +59,7 @@ export async function build(
59
59
  step: join(out, "part", "model.step"),
60
60
  nativeJob: join(out, "part", "native-job.json"),
61
61
  geometry: receipt.geometry,
62
+ ...(receipt.query_revision_id?{query_revision_id:receipt.query_revision_id}:{}),
62
63
  };
63
64
  } catch (error) {
64
65
  if (owned) await rm(out, { recursive: true, force: true });
package/src/index.d.mts CHANGED
@@ -42,11 +42,12 @@ export function kernelModel(
42
42
  export function build(
43
43
  tree: FeatureTree,
44
44
  destination: string,
45
- options?: { preview?: boolean; binary?: string },
45
+ options?: { preview?: boolean; queryable?: boolean; binary?: string },
46
46
  ): Promise<{
47
47
  directory: string;
48
48
  step: string;
49
49
  nativeJob: string;
50
+ query_revision_id?: string;
50
51
  geometry: Geometry;
51
52
  }>;
52
53
  export function writeSolidWorks(
package/src/session.d.mts CHANGED
@@ -1,13 +1,14 @@
1
- import type { Config, Model, Receipt, PreviewOptions, Sketch } from '../kernel/dist/types.js';
2
- export interface StepMetadata { label?: string; kind?: string; }
1
+ import type { Config, Model, Receipt, PreviewOptions, Sketch, QueryRequest } from '../kernel/dist/types.js';
2
+ export interface StepMetadata { label?: string; kind?: string; queryable?: boolean; }
3
3
  export interface SessionStep {
4
- id: string; label: string; kind: string; operation: 'build'|'edit'|'observe';
4
+ id: string; label: string; kind: string; operation: 'build'|'edit'|'observe'|'query';
5
5
  status: 'running'|'succeeded'|'failed'|'interrupted'; startedAt: string;
6
6
  finishedAt?: string; durationMs?: number; inputFile: string; inputSha256: string;
7
7
  receiptFile?: string; receiptSha256?: string; artifactDirectory?: string;
8
8
  geometry?: Record<string, unknown>; error?: { code: string; message: string };
9
9
  nativeTimingMs?: Record<string, unknown>; degradations?: Record<string, unknown>[];
10
10
  requestedParameters?: Record<string, number>;
11
+ queryable?: boolean; queryRequestFile?: string; queryRequestSha256?: string;
11
12
  }
12
13
  export interface SessionLedger { format: 'colocad/session/1'; id: string; title: string; createdAt: string; steps: SessionStep[]; }
13
14
  export type SessionConfig = Omit<Config, 'outputRoot'>;
@@ -22,6 +23,7 @@ export class ModelingSession {
22
23
  edit(parameters: Record<string, number>, metadata?: StepMetadata): Promise<RecordedReceipt>;
23
24
  preview(model: Model, options?: Partial<PreviewOptions>, metadata?: StepMetadata): Promise<RecordedReceipt>;
24
25
  observe(options?: Partial<PreviewOptions>, metadata?: StepMetadata): Promise<RecordedReceipt>;
26
+ query(request: QueryRequest, metadata?: StepMetadata): Promise<RecordedReceipt>;
25
27
  capabilities(): Promise<Receipt>; schema(): Promise<Receipt>; validate(model: Model): Promise<Receipt>;
26
28
  solveSketch(sketch: Sketch, parameters?: Record<string,number>): Promise<Receipt>;
27
29
  inspectStep(model: Model, asset: string): Promise<Receipt>;
package/src/session.mjs CHANGED
@@ -40,8 +40,8 @@ export class ModelingSession {
40
40
  try{await writeFile(file,json({pid:process.pid}),{flag:'wx'});}catch(e){if(e.code==='EEXIST')throw Error('SESSION_BUSY: another local writer owns this session');throw e;}
41
41
  try{return await fn();}finally{await rm(file,{force:true});}
42
42
  }
43
- async source(){const l=await this.read(),s=l.steps.findLast(x=>x.status==='succeeded'&&x.operation!=='observe');if(!s)throw Error('SESSION_EMPTY: build a model first');return JSON.parse(await checked(this.root,s.inputFile,s.inputSha256));}
44
- async latestGeometry(){return (await this.read()).steps.findLast(x=>x.status==='succeeded'&&x.operation!=='observe');}
43
+ async source(){const l=await this.read(),s=l.steps.findLast(x=>x.status==='succeeded'&&!['observe','query'].includes(x.operation));if(!s)throw Error('SESSION_EMPTY: build a model first');return JSON.parse(await checked(this.root,s.inputFile,s.inputSha256));}
44
+ async latestGeometry(){return (await this.read()).steps.findLast(x=>x.status==='succeeded'&&!['observe','query'].includes(x.operation));}
45
45
  async build(model,metadata={}){const input=structuredClone(model);return this.lock(()=>this.run(input,'build',metadata));}
46
46
  async edit(parameters,metadata={}){return this.lock(async()=>{
47
47
  const model=await this.source();
@@ -56,20 +56,28 @@ export class ModelingSession {
56
56
  }return this.run(next,'build',metadata);
57
57
  });}
58
58
  async observe(options={},metadata={}){return this.lock(async()=>{const model=await this.source();model.preview={...model.preview,...options};return this.run(model,'observe',metadata);});}
59
- async run(model,operation,{label=operation,kind=operation==='observe'?'inspection':'geometry'}={},preset,requestedParameters){
59
+ async query(request,metadata={}){const input=structuredClone(request);return this.lock(async()=>this.run(await this.source(),'query',metadata,undefined,undefined,input));}
60
+ async run(model,operation,{label=operation,kind=['observe','query'].includes(operation)?'inspection':'geometry',queryable}={},preset,requestedParameters,queryRequest){
60
61
  const ledger=await this.read(),id='s'+String(ledger.steps.length+1).padStart(4,'0'),dir=join('steps',id);
61
62
  await mkdir(join(this.root,dir),{recursive:true});
62
- if(operation!=='observe')model.preview={view:'iso',chord_mm:.6,width:960,height:640,...model.preview};
63
+ if(!['observe','query'].includes(operation))model.preview={view:'iso',chord_mm:.6,width:960,height:640,...model.preview};
63
64
  const bytes=json(model);await writeFile(join(this.root,dir,'input.json'),bytes);
64
65
  const step={id,label:String(label),kind:String(kind),operation,status:'running',startedAt:new Date().toISOString(),inputFile:dir+'/input.json',inputSha256:sha(bytes),receiptFile:dir+'/receipt.json'};
65
66
  if(requestedParameters)step.requestedParameters=requestedParameters;
67
+ if(queryRequest){const requestBytes=json(queryRequest);step.queryRequestFile=dir+'/query.json';step.queryRequestSha256=sha(requestBytes);await writeFile(join(this.root,step.queryRequestFile),requestBytes);}
66
68
  ledger.steps.push(step);await atomic(join(this.root,'session.json'),ledger);
67
69
  const start=performance.now();let result;
68
70
  try{
69
- const previous=ledger.steps.slice(0,-1).findLast(x=>x.status==='succeeded'&&x.operation!=='observe');
70
- result=preset??await (operation==='observe'
71
+ const previous=ledger.steps.slice(0,-1).findLast(x=>x.status==='succeeded'&&!['observe','query'].includes(x.operation));
72
+ step.queryable=queryable??((model.datums?.length||model.interfaces?.length)?true:previous?.queryable??false);
73
+ const accepted=operation==='query'?JSON.parse(await checked(this.root,previous.receiptFile,previous.receiptSha256)):undefined;
74
+ if(accepted&&queryRequest.query_revision_id!==accepted.data.query_revision_id)preset={ok:false,error:{code:'QUERY_REVISION_MISMATCH',message:'Query must target the accepted geometry revision'}};
75
+ result=preset??await (operation==='query'
76
+ ?this.cad.query(inside(this.root,previous.artifactDirectory),queryRequest)
77
+ :operation==='observe'
71
78
  ?this.cad.observeArtifact(inside(this.root,previous.artifactDirectory),model.preview)
72
- :this.cad.build(model,previous?inside(this.root,previous.artifactDirectory):undefined));
79
+ :this.cad.build(model,{previousRevision:previous?inside(this.root,previous.artifactDirectory):undefined,queryable:step.queryable}));
80
+ if(operation==='query'&&result.ok){result.data.artifact_directory=inside(this.root,previous.artifactDirectory);result.data.source_artifact_directory=result.data.artifact_directory;result.data.source_artifact_sha256=accepted.data.artifact_sha256;}
73
81
  }catch(e){result={ok:false,error:{code:'SESSION_EXECUTION_FAILED',message:String(e.message)}};}
74
82
  step.durationMs=performance.now()-start;step.finishedAt=new Date().toISOString();step.status=result.ok?'succeeded':'failed';
75
83
  const saved=structuredClone(result);
@@ -91,7 +99,12 @@ export class ModelingSession {
91
99
  export async function createSessionTools(session) {
92
100
  const tools=await createCadTools(session.cad);
93
101
  for(const tool of tools){
94
- if(tool.name==='cad_build')tool.execute=({model})=>session.build(model,{label:'Agent build'});
102
+ if(tool.name==='cad_build')tool.execute=({model,options})=>session.build(model,{label:'Agent build',queryable:options?.queryable});
103
+ if(tool.name==='cad_query'){
104
+ delete tool.inputSchema.properties.artifact_directory;tool.inputSchema.required=['request'];
105
+ tool.description='Query the latest accepted exact snapshot, persist request/result, and reject stale revisions without changing accepted source.';
106
+ tool.execute=({request})=>session.query(request,{label:'Agent geometry query'});
107
+ }
95
108
  if(tool.name==='cad_preview')tool.execute=({model,options})=>session.preview(model,options,{label:'Agent preview'});
96
109
  if(tool.name==='cad_edit'){
97
110
  delete tool.inputSchema.properties.model;
@@ -107,16 +120,19 @@ export async function readSessionBundle(directory,{cutaway=false,view='iso'}={})
107
120
  const root=resolve(directory),ledger=await load(join(root,'session.json'));
108
121
  if(ledger.format!==format)throw Error('SESSION_FORMAT');
109
122
  const bundle={format:'colocad/viewer/1',title:ledger.title,id:ledger.id,createdAt:ledger.createdAt,display:{cutaway,view},steps:[],meshes:{}};
110
- const last=ledger.steps.findLast(x=>x.status==='succeeded'&&x.operation!=='observe');
123
+ const last=ledger.steps.findLast(x=>x.status==='succeeded'&&!['observe','query'].includes(x.operation));
111
124
  for(const entry of ledger.steps){
112
125
  const step={...entry};
113
126
  if(entry.inputFile)step.model=JSON.parse(await checked(root,entry.inputFile,entry.inputSha256));
114
127
  if(entry.receiptFile&&entry.receiptSha256)step.receipt=JSON.parse(await checked(root,entry.receiptFile,entry.receiptSha256));
128
+ if(entry.queryRequestFile)step.queryRequest=JSON.parse(await checked(root,entry.queryRequestFile,entry.queryRequestSha256));
115
129
  if(entry.status==='succeeded'){
116
130
  const data=step.receipt.data,artifact=entry.artifactDirectory;inside(root,artifact);
117
131
  // Observation results keep their original exact-geometry source for later lookup.
118
132
  const source=data.source_artifact_directory??artifact;
119
- const sourceReport=source===artifact?data:await load(inside(root,source+'/report.json'));
133
+ const sourceReport=entry.operation==='query'?{artifact_sha256:data.source_artifact_sha256}:source===artifact?data:await load(inside(root,source+'/report.json'));
134
+ const guideHash=sourceReport.artifact_sha256?.['query-display.json'];
135
+ if(guideHash)step.queryDisplay=JSON.parse(await checked(root,source+'/query-display.json',guideHash));
120
136
  const hash=sourceReport.artifact_sha256?.['preview.mesh.json'];
121
137
  if(!hash)throw Error('SESSION_INTEGRITY: missing native preview mesh hash');
122
138
  const scene=JSON.parse(await checked(root,source+'/preview.mesh.json',hash));