@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
@@ -0,0 +1,124 @@
1
+ # Exact queries and geometry-backed assembly
2
+
3
+ **Available in @coloopx/colocad 0.1.0-alpha.7**, including all three packaged native targets. For source development, build the native executable and SDK from the same checkout. [中文](engineering-queries.zh-CN.md) · [Runnable example](../examples/engineering-queries/README.md) · [Detailed contract](../specs/0004-engineering-query-and-assembly-interfaces.md).
4
+
5
+ Use this layer when a part's installation geometry must be measured or selected before assembly. The local Rust executable evaluates exact B-rep geometry; the SDK, CLI and agent tools share that implementation. No Python geometry workflow or separate service is required. Agent, harness and executable run in the same sandbox.
6
+
7
+ ## Readiness and compatibility
8
+
9
+ This layer is ready for the declared mechanical assembly workflows: exact topology selection, primitive datums, analytic bores/groups, planar mounting interfaces, geometry-driven replacement and explicit pair measurements. The release is alpha. Colocad uses its own JSON/TypeScript contracts; it does not run CadQuery Python programs or promise identical selector syntax or feature coverage.
10
+
11
+ G1–G3 acceptance covers the frozen 24-case corpus, lifecycle tests and two live agent tasks. [Release archive checks](evidence/release-alpha.7.json) verify the installed SDK/CLI/native together on macOS arm64 and Linux arm64/x64; x64 is emulated on an arm64 host. Unsupported recognition/contact domains are listed below and remain explicit partial/error results.
12
+
13
+ Alpha.8 fixes the alpha.7 grid snapshot defect: nested lazy UV lines on cylinder seams are materialized exactly on the serialization copy. No tessellation, STEP reimport or geometry healing is substituted. See [repair and installed-package evidence](evidence/release-alpha.8.json); [the original failure](evidence/alpha.7-query-guidance.json) remains preserved.
14
+
15
+ ## Build once, query the accepted revision
16
+
17
+ ```js
18
+ import { CadClient } from '@coloopx/colocad/kernel';
19
+ const cad = new CadClient({ outputRoot: './jobs' });
20
+ const built = await cad.build(model, { queryable: true });
21
+ if (!built.ok) throw Error(built.error.message);
22
+ const request = {
23
+ schema: 'colocad.query/1',
24
+ query_revision_id: built.data.query_revision_id,
25
+ target: { definition_id: 'part' }, // a final feature ID in this model
26
+ space: 'definition',
27
+ tolerance: { linear_mm: 1e-5, angular_rad: 1e-7 },
28
+ queries: [{
29
+ id: 'top', op: 'faces',
30
+ where: { planar_normal_aligned_with: [0, 0, 1] },
31
+ limit: 64
32
+ }]
33
+ };
34
+ const result = await cad.query(built.data.artifact_directory, request);
35
+ ```
36
+
37
+ A queryable build saves `query-manifest.json` plus exact `query-definition-*.smb` payloads. Reopen them in a fresh process or move the entire artifact directory: references retain identity. Queries do not replay features, read STEP, export STEP, heal geometry or generate preview meshes. The receipt reports definition loading, indexing and query time separately. Ordinary builds remain opt-in; a model declaring `datums` or `interfaces` automatically requires these artifacts. Explicitly disabling them with such a declaration fails.
38
+
39
+ Use `target: {instance_path: ['subassembly', 'instance']}` with `space: 'assembly'` for world-space measurements. Positions include the solved rigid translation; directions do not. Queries use normal solved placements, independently of exploded previews. Lengths and areas are invariant. The SDK confines paths to host-configured `queryRoots` (default `outputRoot`); agents cannot change that configuration through query JSON.
40
+
41
+ The CLI accepts the same request file:
42
+
43
+ ```sh
44
+ colocad record model.json session --queryable --label 'Queryable part'
45
+ # Use artifact_directory and query_revision_id from the build receipt.
46
+ colocad query ARTIFACT_DIRECTORY request.json --out receipt.json
47
+ colocad view session
48
+ ```
49
+
50
+ `--out` creates a new file and refuses to overwrite one. For a `colocad/1` tree, `colocad build tree.json NEW_DIR --queryable` also enables queries. `ModelingSession.query(request)` records the observation and source revision without changing accepted geometry. A query failure is retained in history. In `createSessionTools`, `cad_query` is bound to the latest accepted artifact; raw `createCadTools` takes an allowed artifact directory explicitly. With a queryable preview, the Query tab highlights native face/edge/loop outlines and datum/group markers. The build saves hash-bound `query-display.json`; these sampled outlines are display aids, never measurement authority. Exploding the viewer moves overlays with their parts without changing query coordinates.
51
+
52
+ ## Select intent, preserve ambiguity
53
+
54
+ Selections are bounded expressions, not executable code. Available operations are `entities`, `refs`, `filter`, `children`, `ancestors`, `siblings`, `union`, `intersection`, `difference`, `rank` and `expect`. Filters provide typed analytic classes, names, area/length/radius ranges, planar normal tests, loop roles and bounded `all`/`any`/`not`.
55
+
56
+ For a hole center on one installation face, select that face, then its inner loops, their circular edges, and derive point datums. Selecting all circular edges on the body would also collect the opposite openings. `siblings` requires an explicit shared child type: faces connected through an edge use `{kind:'siblings', input: selectedFace, entity:'face', via:'edge'}`. It does not return every face in the body.
57
+
58
+ `rank` returns the entire tied rank. An `expect` asserting one result fails on a tie, even when the page limit is one. Exact identity deduplicates entity sets; ordered loop edge uses preserve repeated seam uses. Cursors bind the revision, target, space, tolerance and operation. Snapshot `TopologyRef` values are observations, not permanent edit recipes; an edit invalidates old references.
59
+
60
+ Limits: 64 queries per batch, 256 results per page, expression depth 8 / 128 nodes, 200,000 adjacency visits, 2 MiB input, 8 MiB output and 64 MiB total exact snapshot payload. These are admission limits, not proof of a 512 MiB runtime envelope. Source accuracy remains unknown when the source does not specify it.
61
+
62
+ ## Name geometry for mates
63
+
64
+ A declaration belongs to a final part definition, independently of its assembly occurrences:
65
+
66
+ ```json
67
+ {
68
+ "id": "seat",
69
+ "definition": "part",
70
+ "tolerance": { "linear_mm": 0.00001, "angular_rad": 0.0000001 },
71
+ "derive": {
72
+ "kind": "selected",
73
+ "selection": {
74
+ "kind": "filter",
75
+ "input": { "kind": "entities", "entity": "face" },
76
+ "where": { "planar_normal_aligned_with": [0, 0, 1] }
77
+ },
78
+ "derive": { "kind": "plane" }
79
+ }
80
+ }
81
+ ```
82
+
83
+ Put declarations in `Model.datums`. IDs are unique within a definition. A selected primitive requires exactly one entity. `selected` supports vertex/circle points, analytic planes, cylinder/circle axes and straight-edge directions. Other recipes are `design_point`, ordered `point_difference`, and `frame`. A frame names an origin point and two nonparallel orthogonal directions (`x` and `z`, each with explicit positive/negative sense); it is right-handed. Its dependencies must occur earlier in the same definition. Persistent selections cannot contain prior-snapshot refs. Derived versus declared design intent remains visible in receipts.
84
+
85
+ Use `{instance:'part_occurrence', datum:'seat'}` instead of a numeric attachment frame. Plane mates consume a plane, concentric mates an axis, coincidence/distance a point, and fixed/prismatic/revolute mates require a full frame. A full frame can also provide these lower-dimensional attachments. `frame` and `datum` are mutually exclusive; omitted legacy attachment data still uses the original identity frame.
86
+
87
+ An internal basis completes a plane/axis only for numerical evaluation. It adds no physical orientation constraint: an axis plus an axial plane leaves rotation about that axis free. A cylinder axis alone cannot establish the axial origin required by a revolute joint. Declare the required point/frame or combine axis and plane constraints explicitly.
88
+
89
+ Read accepted named datums using `{id:'mount', op:'named_datums', ids:['seat']}`. Their source refs bind to the final query revision and transform with the chosen occurrence. Rebuilding after parameter edits reruns recipes. Missing, ambiguous, degenerate and incompatible datum kinds fail with structured errors; they do not silently select the first candidate.
90
+
91
+ ## Holes, groups and installation interfaces
92
+
93
+ `holes` recognizes connected analytic cylindrical bores with planar entrances/ends in consistently oriented closed solids. It distinguishes through, blind and counterbored holes, joins supported axial/angular split patches, and excludes external shafts. A counterbore is one physical hole with multiple segments. Conical tips, intersecting bores, side-open recesses and spline cylinders return partial coverage with source references; they are not silently called complete holes.
94
+
95
+ `hole_groups` accepts optional `support_faces` refs and `where: {pattern, member_count, equal_diameter}`. Patterns are linear, rectangular, circular or unstructured. It returns physical centers, axes, dimensions, residuals, competing subsets, excluded openings and symmetry. Plane-scoped coverage excludes uncertainty away from that support's topology, but retains its diagnostic. Recognition is bounded to 64 openings per support and 10,000 hypotheses; large searches fail `QUERY_LIMIT`.
96
+
97
+ `interfaces` observes named declarations (`ids`) or recognizes candidates (`profile: 'planar_hole_mount/v1'`, optional `support_faces` and group filter). Candidates do not acquire a unique engineering orientation from symmetric holes. Put persistent intent in `Model.interfaces`: uniquely select a plane and hole group, optionally a coaxial register, specify the group-center/axis-intersection/design-point origin, verification tolerance, pattern dimensions, bore sizes and termination. Add an explicit design direction or geometry-backed orientation datum when an oriented mate needs one. The declaration is reevaluated against the built geometry; unsupported, missing, multiple or incompatible results fail.
98
+
99
+ Use `{instance, interface, orientation?}` in a mate. Full-frame mates require an orientation; lower-dimensional mates retain unresolved freedoms. `interface_compatibility` checks all-hole correspondence, plane relation/gap, axis offsets, each side's diameter range and optional register radial clearance. It records ambiguity and actual paired refs. Independent diameter ranges do not prove bolt or thread fit.
100
+
101
+ The [complete external assembly example](../examples/engineering-interfaces/README.md) shows the actual typed declaration, replacement and error workflow. Relative filters accept `planar_normal_aligned_with: {datum}`, `planar_normal_parallel_to: {datum}`, and `planar_coplanar_with: {datum}`. The last requires a plane and uses both normal and offset, avoiding a blind-hole bottom with the same normal. Projection ranks also accept a named datum direction. Dependencies must be earlier in the definition; ordered circle-center differences follow a rigidly rotated source instead of relying on its global axes.
102
+
103
+ ## Exact relationships and acceptance checks
104
+
105
+ A read-only query can request:
106
+
107
+ ```js
108
+ { id: 'gap', op: 'measure',
109
+ a: { instance_path: ['shaft'] }, b: { instance_path: ['support'] } }
110
+ ```
111
+
112
+ The snapshot target and both measurement targets remain explicit. Definition space measures local shapes; assembly space uses solved occurrence poses. The result distinguishes separated, touching, overlapping, contained and indeterminate, with unsigned boundary distance, overlap volume, witness points and numerical tolerances. Containment can have a positive boundary gap; distance is not penetration depth. `items[0]` is also exposed as `measurement`. Indeterminate is a partial result; required assembly checks fail. Witness topology refs are marked unavailable where the copy-based solver cannot preserve their mapping.
113
+
114
+ `checks: [{kind:'geometric_relationship', a:{instance}, b:{instance}, tolerance, max_overlap_mm3, min_clearance_mm?, allowed_contacts?, pose_samples?}]` makes a required claim. Minimum clearance requires separation. Explicit pose deltas (at most 32) are evaluated individually and retained even on failure; this does not establish continuous-motion clearance. Required exact checks reject degraded feature ancestry and reduced representations.
115
+
116
+ Allowed contacts currently certify selected opposing planar faces on polyhedral solids by checking both complete solids against their support half-spaces. A single closest witness is insufficient. Other overlap is never exempted. Curved contact certification and region-restricted measurements fail explicitly as unsupported. Ordinary whole-part measurements support curved solids.
117
+
118
+ ## Evidence and boundaries
119
+
120
+ The foreign flange workflow passes base, different-housing and arbitrarily rotated replacement inputs while rejecting wrong pitch and missing holes. The complete KK60 reconstruction with an independently authored bracket passes 82-solid OCCT readback and nine explicit contact/gap samples. These cases, tolerances and provenance are retained in the [experiment ledger](../specs/experiments/0004/README.md); they are not a general industrial success rate.
121
+
122
+ Descriptors include native UV/periodicity, ordered pcurves, seam uses, adjacency and tolerances. Trimmed definition bounds are transformed AABBs and may be conservative after rotation; `bounds_semantics` identifies this. Query results do not certify machining tolerances, threads, load capacity or global uniqueness of a local mate solution. Broader reliability and target sandbox acceptance are governed by [the ordered goals](../specs/0005-capability-reliability-and-optimization.md).
123
+
124
+ Development checkpoints carry `execution_policy`, a deterministic fingerprint of the executor Rust sources, manifest/lockfile, compiler and target. A missing or different policy forces replay, even when the version string matches. This prevents a development upgrade from restoring old feature semantics. The [G3 evidence](../specs/experiments/0005/README.md) covers actual process interruption, reopen/relocation, semantic split/merge/delete, replacements and Linux resource limits.
@@ -0,0 +1,76 @@
1
+ # 精确查询与几何基准装配
2
+
3
+ **从 @coloopx/colocad 0.1.0-alpha.7 起提供,包含三平台预编译内核。** 源码开发仍需使用同一份 checkout 编译的内核和 SDK。[English](engineering-queries.md) · [可运行例子](../examples/engineering-queries/README.md) · [详细规范](../specs/0004-engineering-query-and-assembly-interfaces.zh-CN.md)。
4
+
5
+ 这层能力用于在装配前查询零件的安装几何。几何解释在本地 Rust 内核中完成,SDK、CLI 与 agent 工具共用实现;agent、harness 和可执行文件仍位于同一沙箱中。
6
+
7
+ alpha.8 修复 alpha.7 的孔阵列快照问题:在序列化副本上精确补齐圆柱接缝内部 UV 直线数据,不使用三角化、STEP 重导入或几何修补代替快照。见[修复与安装包证据](evidence/release-alpha.8.json);[原始失败](evidence/alpha.7-query-guidance.json)保持留档。
8
+
9
+ ## 构建一次,查询已接受版本
10
+
11
+ `cad.build(model, {queryable:true})` 返回 `artifact_directory` 和 `query_revision_id`,并保存 `query-manifest.json` 与精确 `query-definition-*.smb`。将带预期版本号、目标、坐标系、容差和查询列表的请求交给 `cad.query(directory, request)`。完整 SDK 代码见英文页。
12
+
13
+ 查询不重放建模特征、不读 STEP、不导出 STEP、不修补几何、不生成网格。整个工件目录迁移或换进程重开后,快照引用保持一致。普通模型按需启用;声明 `Model.datums` 或 `Model.interfaces` 的模型自动启用,显式关闭会报错。SDK 的 `queryRoots` 由宿主配置,默认只允许 `outputRoot` 下的工件。
14
+
15
+ ```sh
16
+ colocad record model.json session --queryable --label '可查询零件'
17
+ # 采用构建回执里的 artifact_directory 与 query_revision_id。
18
+ colocad query ARTIFACT_DIRECTORY request.json --out receipt.json
19
+ colocad view session
20
+ ```
21
+
22
+ CLI 的 `--out` 拒绝覆盖已有文件。`colocad/1` 特征树也可使用 `colocad build tree.json NEW_DIR --queryable`。`ModelingSession.query(request)` 保存查询输入、回执和源版本,不替换已接受几何,失败查询同样留档。session 工具自动绑定最后接受的几何工件;原始 SDK 工具显式接收受宿主限制的工件路径。Query 页支持 native ref 绑定的拓扑轮廓高亮,见下文。
23
+
24
+ 定义坐标使用 `target:{definition_id:'part'}`;装配坐标使用 `target:{instance_path:['group','part_occurrence']}` 与 `space:'assembly'`。位置包含平移,方向不包含平移。查询采用求解后的正常装配位置,不随爆炸预览姿态变化。
25
+
26
+ ## 选择表达意图,歧义必须保留
27
+
28
+ 支持实体枚举、过滤、子拓扑、祖先、相邻拓扑、集合运算、排序和数量断言。筛选项包括名称、解析几何类型、面积/长度/半径范围、平面法向、内外环,以及有界的 `all/any/not`。
29
+
30
+ 安装面上的孔中心应按“指定平面 → 内环 → 圆边 → 圆心”查询,避免把背面的开口也选进来。`siblings` 显式指定共享子拓扑,例如通过边相邻的面:`{kind:'siblings',input:selectedFace,entity:'face',via:'edge'}`。
31
+
32
+ 排序并列时返回整个并列集合,随后 `expect:1` 必须失败;分页不能把歧义隐藏成唯一结果。集合按精确拓扑身份去重,环内重复使用的接缝边保留。游标绑定版本、目标、坐标系、容差和操作。快照引用用于观察;改参后旧引用会失效,持久化意图应使用语义选择配方。
33
+
34
+ 限制:每批 64 项查询、每页 256 项、表达式深度 8 / 128 节点、20 万次邻接访问、2 MiB 输入、8 MiB 输出、64 MiB 精确快照。它们是输入边界,不能据此宣称 512 MiB 沙箱已验收。源数据未声明的工程精度仍是未知。
35
+
36
+ ## 把基准直接用于配合
37
+
38
+ `Model.datums` 的声明包含 `id`、最终零件 `definition`、`tolerance` 和 `derive`。名称在同一定义中唯一;输出类型由推导规则确定。`selected` 配方使用通用选择,必须得到唯一实体,然后推导顶点/圆心、解析平面、圆柱/圆轴或直边方向。
39
+
40
+ 其他配方包括显式设计点 `design_point`、有序点差 `point_difference` 和完整 `frame`。frame 引用一个原点基准及 x/z 方向基准,每个方向显式选择正负;检查非退化和正交,构成右手系。依赖必须是同一定义中较早的声明;不能使用旧快照引用。回执区分几何推导与显式设计意图。
41
+
42
+ 附件可以写成 `{instance:'part_occurrence',datum:'seat'}`。平面配合需要 plane,同心需要 axis,点重合/距离需要 point;固定、滑动和转动关节需要完整 frame。完整 frame 也可提供低维附件。`frame` 与 `datum` 互斥;旧式附件全部省略时仍采用原有默认 frame。
43
+
44
+ 内部补出的数值基底不会增加工程约束。轴线加轴向平面保留绕轴的一个自由度;单独的圆柱轴线没有转动关节所需的轴向原点,需补足点/frame 或组合轴和平面约束。
45
+
46
+ 通过 `{id:'mount',op:'named_datums',ids:['seat']}` 回读命名基准。回执中的源拓扑引用绑定最终版本,并按目标实例变换。改参重建会重算配方;缺失、歧义、退化或类型不兼容均返回结构化错误。
47
+
48
+ ## 验收范围
49
+
50
+ 例子将 OCCT 独立生成的法兰 STEP 导入,选择孔轴和底面,用几何基准装配轴,导出 STEP;过粗的轴被精确碰撞检查拒绝。独立 OCCT 回读检查两个实体、解析体积及 0.2 mm 最小间隙。这是通用解析验证件,不是商业产品复原,也不是工业模型成功率语料。
51
+
52
+ G1 新增的相对筛选、专用描述、孔/沉孔识别、孔组、安装接口和测量见下文;更广泛的 G2/G3 验收由实验账本记录。装配包围盒由定义 AABB 刚性变换得到,旋转后可能偏宽。查询结果不证明加工精度、螺纹、承载能力或局部求解的全局唯一性。[四阶段目标与后续自优化循环](../specs/0005-capability-reliability-and-optimization.zh-CN.md)。
53
+
54
+
55
+ ## G1 扩展:孔、接口、测量与显示
56
+
57
+ 以[英文 API 指南](engineering-queries.md)和 Rust 生成的 schema 为字段依据。开发源代码新增:
58
+
59
+ - `holes`:封闭定向实体中的解析圆柱通孔、平底盲孔和沉孔;支持受限的轴向/角向分片合并,轴外表面不作为孔。锥底、相交孔、侧开口、样条圆柱明确返回 partial 和来源诊断。
60
+ - `hole_groups`:指定安装面或枚举支持面,识别直线、矩形、圆形和无结构孔组;保留子集、额外孔、尺寸、残差与对称性。每面最多 64 个开口、10,000 个候选假设。面范围内的完整性单独判断,远离该面的不支持几何仍保留诊断。
61
+ - `interfaces` / `Model.interfaces`:`planar_hole_mount/v1` 声明重建后重新验证几何,支持安装面、孔组、可选定位圆柱、原点、方向和尺寸要求。不能从对称孔组猜出工程方向。完整坐标系配合必须提供方向;缺失、歧义、尺寸不匹配会失败。
62
+ - 相对选择支持 `planar_normal_aligned_with: {datum}`、`planar_normal_parallel_to: {datum}`、`planar_coplanar_with: {datum}`。共面测试同时检查法向和位置,防止误选同法向的盲孔底。基准只能引用同一零件中更早的声明。
63
+ - `interface_compatibility`:验证所有孔的对应、平面方向/间距、孔轴偏移、双方直径范围与可选定位间隙;独立直径范围不代表已经验证螺纹或螺栓配合。
64
+ - `measure`:显式两个目标,返回分离/接触/重叠/包含/不确定、边界距离、重叠体积和见证点。正距离不排除实体包含。结果在 `items[0]` 和 `measurement` 中;不确定为 partial,必需的装配检查不通过。复制求解器无法可靠恢复的见证拓扑 refs 明确不可用。
65
+ - `geometric_relationship`:必需的整零件关系检查和最多 32 个显式姿态样本;不等同连续运动认证。允许接触目前仅支持多面体中可通过完整半空间证明的相对平面,其他碰撞不豁免;曲面接触认证、局部区域限定测量明确不支持。
66
+ - `colocad view SESSION` 的 Query 页可高亮 native ref 对应的面/边/环轮廓及基准/孔组。可查询 preview 在建模时保存有哈希绑定的 `query-display.json`,采样轮廓只作显示依据;查询不重建、不导出、不三角化。爆炸图跟随零件移动,不修改查询坐标。
67
+
68
+ `datums` 或 `interfaces` 自动要求精确快照,显式禁用会报错。外部 STEP 示例包含底座、不同外形替换件、任意旋转来源及错误孔距/缺孔拒绝。完整 KK60 加附件例子保留 82 个实体和九项行程检查,见[复现实例](../examples/engineering-interfaces/README.md)。以上是明确范围内的功能证据,G2/G3 的可靠性、生命周期和沙箱资源验收另行记录。
69
+
70
+ 开发检查点新增 `execution_policy`,绑定 Rust 源码、依赖锁、编译器与目标平台;缺失或不匹配即重新计算,不能因为版本字符串相同就复用旧语义。[G3 证据](../specs/experiments/0005/README.md)覆盖真实进程中断、重新打开/迁移、语义面拆分/合并/删除、零件替换和 Linux 沙箱限额。
71
+
72
+ ## 可用性与 CadQuery 的关系
73
+
74
+ 这层能力已可用于声明支持的机械装配工作流:精确拓扑选择、基本基准、解析孔/孔组、平面安装接口、几何驱动替换及显式零件对测量。当前仍为 alpha;使用 Colocad 自己的 JSON/TypeScript 契约,不执行 CadQuery Python 程序,也不保证其选择器语法或全部特征等价。
75
+
76
+ G1–G3 的冻结语料、生命周期与两条真实 agent 任务已验收;[alpha.7 安装包验证](evidence/release-alpha.7.json)进一步覆盖 macOS arm64、Linux arm64/x64 上包内 SDK/CLI/native 的实际调用,其中 x64 在 arm64 宿主模拟执行。锥形/相交/侧开孔识别可能为 partial;曲面接触认证与局部区域限定测量仍显式不支持。
@@ -10,7 +10,7 @@ Run in a new project directory:
10
10
  mkdir my-cad-project
11
11
  cd my-cad-project
12
12
  npm init -y
13
- npm install --save-exact @coloopx/colocad@0.1.0-alpha.6
13
+ npm install --save-exact @coloopx/colocad@0.1.0-alpha.7
14
14
  cp node_modules/@coloopx/colocad/examples/manifold.json manifold.json
15
15
  ./node_modules/.bin/colocad plan manifold.json
16
16
  ./node_modules/.bin/colocad build manifold.json ./manifold-v1 --preview
@@ -7,7 +7,7 @@ Use a project skill with Claude Code's existing Bash and file/image tools. Insta
7
7
  From your project's root (with a `package.json`; create one with `npm init -y` if needed):
8
8
 
9
9
  ```sh
10
- npm install --save-exact @coloopx/colocad@0.1.0-alpha.6
10
+ npm install --save-exact @coloopx/colocad@0.1.0-alpha.7
11
11
  mkdir -p .claude/skills
12
12
  test ! -e .claude/skills/colocad && \
13
13
  cp -R node_modules/@coloopx/colocad/skills/colocad .claude/skills/colocad
@@ -7,7 +7,7 @@ Install a project skill and let Codex use its existing terminal and image tools.
7
7
  From the root of a Node project:
8
8
 
9
9
  ```sh
10
- npm install --save-exact @coloopx/colocad@0.1.0-alpha.6
10
+ npm install --save-exact @coloopx/colocad@0.1.0-alpha.7
11
11
  mkdir -p .agents/skills
12
12
  test ! -e .agents/skills/colocad && \
13
13
  cp -R node_modules/@coloopx/colocad/skills/colocad .agents/skills/colocad
@@ -36,9 +36,11 @@ With typed tools, allocate one `CadClient` for each sequential modeling session.
36
36
 
37
37
  With shell tools, use argument arrays in a process API rather than interpolating model text into shell commands. Store JSON in a file. Agent-controlled dimensions belong in model input; executable paths, output roots and credentials belong to harness configuration. Keep normal harness permissions in force.
38
38
 
39
+ For exact queries, enable `queryable` when needed (datum/interface declarations enable it automatically). Register `cad_query` only when native capabilities advertise it. Raw `createCadTools` takes `{artifact_directory, request}`; session-bound tools take `{request}` and bind the accepted artifact. The host owns `queryRoots`; the agent chooses a target/space/tolerance within that boundary. Preserve `query_revision_id` in compact build/edit feedback and re-query after edits. Stale refs, partial coverage and ambiguity remain visible. [Query/edit walkthrough](../best-practices.md#query-declare-intent-assemble-then-challenge-the-edit).
40
+
39
41
  ## Results and failures
40
42
 
41
- A useful tool result includes the artifact directory, counts/bounds/volume, validation summary and timings. Keep detailed feature diagnostics in the full receipt and attach a PNG for visual inspection. A path in text is not itself an image input to a remote vision model. The [Pi adapter](../../examples/integrations/pi-tools.mjs) shows text/image content and full `details` together.
43
+ A useful tool result includes the artifact directory, revision, relevant measurements, coverage/ambiguity, counts/bounds/volume, validation and timings. Keep detailed feature/query diagnostics in the full receipt and attach a PNG for visual inspection. A path in text is not itself an image input to a remote vision model. The [Pi adapter](../../examples/integrations/pi-tools.mjs) shows text/image content and full `details` together.
42
44
 
43
45
  `cad_validate` success is only preflight. A nonzero child exit, a failed receipt or an explicit degraded feature must remain visible. Do not turn a failed build into a success containing an empty output path. Do not retry the same invalid geometry indefinitely; change the failing feature or report the unresolved constraint.
44
46
 
@@ -4,15 +4,23 @@ The adapter is tested with `@earendil-works/pi-agent-core@1.5.0` and `@earendil-
4
4
 
5
5
  ## Pi agent core: register local tools
6
6
 
7
- Clone the example project and install its lockfile:
7
+ Clone the repository and build the matching development native/SDK before running the current query-enabled adapter tests (Node.js 22+ and Rust required):
8
8
 
9
9
  ```sh
10
10
  git clone https://github.com/Coloopx/colocad.git
11
- cd colocad/examples/integrations
11
+ cd colocad
12
+ node scripts/vendor.mjs
13
+ cargo build --locked --release -p agent-cad
14
+ export AGENT_CAD_BINARY="$PWD/target/release/agent-cad"
15
+ npm ci --prefix kernel --ignore-scripts
16
+ npm run build --prefix kernel
17
+ cd examples/integrations
12
18
  npm ci --ignore-scripts
13
19
  npm test
14
20
  ```
15
21
 
22
+ If `CARGO_TARGET_DIR` is configured, use its release executable in `AGENT_CAD_BINARY`. Published alpha.6 natives do not expose the new query contract. The separate legacy `sdk.mjs` example still pins alpha.3.
23
+
16
24
  [pi-tools.mjs](../../examples/integrations/pi-tools.mjs) adapts colocad's JSON Schemas and receipts to Pi `AgentTool`s. [pi-core.mjs](../../examples/integrations/pi-core.mjs) constructs an agent with these tools. Your harness supplies its existing model, stream function and authentication:
17
25
 
18
26
  ```js
@@ -45,7 +53,7 @@ From the example project after `npm ci`:
45
53
  ./node_modules/.bin/pi --extension ./pi-extension.mjs
46
54
  ```
47
55
 
48
- The extension registers five `cad_*` tools. Output defaults to `./cad-output`; set `COLOCAD_OUTPUT_DIR` in the shell launching Pi to choose a trusted absolute destination. Start it from the intended project directory and restart/rebind when changing projects. Use Pi's existing model/auth configuration.
56
+ The extension registers five core `cad_*` tools plus `cad_query` when the native capabilities advertise the exact query API. Output defaults to `./cad-output`; set `COLOCAD_OUTPUT_DIR` in the shell launching Pi to choose a trusted absolute destination. Start it from the intended project directory and restart/rebind when changing projects. Use Pi's existing model/auth configuration.
49
57
 
50
58
  For the modeling workflow as well, load the bundled skill:
51
59
 
@@ -68,6 +76,11 @@ test ! -e .agents/skills/colocad && \
68
76
 
69
77
  Start Pi in that project and invoke `/skill:colocad`. Keep the complete folder: its instructions reference scripts, assets and supporting guides. Review the project skill under Pi's normal project trust flow. No global install or permissions bypass is required.
70
78
 
71
- The example tests execute the actual Pi core loop with deterministic model responses, the actual extension loader, and the published Rust binary. They do not call a live model provider. See [verification scope](verification.md).
79
+ The example tests execute the actual Pi core loop with deterministic model responses, the actual extension loader, and the configured Rust binary. These six deterministic tests do not call a live model provider. Separate [G3 acceptance](../../specs/experiments/0005/README.md) records actual Pi inference, local tools, session history and native CAD inside Linux arm64 1 vCPU / 512 MiB, including a text-built plate and a sourced 82-solid product edit. See [verification scope](verification.md).
72
80
 
73
81
  References checked 2026-11-07: [Pi core](https://github.com/earendil-works/pi/tree/main/packages/agent), [extensions](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/extensions.md), [skills](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/skills.md). The installed 1.5.0 declarations and CLI help were also checked.
82
+
83
+
84
+ For Pi AI 1.5, provider-specific streaming comes from `@earendil-works/pi-ai/api/openai-completions`, which exports `streamSimple`; it is not exported by the package root. Supply this through the harness's `streamFn` with its configured endpoint/model/auth. The [live acceptance runner](../../specs/experiments/0005/sandbox/live.mjs) is a complete example with an external read-only credential file, bounded turns/time, persisted tool/inference traces and resource accounting. Keep credentials out of model prompts and traces.
85
+
86
+ Build/edit feedback retains the query revision and full receipts on disk. The adapter exposes structured query results and explicit degradation. The source adapter imports this checkout's SDK; its published alpha.3 dependency remains only for the separate legacy SDK compatibility example. For new query work compile the native and SDK from the same checkout as explained in the [query guide](../engineering-queries.md).
@@ -1,6 +1,6 @@
1
1
  # Integration verification
2
2
 
3
- Verified on **2026-11-07**, Node.js **22.23.3**, **macOS arm64**, using the public npm package **@coloopx/colocad@0.1.0-alpha.3** and its bundled Rust binary. Pi core, Pi AI and Pi coding agent are pinned to **1.5.0** in the example lockfile.
3
+ Historical baseline verified on **2026-11-07**, Node.js **22.23.3**, **macOS arm64**, using the public npm package **@coloopx/colocad@0.1.0-alpha.3** and its bundled Rust binary. Pi core, Pi AI and Pi coding agent are pinned to **1.5.0** in the example lockfile.
4
4
 
5
5
  | Check | Result | What it establishes |
6
6
  | --- | --- | --- |
@@ -28,3 +28,9 @@ The five integration tests run native CAD operations and actual Pi library code.
28
28
  Codex skill paths/invocation and Claude Code skill paths/invocation were checked against their official documentation. The bundled helper was run from both `.agents/skills/colocad` and `.claude/skills/colocad`. No Claude Code live session was run, and this test run did not evaluate a live Codex model reconstructing a drawing. The Pi live-provider schema negotiation remains dependent on the provider you configure.
29
29
 
30
30
  This verification adds no new performance claims. Cross-platform npm release checks are recorded separately in [release-alpha.3.json](../evidence/release-alpha.3.json); the new adapter regression itself was run on macOS arm64. Native SOLIDWORKS acceptance remains subject to the [existing limitations](../validation.md).
31
+
32
+ ## Engineering-query and release verification (2026-11-09)
33
+
34
+ Current source passes six deterministic Pi/integration tests, including capability-gated `cad_query`, revision-aware feedback and recorded errors. Two additional [G3 live Pi tasks](../../specs/experiments/0005/README.md) use real remote inference while the agent/harness/SDK/native execute in one limited Linux sandbox. They cover a text-built plate and an edit/query of a seeded 82-solid product; they do not measure unseen-image reconstruction.
35
+
36
+ The [alpha.7 archive record](../evidence/release-alpha.7.json) adds fresh-package SDK/CLI/query/foreign-replacement checks on macOS arm64 and Linux arm64/x64, independent OCCT readback and offline browser verification. Historical alpha.3 verification above remains scoped to that release.
@@ -6,12 +6,24 @@
6
6
  | Skill helper cannot import colocad | Install the pinned package in the current project and run the helper from there. Copy the complete skill folder. |
7
7
  | `colocad build` rejects `version: 1` | That CLI expects `format: "colocad/1"`. Use `CadClient` or the skill helper for a kernel model. |
8
8
  | Output directory already exists | Pick a new revision destination for the CLI/helper. Keep earlier accepted output. `CadClient.outputRoot` can contain multiple revisions. |
9
- | Unsupported platform / missing executable | Alpha.3 bundles Linux x64/arm64 and macOS arm64. Check `process.platform`, `process.arch` and the installed `kernel/native` directory. Source builds require a Rust toolchain and the pinned dependency. |
9
+ | Unsupported platform / missing executable | Alpha.8 bundles Linux x64/arm64 and macOS arm64. Check `process.platform`, `process.arch` and the installed `kernel/native` directory. Source builds require a Rust toolchain and the pinned dependency. |
10
10
  | Native launch fails | Check `LOCAL_EXECUTION_FAILED`, executable permissions, mount policy and `binary`/`AGENT_CAD_BINARY` overrides. Run the local CLI to isolate harness wiring. |
11
11
  | `TIMEOUT` | Inspect the failing feature and workload. Simplify or split unnecessary work; adjust `wallMs` within 1–120,000 only when appropriate. Sandbox memory failures need sandbox diagnostics too. |
12
12
  | `RESOURCE_LIMIT` / `OUTPUT_LIMIT` | Inspect capabilities and reduce model/mesh payload. SDK stdin is limited to 32 MiB; the feature-tree CLI accepts 2 MiB. |
13
13
  | Unknown/missing parameter | Use an existing finite numeric parameter. `edit()` does not create parameters; update the owned source to add one. |
14
14
  | An edit undoes a prior change | You reused stale source. Load the last accepted `model.json` or persist the merged parameters after each successful edit. |
15
+ | `cad_query` is absent | Inspect installed native capabilities. Alpha.7 includes exact queries; an older package or `AGENT_CAD_BINARY` override can expose older capabilities. Keep SDK and native from the same release/build. |
16
+ | No exact query snapshot | Rebuild the accepted source with `{queryable:true}` or CLI `--queryable`. A preview mesh or STEP file alone is not the native snapshot. Datums/interfaces require snapshots and reject explicit disabling with `QUERY_SNAPSHOT_REQUIRED`. |
17
+ | Alpha.7 `face_hole_grid` + `queryable` reports `BSplineCurve::make_nurb` status 1001 | Upgrade to alpha.8 with its matching native. The nested seam UV-line snapshot defect is fixed; preview precision was not the cause. Check `AGENT_CAD_BINARY` if an old native is still used. [Repair evidence](evidence/release-alpha.8.json). |
18
+ | `QUERY_REVISION_MISMATCH` | Obtain the latest accepted `query_revision_id` and rerun the semantic selection. Do not rewrite an old topology ref's revision field to bypass the check. |
19
+ | `QUERY_ARTIFACT_OUTSIDE_ROOT` | The harness must configure the appropriate trusted `queryRoots` or relocate the complete artifact directory under its allowed output root. The agent's query JSON cannot grant itself new roots. |
20
+ | `SELECTION_CARDINALITY`, missing datum/interface or ambiguous candidates | Inspect actual candidates, support plane, coordinate space and orientation. Refine a geometric rule; do not choose the first face or suppress ambiguity. |
21
+ | `INTERFACE_INCOMPATIBLE` / `INTERFACE_NOT_FOUND` during replacement | Compare required pitch, bore size, count, plane relation and register geometry. Preserve accepted source; retain a genuinely incompatible replacement as a failed attempt. |
22
+ | Query succeeds with `partial` coverage | Read diagnostics and source refs. Unsupported or unobserved geometry is not evidence of absence; required fit/clearance claims need complete supported evidence. |
23
+ | `QUERY_LIMIT` | Reduce target scope, nested selection/search size or page size. Check advertised budgets. Do not truncate candidates and still claim unique/complete recognition. |
24
+ | Positive distance but clearance fails | Inspect `relationship` and `overlap_mm3`. Boundary distance is unsigned; containment is not separation. Curved/region-specific contact certification also has explicit support limits. |
25
+ | `NO_MATERIAL_REMOVED` | The required cut was disjoint or tangent. Check tool placement, axis, depth and intended stock; do not treat the unchanged body as a machined result. |
26
+ | Old checkpoint is not reused after an upgrade | A changed/missing `execution_policy` intentionally forces replay. Keep accepted source and let the new executor rebuild; do not forge cache metadata. |
15
27
  | Preview succeeds but no STEP in its directory | A cached observation points to `source_artifact_directory`. Retrieve STEP from the source geometry revision. |
16
28
  | Cached preview cannot be read | Retain its source directory and files; do not modify cache bytes. Rebuild from the saved model if the cache was pruned or is invalid. |
17
29
  | Agent cannot see the rendered image | Attach PNG as image content or invoke the harness's image-reading tool. Printing the local filename alone is insufficient. |
@@ -1,27 +1,36 @@
1
1
  # Runnable integration examples
2
2
 
3
- This example project installs published `@coloopx/colocad@0.1.0-alpha.3`. It does not depend on a locally compiled kernel. Node.js 22+ and one of the package's supported platforms are required.
3
+ The standalone `sdk.mjs` keeps published `@coloopx/colocad@0.1.0-alpha.3` as a compatibility example. The Pi/session adapters import this checkout's SDK; their current query tests require the matching development native. Node.js 22+ is required, plus Rust to build the development executable.
4
4
 
5
5
  From the repository root:
6
6
 
7
7
  ```sh
8
+ node scripts/vendor.mjs
9
+ cargo build --locked --release -p agent-cad
10
+ export AGENT_CAD_BINARY="$PWD/target/release/agent-cad"
11
+ npm ci --prefix kernel --ignore-scripts
12
+ npm run build --prefix kernel
8
13
  npm ci --prefix examples/integrations --ignore-scripts
9
14
  npm test --prefix examples/integrations
10
15
  node examples/integrations/sdk.mjs ./out/sdk-example
11
16
  ```
12
17
 
18
+ If you set `CARGO_TARGET_DIR`, point `AGENT_CAD_BINARY` at that directory's release executable instead. Unset `AGENT_CAD_BINARY` to run only the legacy `sdk.mjs` against its bundled alpha.3 native; that does not test the new query API.
19
+
13
20
  `sdk.mjs` validates a four-hole plate, renders it, changes the camera using its cached mesh, changes the bore diameter and saves the current source. It prints the artifact paths. Its output root can be reused because the SDK creates new revision subdirectories.
14
21
 
15
22
  | File | Purpose |
16
23
  | --- | --- |
17
24
  | [sdk.mjs](sdk.mjs) | Actual SDK modeling/edit/observation cycle |
18
- | [pi-tools.mjs](pi-tools.mjs) | Five Pi tools, schema preservation, error mapping and PNG attachment |
25
+ | [pi-tools.mjs](pi-tools.mjs) | Five core Pi tools plus capability-gated `cad_query`, schema preservation, revision-aware feedback, error mapping and PNG attachment |
19
26
  | [pi-core.mjs](pi-core.mjs) | Construct a Pi core agent with a caller-supplied model and stream function |
20
27
  | [pi-extension.mjs](pi-extension.mjs) | Register the same tools in Pi coding agent |
21
28
  | [integration.test.mjs](integration.test.mjs) | Real native calls and Pi loop/extension/skill discovery regression tests |
22
29
 
23
30
  The test model stream is scripted; no LLM provider or credentials are needed. The test asserts a failed edit reaches the agent as an error and the subsequent corrected call exports STEP. It measures integration correctness, not model intelligence or drawing reconstruction success.
24
31
 
32
+ Separate [G3 live acceptance](../../specs/experiments/0005/README.md) runs Pi inference with local tools, harness and native in the same 1 vCPU / 512 MiB sandbox. It includes a text-built plate and a seeded 82-solid product edit, with actual tool traces and independent STEP readback. These are bounded tasks, not a drawing-reconstruction success-rate study.
33
+
25
34
  Use the [Pi guide](../../docs/integrations/pi.md) to connect real inference. [Codex](../../docs/integrations/codex.md) and [Claude Code](../../docs/integrations/claude-code.md) use the bundled skill and local CLI. These example files live in GitHub and are not part of the existing alpha.3 tarball.
26
35
 
27
36
  ## Record history in the source checkout
@@ -10,7 +10,7 @@ export function compactReceipt(receipt){
10
10
  .map(([name,sha256])=>[name,{path:join(d.artifact_directory,name),sha256}]));
11
11
  return {ok:true,...(receipt.session_step?{session_step:receipt.session_step}:{}),data:{
12
12
  artifact_directory:d.artifact_directory,source_artifact_directory:d.source_artifact_directory,
13
- model_hash:d.model_hash,source_hash:d.source_hash,geometry:structuredClone(d.geometry),
13
+ model_hash:d.model_hash,source_hash:d.source_hash,query_revision_id:d.query_revision_id,execution_policy:d.execution_policy,geometry:structuredClone(d.geometry),
14
14
  timing_ms:structuredClone(d.timing_ms),validation:structuredClone(d.validation),artifacts,
15
15
  feature_summary:{count:features.length,reused:features.filter(f=>f.cache_hit).length,
16
16
  slowest:[...features].sort((a,b)=>(b.elapsed_ms??0)-(a.elapsed_ms??0)).slice(0,3).map(f=>({id:f.id,elapsed_ms:f.elapsed_ms,cache_hit:f.cache_hit})),
@@ -1,21 +1,24 @@
1
- import type { Config, Model, Receipt, PreviewOptions, Sketch } from './types.js';
1
+ import type { Config, Model, Receipt, PreviewOptions, Sketch, BuildOptions, QueryRequest } from './types.js';
2
2
  export type * from './types.js';
3
3
  export { attachStep } from './assets.js';
4
4
  /** Local CAD API for the Harness and Agent sharing this sandbox. */
5
5
  export declare class CadClient {
6
6
  private readonly config;
7
7
  private previousRevision?;
8
+ private previousQueryable;
8
9
  private readonly previewCache;
9
10
  constructor(config: Config);
10
11
  capabilities(): Promise<Receipt>;
11
12
  schema(): Promise<Receipt>;
13
+ querySchema(): Promise<Receipt>;
14
+ query(directory: string, request: QueryRequest): Promise<Receipt>;
12
15
  validate(model: Model): Promise<Receipt>;
13
16
  solveSketch(sketch: Sketch, parameters?: Record<string, number>): Promise<Receipt>;
14
17
  inspectStep(model: Model, asset: string): Promise<Receipt>;
15
18
  preview(model: Model, options?: Partial<PreviewOptions>): Promise<Receipt>;
16
19
  /** Resume display from a trusted host artifact path, including in a new SDK process. */
17
20
  observeArtifact(directory: string, options?: Partial<PreviewOptions>): Promise<Receipt>;
18
- build(model: Model, previousRevision?: string | undefined): Promise<Receipt>;
21
+ build(model: Model, optionsOrRevision?: BuildOptions | string): Promise<Receipt>;
19
22
  edit(model: Model, parameters: Record<string, number>): Promise<Receipt>;
20
23
  inspect(artifactDirectory: string): Promise<Record<string, unknown>>;
21
24
  private invoke;
@@ -1,5 +1,5 @@
1
- import { readFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
1
+ import { readFile, realpath } from 'node:fs/promises';
2
+ import { join, relative, isAbsolute, sep } from 'node:path';
3
3
  import { artifactJob } from './artifacts.js';
4
4
  import { resolveBinary } from './binary.js';
5
5
  import { execute, receipt, error } from './process.js';
@@ -9,6 +9,7 @@ export { attachStep } from './assets.js';
9
9
  export class CadClient {
10
10
  config;
11
11
  previousRevision;
12
+ previousQueryable = false;
12
13
  previewCache = new Map();
13
14
  constructor(config) {
14
15
  this.config = config;
@@ -20,6 +21,26 @@ export class CadClient {
20
21
  }
21
22
  async capabilities() { return this.invoke(['capabilities']); }
22
23
  async schema() { return this.invoke(['schema']); }
24
+ async querySchema() { return this.invoke(['query-schema']); }
25
+ async query(directory, request) {
26
+ try {
27
+ const actual = await realpath(directory);
28
+ let allowed = false;
29
+ for (const root of this.config.queryRoots ?? [this.config.outputRoot]) {
30
+ const base = await realpath(root), path = relative(base, actual);
31
+ if (path === '' || (!isAbsolute(path) && path !== '..' && !path.startsWith('..' + sep)))
32
+ allowed = true;
33
+ }
34
+ if (!allowed)
35
+ return error('QUERY_ARTIFACT_OUTSIDE_ROOT', 'Artifact is outside the host-configured query roots');
36
+ if (Buffer.byteLength(JSON.stringify(request)) > 2 * 1024 * 1024)
37
+ return error('QUERY_LIMIT', 'Query request exceeds 2 MiB');
38
+ return this.invoke(['query', '--snapshot', actual], request);
39
+ }
40
+ catch (cause) {
41
+ return error('QUERY_ARTIFACT_READ_FAILED', String(cause));
42
+ }
43
+ }
23
44
  async validate(model) { return this.invoke(['validate'], model); }
24
45
  async solveSketch(sketch, parameters = {}) {
25
46
  return this.invoke(['solve-sketch'], { sketch, parameters });
@@ -60,11 +81,18 @@ export class CadClient {
60
81
  return error(cause instanceof CacheError ? cause.code : 'PREVIEW_CACHE_READ_FAILED', String(cause));
61
82
  }
62
83
  }
63
- async build(model, previousRevision = this.previousRevision) {
84
+ async build(model, optionsOrRevision) {
85
+ const options = typeof optionsOrRevision === 'string' ? { previousRevision: optionsOrRevision } : optionsOrRevision ?? {};
86
+ if (options.queryable === false && (model.datums?.length || model.interfaces?.length))
87
+ return error('QUERY_SNAPSHOT_REQUIRED', 'Datum/interface declarations require queryable artifacts');
88
+ const queryable = options.queryable ?? !!(model.datums?.length || model.interfaces?.length);
89
+ const previousRevision = options.previousRevision ?? this.previousRevision;
64
90
  const checkpoints = previousRevision ? ['--reuse', previousRevision] : ['--checkpoints'];
65
- const result = await artifactJob(this.config, 'job-', (_job, destination) => this.invoke(['build', '--out', destination, ...checkpoints], model));
66
- if (result.ok)
91
+ const result = await artifactJob(this.config, 'job-', (_job, destination) => this.invoke(['build', '--out', destination, ...checkpoints, ...(queryable ? ['--queryable'] : [])], model));
92
+ if (result.ok) {
67
93
  this.previousRevision = result.data.artifact_directory;
94
+ this.previousQueryable = queryable;
95
+ }
68
96
  if (result.ok && model.preview && result.data.artifact_sha256?.['preview.mesh.json']) {
69
97
  this.previewCache.set(previewKey(model), result.data.artifact_directory);
70
98
  if (this.previewCache.size > 16)
@@ -79,7 +107,7 @@ export class CadClient {
79
107
  if (!Number.isFinite(value))
80
108
  return error('INVALID_PARAMETER', key);
81
109
  }
82
- return this.build({ ...structuredClone(model), parameters: { ...model.parameters, ...parameters } });
110
+ return this.build({ ...structuredClone(model), parameters: { ...model.parameters, ...parameters } }, { queryable: this.previousQueryable });
83
111
  }
84
112
  async inspect(artifactDirectory) {
85
113
  return JSON.parse(await readFile(join(artifactDirectory, 'report.json'), 'utf8'));
@@ -90,7 +118,7 @@ export class CadClient {
90
118
  return error('RESOURCE_LIMIT', 'input exceeds 32 MiB');
91
119
  try {
92
120
  const binary = resolveBinary(this.config.binary ?? this.config.runner?.binary);
93
- return receipt(await execute(binary, args, input, this.config.wallMs ?? 30_000));
121
+ return receipt(await execute(binary, args, input, this.config.wallMs ?? 30_000, args[0] === 'query' ? 8 * 1024 * 1024 : 2 * 1024 * 1024));
94
122
  }
95
123
  catch (cause) {
96
124
  return error('LOCAL_EXECUTION_FAILED', String(cause));