diff --git a/.gitattributes b/.gitattributes index 3f61129..5f428f8 100644 --- a/.gitattributes +++ b/.gitattributes @@ -19,6 +19,10 @@ third_party/sqlite/sqlite3* -text whitespace=-blank-at-eol # Preserve the pinned upstream decoder and license byte for byte. third_party/stb/stb_image.h -text whitespace=-blank-at-eol third_party/stb/LICENSE -text whitespace=-blank-at-eol +# Preserve the verified zstd 1.5.7 sources and licenses byte for byte. +third_party/zstd/lib/** -text whitespace=-blank-at-eol +third_party/zstd/LICENSE -text whitespace=-blank-at-eol +third_party/zstd/COPYING -text whitespace=-blank-at-eol # Preserve the official ONNX Runtime headers and notices byte for byte. third_party/onnxruntime/*.h -text whitespace=cr-at-eol,-blank-at-eol third_party/onnxruntime/LICENSE -text whitespace=cr-at-eol,-blank-at-eol diff --git a/CMakeLists.txt b/CMakeLists.txt index 0a74d12..f680e94 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,16 +27,37 @@ add_library(ark-sqlite STATIC third_party/sqlite/sqlite3.c) target_include_directories(ark-sqlite PUBLIC third_party/sqlite) target_compile_definitions(ark-sqlite PRIVATE SQLITE_ENABLE_FTS5=1 SQLITE_THREADSAFE=1 SQLITE_OMIT_LOAD_EXTENSION=1 SQLITE_DQS=0 SQLITE_DEFAULT_FOREIGN_KEYS=1) target_link_libraries(ark-sqlite PUBLIC Threads::Threads) +# 051A: unmodified zstd 1.5.7 library sources for the derived-section pack. +# Single-threaded, no assembly, no legacy formats and no dictionary builder. +add_library(ark-zstd STATIC + third_party/zstd/lib/common/debug.c third_party/zstd/lib/common/entropy_common.c third_party/zstd/lib/common/error_private.c + third_party/zstd/lib/common/fse_decompress.c third_party/zstd/lib/common/pool.c third_party/zstd/lib/common/threading.c + third_party/zstd/lib/common/xxhash.c third_party/zstd/lib/common/zstd_common.c + third_party/zstd/lib/compress/fse_compress.c third_party/zstd/lib/compress/hist.c third_party/zstd/lib/compress/huf_compress.c + third_party/zstd/lib/compress/zstd_compress.c third_party/zstd/lib/compress/zstd_compress_literals.c + third_party/zstd/lib/compress/zstd_compress_sequences.c third_party/zstd/lib/compress/zstd_compress_superblock.c + third_party/zstd/lib/compress/zstd_double_fast.c third_party/zstd/lib/compress/zstd_fast.c third_party/zstd/lib/compress/zstd_lazy.c + third_party/zstd/lib/compress/zstd_ldm.c third_party/zstd/lib/compress/zstd_opt.c third_party/zstd/lib/compress/zstd_preSplit.c + third_party/zstd/lib/compress/zstdmt_compress.c + third_party/zstd/lib/decompress/huf_decompress.c third_party/zstd/lib/decompress/zstd_ddict.c + third_party/zstd/lib/decompress/zstd_decompress.c third_party/zstd/lib/decompress/zstd_decompress_block.c) +target_include_directories(ark-zstd PUBLIC third_party/zstd/lib) +target_compile_definitions(ark-zstd PRIVATE ZSTD_DISABLE_ASM=1 ZSTD_LEGACY_SUPPORT=0) add_library(ark STATIC + src/command_catalog.cpp + src/derived_pack_051a.cpp src/curve_pattern_044b.cpp src/media_044b.cpp src/modeling_031b.cpp src/geometry_storage_032d.cpp src/wood_tools.cpp - src/authoring_024b.cpp src/appearance_024b.cpp src/plane_sections_024b.cpp + src/authoring_024b.cpp src/media_authoring.cpp src/appearance_024b.cpp src/plane_sections_024b.cpp src/authoring_023b.cpp src/cad_import.cpp src/holes_orchestrator.cpp src/design_containers.cpp + src/parametric_components.cpp + src/design_disciplines.cpp + src/motion_cables.cpp src/assembly_patterns.cpp src/motion_graph.cpp src/exploded_view.cpp src/visualize.cpp src/derived_bakes_049a.cpp src/drag_chain.cpp - src/direct_preview.cpp + src/direct_preview.cpp src/async_authoring_051a.cpp src/exact_jobs_046b.cpp src/parametric_hud.cpp src/agent_activity.cpp @@ -46,7 +67,7 @@ add_library(ark STATIC src/bom.cpp src/bom_review.cpp src/bom_export.cpp src/curve_equation.cpp src/spatial_sketch.cpp src/sketch_entities.cpp src/datum_authoring.cpp src/updates.cpp src/document_container.cpp - src/iteration_history.cpp + src/iteration_history.cpp src/history_compaction_051a.cpp src/history_authoring.cpp src/assembly_authoring.cpp src/recovery.cpp src/pricing.cpp src/agent_team.cpp @@ -63,13 +84,17 @@ add_library(ark STATIC src/agent_transactions.cpp src/agent_failures.cpp src/agent_benchmark.cpp - src/physics.cpp + src/physics.cpp src/inertial_simulation.cpp src/rubber.cpp src/rubber_patterns.cpp src/rubber_dynamics.cpp src/surface_edit_059c.cpp src/core.cpp src/nurbs.cpp src/brep.cpp src/mesh.cpp src/csg.cpp src/model.cpp src/evaluate.cpp src/native_features.cpp src/frame.cpp src/electronics.cpp src/usage.cpp src/stock_preview.cpp src/suspension.cpp src/chatgpt_auth.cpp src/assistant_credentials.cpp src/sheet_commands.cpp src/sheet_preview.cpp src/references.cpp src/datum.cpp src/solver.cpp src/sketch.cpp src/prism_cut.cpp src/onboarding.cpp src/live_session.cpp src/assistant.cpp src/io.cpp src/serialize.cpp src/source_tube.cpp src/notch.cpp src/notch_preview.cpp src/step_export.cpp src/tube.cpp src/assembly.cpp src/assembly_io.cpp src/compute.cpp src/api.cpp src/mesh_query.cpp src/mesh_analysis.cpp src/mesh_model.cpp src/agent.cpp src/agent_features.cpp src/result_path.cpp src/kernels_scalar.cpp src/snapshot_032d.cpp) target_include_directories(ark PUBLIC include "${CMAKE_CURRENT_BINARY_DIR}/generated") target_include_directories(ark SYSTEM PRIVATE third_party) +add_executable(ark-async-authoring-051a-tests tests/async_authoring_051a_tests.cpp) +target_link_libraries(ark-async-authoring-051a-tests PRIVATE ark) +add_test(NAME async-authoring-051a COMMAND ark-async-authoring-051a-tests) +set_tests_properties(async-authoring-051a PROPERTIES TIMEOUT 180) add_executable(ark-direct-preview-tests tests/direct_preview_tests.cpp) target_link_libraries(ark-direct-preview-tests PRIVATE ark) add_test(NAME direct-preview-worker COMMAND ark-direct-preview-tests) @@ -94,9 +119,26 @@ if(ARK_WITH_OCCT) target_compile_definitions(ark-authoring-022b-contract-tests PRIVATE ARK_022B_NATIVE_TESTS=1) add_dependencies(ark-authoring-022b-contract-tests ark-occt-worker) endif() -target_link_libraries(ark PUBLIC Threads::Threads PRIVATE ark-sqlite) +target_link_libraries(ark PUBLIC Threads::Threads PRIVATE ark-sqlite ark-zstd) if(WIN32) - target_link_libraries(ark PRIVATE bcrypt normaliz) + target_link_libraries(ark PRIVATE bcrypt normaliz gdi32 d3d11 d3dcompiler dxgi) +endif() +add_executable(ark-inertial-056c-tests tests/inertial_056c_tests.cpp) +add_executable(ark-rubber-patterns-tests tests/rubber_patterns_tests.cpp) +target_link_libraries(ark-rubber-patterns-tests PRIVATE ark) +add_test(NAME rubber-patterns-059c COMMAND ark-rubber-patterns-tests) +add_executable(ark-rubber-dynamics-tests tests/rubber_dynamics_tests.cpp) +target_link_libraries(ark-rubber-dynamics-tests PRIVATE ark) +add_test(NAME rubber-dynamics-059c COMMAND ark-rubber-dynamics-tests) +set_tests_properties(rubber-dynamics-059c PROPERTIES TIMEOUT 180) +add_executable(ark-rubber-runtime-059c-benchmark EXCLUDE_FROM_ALL benchmarks/rubber_runtime_059c.cpp) +target_link_libraries(ark-rubber-runtime-059c-benchmark PRIVATE ark) +target_link_libraries(ark-inertial-056c-tests PRIVATE ark) +add_test(NAME inertial-056c COMMAND ark-inertial-056c-tests) +set_tests_properties(inertial-056c PROPERTIES TIMEOUT 180) +if(ARK_WITH_OCCT) + target_compile_definitions(ark-inertial-056c-tests PRIVATE ARK_INERTIAL_NATIVE=1) + add_dependencies(ark-inertial-056c-tests ark-occt-worker) endif() add_executable(ark-product-tools-030d-tests tests/product_tools_030d_tests.cpp) target_link_libraries(ark-product-tools-030d-tests PRIVATE ark) @@ -112,6 +154,20 @@ else() target_compile_options(ark PRIVATE -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -fno-fast-math) endif() add_executable(ark-cli src/app/cli.cpp) +add_executable(ark-design-disciplines-054b-tests tests/design_disciplines_054b_tests.cpp) +target_link_libraries(ark-design-disciplines-054b-tests PRIVATE ark) +add_test(NAME design-disciplines-054b COMMAND ark-design-disciplines-054b-tests) +set_tests_properties(design-disciplines-054b PROPERTIES TIMEOUT 180) +if(ARK_WITH_OCCT) + add_dependencies(ark-design-disciplines-054b-tests ark-occt-worker) +endif() +add_executable(ark-parametric-components-053b-tests tests/parametric_components_053b_tests.cpp) +target_link_libraries(ark-parametric-components-053b-tests PRIVATE ark) +add_test(NAME parametric-components-053b COMMAND ark-parametric-components-053b-tests) +set_tests_properties(parametric-components-053b PROPERTIES TIMEOUT 180) +if(ARK_WITH_OCCT) + add_dependencies(ark-parametric-components-053b-tests ark-occt-worker) +endif() add_executable(ark-project-memory-tests tests/project_memory_tests.cpp) target_link_libraries(ark-project-memory-tests PRIVATE ark ark-sqlite) add_test(NAME project-memory COMMAND ark-project-memory-tests) @@ -177,10 +233,14 @@ add_executable(ark-benchmark src/app/benchmark.cpp) target_link_libraries(ark-benchmark PRIVATE ark) add_custom_command(TARGET ark-benchmark POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory "$/benchmarks" "$/examples" - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/benchmarks/agent_briefs_v1.json" "${CMAKE_SOURCE_DIR}/benchmarks/offline.json" "${CMAKE_SOURCE_DIR}/benchmarks/ollama-qwen-q3.json" "${CMAKE_SOURCE_DIR}/benchmarks/ollama-qwen-27b.json" "$/benchmarks" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/benchmarks/agent_briefs_v1.json" "${CMAKE_SOURCE_DIR}/benchmarks/agent_outcomes_v2.json" "${CMAKE_SOURCE_DIR}/benchmarks/part_agents_052d.json" "${CMAKE_SOURCE_DIR}/benchmarks/part_agents_offline_052d.json" "${CMAKE_SOURCE_DIR}/benchmarks/part_agents_sol_052d.json" "${CMAKE_SOURCE_DIR}/benchmarks/part_agents_neutral_sol_052d.json" "${CMAKE_SOURCE_DIR}/benchmarks/offline.json" "${CMAKE_SOURCE_DIR}/benchmarks/ollama-qwen-q3.json" "${CMAKE_SOURCE_DIR}/benchmarks/ollama-qwen-27b.json" "$/benchmarks" COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_SOURCE_DIR}/examples/pneumatic-cylinder.arkops" "$/examples") add_executable(ark-tests tests/tests.cpp) add_executable(ark-agent-tests tests/agent_tests.cpp) +add_executable(ark-scoped-sketches-051a-tests tests/scoped_sketches_051a_tests.cpp) +target_link_libraries(ark-scoped-sketches-051a-tests PRIVATE ark) +add_test(NAME scoped-sketches-051a COMMAND ark-scoped-sketches-051a-tests) +add_test(NAME scoped-sketches-history-051a COMMAND ark-scoped-sketches-051a-tests --history) add_executable(ark-mesh-model-tests tests/mesh_model_tests.cpp) foreach(app ark-cli ark-mcp ark-tests ark-agent-tests ark-mesh-model-tests) target_link_libraries(${app} PRIVATE ark) @@ -344,6 +404,23 @@ add_executable(ark-document-container-tests tests/document_container_tests.cpp) target_link_libraries(ark-document-container-tests PRIVATE ark ark-sqlite) add_test(NAME document-container COMMAND ark-document-container-tests) set_tests_properties(document-container PROPERTIES TIMEOUT 60) +add_executable(ark-history-compaction-051a-tests tests/history_compaction_051a_tests.cpp) +target_link_libraries(ark-history-compaction-051a-tests PRIVATE ark) +add_test(NAME history-compaction-051a COMMAND ark-history-compaction-051a-tests) +set_tests_properties(history-compaction-051a PROPERTIES TIMEOUT 180) +# 051A derived pack: exact round trip, hostile frames, legacy rows, capacity tail and compaction. +add_executable(ark-derived-pack-051a-tests tests/derived_pack_051a_tests.cpp) +target_link_libraries(ark-derived-pack-051a-tests PRIVATE ark ark-sqlite ark-zstd) +add_test(NAME derived-pack-051a COMMAND ark-derived-pack-051a-tests) +set_tests_properties(derived-pack-051a PROPERTIES TIMEOUT 300) +add_executable(ark-command-catalog-056c-tests tests/command_catalog_056c_tests.cpp) +target_link_libraries(ark-command-catalog-056c-tests PRIVATE ark) +add_test(NAME command-catalog-056c COMMAND ark-command-catalog-056c-tests) +set_tests_properties(command-catalog-056c PROPERTIES TIMEOUT 120) +if(ARK_WITH_OCCT) + target_compile_definitions(ark-command-catalog-056c-tests PRIVATE ARK_COMMAND_NATIVE_TESTS=1) + add_dependencies(ark-command-catalog-056c-tests ark-occt-worker) +endif() add_executable(ark-iteration-history-tests tests/iteration_history_tests.cpp) target_link_libraries(ark-iteration-history-tests PRIVATE ark) add_test(NAME iteration-history COMMAND ark-iteration-history-tests) @@ -384,6 +461,8 @@ if(ARK_WITH_OCCT) target_compile_definitions(ark-sketch-entity-tests PRIVATE ARK_SKETCH_ENTITIES_NATIVE_TESTS=1) add_dependencies(ark-sketch-entity-tests ark-occt-worker) target_compile_definitions(ark-agent-tests PRIVATE ARK_TEST_WITH_OCCT=1) + add_dependencies(ark-scoped-sketches-051a-tests ark-occt-worker) + add_test(NAME scoped-sketches-native-051a COMMAND ark-scoped-sketches-051a-tests --native) add_dependencies(ark-agent-tests ark-occt-worker) find_package(OpenCASCADE REQUIRED) add_executable(ark-surface-edit-tests tests/surface_edit_tests.cpp) @@ -427,6 +506,33 @@ if(ARK_WITH_OCCT) target_include_directories(ark-occt PUBLIC include PRIVATE src/occt) target_include_directories(ark-occt SYSTEM PUBLIC ${OpenCASCADE_INCLUDE_DIR}) target_link_libraries(ark-occt PUBLIC ${OpenCASCADE_LIBRARIES} PRIVATE ark) + add_executable(ark-rubber-059c-tests tests/rubber_059c_tests.cpp) + target_link_libraries(ark-rubber-059c-tests PRIVATE ark-occt ark) + add_dependencies(ark-rubber-059c-tests ark-occt-worker) + add_test(NAME rubber-authoring-059c COMMAND ark-rubber-059c-tests) + set_tests_properties(rubber-authoring-059c PROPERTIES TIMEOUT 180) + add_executable(ark-surfacing-059c-tests tests/surfacing_059c_tests.cpp) + target_link_libraries(ark-surfacing-059c-tests PRIVATE ark-occt ark) + add_test(NAME surfacing-059c COMMAND ark-surfacing-059c-tests) + set_tests_properties(surfacing-059c PROPERTIES TIMEOUT 180) + add_executable(ark-surfacing-workflow-059c-tests tests/surfacing_workflow_059c_tests.cpp) + target_link_libraries(ark-surfacing-workflow-059c-tests PRIVATE ark) + add_dependencies(ark-surfacing-workflow-059c-tests ark-occt-worker) + add_test(NAME surfacing-workflow-059c COMMAND ark-surfacing-workflow-059c-tests) + set_tests_properties(surfacing-workflow-059c PROPERTIES TIMEOUT 180) + add_executable(ark-surface-support-visibility-059c-tests tests/surface_support_visibility_059c_tests.cpp) + target_link_libraries(ark-surface-support-visibility-059c-tests PRIVATE ark) + add_dependencies(ark-surface-support-visibility-059c-tests ark-occt-worker) + add_test(NAME surface-support-visibility-059c COMMAND ark-surface-support-visibility-059c-tests "${CMAKE_CURRENT_BINARY_DIR}/surface-support-visibility-059c.png") + set_tests_properties(surface-support-visibility-059c PROPERTIES TIMEOUT 180) + add_executable(ark-surface-deform-059c-tests tests/surface_deform_059c_tests.cpp) + target_link_libraries(ark-surface-deform-059c-tests PRIVATE ark-occt ark) + add_test(NAME surface-deform-059c COMMAND ark-surface-deform-059c-tests) + add_executable(ark-surface-control-059c-tests tests/surface_control_059c_tests.cpp) + target_link_libraries(ark-surface-control-059c-tests PRIVATE ark) + add_dependencies(ark-surface-control-059c-tests ark-occt-worker) + add_test(NAME surface-control-059c COMMAND ark-surface-control-059c-tests) + set_tests_properties(surface-deform-059c surface-control-059c PROPERTIES TIMEOUT 180) add_executable(ark-occt-surface-repair-tests tests/occt_surface_repair_tests.cpp) target_link_libraries(ark-occt-surface-repair-tests PRIVATE ark-occt ark) add_test(NAME native-surface-repair COMMAND ark-occt-surface-repair-tests) @@ -546,16 +652,16 @@ if(WIN32) set_tests_properties(studio-navigation-036a PROPERTIES TIMEOUT 180 RUN_SERIAL TRUE) add_test(NAME studio-datum-authoring-036a COMMAND ark-studio --datum-authoring-ui-test --settings-file "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/datum-authoring-036a.settings.json" --shot "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/datum-authoring-036a.png" --size 1440 900) set_tests_properties(studio-datum-authoring-036a PROPERTIES TIMEOUT 180 RUN_SERIAL TRUE) - foreach(check async-exact-ui team-blockers-ui realtime-ui product-tools-ui scene-cache-ui authoring-assistance-ui editor-scroll-ui feature-editor-picking-ui history-ui recovery-ui configuration-workspace-ui interaction-performance-ui) + foreach(check surface-edit-ui surface-workflow-ui viewport-capture-ui rubber-ui rubber-engine-ui async-exact-ui async-authoring-ui team-blockers-ui realtime-ui product-tools-ui scene-cache-ui authoring-assistance-ui editor-scroll-ui feature-editor-picking-ui history-ui history-compaction-ui recovery-ui configuration-workspace-ui interaction-performance-ui) add_test(NAME studio-${check} COMMAND ark-studio --self-test-${check} --settings-file "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.settings.json" --shot "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.png" --size 1280 800) set_tests_properties(studio-${check} PROPERTIES TIMEOUT 300 RUN_SERIAL TRUE) endforeach() - foreach(check connectors-ui local-models-ui viewport-dock-ui assistant-steering-ui stamps-ui media-044b-ui planes-sections-ui holes-orchestrator-ui design-container-ui cad-import-ui native-vertex-pull-ui advanced-sheetmetal-ui specialized-pattern-ui drawing-viewport-ui direct-authoring-ui parametric-authoring-ui selection-glow-ui selection-picking-ui image-attachment-ui sketch-edit-ui sketch-drawing-ui typed-sketch-ui arc-ui assistant-ui render-ui action-icons-ui interaction-ui baked-motions-ui exploded-views-ui drag-chain-ui) + foreach(check inertial-ui viewport-quality-ui connectors-ui local-models-ui viewport-dock-ui context-ui suspension-ui assistant-steering-ui assistant-chat-ui stamps-ui media-044b-ui planes-sections-ui holes-orchestrator-ui design-container-ui parametric-graph-ui design-disciplines-ui cad-import-ui native-vertex-pull-ui advanced-sheetmetal-ui specialized-pattern-ui drawing-viewport-ui direct-authoring-ui parametric-authoring-ui selection-glow-ui selection-picking-ui image-attachment-ui sketch-edit-ui sketch-drawing-ui typed-sketch-ui arc-ui assistant-ui render-ui action-icons-ui interaction-ui baked-motions-ui exploded-views-ui drag-chain-ui) add_test(NAME studio-${check} COMMAND ark-studio --self-test-${check} --settings-file "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.settings.json" --shot "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}.png" --size 1440 900) set_tests_properties(studio-${check} PROPERTIES TIMEOUT 180 RUN_SERIAL TRUE) endforeach() set_tests_properties(studio-interaction-ui PROPERTIES WORKING_DIRECTORY "${CMAKE_SOURCE_DIR}") - foreach(check team-blockers-ui local-models-ui viewport-dock-ui assistant-steering-ui stamps-ui planes-sections-ui baked-motions-ui exploded-views-ui) + foreach(check team-blockers-ui local-models-ui viewport-dock-ui assistant-steering-ui assistant-chat-ui stamps-ui planes-sections-ui baked-motions-ui exploded-views-ui) add_test(NAME studio-${check}-compact COMMAND ark-studio --self-test-${check} --settings-file "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}-compact.settings.json" --shot "${ARK_STUDIO_TEST_ARTIFACT_ROOT}/${check}-compact.png" --size 1366 800) set_tests_properties(studio-${check}-compact PROPERTIES TIMEOUT 180 RUN_SERIAL TRUE) endforeach() @@ -639,6 +745,13 @@ if(ARK_WITH_OCCT) add_dependencies(ark-agent-team-tests ark-occt-worker) endif() add_test(NAME agent-team COMMAND ark-agent-team-tests) +add_executable(ark-part-agents-tests tests/part_agents_052d_tests.cpp) +target_link_libraries(ark-part-agents-tests PRIVATE ark) +if(ARK_WITH_OCCT) + add_dependencies(ark-part-agents-tests ark-occt-worker) +endif() +add_test(NAME part-agents-052d COMMAND ark-part-agents-tests) +set_tests_properties(part-agents-052d PROPERTIES TIMEOUT 60) set_tests_properties(agent-team PROPERTIES TIMEOUT 45) add_executable(ark-agent-tool-layer-042d-tests tests/agent_tool_layer_042d_tests.cpp) @@ -723,6 +836,10 @@ if(ARK_WITH_OCCT) add_dependencies(ark-dfm-tests ark-occt-worker) endif() +add_executable(ark-media-authoring-tests tests/media_authoring_tests.cpp) +target_link_libraries(ark-media-authoring-tests PRIVATE ark) +add_test(NAME media-authoring COMMAND ark-media-authoring-tests) +set_tests_properties(media-authoring PROPERTIES TIMEOUT 180) add_executable(ark-media-044b-tests tests/media_044b_tests.cpp) target_link_libraries(ark-media-044b-tests PRIVATE ark) add_test(NAME media-044b COMMAND ark-media-044b-tests) diff --git a/benchmarks/agent_outcomes_v2.json b/benchmarks/agent_outcomes_v2.json new file mode 100644 index 0000000..ae7d655 --- /dev/null +++ b/benchmarks/agent_outcomes_v2.json @@ -0,0 +1,302 @@ +{ + "id": "ark-agent-outcomes-v2", + "version": 2, + "source": "Synthetic editable tasks; all attempts are saved and cold-reopened by the host oracle. Reference commands are never sent to live models.", + "milestones": [ + "A.02", + "D.02" + ], + "cases": [ + { + "id": "E01", + "version": 1, + "category": "parametric_edit", + "brief": "Change driving parameter width from 10 to 15 mm. Keep Block width driven by width, depth 20 and height 30. Preserve editable parameter and feature expressions.", + "baseline": [ + { + "op": "param.set", + "name": "width", + "expr": "10" + }, + { + "op": "feature.add", + "type": "native_solid", + "name": "Block", + "native": { + "op": "box" + }, + "p": { + "width": "width", + "depth": 20, + "height": 30 + } + } + ], + "reference": [ + { + "op": "param.set", + "name": "width", + "expr": "15" + } + ], + "checks": [ + { + "id": "valid", + "query": { + "tool": "native_inspect", + "args": { + "id": 1 + }, + "path": "report.brep_valid" + }, + "equals": true + }, + { + "id": "single_solid", + "query": { + "tool": "native_inspect", + "args": { + "id": 1 + }, + "path": "report.solids" + }, + "equals": 1 + }, + { + "id": "volume", + "query": { + "tool": "native_inspect", + "args": { + "id": 1 + }, + "path": "report.volume_mm3" + }, + "equals": 9000, + "absolute_tolerance": 1e-05 + }, + { + "id": "bound_3", + "query": { + "tool": "native_inspect", + "args": { + "id": 1 + }, + "path": "report.bounds_mm.3" + }, + "equals": 15, + "absolute_tolerance": 1e-05 + }, + { + "id": "driving_parameter", + "query": { + "tool": "eval_expr", + "args": { + "expr": "width" + }, + "path": "value" + }, + "equals": 15 + }, + { + "id": "editable_expression", + "query": { + "tool": "doc_get", + "args": {}, + "path": "document.features.0.p.width" + }, + "equals": "width" + } + ] + }, + { + "id": "E02", + "version": 1, + "category": "assembly_edit", + "brief": "Move Free Block instance to X=25 mm, retaining Fixed at origin and unchanged 10 by 20 by 30 Block geometry. Exact gap must be 15 mm.", + "baseline": [ + { + "op": "feature.add", + "type": "native_solid", + "name": "Block", + "native": { + "op": "box" + }, + "p": { + "width": 10, + "depth": 20, + "height": 30 + } + }, + { + "op": "assembly.add", + "name": "Fixed", + "feature": "Block", + "p": {}, + "fixed": true + }, + { + "op": "assembly.add", + "name": "Free", + "feature": "Block", + "p": { + "tx": 15 + } + } + ], + "reference": [ + { + "op": "assembly.edit", + "id": "Free", + "p": { + "tx": 25 + } + } + ], + "checks": [ + { + "id": "valid", + "query": { + "tool": "native_inspect", + "args": { + "id": 1 + }, + "path": "report.brep_valid" + }, + "equals": true + }, + { + "id": "single_solid", + "query": { + "tool": "native_inspect", + "args": { + "id": 1 + }, + "path": "report.solids" + }, + "equals": 1 + }, + { + "id": "volume", + "query": { + "tool": "native_inspect", + "args": { + "id": 1 + }, + "path": "report.volume_mm3" + }, + "equals": 6000, + "absolute_tolerance": 1e-05 + }, + { + "id": "exact_gap", + "query": { + "tool": "assembly_info", + "args": { + "clearance": { + "a": "Fixed", + "b": "Free" + } + }, + "path": "separation_mm" + }, + "equals": 15, + "absolute_tolerance": 1e-05 + } + ] + }, + { + "id": "E03", + "version": 1, + "category": "rejection_recovery", + "brief": "A previous atomic edit attempted to set Block depth to 99 and width to -1 and was rejected. Recover from the unchanged baseline: set width to 15, retain original depth 20 and height 30, and keep the feature editable. Inspect the rejection and current document first.", + "baseline": [ + { + "op": "feature.add", + "type": "native_solid", + "name": "Block", + "native": { + "op": "box" + }, + "p": { + "width": 10, + "depth": 20, + "height": 30 + } + } + ], + "reference": [ + { + "op": "feature.edit", + "id": "Block", + "p": { + "width": 15 + } + } + ], + "checks": [ + { + "id": "valid", + "query": { + "tool": "native_inspect", + "args": { + "id": 1 + }, + "path": "report.brep_valid" + }, + "equals": true + }, + { + "id": "single_solid", + "query": { + "tool": "native_inspect", + "args": { + "id": 1 + }, + "path": "report.solids" + }, + "equals": 1 + }, + { + "id": "volume", + "query": { + "tool": "native_inspect", + "args": { + "id": 1 + }, + "path": "report.volume_mm3" + }, + "equals": 9000, + "absolute_tolerance": 1e-05 + }, + { + "id": "bound_3", + "query": { + "tool": "native_inspect", + "args": { + "id": 1 + }, + "path": "report.bounds_mm.3" + }, + "equals": 15, + "absolute_tolerance": 1e-05 + } + ], + "rejected_commands": [ + { + "op": "feature.edit", + "id": "Block", + "p": { + "depth": 99 + } + }, + { + "op": "feature.edit", + "id": "Block", + "p": { + "width": -1 + } + } + ] + } + ] +} diff --git a/benchmarks/part_agents_052d.json b/benchmarks/part_agents_052d.json new file mode 100644 index 0000000..0871b7f --- /dev/null +++ b/benchmarks/part_agents_052d.json @@ -0,0 +1,30 @@ +{ + "id": "ark-part-delegation-052d", + "version": 1, + "source": "Synthetic scoped detail with a shared read-only interface and reused part definition. Reference commands are offline harness input only.", + "cases": [{ + "id": "PD01", + "version": 1, + "category": "isolated_parametric_part_detail", + "part_container": 1, + "brief": "The initial editable concept is complete. Detail the Part definition in PartGroup (container 1): change its depth from 6 to 9 mm, retain width driven by SharedWidth=12 mm and height 7 mm. Both occurrences must reuse that definition. Preserve the other module and shared interfaces. Review the result and preserve editable authoring.", + "baseline": [ + {"op":"param.set","name":"SharedWidth","expr":12}, + {"op":"feature.add","type":"native_solid","name":"Part","native":{"op":"box"},"p":{"width":"SharedWidth","depth":6,"height":7}}, + {"op":"feature.add","type":"native_solid","name":"OtherModule","native":{"op":"box"},"p":{"width":"SharedWidth","depth":3,"height":4}}, + {"op":"assembly.add","name":"PartGroup","feature":0}, + {"op":"assembly.add","name":"PartA","feature":1,"parent":1}, + {"op":"assembly.add","name":"PartB","feature":1,"parent":1,"p":{"tx":30}}, + {"op":"assembly.add","name":"OtherOccurrence","feature":2,"p":{"tx":60}} + ], + "reference": [{"op":"feature.edit","id":1,"p":{"depth":9}}], + "checks": [ + {"id":"valid_part","query":{"tool":"native_inspect","args":{"id":1},"path":"report.brep_valid"},"equals":true}, + {"id":"detail_volume","query":{"tool":"native_inspect","args":{"id":1},"path":"report.volume_mm3"},"equals":756,"absolute_tolerance":0.00001}, + {"id":"outside_volume","query":{"tool":"native_inspect","args":{"id":2},"path":"report.volume_mm3"},"equals":144,"absolute_tolerance":0.00001}, + {"id":"shared_interface","query":{"tool":"eval_expr","args":{"expr":"SharedWidth"},"path":"value"},"equals":12}, + {"id":"authored_expression","query":{"tool":"doc_get","args":{},"path":"document.features.0.p.width"},"equals":"SharedWidth"}, + {"id":"reused_definition","query":{"tool":"doc_get","args":{},"path":"document.assembly.2.feature"},"equals":1} + ] + }] +} diff --git a/benchmarks/part_agents_neutral_sol_052d.json b/benchmarks/part_agents_neutral_sol_052d.json new file mode 100644 index 0000000..22af84b --- /dev/null +++ b/benchmarks/part_agents_neutral_sol_052d.json @@ -0,0 +1,17 @@ +{ + "assistant": { + "provider": "openai", + "model": "gpt-6.1-sol", + "protocol": "responses", + "endpoint": "https://api.openai.com/v1/responses", + "api_key_env": "", + "auth_mode": "chatgpt-plan", + "reasoning_effort": "medium", + "timeout_seconds": 120 + }, + "require_part_delegation": false, + "repetitions": 2, + "deadline_seconds": 300, + "strategies": ["Single", "PartFocused"], + "artifact_directory": "out/052d-neutral-artifacts" +} diff --git a/benchmarks/part_agents_offline_052d.json b/benchmarks/part_agents_offline_052d.json new file mode 100644 index 0000000..ee01c58 --- /dev/null +++ b/benchmarks/part_agents_offline_052d.json @@ -0,0 +1,14 @@ +{ + "assistant": { + "provider": "offline", + "model": "deterministic-native-reference-v1", + "protocol": "responses", + "endpoint": "http://127.0.0.1:11434/v1/responses", + "api_key_env": "", + "reasoning_effort": "", + "timeout_seconds": 60 + }, + "repetitions": 3, + "deadline_seconds": 120, + "strategies": ["Single", "Focused", "PartFocused"] +} diff --git a/benchmarks/part_agents_sol_052d.json b/benchmarks/part_agents_sol_052d.json new file mode 100644 index 0000000..cf32f64 --- /dev/null +++ b/benchmarks/part_agents_sol_052d.json @@ -0,0 +1,16 @@ +{ + "assistant": { + "provider": "openai", + "model": "gpt-6.1-sol", + "protocol": "responses", + "endpoint": "https://api.openai.com/v1/responses", + "api_key_env": "", + "auth_mode": "chatgpt-plan", + "reasoning_effort": "medium", + "timeout_seconds": 120 + }, + "repetitions": 2, + "deadline_seconds": 300, + "strategies": ["Single", "PartFocused"], + "artifact_directory": "out/052d-live-artifacts" +} diff --git a/benchmarks/rubber_runtime_059c.cpp b/benchmarks/rubber_runtime_059c.cpp new file mode 100644 index 0000000..e3bb0c0 --- /dev/null +++ b/benchmarks/rubber_runtime_059c.cpp @@ -0,0 +1,39 @@ +// C.04/A.04 synthetic runtime comparison, with no drawing/session input. +// Matches the 059C native UI fixture: hollow sphere R30/wall3 mm, density1100, +// E3MPa, 16x8 latitude grid + two poles; 130 nodes/720 links/23 colours. +// The literal mass is the fixture's exact native B-rep mass in kg. A_eff and +// triangle lumping intentionally match the production reduced-network bridge. +// Run baseline and candidate executables alternately on the same machine. +// GPU run0 includes device/shader initialization; runs1..3 reuse both device and +// constraint cache. Compare cold and warm separately and retain all attempts. +// The digest contains scalar coordinates, velocities and forces (no Vec3 +// padding), so identical hashes establish same-adapter before/after equivalence. +// Link with ark, including rubber_patterns.cpp and the D3D11 dependencies. +#include "ark/rubber_dynamics.hpp" +#include "ark/rubber_patterns.hpp" +#include "ark/iteration_history.hpp" +#include +#include +#include +#include +using namespace ark; +using V=arkjson::Value; +std::string digest(const RubberDynamicsResult& r){std::string bytes;auto add=[&](double v){bytes.append((const char*)&v,sizeof(v));};for(const auto& f:r.frames)for(const auto& p:f){add(p.x);add(p.y);add(p.z);}for(const auto& v:r.finalVelocities){add(v.x);add(v.y);add(v.z);}for(double v:r.finalLinkForces_N)add(v);return iterationSha256(bytes);} +int main(){try{ + V recipe;arkjson::parse(R"({"surface":{"kind":"sphere","radius_mm":30},"distribution":"grid","around":16,"rows":8})",recipe);RubberPatternPlan plan(recipe); + constexpr unsigned around=16,rows=8;std::vector points,normals;std::vector triangles; + const Vec3 translation{80,0,80};for(unsigned j=0;j weights(points.size(),0);std::set> edges;auto edge=[&](unsigned x,unsigned y){if(x!=y)edges.insert(std::minmax(x,y));}; + for(size_t t=0;t nodes;for(size_t i=0;i links;for(auto e:edges){const double length=(points[e.second]-points[e.first]).len();links.push_back({e.first,e.second,length,length/(3e6*section)});} + RubberDynamicsOptions o;o.backend="cpu";o.duration=.2;o.step=1./240;o.outputFps=30;o.iterations=8;o.gravity={0,0,-9.80665};o.ground=true;o.friction=.7;o.damping=2; + auto reference=simulateRubber(nodes,links,o);std::cout<<"CPU "<::`; unqualified names only select legacy document sketches. Definition renames preserve ownership; explicitly remove its sketches before deleting a definition. Ownership is metadata, not a geometric dependency. Scoped sketches require document format50; legacy global sketches keep their prior format. JSON nesting is limited to 64; mathematical expressions to 2048 characters. These are request limits, not a bound on all possible boolean or solver runtime. Mesh buffers, reports and BVHs are cached per session revision and selected feature ID. One geometry recompute handles the whole batch. Version-27 documents retain immutable iteration deltas and shared large source strings, with persistent undo/redo. Limits are 512 nodes, 131072 replay operations and the total 4 MiB document cap; excess capacity rejects the mutation atomically. Existing documents acquire only their first observed baseline. Evaluated meshes and usage snapshots are excluded from the journal. See [persistent iterations](ITERATION_HISTORY.md). The old hand-written SIMD routines are retained as source archaeology but are disabled until ABI/numerical parity and profiling justify them. diff --git a/docs/AGENT_BENCHMARK.md b/docs/AGENT_BENCHMARK.md index f545cf8..780d0e6 100644 --- a/docs/AGENT_BENCHMARK.md +++ b/docs/AGENT_BENCHMARK.md @@ -1,5 +1,11 @@ # Benchmark nativo dos agentes — D.01 / D.02 +052D acrescenta `PartFocused`: delegação real para um documento privado, revisão +e integração pelo engenheiro. O exemplo, configuração de modelos por papel e +limites estão em [Part agents](PART_AGENTS_052D.md). Os contratos +Single/Focused/Parallel abaixo continuam disponíveis como controlos; +o antigo `team_send scope` não passa a ser isolamento por esta alteração. + `ark-benchmark` compara Single (`runAssistant`), Focused e Parallel (`AgentTeam`) com o executor real `AgentSession`. Cada tentativa começa num documento novo, com o mesmo baseline sintético, brief, modelo, esforço e critérios nativos. diff --git a/docs/AGENT_OUTCOMES_051A.md b/docs/AGENT_OUTCOMES_051A.md new file mode 100644 index 0000000..32cd545 --- /dev/null +++ b/docs/AGENT_OUTCOMES_051A.md @@ -0,0 +1,68 @@ +# Agent outcomes, 051A + +D.01/D.02 and A.02: **Verificado no escopo** for the offline harness checks below; +real provider comparisons remain **Parcial**. No paid provider was called. + +The existing `ark-benchmark` harness now records distinct `completed`, +`postconditions_passed`, `persisted` and `accepted` outcomes. Acceptance requires +completion, no terminal error/timeout, the native oracle, and successful persistence. +Every attempt, including a failed one, remains in the report and strategy denominator. + +`benchmarks/agent_outcomes_v2.json` adds three synthetic cases: a driving parameter +edit with an expression-preservation check, an assembly placement edit with exact +clearance, and recovery after a rejected two-command edit. Before the recovery run, +the host executes the invalid batch and records the actual rejection, before/after +revision and authoring SHA-256. Recovery counts only if that rejection was atomic. +The model receives the brief, acceptance criteria and rejection receipt. The reference +repair is available only to preflight and the deterministic offline transport. + +After model execution the host oracle reserves a unique directory, saves `result.ark`, hashes its actual bytes, +loads it, reconstructs authoring without the saved derived geometry in a fresh session, +and reruns the same independent oracle. This is fresh-session authoring reconstruction, +not a process-cold kernel: shared worker/process caches are not reset. Saving and +reopening are host actions; these receipts do not prove the model issued save/load. It compares authoring and checks file bytes +again after reopen. `persistence.saved` means writing succeeded; `persisted` also +requires the reopened oracle and authoring comparison. A completed response or an in-memory +valid body alone cannot satisfy this gate. `artifact_directory` in the config selects +the parent; otherwise files remain under the system temporary directory's +`ark-agent-benchmark` folder. These artifacts contain synthetic fixtures only. + +Every attempt includes the case version and SHA-256 of its normalized definition +(including oracle and reference), application identity and running executable SHA-256. +The executable fingerprint does not attest loaded native DLLs: comparisons must also +record the selected SDK/runtime evidence. Fixture hashes are sensitive to JSON field +order; use the same versioned fixture file for comparable runs. + +Run the new suite through the existing CLI: + +```powershell +ark-benchmark --suite benchmarks/agent_outcomes_v2.json --preflight +ark-benchmark --suite benchmarks/agent_outcomes_v2.json --repetitions 1 --out out/outcomes.jsonl +``` + +An optional config `tariff` object accepts `provider`, `model`, `currency` (three +uppercase letters), `as_of` (calendar date), `source`, `basis` equal to +`flat_input_output_tokens`, and nonnegative finite `input_per_million` and +`output_per_million`. These are explicit user-supplied estimates, not verified +provider charges. The flat input rate includes cached tokens; output includes +reasoning tokens. Discounted-cache, tiered and subscription billing are not modeled. +No rate is invented or downloaded. Rates must match the configured provider/model. +Offline runs, absent tariffs, missing/partial usage or a mismatch between accounted +responses and provider requests produce `cost: null`. Strategy summaries sum all +known attempt costs, including failures; cost per accepted outcome stays null if +any attempt cost is unknown or none is accepted. Provenance is retained with receipts. Priced strategy aggregates reject mixtures of +tariff definitions, currencies or model provenance. Baseline setup failures and +attempts with no accounted provider response keep unknown cost. + +Validation: the extended `agent-benchmark` test passed locally with actual native +executor calls and real .ark files: the original 30 preflights and nine strategy +runs, plus three v2 preflights and nine v2 strategy runs. Negative checks cover +completion without acceptable geometry, save failure, changed authoring on reopen, +atomic rejection/recovery, incomplete usage, mismatched tariff, and failed-attempt +cost accounting. The integrated 051A native `agent-benchmark` suite also passed +against the verified patched SDK. The built CLI passed all three v2 preflights +and accepted/persisted all nine offline attempts (three cases across +Single/Focused/Parallel). These deterministic harness checks are not a live-model +quality, speed or cost comparison. Local receipts are +`out/051a-outcomes-preflight.log` and `out/051a-outcomes.jsonl`; no paid provider +calls or deployment were used. diff --git a/docs/ASSISTANT_CONVERSATION.md b/docs/ASSISTANT_CONVERSATION.md new file mode 100644 index 0000000..ea30c79 --- /dev/null +++ b/docs/ASSISTANT_CONVERSATION.md @@ -0,0 +1,73 @@ +# Studio agent conversation + +Milestones: **A.02 / D.02**. This is a local Studio presentation change within +the current development iteration. It does not change the document format or +the agent's permission, revision, publication or completion contracts. + +The Assistant dock presents user messages and agent replies in separate native +conversation bubbles. The body and composer use 18 px Segoe UI. Paragraphs and +Unicode are retained. Each message is read-only but selectable with the mouse, +Ctrl+A and Ctrl+C. **Copy chat** copies the goal and the conversation as Unicode +text with paragraph boundaries. Copying does not submit a provider request. + +The goal remains above the scrolling messages. Its height uses native text +layout, up to three lines; in a short split view it reserves room for readable +messages. Any goal exceeding the available height has its own scrollbar. +**Expand** gives +the conversation the workspace, and **Restore** returns to the CAD split. +**Latest** returns to the newest message. New progress follows the end only when +the reader was already there; it does not displace someone reading earlier work. +Messages are retained for the open-document session rather than discarded after +200 entries. Native message controls are created only for the visible portion +of the history. This is not persistence across an application restart. + +**Agents** opens the existing Team role controls in the expanded workspace; +**Chat** returns to the conversation. Focused remains the default workflow. +**Run info** in Single exposes usage and observed activity without placing token +counters over the conversation. + +Status labels distinguish: + +- **Thinking**: an active model request; not a claim about private reasoning. +- **Working**: a host-observed tool operation. +- **Waiting for the connection**: an observed provider retry. +- **Waiting for your input**: Team explicitly reports `NeedsInput`, or a Single + final reply begins with `needs_input:` and a concrete question. The display + marker is omitted from the bubble; it grants no completion authority. +- **BOM review pending**: the Single agent repeated an unqualified final reply + without new inspection or authoring evidence. The proposed completion is held, + the current missing-field counts are shown, and the work is retained. This is + a recoverable review stop, not a provider interruption or a completed goal. +- **Stopping**, **Stopped**, **Paused** and **Interrupted**: cancellation, + pause and error states remain distinct; prior document changes are retained. +- **Reply ready**: Single has returned a reply, without asserting that the goal + or the project is complete. Team completion is labelled **Goal reported + complete** only when it has been explicitly declared. + +The UI self-test covers the status lifecycle, native selection, paragraph and +goal copying, long replies, history beyond 200 entries, bounded native controls, +scroll retention, pinned goal layout, expanded mode and Team controls. Native +captures must be inspected as well as checking the test exit code. + +057B measures response height from native character positions and font metrics, +so **Latest** reaches visible text instead of an estimated blank tail. Message +updates retain existing native controls and selection, and geometry changes +retain the reader's message anchor. Unchanged frames do not repaint the composer +or conversation header. The regression includes a long response's final line, +updates while reading/selecting, compact and wide layouts, and actual window +pixels after repeated OpenGL swaps. See [057B evidence](iterations/057B.md). + +058A explicitly refreshes native screen-width wrapping before measuring text. +RichEdit can defer resize layout while Studio is minimized; using those stale +line positions created enormous blank bubbles after background messages arrived. +The regression now minimizes Studio during new messages and subsequent updates, +restores it, compares measured and cached heights, preserves selection and checks +actual final-line pixels after OpenGL swaps. Expanded conversation also suppresses +the viewport navigation/appearance controls that overlapped its Single/Team row. +See [058A evidence](iterations/058A.md). + +Bare Resume/Continue in an existing Single conversation retains the displayed +goal and the host BOM task boundary. The agent receives an explicit instruction +to continue unfinished work; an explicit request to summarize remains separate. +Detailed BOM review notes stay in receipts instead of being appended in full to +every visible reply. See [the BOM recovery contract](BOM.md). diff --git a/docs/ASYNC_AUTHORING_051A.md b/docs/ASYNC_AUTHORING_051A.md new file mode 100644 index 0000000..727042c --- /dev/null +++ b/docs/ASYNC_AUTHORING_051A.md @@ -0,0 +1,75 @@ +# Background authoring — 051A + +The Studio authoring path prepares ordinary geometry-changing `doc_apply` +requests on a private document snapshot. This covers feature editors, parameter +HUD rebuilds and ordinary `doc_apply` requests queued through Studio's MCP and +Assistant bridge. Metadata-only edits and already prepared candidates keep their +existing paths. Other operations retain their existing execution contracts. + +The evaluator has no live-session, window or graphics context access. Its copy +has no shared activity ledger or pending saved-native-geometry custody. Original +commands and checks execute on the private candidate, with progress from the +normal evaluation observer. A successful result must supply an existing +`PreparedTransfer` within the existing 128 MiB candidate allocation limit. There +is no fallback that recomputes against a newer drawing or reports an uncached +candidate as committed. + +Studio retains synchronous editor completion semantics while pumping a live +render of the committed scene. During preparation, middle-button orbit/pan, +wheel zoom and body selection operate on that scene. Editing controls are +temporarily held, incoming external calls queue, and authored animation/direct +editing actions do not run from the rendering loop. **Cancel (Esc)** cancels +publication immediately. Closing the window cancels preparation before normal +close/save handling. This preparation state is separate from the existing busy +mode whose worker owns the live session; that older mode still renders only its +captured frame and does not enable navigation. + +The host publishes once, on the session-owning thread. It checks both captured +revision and document epoch, including a replacement drawing with identical +bytes and the same public revision. Prepared transfer adoption also checks the +existing authoring fingerprint. Queued Studio requests retain their arrival +epoch and their explicit expected revision (or an arrival revision when the +host API omitted one). They cannot silently apply against the preceding +request's newer state. + +The host-only completion helper feeds the original request through normal +`AgentSession::call` transaction, actor/motivation, journal-capacity, failure +capture and usage-preservation rules. Dispatch consumes the prepared candidate; +the journal still describes the original commands and the checks already ran on +that candidate. Publication preserves usage and activity received after capture. +Failure to append history rolls the prepared geometry back. A stale, cancelled, +invalid or over-capacity result remains a failed result. + +Cancellation uses the existing native RPC cancellation scope with its existing +request limit. Evaluation-pool tasks capture that scope when scheduled, so their +native requests inherit cancellation and the request limit. CPU work without an +interrupt point may still finish privately. Its cancelled generation cannot +publish. The persistent worker joins at shutdown, so closing or the next queued +edit can wait for that remaining private work to finish. +There are no new agent turn/token budgets, geometry tolerances or silent rebases. + +Local verification: + +- `async-authoring-051a` exercises isolation while blocked, original journal + commands/provenance, newer usage/activity, caller checks, invalid geometry, + recipe mismatch, same-revision replacement epoch, concurrent edits, immediate + cancel (including a ready result cancelled at publication), rejection with + history suppression, malformed arguments, no-op preservation of ordinary and + compacted journals/undo/redo, journal-capacity failure after successful + preparation, parameter-driven evaluated geometry, and shutdown. +- `studio-async-authoring-ui` drives actual queued window messages during a HUD + rebuild, checks orbit/zoom/selection and unchanged live authoring before + publication, captures the live scene, and checks successful geometry, a stale + external queued request, Escape, same-revision replacement and close cancellation. + +The portable worker target passed locally on the isolated build. Both Studio +async-authoring and history-compaction selftests exited successfully with fresh, +revision-guarded synthetic drawings. Inspected captures show live orbit/zoom and +selection during preparation, the progress and Cancel control, published geometry, +and the retained drawing during cancellation. These are local runtime/UI checks, +not provider latency, deployment or manufacturing qualification evidence. Native +pool cancellation has its separate evaluation-schedule test. The integrated +051A core and patched-native worker suites also passed, followed by native +Studio async-authoring and history-compaction selftests (exit 0). The final +native captures confirm navigation/selection, publication and cancellation on +that build; the initial isolated capture build used the portable backend. diff --git a/docs/ASYNC_EXACT_046B.md b/docs/ASYNC_EXACT_046B.md index cee5232..c1297ef 100644 --- a/docs/ASYNC_EXACT_046B.md +++ b/docs/ASYNC_EXACT_046B.md @@ -70,8 +70,19 @@ Both are reported in `exact_job`. Timeouts keep the "worker limit" text, so the error code stays `RESOURCE_LIMIT`. Requests outside jobs keep 30 s. **Indicator.** While a job runs, a chip above the viewport dock shows the tool, -elapsed time and observed revision, with **Cancel**. It does not capture input; -orbit, zoom and selection stay live. +elapsed time and observed revision, with **Cancel**. In short viewports it can +overlap the dock. The foreground chip owns pointer input only inside its visible +bounds: Cancel precedes its neutral background, then underlying controls. +Clicks on its background do nothing; orbit, zoom and selection remain live +elsewhere. The chip is painted after drawing sheets too, matching this input +priority. + +**056C integration regression (A.04).** With the assistant dock open at 1280x800, +the existing asynchronous UI test found the visible Cancel button behind the +viewport dock's `965` and `969` input zones. Foreground hit ordering and neutral +panel handling now match drawing order. The original fixture and its assertion +remain unchanged; integrated validation reruns `studio-async-exact-ui`, +`studio-viewport-dock-ui`, `studio-drawing-viewport-ui` and `studio-inertial-ui`. **Studio API** (`src/view/exact_jobs_046b.inl`): diff --git a/docs/BOM.md b/docs/BOM.md index d5571eb..1c589bf 100644 --- a/docs/BOM.md +++ b/docs/BOM.md @@ -1,5 +1,9 @@ # Persistent part metadata and BOM — 011E +056C adds [actionable sourcing recovery and bounded public-page reads](BOM_RESEARCH_056C.md). +BOM onboarding offers research tools directly; web results identify the actual +supplier and provide a page action. Detailed review retains every existing gate. + In 015B, the BOM workspace adds a dark layout, search, All/Needs review/Buy/Make filters, status badges and selected-part details. Sort or filter before editing: selection remains bound to the original definition ID. Locate part returns to @@ -19,8 +23,8 @@ the versioned interchange format; it does not embed B-reps or display meshes. ## Authoring -Call `agent_onboard {"topic":"bom"}` or `{"topic":"fasteners"}`. The current -discovery has 73 tools, including `bom_inspect`, `bom_export` and +Call `agent_onboard {"topic":"bom"}` or `{"topic":"fasteners"}`. Tool +discovery includes `bom_inspect`, `bom_review`, `bom_export` and `fastener_recipe`. The ordinary `assembly_info.bom` contains the same enriched items while retaining the earlier `feature`, `name` and `quantity` fields. @@ -56,6 +60,46 @@ HTTPS without credentials. The existing feature `material` field refers to a named document material. `manufacturing.route` remains the fabrication intent. Metadata-only changes preserve native geometry and are part of undo/redo. +For an incremental edit, prefer `feature.edit` with `part_patch`. For example, +`{"op":"feature.edit","id":12,"part_patch":{"description":"Motor bracket"}}` +changes only the description. Omitted fields, including supplier references, +are preserved. The merged record must satisfy the same validation as `part`; +selecting sourcing may reuse its existing URL/reference, but clearing a required +source on a selected record rejects atomically. `part_patch` requires the current +`expected_revision`, is supported by preview/commit, and cannot be combined with +`part` or used on another operation. It changes no document format. + +## Recoverable agent review — A.02 / D.02 + +A completion rejection reports current counts, bounded missing-identity rows, +unresolved field counts, document issues and the next inspection request. +Progress includes current authoring, revision and the inspected definitions. +Reading another page at the same revision is progress. This data is diagnostic, +not a completed inspection or a review attestation. Internal identity fields can +be assigned from design intent; unknown materials and commercial data remain +unresolved. Material is a feature field and fabrication intent is +`manufacturing.route`, not a key inside `part_patch`. + +Single offers the BOM inspection/review tools after a completion rejection. +An explicit leading `needs_input:` request reaches the user without approving +project completion. Repeating a final answer at the same unresolved review state +ends with **BOM review pending**, retaining the work and withholding the proposed +completion text. This is distinct from a provider interruption. Team receives +the same structured recovery with its rejected `team_finish_goal` call. + +For explicitly limited work, `bom_review{completion:"task",...}` may omit `ids`: +the host selects all affected definitions (up to 64). An empty affected set can +review display-only or read-only work after a current inspection. Explicit IDs +still must cover every affected definition. Removed definitions, unavailable +baseline or a larger set require project review. Concept/detailed requirements +are unchanged. No task receipt approves the global BOM. + +A bare Resume/Continue request in an existing Single conversation preserves its +goal and BOM baseline. It continues the unfinished work rather than starting a +summary-only task. An explicitly requested summary remains a separate request. +The visible completion qualification is short; detailed pending/fastening notes +remain in the `bom_review` receipt. Receipts are session-local. + `procurement` is `make`, `buy` or `unspecified`. `sourcing_status` is `unresolved`, `candidate` or `selected`; selection requires a source URL and an explicit manufacturer/supplier reference. These are caller declarations, not diff --git a/docs/BOM_RESEARCH_056C.md b/docs/BOM_RESEARCH_056C.md new file mode 100644 index 0000000..09dcdc3 --- /dev/null +++ b/docs/BOM_RESEARCH_056C.md @@ -0,0 +1,111 @@ +# 056C — BOM recovery and public component research + +Milestones **A.02 / D.02 / E.01**: **Verificado no escopo** for the local +regressions and the public Windows HTTPS observations below. Overall project, +supplier, manufacturing and commercial integration qualification remain +**Parcial**. + +## Corrected failure and agent workflow + +General web search previously attached `vendor:"web"` to supplier candidates. +Passing that observed vendor into `library_source_page` rejected the supplier +URL because the `web` policy describes the search engine's domain. Search now +returns the actual supplier policy ID in `vendor`, preserves `discovery_source`, +and supplies a concrete `next_action` with the observed URL, actual vendor and +the requested local policy root. The page call still checks the current policy; +search does not authorize a disabled supplier or cross-host redirect. + +`agent_onboard{topic:"bom"}` now offers local library lookup and public sourcing +tools directly. Single-assistant completion recovery also offers these tools +from its permitted catalogue. Loading BOM does not execute a network request. + +BOM recovery reports up to 32 unresolved definitions with their actual feature +IDs and required fields. For a bought item lacking source selection or supplier +identity, `research_action` points to its declared public source URL, or suggests +a search from declared manufacturer/reference fields. A description is used only +when no commercial identity was declared. These actions are suggestions, never +evidence of a matching component. Detailed review failures carry the same +structured recovery instead of only a generic rejection. + +1. Inspect the counted definitions and any local component record. +2. Follow a source search candidate's `next_action`, or read an already observed + product URL with `library_source_page`. +3. Match the actual manufacturer/reference and the requested specifications. + Search titles and lexical matches remain unverified candidates. +4. Use revision-checked `feature.edit part_patch` to preserve existing identity + while recording supported sourcing declarations. Keep missing claims unresolved. +5. Reinspect the current revision before `bom_review`. An old inspection or review + is not rebased after a metadata edit. + +This does not change global, detailed or limited-task completion authority. +Candidate sourcing still fails detailed completion. Unresolved representation, +material, manufacturing intent, fastening and project issues retain their +existing gates. `part` metadata remains caller-declared; a complete metadata +record does not prove a supplier match, engineering suitability or manufacture. + +## Reading bounded product evidence + +`library_source_page` retains the 2 MiB network resource limit, explicit redirect +authorization, untrusted-content label and full-byte SHA256/UTC receipt. The +first response still returns at most 32,000 text bytes. New read arguments are: + +| Argument | Meaning | +| --- | --- | +| `query` | A literal reference/text query, 1–256 bytes; ASCII case-insensitive. Returns a window around its first match and explicit `query_found`. | +| `text_offset` | A byte offset into extracted text, up to 2 MiB; mutually exclusive with `query`. | +| `max_text_bytes` | Response window from 256 to 32,000 bytes. UTF-8 characters are not split. | +| `expected_evidence_sha256` | An observed exact page-byte hash; rejects if a later read fetched different bytes. | + +`text_window` reports the total extracted byte count, actual offset, returned +bytes and `next_text_offset`. A missing query returns no matching text and +`query_found:false`; it never invents evidence. Read continuation with the prior +hash to avoid combining evidence from different pages. Dynamic HTML may change +between requests, even when its visible text is unchanged; the exact hash check +deliberately rejects that case. A targeted query obtains its evidence in one +request. There is no persistent supplier-page cache. + +Public access still has no JavaScript execution, browser cookies, account +authentication or PDF text extraction. Provider challenges and unavailable data +remain explicit failures. No API adapter, price, stock, material certification, +licensed CAD download or automatic product matching is newly claimed. + +## Observed verification + +Local Release build with LLVM-MinGW, without the native OCCT worker: + +- `component-sources`: passes the real search-to-page provider handoff using an + injected HTTP transport, known and generic supplier IDs, policy-root retention, + long-page reading, literal lookup, no-match results, changed evidence rejection, + invalid bounds/hash rejection before network access and UTF-8 window boundaries. + Existing URL, HTTP, redirect and STEP-byte rejection checks also pass. +- `bom-completion`: passes per-definition research recovery, detailed candidate + rejection, metadata preservation, stale review rejection and required current + inspection. Existing Single/Team completion and limited-task regressions pass. +- `ark-assistant-tests`: **553 checks passed**, including BOM source-tool exposure + and completion-recovery tool availability; existing assistant behavior passes. +- `component-vendors-035b` and `component-library-tools`: pass their local + policy and core tool-contract regressions. + +Two opt-in native Windows HTTPS observations on **2026-10-23**, independent of +offline tests, both passed. `ark-component-sources-tests --live-web` searched +`Raspberry Pi RP2040 site:raspberrypi.com`, followed the returned page action and +read the [manufacturer's RP2040 page](https://www.raspberrypi.com/products/rp2040/) +with HTTP 200, `vendor:direct_https`, the requested reference present, and no +credentials sent. `--live-page` read that already-known page directly. The +observed resource was 373,191 bytes with 3,043 extracted text bytes; no buying or +engineering qualification was performed. + +| Observation UTC | Exact resource SHA256 | +| --- | --- | +| 09:40:01, direct page | `18df3f81f482a5a0a54e4a6acea581136497f11fdc7c2b64f5d6687505962c64` | +| 09:40:02, search then page | `fc91f3c564eeba91665ab0d4d4a9d0a3daad8fde0b4c68d75af5c930f554ca46` | + +These observations establish this public connector path on this machine and +date. They do not establish every supplier's availability, deployment, hosted +CI, live-model task completion or a reduction in agent cost. Native BOM/library +integration was not run in that core build. The subsequent integrated 056C native +run passed `bom-contract`, `bom-completion`, `component-sources`, +`component-vendors-035b`, `component-library`, `component-library-tools`, +`assistant-connector` and `agent-team`; see [056C](iterations/056C.md) for the +complete result and any unrelated failures. No user drawing was used and no +`.ark` document format changed. diff --git a/docs/DISCIPLINES_SCHEMATICS_054B.md b/docs/DISCIPLINES_SCHEMATICS_054B.md new file mode 100644 index 0000000..b5ab0bd --- /dev/null +++ b/docs/DISCIPLINES_SCHEMATICS_054B.md @@ -0,0 +1,122 @@ +# Families, electrical schematics and flexible motion — 054B + +Scope: **A.02, B.04, B.05, C.04, D.02**. These broader milestones remain +**Parcial**. This iteration adds local authoring and display contracts, with +verification recorded in [054B](iterations/054B.md). + +## Families and Eye mode + +Definitions and assembly occurrences/groups accept `classification` metadata: +`families` and free-form `tags`. Published families are `electrical`, +`electronics`, `mechanical`, `bodywork`, `sheet_metal`, and `plastics`. +Multiple families are permitted. The nearest occurrence/group with nonempty +families overrides its ancestors; otherwise the definition supplies them. +Tags remain attached to their declared object. + +In Studio, **Inspect → Families** edits the selected definition, occurrence or +group. **Inspect → Eye mode** shows all, unclassified, or the union of selected +families. Filtering affects display and picking; it changes no geometry, mate, +BOM quantity or document revision. A newly opened document starts with all +families visible. Existing visibility and loading rules still apply. + +Agents use `doc_apply` with the observed `expected_revision`: + +```json +{"commands":[{"op":"classification.set","feature":12, + "families":["bodywork","sheet_metal"],"tags":["housing","removable"]}], + "expected_revision":7} +``` + +Use `node` instead of `feature` for an occurrence or group. Omitted fields keep +their previous values; empty arrays clear them. `classification_info{feature}` +or `{node}` inspects one object; no selector lists declarations. There are at +most six families and sixteen unique tags of at most 64 bytes each. These are +design classifications, not electrical ratings, material specifications or +manufacturing evidence. Reusable `.arkprt`/`.arktop` recipes retain declarations. + +## Editable electrical sheets + +**Inspect → Schematic** opens the native Schematic Designer. New creates a sheet; +Symbol adds a block, connector, resistor, switch, ground or power symbol. Symbol +properties edit the reference, position, rotation, procurement metadata and +optional CAD source. Pins edits stable pin IDs and their local coordinates. +Wire connects two explicitly selected pins and asks for a net name. Properties +edits the selected wire's net and bend points. Dragging a symbol previews locally +and publishes one revision on release. Undo/redo uses the document history. + +The side panel is the sheet's BOM. Each included symbol contributes one component +reference, with explicit metadata taking priority over linked CAD part metadata. +**Include in BOM: No** excludes ground/net annotations without deleting their +connections. A symbol may bind `feature:ID` or `node:ID` with an explicit pattern +copy. Selecting it selects that source in 3D. Removing a referenced CAD source +rejects until its schematic binding is updated or removed. + +The source contract is `schematic.set{sheet}` or `schematic.remove{name}` through +revision-checked `doc_apply`/`doc_preview`. A sheet replacement is atomic: + +```json +{"name":"Control","width":297,"height":210, + "symbols":[ + {"id":"supply","ref":"X1","kind":"connector","x":40,"y":50, + "part_number":"DECLARED-EXAMPLE","pins":[{"id":"1","x":10,"y":0}]}, + {"id":"load","ref":"R1","kind":"resistor","x":100,"y":50, + "pins":[{"id":"1","x":-10,"y":0},{"id":"2","x":10,"y":0}]}], + "wires":[{"id":"w1","net":"SUPPLY", + "from":{"symbol":"supply","pin":"1"}, + "to":{"symbol":"load","pin":"1"},"points":[]}]} +``` + +Sheet fields: `name`, optional `title`, `width` and `height`, `symbols`, `wires`. +Symbol fields: `id`, `ref`, `kind`, `x`, `y`, `pins`, optional `label`, +`rotation` (0/90/180/270), `width`, `height`, `feature` or `node`, `copy`, +`part_number`, `manufacturer`, `description`, `bom` (default true). +Pin fields: `id`, optional `label`, `x`, `y`. Wire fields: `id`, `net`, +`from`/`to` (`symbol`, `pin`), optional `points` as sheet-mm coordinate pairs. + +`schematic_inspect{name}` returns the editable sheet, nets, unconnected pins and +its BOM; no name lists sheets. Crossings do not create connections. Equal net +names join their declared pin endpoints. One pin cannot have two different net +names. Component references and symbol IDs are unique within a sheet; one CAD +occurrence copy cannot represent two components on that sheet. Source limits: +32 sheets, 512 symbols and 2048 wires per sheet, 64 pins per symbol, 64 bend +points per wire. Sheet dimensions are 50–2000 mm; anchors and pins stay inside. + +The same drawing primitives feed the editor and `schematic_export`: +`{name,format:"dxf"|"svg"|"bom_csv",path,expected_revision}`. Exports publish to +a new path; existing files and stale-revision exports reject. DXF contains +millimetre LINE/TEXT entities on SYMBOLS/WIRES/PINS/LABELS layers. The `.ark` +retains electrical connectivity; DXF is graphical exchange, not a netlist. +The editor does not simulate circuits, select conductor sizes, infer voltage +ratings, or qualify compliance with an electrical drafting/safety standard. + +Classifications and sheets require conditional authoring format **52**. The +binary container is unchanged. Ordinary documents without these fields keep +their existing semantic version. Schematics are project-level context and are +excluded from private part checkout and reusable component source closures. + +## Cables in baked motion + +A `cable_route` with start/end/waypoint or obstacle bindings to moving occurrence +IDs is prepared at the recorded assembly poses before Studio playback. For each +distinct pose, the existing native cable producer constructs and validates the +sweep. Invalid routes report the cable and frame; they are never replaced by a +frozen cable. Preparation runs in the background, displays progress and supports +Stop/cancellation. Repeated requests share geometry; the derived display cache +is compressed losslessly when the platform codec is available. + +Only display meshes change during playback. Stop restores the original mesh and +picking data. Document recipes, evaluated B-reps, history and revisions remain +unchanged. The cache is private to this process and invalidates on source/motion +replacement. Bound-cable geometry participates in the motion source digest; +families, schematic sheets and appearance do not. A stale motion with flexible +cables requires an explicit **Bake** before playback. Legacy rigid-only stale +playback retains its existing inspection behavior and STALE badge. + +Capacity is 32 flexible cables, 32768 cable-frame entries and 512 MiB of retained +display data. Capacity errors ask for fewer frames; no geometry is discarded. +Cold preparation cost scales with distinct poses. Native validity at sampled +poses does not prove constant cable length, strain, fatigue, dynamics, supplier +qualification or continuous clearance between frames. Rigid motion clearance +rejects any requested scope containing a deforming cable; explicit rigid-only +pairs remain queryable. Animated image/export consumers outside Studio's baked +playback have not acquired this display cache contract. diff --git a/docs/DOCUMENT_CONTAINER.md b/docs/DOCUMENT_CONTAINER.md index c118364..e0d5f6c 100644 --- a/docs/DOCUMENT_CONTAINER.md +++ b/docs/DOCUMENT_CONTAINER.md @@ -12,10 +12,13 @@ This physical version is independent of the authored document version, including the version-27 iteration journal. The existing C++ document parser, authoring rules, journal checks and exact geometry authority remain the semantic contract. Container version 2 (`user_version` 2) adds an optional `ark_derived` table of -saved native geometry, with its own 128 MiB capacity and a 256 MiB physical -file limit; see [formats](FORMATS.md). Since 049A it also carries cached +saved native geometry, with a 256 MiB decoded capacity, 128 MiB stored capacity +and a 256 MiB physical file limit; see [formats](FORMATS.md). Since 049A it also carries cached baked-motion frames, verified against their receipts on open -([derived bakes](DERIVED_BAKES_049A.md)); the table schema is unchanged. The 64 MiB physical cap below applies to +([derived bakes](DERIVED_BAKES_049A.md)). The 056C integration stores these entries +as one checksummed Zstandard pack, split into ordered `pack1..` +rows. Legacy per-entry rows remain readable; the table schema and physical +version are unchanged. The 64 MiB physical cap below applies to version 1; the authoring limits apply to both versions. ## Storage and incremental writes @@ -57,6 +60,15 @@ the next load permits SQLite's recovery before reading the validated snapshot. This recovery requires write access to the file/directory when a hot journal exists. An ordinary clean container remains readable with read-only access. +When an incremental save frees at least 1 MiB and a quarter of the file, ARK +reclaims pages with SQLite's transactional `VACUUM` on the same connection. +This keeps SQLite's locks and rollback protocol instead of replacing a snapshot +after releasing the source connection. Existing idle connections continue to +observe the current file. A failure leaves the preceding committed save intact +and reports `compaction_skipped`; it does not undo that save or claim compaction. +This is storage maintenance, not a document merge or permission to overwrite +another user's authored state. + ## Limits and rejection rules The existing **4 MiB logical document/journal cap is unchanged**. The physical diff --git a/docs/FACE_CYCLE_059C.md b/docs/FACE_CYCLE_059C.md new file mode 100644 index 0000000..8b6ea39 --- /dev/null +++ b/docs/FACE_CYCLE_059C.md @@ -0,0 +1,49 @@ +# 059C — exact face traversal in the viewport + +B.01 / A.04 / A.02: implemented for local native verification. This note does not +claim a distributed release or manufacturing qualification. + +Click a body in Body selection mode, then press Tab to select its first eligible +exact face. Further Tab presses cycle forward; Shift+Tab cycles backward and, +before the first forward step, starts at the last face. The cycle wraps. The +selected body occurrence and Body mode remain active, so clicking another body +starts a new cycle. The status line identifies the selected face and its position. + +Traversal uses the producer's canonical face order and preferred bound semantic +reference, including current-B-rep generated references where no named reference +exists. Repeated mesh spans and aliases do not create extra faces. The selected +reference retains the feature, assembly node and pattern copy; the cycle retains +the producer's B-rep SHA-256 and immutable native payload identity. Display mesh +triangles only locate and highlight these references, never define CAD topology. + +Revision, document epoch, display generation, selection generation, occurrence +identity, native payload and placement guards prevent silent rebinding. Hidden +occurrences, absent exact references, sampled meshes, flat/stock/deformed previews, +mechanical or baked playback, inertial playback and exploded display are rejected +explicitly. Suspension and segmented source/notched-tube previews are outside this +first traversal scope. Re-click the body in its authored static / Formed view to +restart after a rejection. Existing sketch, dimension and direct-edit Tab shortcuts +take precedence; native text controls retain keyboard focus. Explorer-only +selection does not arm a cycle until the body is clicked in the viewport. + +No geometry, placement, document selection transaction or revision is written. +The canonical list is built on the first Tab after a body click, not every frame. +Subsequent steps use the cached list and existing selection render buffers; they +do not recompute B-rep geometry, serialize the document, or invoke a native worker. + +## Verification contract + +`studio-selection-picking-ui` now sends native mouse and keyboard messages through +the production window procedure and verifies: + +- six unique exact box faces, deterministic order, wrapping and reverse traversal; +- a third patterned copy and a separately placed occurrence of the same definition; +- the selected face fill and unchanged authored document/revision; +- native Edit focus, including a forwarded Tab message; +- rejection after a real exact source edit, hiding, sampled-mesh selection and an + explicit unsupported stock-display state; +- captures `.tab-pattern-face.png` and `.tab-exact-face-final.png`. + +The stock-display guard probe sets the display flag in the isolated fixture; it is +not evidence of a complete stock authoring workflow. Native compilation, test +execution and screenshot inspection are pending the integrated 059C build. diff --git a/docs/FORMATS.md b/docs/FORMATS.md index dade2c5..76572b3 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -1,4 +1,14 @@ -# Current source semantics — format 43 +# Current source semantics — conditional format 51 + +053B selects source51 only when a project retains `parametric_components`: +embedded immutable authored definitions, namespace/identity maps, configured +public parameters and fingerprints for explicit revision replacement. `.arkprt` +and `.arktop` use the owned binary container with an +`ark.parametric-component.v1` envelope. The physical container version and +`.arkops` command replay do not change. See +[parametric components](PARAMETRIC_COMPONENTS_053B.md) for the contract and limits. + +## Earlier source semantics 031B conditionally selects source43 for the retained solid recipes, advanced fillet/chamfer/split semantics, constrained fill/blend, surface extend/untrim/ @@ -221,12 +231,35 @@ the timing of an already validated local cache hit. Authored content retains its **4 MiB logical limit** and **16 MiB typed-value and authored payload limits**. Optional derived data has a separate **64 MiB per-entry -limit**, **128 MiB total limit** and at most **8192 entries**; the physical file +limit**, **256 MiB decoded total**, **128 MiB stored total** and at most **8192 entries**; the physical file limit is **256 MiB**. Derived bytes do not enter the authoring hash or iteration history. A malformed optional payload discards the derived section with an explicit diagnostic; authoring checksum, schema and structural database failures remain hard load failures. Missing geometry can be rebuilt from valid authoring. +The 056C integration stores the optional section as one Zstandard 1.5.7 frame +over entries in document order. Rows `pack1..` contain ordered +chunks of at most 16 MiB with individual SHA-256 hashes. The manifest covers +entry keys, lengths and hashes and is verified again after decoding. Canonical +base64 strings of at least 1024 characters travel as decoded bytes, permitting +common geometry to compress across entries. Decoding reconstructs every entry +byte exactly; B-rep identities and references are unchanged. + +The frame must include a checksum and bounded content size, use a window no +larger than 128 MiB, and contain exactly one complete frame. Missing chunks, +mixed legacy/pack rows and inconsistent manifests discard only the optional +section. Legacy per-entry rows still load and migrate when saved. Readers +without pack support reject its derived keys, load the authored document and +recompute its geometry. Neither the semantic document version nor container +version increases for this cache encoding. + +An intact pack with an unchanged manifest is retained without recompression. +If the stored limit is exceeded, a bounded document-order prefix is retained +and the omitted tail is reported; authoring is saved in full. This prefix need +not be the maximal possible prefix. After an incremental save frees at least +1 MiB and a quarter of the file, transactional SQLite `VACUUM` reclaims pages. +A compaction failure retains the committed save and is reported explicitly. + Since 049A the same section also holds the cached frames of current baked-motion receipts (`ARK-MOTION-FRAMES1` entries keyed by motion name and receipt digests). They use the capacity left after saved geometry; on open, an entry is accepted @@ -241,6 +274,14 @@ receipt reports `saved_geometry` (`status` `saved` or `partial`, `capacity_bytes`), and Studio states a partial save in its status bar. A failed save now returns its reason instead of only "Could not save document". +`saved_geometry` also reports `encoding:zstd_pack`, `stored_bytes` for the +whole geometry/motion pack, and `stored_capacity_bytes`. The `container` +receipt reports `physical_bytes`, `compacted`, optional +`bytes_before_compaction`, and `compaction_skipped` on maintenance failure. +Stored-capacity omissions are included in the existing geometry/motion +omission counters. The load receipt adds `container_encoding`, `stored_bytes` +and `decoded_bytes` to the derived geometry status. + New authoring-only binary saves remain version 1. Adding saved geometry upgrades to version 2. Saving an existing version-2 file without derived entries removes stale entries and keeps version 2. Physical format downgrade is unsupported; diff --git a/docs/HISTORY_COMPACTION_051A.md b/docs/HISTORY_COMPACTION_051A.md new file mode 100644 index 0000000..222afb8 --- /dev/null +++ b/docs/HISTORY_COMPACTION_051A.md @@ -0,0 +1,91 @@ +# Recoverable history compaction — 051A + +Milestone **A.02**: **Verificado no escopo** for the synthetic persistence and +Studio checks recorded in [051A](iterations/051A.md). The broader recovery +milestone remains partial. + +`history_compact` is an explicit operation for a long-running drawing. ARK still +rejects an edit beyond 512 retained nodes or the 4 MiB metadata limit. It never +prunes history automatically. The tool requires an observed `expected_revision`, +`confirm:true`, `keep_recent` (integer 0–256), and a new `archive_path` ending in +`.ark`. Optional actor and motivation are caller-declared provenance. + +ARK writes the **complete current document**, including unsaved authoring, all +history branches, usage and activity, to private staging beside the archive. The +normal document writer preserves retained native geometry and optional derived +sections. ARK reopens the staging archive and compares its complete logical +document with the original. It validates and reopens the prospective compacted +document before publishing the archive with a no-replacement operation. Only then +does it replace the in-memory document and advance revision. Stale revision, +invalid retention, occupied destination, save/reopen failure or retained-capacity +failure leaves the current document unchanged. An existing archive is never replaced. + +Retention follows the current head's **ancestor path**, keeping at most +`keep_recent` nodes plus the state preceding that range as its baseline. Geometry, +authoring and current receipts are unchanged. Node ids and before-state hashes are +recomputed for the retained chain; node metadata also identifies its original id, +parent and previous active head. Other branch heads and older states remain in +the archive. Optional `retain_ids` explicitly preserves other selected iteration +states as separate nodes based on the new baseline, without changing current +authoring. Ancestors plus selected nodes may total at most 256; duplicate selected +ids are kept only once. The receipt maps every selected original id to its new id. + +Undo follows previous active states, which can cross branches. Compaction retains +only the contiguous newest suffix of the undo stack whose targets are available +in the retained range. It stops at the first missing target; it never jumps over +that state. Consequently, undo may be empty immediately after restoring a branch. +Redo is explicitly cleared. Undo and redo generated after compaction work normally. +`keep_recent:0` makes the current authoring the baseline and clears both stacks. + +`history_info.compaction` and the tool receipt report retained node/undo counts, +cleared redo count, other branch heads archived, original-to-current retained ids, +and archive path, binary file SHA-256, logical document SHA-256 and verified size. +The receipt is fingerprinted for corruption detection, not authenticated identity. +Only the latest receipt is kept in the active journal; each complete archive +contains the previous receipt, forming a recoverable archive chain without an +ever-growing receipt list. Archives must be kept with the project. Their recorded +paths are local references and are not fetched automatically on document load. + +Compacted documents require document format **50**, so older readers reject them. +The existing journal delta encoding remains schema 1 or 2. A paired compaction +marker and validated receipt are mandatory; unsupported versions, missing receipts +and altered receipt fingerprints fail closed. This version change is for the new +persistence contract, not the application release label. + +Save the result using `doc_save`. Restore the complete archive using `doc_load` +or Studio **File → Open**. An archive at its old 512-node bound can be inspected +and saved immediately; compact a copy explicitly before recording further edits +or undo operations. To recover an arbitrary old branch state from a full archive: +load the archive, inspect `history_info`, compact with `keep_recent:0` and +`retain_ids:[selected_id]` to a new archive path, then use `iteration_restore` with +the mapped id from `compaction.retained_ids`. The selection is explicit and the +current design remains unchanged until that restore. Studio +**Iterations → Archive and compact…** shows current +capacity, asks for archive and retention, explains bounded undo/cleared redo, +confirms the operation and saves the result. The history details show the exact +archive path for recovery. If the subsequent save fails, Studio reports the +in-memory result and the archive location; the verified archive remains intact. + +Verification targets: + +- `history-compaction-051a`: synthetic project with 601 successful authoring edits, + compaction at 512 nodes, continued edits, repeat compaction, binary save/reopen, + all retained undo targets, redo after undo, archive restore through `doc_load`, + branches, selected off-path intermediate state recovery from a full 512-node + archive, duplicate/unknown selections, zero retention, + stale/no-confirm/archive failure/no-overwrite and + corrupted/missing receipt rejection. +- `iteration-history`: existing journal integrity, capacity, undo/redo, ownership + of usage receipts and atomic rejection contracts. +- `studio-history-compaction-ui`: synthetic Studio control exercise with decline, + confirmation, saved archive and compacted reopen, and before/after captures. + +The integrated core and patched-native suites passed `history-compaction-051a`, +`iteration-history` and `scoped-sketches-history-051a`. The latter preserves two +same-named definition-owned sketches, their canonical consumers and a legacy +global sketch through compaction, selected branch restore and full archive load. +Portable and native Studio compaction selftests exited 0; captures were inspected. + +These are local persistence/UI checks. They do not qualify manufacturing geometry, +external deployment, archive storage availability or protection against external +deletion. Native geometry remains governed by its existing producer contracts. diff --git a/docs/INERTIAL_SIMULATION_056C.md b/docs/INERTIAL_SIMULATION_056C.md new file mode 100644 index 0000000..ff3b683 --- /dev/null +++ b/docs/INERTIAL_SIMULATION_056C.md @@ -0,0 +1,145 @@ +# 056C inertial dynamics + +Milestone **C.04**, **Verificado no escopo** locally; the broader milestone remains +**Parcial**. This is a +derived rigid-body study in the ARK design workspace. The study does not replace +the B-rep, update assembly placements, qualify manufacture or claim superiority +over another simulation product. + +## Inputs and authority + +`physics_inspect` retains its static physics contract. Its explicit `simulation` +argument runs a separate time-dependent study. A run requires the current +`expected_revision`; static fields such as top-level `id`, `gravity` or `loads` +cannot be mixed with a simulation and silently ignored. Query +`simulation:{action:"capabilities"}` first. The `physics` onboarding guide and +`agent_onboard{topic:"commands",query:"simulation"}` expose the actual schema. + +```json +{ + "expected_revision": 12, + "simulation": { + "backend": "gpu", + "duration_s": 1, + "step_s": 0.004166666666666667, + "output_fps": 30, + "solver_iterations": 16, + "gravity_m_s2": [0, 0, -9.80665], + "ground_z_mm": 0, + "restitution": 0.1, + "friction": 0.5, + "bodies": [{"node": 123, "copy": 0, "force_N": [0, 0, 0]}] + } +} +``` + +IDs in that example are placeholders for observed occurrence IDs and revisions. +Select an occurrence using `node` and `copy`, or a uniquely placed definition +using `id`. Omitting `bodies` selects visible assembly occurrences, or active +unconsumed definitions without an assembly. Missing density or native mass +properties rejects the study. Native mass, centre of mass and centroidal inertia +come from the existing exact CAD producer and declared density; heterogeneous +PCBs do not become fictitious uniform solids. + +Body overrides accept `fixed`, `velocity_m_s`, `angular_velocity_rad_s`, +`force_N` and `torque_Nm`. Forces and couples are constant in world axes and apply +at the centre of mass. A fixed occurrence or fixed ancestor stays grounded unless +the study explicitly overrides it. The solver uses metres, kg, seconds, N and +Nm; CAD positions and ground height remain mm. Fixed bodies cannot have velocity. + +## Solver and meshes + +The Windows GPU backend uses a hardware Direct3D 11 compute device, shader model +5. Integration, convex separation-axis tests, contact impulses, friction and +joint iterations execute on the GPU. The CPU prepares exact mass properties, +validates meshes, schedules work and reads output frames. This is not GPU B-rep +evaluation. GPU unavailability or failure is explicit; `backend:"cpu"` selects +the portable float64 reference solver, with no silent fallback. + +Translation integrates the declared constant external force; rotation uses a +midpoint gyroscopic step and normalized quaternions. Contacts use discrete convex +SAT with face axes and cross-edge axes. Each GPU pair has one canonical normal +and opposite impulses. The contact point averages distinct clipped intersection +vertices, with coincident endpoints counted once (1 micrometre comparison). +This avoids weighting shared vertices by edge multiplicity. Failure +to find an intersection witness rejects the result. The response uses a single +contact point, restitution, Coulomb friction and relaxed Jacobi iterations. +It is not a multi-point persistent contact manifold or continuous collision +detection. Resting stacks, high-speed contact and complex friction require +additional convergence and validation. + +Collision meshes must be finite, closed, consistently outward and convex. Their +positions are the current derived display mesh; exact mass remains separately +authoritative. Concave solids are rejected, without replacing them with a convex +hull or discarding geometry. Exact duplicate vertices and coplanar triangle +diagonals are removed from the collision representation. One definition supplies +all its selected occurrences. GPU mesh buffers are cached by exact packed bytes; +an unchanged subsequent study uploads no mesh bytes. The separate viewport +cache compresses normals, and persistent derived storage uses lossless zstd; +see [viewport](VIEWPORT_056C.md) and [storage](PROJECT_SCALE_COMMANDS_056C.md). + +Unlimited revolute mates between leaf occurrences in the same carrier scope +are supported. Joint anchors/axes come from the current CAD mate solve. Limited, +prismatic, rigid/coupled, cross-group carrier joints and patterned bodies reject until +their dynamic contracts are implemented. `assembly_joints:false` explicitly +requests detached bodies; it is never inferred after a failed mate. This scope +does not include deformable parts, structural FEA, stress, thermal analysis, +fatigue, actuator control or external solver qualification. + +## Resource, revision and result contracts + +The initial scope supports 128 bodies, 128 joints, 4,096 unique vertices per +convex shape, 131,072 vertices per study, 60 seconds, 14,400 actual frame-aligned +steps, 120 output frames/s and 65,536 stored body states. Requested JSON frame +output is bounded to 32,768 body states. Total worst-case collision work is +validated before dispatch, in addition to per-pair complexity. Overflow rejects +with a concrete cause. These are solver resource contracts, not agent budgets. + +The host cancellation policy is checked during CPU/GPU stepping and while +waiting for the shared GPU device. GPU state is float32, including contacts; +the reference path is float64. Invalid inertia, non-unit quaternions, nonfinite +geometry/state and unsupported numeric ranges reject. The native worker's +existing exact geometry cancellation and revision guards remain in force. + +Results carry the observed revision, source hash, explicit input study, +backend/device, transfer-inclusive elapsed time, GPU mesh uploads/cache hit, +initial/final state and energy, and maximum sampled joint-anchor drift. Optional +frames contain column-major display transforms with occurrence IDs. They are +not authored assembly changes. Refining the time step and comparing analytic +cases is required for new use cases; `qualified:false` remains explicit. + +## Verification record + +Final integrated commands/results are recorded in [056C](iterations/056C.md). +Development failures are retained: the first GPU shader compilation rejected +the HLSL-reserved word `point`; it was renamed. Independent review identified +coincident-pair momentum asymmetry, invalid peripheral support contact points, +partial GPU initialization, frame-aligned resource accounting and unsupported +group carriers. Corrections have dedicated regressions or explicit rejection. +The peripheral-support regression initially still found edge-multiplicity bias +in the clipped witness; deduplicating endpoints corrected it without relaxing +the angular-velocity assertion. Worst-case GPU work includes that deduplication. +Partial selection of a carrier sibling/nested descendant and a pattern copy +without its seed also reject; selecting fewer endpoints cannot hide constraints. + +The integrated native test passes 60 assertions across CPU reference +and the NVIDIA GeForce RTX 4070 Ti: analytic free fall, constant force, torque, +torque-free asymmetric inertia, fixed bodies, restitution/momentum, coincident +contacts, peripheral support, ground/friction, hinge drift, repeat-run mesh cache, +exact native mass, revision/authoring preservation and explicit invalid-input +rejections. The 0.7 s single-body ground fixture took 3.082 ms on CPU and 12.197 ms +on GPU in one local run (168 steps, 3,024 dispatches). This small case shows GPU +overhead, not a speedup. It does not qualify large assemblies or general contact +accuracy; no superiority or broader performance claim follows from these tests. + +Fixed bodies retain their exact prescribed CAD pose in returned frames; they +are not needlessly converted back from the GPU's float32 working coordinates. +A non-float32-representable pose regression checks exact preservation. +The [Studio study](INERTIAL_UI_056C.md) also ran both real solvers through the +private background scheduler at 1440x900 and 1180x800, with playback/reset and +unchanged authoring/revision checks. These are synthetic native CAD fixtures. + +Implementation references: [Microsoft compute shaders](https://learn.microsoft.com/en-us/windows/win32/direct3d11/direct3d-11-advanced-stages-compute-create) +and [Baraff/Witkin rigid-body course](https://www.cs.cmu.edu/~baraff/sigcourse/). +They describe the API and mechanics background; they are not evidence that this +implementation has been independently qualified. diff --git a/docs/INERTIAL_UI_056C.md b/docs/INERTIAL_UI_056C.md new file mode 100644 index 0000000..b4c6e49 --- /dev/null +++ b/docs/INERTIAL_UI_056C.md @@ -0,0 +1,92 @@ +# 056C Inertial Simulation Studio + +Milestones: **C.04 — Parcial**, **A.04 — Verificado no escopo** for the local +Studio transport/control checks described below. The integrated GPU runtime +also passed the actual engine path below; physics accuracy is separately +bounded by the [engine verification record](INERTIAL_SIMULATION_056C.md). +The synthetic UI transport fixture is explicitly not physics evidence. + +## Delivered controls + +`Inspect > Simulation` and the `Simulation` command category open a docked +study. Study selects all visible or selected occurrences, explicit GPU or CPU +reference, duration, integration step, output rate and solver iterations. +Environment sets world XYZ gravity, optional ground Z, contact coefficients, +body contacts and preservation of supported CAD mates. Choosing detached bodies +is explicit. Body loads select a named feature/node/copy occurrence and set CAD +fixing, dynamic/fixed override, constant force/torque, and initial linear/angular +velocity. SI units are shown; ground and display positions use millimetres. + +Run submits `physics_inspect` to the existing background exact-read scheduler. +The scheduler captures an immutable private session on the UI thread; calculation +and cooperative cancellation run off that thread. Run is unavailable when this +service is disabled, with an explicit error. It never falls back to a blocking +UI call or silently changes the solver. One study job is retained until its +completion/cancellation; editing study inputs cancels that job before another +can start. Closing Studio retains the scheduler's existing shutdown/join path. + +Play/pause, timeline drag, previous/next frame, playback speed and Reset pose +operate on display matrices only. Space toggles play, arrows step, Home/End +seek and Esc restores authored CAD. Fit remains available while displaying the +result. Other authoring actions reset the preview. Other motion and drawing +panels are mutually exclusive with this dock. Closing the dock restores CAD +pose; it does not discard a background computation. + +Results are bound to the captured revision, document epoch and request +generation. Unexpected revision/occurrence identities, duplicate bodies, +incomplete or unordered frame times, nonfinite and nonrigid poses are rejected. +An edit, document replacement or late callback cannot publish an old playback. +Loads clear on document replacement. Results and overrides are session-local; +this UI does not save a study, change `.ark` schema, call `doc_apply` for poses, +or alter B-rep authority. Evidence is a read-only formatted result with the +request, source SHA256, diagnostics, initial/final states and solver limits. + +## Scope and limits + +The engine contract requires declared material density, exact CAD mass and +inertia, and closed convex collision meshes. It currently supports unlimited +revolute CAD mates; unsupported mates are explicit failures. The UI preserves +these contracts, including 128 bodies, 14,400 integration steps and 32,768 +returned body states. Ground and body contacts are discrete; this is not FEA, +deformation, CCD or manufacturing qualification. CPU reference is an explicit +comparison mode. CPU preparation and GPU solving remain separate stages. + +## Verification + +`studio-inertial-ui` drives the real Inspect ribbon, dock buttons, timeline and +native modal controls on an isolated synthetic CAD assembly with declared +density. Its deferred transport supplies labelled synthetic frames and checks: + +- Apply, Cancel, invalid settings, selected/all occurrence scope and body loads. +- Play, pause, seek, stepping, speed and exact restoration of authored poses. +- Source and revision remain unchanged during simulation controls/playback. +- Cancellation, old-generation callbacks, malformed nonrigid poses, document + replacement and revision changes cannot install stale results. +- OpenGL renders and PNG captures of study, environment, loads, evidence, + running, final, reset and stale states. + +The initial 1440x900 CTest passed in 3.75 seconds. Inspection identified a clipped +angular-unit label and small dock text; these were corrected and a native vector +icon was added. The subsequent four tests passed: inertial UI (3.18 s), action +icons (3.21 s), baked motions (3.75 s), and exploded views (1.95 s). The same +inertial fixture at 1180x800 exited 0. Captures at both sizes were inspected. +Evidence formatting also uses native CRLF line breaks and a result summary; +status text wraps at spaces. No user document is loaded by the fixture, and no +external Studio process is closed by it. + +`--self-test-inertial-engine-ui` performs the same control/playback/source checks +using the production private-session scheduler first with CPU reference, then +with GPU. It has no synthetic transport. Run this on the integrated engine build +with separate `--settings-file`, `--shot` and `--size 1440 900` arguments. Each +solver has a 90-second test wait while the UI pumps and renders. The receipt +retains both actual solver reports. The integrated 056C native build ran this +flag successfully at both 1440x900 and 1180x800 (the latter process exit 0), using +CPU reference and the RTX 4070 Ti hardware backend. Both receipts report actual +solver completion, native control/load checks, playback/reset, exact fixed-body +pose preservation and unchanged authoring/revision. Captures of the final pose, +loads, evidence and minimum-size dock were inspected. The first cold GPU study +included device/shader initialization (2,449.96 ms for the two-body fixture); +it is not a warm solver timing or a performance improvement claim. + +Artifacts are under `out/quality-native/ui-checks`; build and test logs are +`out/inertial-*.log`. These local artifacts are not distribution content. diff --git a/docs/MEDIA_AUTHORING.md b/docs/MEDIA_AUTHORING.md new file mode 100644 index 0000000..20d4beb --- /dev/null +++ b/docs/MEDIA_AUTHORING.md @@ -0,0 +1,109 @@ +# Agent image and animation tools + +Milestones **A.02 / B.04 / D.02 / E.01**. Display media never supplies CAD +geometry, manufacturing qualification, sensor measurements or hardware triggers. +The existing `image_asset` tool exposes the following workflow without increasing +the tool catalog count. Load `agent_onboard` topic `stamps` first. + +## Discover and generate + +`image_asset{action:"capabilities"}` reports local composition, text and video +support and whether image API credentials are configured. Credential presence +does not prove model access or a successful provider request. + +`action:"generate"` requires `model`, `prompt`, a new `.png` output `path`, and +`expected_revision`. Optional `size` is `1024x1024`, `1536x1024`, `1024x1536` or +`auto`; `quality` is `low`, `medium`, `high` or `auto`. The request goes to the +[OpenAI Images API](https://developers.openai.com/api/reference/resources/images/methods/generate) +and returns actual decoded PNG bytes, dimensions, SHA-256 and provider usage when +reported. An unavailable key or rejected response produces an explicit error. + +Configure the key through **Models/account → Image generation / OpenAI API key** +or `OPENAI_API_KEY`. Studio stores it through the existing per-user encrypted +credential store, scoped to the OpenAI provider and HTTPS host. The dialog keeps +the current assistant model and ChatGPT login. It shares the saved OpenAI API key +with the OpenAI API connector; it does not convert ChatGPT plan credentials into +an Images API key. No key is accepted as a model tool argument or written to an +artifact, document, log or settings JSON. + +An external client's image-generation skill may also supply real local PNG/JPEG +files. Such skills are not automatically available inside the Studio agent. + +## Compose locally + +`image_asset{action:"compose",expected_revision,path,format,width,height,fps, +duration_s,background,layers}` writes a new PNG, GIF or MP4. It works without an +image API key. Inputs are explicit layers, not executable scripts: + +- `image`: exactly one PNG/JPEG `asset` name or local `path`. +- `rect`, `ellipse`, `line`: pixel geometry, `color` as `#RRGGBB`, optional + `outline` and `line_width`. +- `text`: Unicode `text`, pixel `font_size`; `{frame}` and `{percent}` expand + from the clip clock. Native text currently requires Windows. +- Layer `x`, `y`, `width`, `height`, `x2`, `y2`, `opacity`, `from_s`, `to_s` and + `line_width` accept numbers or expressions over `t` (seconds), `u`, `frame`, + `duration`, output `width`/`height`, and document parameters. The media clock + names override same-named document parameters. `from_s` is inclusive and + `to_s` exclusive. Text and image layers remain raster display content. + +The default is 512×288 at 20 fps. Limits are 16..1024 pixels per side, up to +60 seconds, 512 frames, 64 layers, 256 MiB of decoded output frames and 64 MiB of +decoded source images. GIF allows 1..50 fps and at most 4 MiB, with a shared +adaptive palette and delta rectangles. MP4 uses the existing Windows H.264 +encoder and requires even dimensions. Unsupported encoders are reported. + +The receipt states actual frame count and duration: non-integral duration×fps +rounds up to a frame, and GIF timing is rounded to centiseconds. It includes +SHA-256 and decoded readback evidence. PNG/GIF readback is exact in their encoded +pixel representation; MP4 is lossy and its first decoded frame is checked for +dimensions. Neither is a real-time playback-performance claim. + +The tools stage and validate output before exclusive publication. Existing +destinations are never replaced. Publication requires filesystem hard-link +support; an unsupported filesystem or racing destination rejects explicitly. +Cancellation before publication leaves no final artifact. Files do not change +the document or count as applied media. + +## Import and apply + +Use `image_asset{action:"import",name,path,expected_revision}` after generation. +GIFs and static images embed their bytes. Use `embed:true` for a portable MP4 up +to 2 MiB; larger clips must remain external and use the existing relative-path +contract. Project the asset with `stamp.set` using inspected face references and +the producer's `source_topology`. Generation never selects production faces. + +## Bind a display preview to motion + +In a **live Studio session**, call: + +```json +{ + "action": "playback", + "mode": "bind", + "motion": "Named baked motion", + "assets": ["Screen loop"], + "leds": [{"feature": 42, "intensity": "max(0,1-abs(t-10.5)/0.15)"}], + "expected_revision": 12 +} +``` + +The named motion must have a current bake. GIF assets use the same discrete +baked-frame clock as the displayed assembly. Existing stamp playback mappings +still apply. LED targets must already have an authored emissive appearance; +their intensity expressions are validated as 0..1 at every baked frame and +replace the independent pulse/blink multiplier during the binding. Expressions +may also use compiled motion channel values. This scales appearance only. + +Start the named motion in **Baked Motions**, or use `action:"playback"` with +`mode:"play"`, `"pause"`, `"stop"` or `"seek"` and the current +`expected_revision`; seek also requires `time_s`. Native flexible-cable +preparation returns `pending:true` with measured progress rather than pretending +playback has started. Play starts automatically when that preparation succeeds; +a pending seek must be requested again after preparation. Pause holds its media +frame, scrubbing uses the selected frame, and Stop returns media/cues to time zero. `mode:"inspect"` +reports the binding; `mode:"clear"` with the current revision removes it. +Bindings are **session-local**, are not saved in `.ark`, and become stale after +a revision or document change. Rebind explicitly after edits. MP4 remains +independent playback: frame-indexed MP4 synchronization is not claimed. +Standalone MCP rejects playback binding and instructs the client to connect to +Studio. No physical camera, sensor or LED hardware is triggered. diff --git a/docs/NATIVE_BUILD.md b/docs/NATIVE_BUILD.md index 4b0d25d..90824b7 100644 --- a/docs/NATIVE_BUILD.md +++ b/docs/NATIVE_BUILD.md @@ -30,6 +30,23 @@ under `install-msvc-ark-offset-001/win64/vc14/lib`, and Release DLLs under applications and tests, or copy the required DLLs alongside a produced `.exe`. Do not mix these MSVC libraries with the existing MinGW build in `out/sketch`. +051A also supports LLVM-MinGW without bypassing the patchset verification: + +```powershell +powershell -NoProfile -File scripts/build-occt.ps1 -Toolchain LLVMMinGW -CompilerDirectory C:/tools/llvm-mingw/bin -Jobs 4 +``` + +The compiler directory must contain `clang.exe`, `clang++.exe` and +`mingw32-make.exe`; CMake and Git must be on PATH. This route uses a separate +`build-mingw-ark-offset-001` and `install-mingw-ark-offset-001`, the same pinned +archive and frozen patches, and the same installed DLL inventory and license +notices. Configure ARK with `MinGW Makefiles`, the same compiler/make program, +`ARK_WITH_OCCT=ON` and `OpenCASCADE_DIR` pointing to that installation's `cmake` +directory. Put its `win64/clang/bin` and compiler `bin` on PATH for tests. Leave +`ARK_ALLOW_UNPATCHED_OCCT` OFF. The optional metadata compression declarations +are handled in source; an external forced-include compatibility header is not +needed. See [051A native geometry evidence](NATIVE_GEOMETRY_051A.md). + The configuration builds FoundationClasses, ModelingData, ModelingAlgorithms, and the `TKDESTEP` toolkit with its dependencies. Full visualization and Draw modules are not requested; the STEP dependency closure still includes some diff --git a/docs/NATIVE_GEOMETRY_051A.md b/docs/NATIVE_GEOMETRY_051A.md new file mode 100644 index 0000000..413a064 --- /dev/null +++ b/docs/NATIVE_GEOMETRY_051A.md @@ -0,0 +1,98 @@ +# Native geometry verification, 051A + +A.03/B.03: the 050B diagnostic run selected an unpatched OCCT 8.0.1 SDK +with `ARK_ALLOW_UNPATCHED_OCCT=ON`. Two existing regression tests failed: +`native-solid` at shallow C0 join classification, and `native-surface` at the +translated analytic C2 frustum (relative volume error 4.26611e-6 against 1e-8). +The other 151 tests in that diagnostic run passed. This is evidence about that +SDK selection, not a reason to weaken either geometric oracle. + +The repository already owns the exact source fixes in `ark-offset-001`: + +- `0005-native-geometry-custody.patch` makes `BRepOffset_Analyse` honor encoded + regularity instead of the fillet helper's weak visual tangent condition. The + existing fixture sews a plane to a planar B-spline at negative, zero and + positive angles and requires genuine shallow concave/convex C0 joins to remain + classified as such. +- `0002-variational-factor-qr.patch` solves the bounded C2 independent-dimension, + two-passpoint domain from its original factors, retaining constraint assembly + and explicit rank checks. This avoids the unstable normal-equation solve in + the tested loft domain. The existing analytic-frustum fixture independently + integrates volume across scales and translation; the unchanged relative + threshold is 1e-8. Other solver domains retain their original dispatch. + +The missing build route was Windows LLVM-MinGW: the PowerShell dependency builder +only prepared MSVC, while the local compiler and old SDK were MinGW. The builder +now accepts `-Toolchain LLVMMinGW -CompilerDirectory `, builds into a separate +patchset-qualified directory, and preserves pinned archive, exact target hashes, +license notices and the installed shared-library inventory. No shared old SDK is +rewritten, no patch is redefined, and no fixture or geometry tolerance is relaxed. + +The optional retained-metadata codec also now exposes its Windows declarations +locally and uses the documented const-input function-pointer ABI for dynamically +loaded compression. The minimum Windows target and unavailable-codec behavior +remain unchanged. This removes the external MinGW forced-include workaround. +The geometry-storage regression passed with the changed source compiled at +`_WIN32_WINNT=0x0601`, without that workaround. + +Build provenance: OCCT V8_0_1 archive SHA-256 +`7c033d917ee8f040c0512d289dcc5f02c148889d5bac17c3e25639accb44f0da`; +patchset manifest SHA-256 +`2fbbd4f68b8c06a36aa04787d378540fa6e9ee43d353a57d7e09870c185f9562`. +LLVM-MinGW 20261006 UCRT x86-64; Release; four compiler jobs. The SDK's +`.ark-occt-build.json` records all installed OCCT DLL bytes and the +`clean-source-rebuild` route. It is an observed build declaration, not independent +compiler-input attestation or manufacturing qualification. + +Observed 051A local result: **Verificado no escopo** for these two existing +regression suites and SDK selection. The same executable bytes were run first +against the original SDK (both exit 1), then against the clean patched SDK (both +exit 0). `native-solid` passed all its cases. `native-surface` passed all its +cases, including the following analytic C2 frustum relative-volume errors: + +| Scale | Translation | Unpatched | Patched | Existing limit | +| --- | --- | --- | --- | --- | +| 1 | 0 | 2.5307e-11 | 7.39408e-15 | 1e-8 | +| 30 | 0 | 1.18897e-9 | 3.29035e-14 | 1e-8 | +| 30 | 100000 | 4.26611e-6 | 6.8587e-13 | 1e-8 | + +Controlled executable SHA-256 values: +`native-solid`: `1a6425e6d058a6fd4a31934b9fe1013898ad3255b79059383c3e943423d3412b`; +`native-surface`: `79e880024837ba940d95d40758b03d056d65c9490ed42bd9e2c055ac5d2e8b08`. +The installed SDK inventory was verified by `ApplyOcctPatch.cmake VERIFY_INSTALLED`. +A separate fresh ARK Release configuration accepted that SDK with +`ARK_ALLOW_UNPATCHED_OCCT=OFF` and empty C/C++ extra flags, without the external +compatibility include. The dependency builder disables CMake's global package +registry export; SDK choice remains explicit and does not require registry writes. + +This comparison isolates the dependency repair using existing test binaries; it +does not stand in for an integrated 051A application build, complete-suite run, +packaging or deployment. Those are separate delivery gates. No manufacturing or +arbitrary-surface qualification is inferred from these regression fixtures. + +## A.04/B.03 cancellation across evaluation threads + +The request cancellation scope and timeout allowance were thread-local. Native +jobs dispatched to the feature pool therefore lost their owner's cancellation +policy and could remain in a worker RPC until the default watchdog expired. +Each submitted job now owns a copy of that policy and installs an RAII scope on +the pool thread. Scope exit restores the thread's prior policy, including after +native failure. This changes neither geometric authority nor tolerances. + +The native variant of `ark-evaluation-schedule-032d-tests` exercises four independent +native boxes on two feature workers with the result cache disabled. Its cancellation +callback permits dispatch and then cancels inside the real isolated process wait. +The local isolated test started two native processes and returned in 29.27 ms +against a 120-second allowance; every job reported `NATIVE_CANCELLED`. A subsequent +recompute succeeded on reused pool threads without invoking the prior callback. +The test also verifies inheritance and restoration of the request allowance. +This evidence uses freshly compiled changed objects linked with the existing +baseline library and worker. An integrated build and suite remain separate gates. + +The integrated 051A build subsequently passed `native-solid`, `native-surface`, +`evaluation_schedule-032d`, `async-exact-046b` and `async-authoring-051a` against +the verified SDK. The fresh native CMake configuration has +`ARK_ALLOW_UNPATCHED_OCCT=OFF` and empty C/C++ extra flags. Full-suite outcomes, +including separately repeated filesystem failures, are recorded in +[051A](iterations/051A.md). This is local build evidence, not hosted CI, +distribution or manufacturing qualification. diff --git a/docs/PARAMETRIC_COMPONENTS_053B.md b/docs/PARAMETRIC_COMPONENTS_053B.md new file mode 100644 index 0000000..2e02e67 --- /dev/null +++ b/docs/PARAMETRIC_COMPONENTS_053B.md @@ -0,0 +1,115 @@ +# Parametric components and Neural Parametric View + +053B addresses A.02/A.03/B.01/B.04/E.01. Reusable components retain authored +parameters, sketches, datums, features and assembly relationships. Geometry is +recomputed by ARK; a picture or a generated mesh is not the source definition. + +## Files and ownership + +| File | Meaning | +| --- | --- | +| `.ark` | Project, including embedded component definitions and local bindings. | +| `.arkprt` | One parametric part result with its dependency closure and local root. | +| `.arktop` | An assembly/subassembly recipe with its retained part definitions. | +| `.arkops` | Existing newline-delimited public-tool command replay. Unchanged. | + +Component files use the owned binary ARK container. Their logical envelope is +`ark.parametric-component.v1`, with `component_id`, `revision`, `kind`, `name`, +`document`, `parameters` and `interfaces`. A subsequent revision also carries +`parent_sha256`. The embedded document contains authored source, not session +conversation, audit, usage or history. `parameters` lists public parameter names; +`interfaces` lists public named datums. Other dependency parameters remain +editable project source, but cannot be configured through the public interface. + +Export is exclusive: it never overwrites an existing component file. Supplying +`previous_path` creates the next revision with the same component ID and the +previous digest. Insertion embeds the definition and its digest, maps numeric +identities, prefixes names and rewrites expression identifiers. Owned sketches +retain their local names and bind to the remapped feature definition. Different +namespaces can configure the same definition independently. + +The first insertion preserves existing terminal bodies as assembly occurrences. +Source files are not consulted during project reopen or recomputation. The project +can be copied to another computer without the original component library. Embedded +definitions and bindings require semantic document version **51**; unrelated +documents retain their required earlier version. The physical container version +does not change. + +## Studio + +Open **Inspect → Graph**, or find **Neural Parametric View** in All tools under +**Components & library**. The same category exposes Export part, Export assembly, +Insert, Update and Configure. The graph toolbar provides those operations too. + +Export selects a part feature ID or assembly group, a new file, comma-separated +public parameter/datum names, and optionally the previous revision file. Insert +selects a file and an identifier namespace. Public overrides are numeric JSON, +for example `{"width":30}`. ARK evaluates an isolated candidate and presents its +receipt for review before Apply. Cancelling either form leaves the project alone. + +Update requires the next revision in the exact digest chain. It preserves target +IDs, numeric public overrides, and independent placement/visibility/name of the +component root. Changes to internal authoring are detected and rejected rather +than overwritten. Export a deliberately edited definition for review when the +installed source has diverged. Other copies and projects remain on their pinned +revision until explicitly updated. + +The graph uses the same local authored relation index as `context_graph`: + +- Select a part or occurrence to select its geometry in Studio. Selecting a + parameter highlights known dependants; the inspector shows authored facts. +- Double-click a part or group to fold/unfold its detail. Search includes direct + neighbours; Focus limits the map around the selected object. +- Drag nodes to arrange the view, drag the background to pan, use the wheel to + zoom, F to fit and Escape to close. +- Colours distinguish object kinds. Links distinguish dependency, assembly and + embedded component reuse; reuse is dashed. Thumbnails use current display meshes. + +Layout and navigation do not edit geometry or call a model. This is a partial +authored relationship index, not a complete evaluator dependency graph, neural +network, manufacturing proof or measured token saving. + +## Public tool flow + +```json +{"tool":"parametric_components","arguments":{"action":"export","kind":"part","feature":1,"name":"Bracket","path":"bracket-r1.arkprt","parameters":["width"],"interfaces":["Mount"],"expected_revision":7}} +{"tool":"parametric_components","arguments":{"action":"prepare","mode":"insert","path":"bracket-r1.arkprt","namespace":"left","overrides":{"width":30},"expected_revision":3}} +``` + +Read the actual returned `candidate_id`, then commit using +`doc_apply{candidate_id,expected_revision}`. No placeholder ID is usable. Prepare +freezes the loaded package, evaluates exact geometry and does not publish edits. +A stale candidate rejects. `mode:update` takes the next file and installed +namespace; `mode:configure` takes the namespace and public overrides, without a +source file. `action:inspect` reads installed manifests or an explicit file. + +The underlying atomic commands are `component.insert`, `component.update` and +`component.configure`. They require `expected_revision`. Insertion/update carries +an embedded `package` and matching `package_sha256`; update/configure additionally +requires `expected_package_sha256` for the installed revision. Ordinary preview, +postcondition, undo/redo and publication rules apply. + +## Current boundaries + +- An assembly export retains its materialized editable recipes. It does not yet + preserve a hierarchy of independently updateable nested library bindings. +- Revision replacement requires the same source identity sets. Adding/removing + source objects or renaming named dependencies requires insertion under a new + namespace and explicit reconnection; there is no silent topology rebase. +- Global Skeleton/motion/drag-chain/configuration/external-reference ownership, + imported source payloads, BOM part metadata and unsupported image appearances + need separate remapping contracts and reject. Cross-boundary assembly mates + reject. Export from an isolated checkout is unsupported. +- Drawings, canvases, exploded display layouts, original project parent placement + and unrelated objects are outside the component recipe. Selected subassemblies + are exported without their parent frame; retained local placement remains explicit. +- Scoped designer checkouts receive only their materialized source closure, not + the owning project's embedded component packages. Result integration is still + governed by the checkout contract; a changed component recipe is then a local + divergence for future library revision updates. +- Existing document/geometry limits apply, including 4 MiB logical persistence, + 256 parameters, 1024 features and at most 128 component bindings. Namespace + prefixes count towards authored name limits. No hosted registry or background + update service is introduced. + +Verification is recorded in [053B](iterations/053B.md). diff --git a/docs/PART_AGENTS_052D.md b/docs/PART_AGENTS_052D.md new file mode 100644 index 0000000..8c5fb71 --- /dev/null +++ b/docs/PART_AGENTS_052D.md @@ -0,0 +1,146 @@ +# Isolated part delegation — 052D + +Scope: **B.04/D.01/D.02/D.03**, partial local implementation. Focused Studio +teams isolate PartDesigner roles. The lead first creates a coherent editable +concept and an existing assembly group; a designer refines that group in a +private document. Source publication requires lead review and integration. +Single and Parallel retain their existing behavior. + +## Context and authority + +The specialist receives a local brief, editable/read-only resource identities, +source revision and optional acceptance checks. It does not inherit the global +user prompt, images, sibling conversations or automatic global progress feeds. +Each assignment starts a fresh private conversation; lifetime provider usage +and request-byte accounting remain cumulative. Existing per-role model/effort +settings are preserved. No cheaper model or turn/token budget is inferred. + +`team_part` is the specialist's only tool. Queries execute against an actual +`AgentSession` containing the design-container dependency closure. There is no +fallback to the source executor. Ordinary private CAD transactions enforce the +ownership manifest, native validity and local revisions. Global memory, file +I/O, external integrations, source writes and peer discovery are unavailable. + +Shared parameter expressions remain authored relationships. Read-only +dependencies cannot be changed. An interface exclusively owned by the editable +part still needs an explicit acceptance condition when it must remain fixed; +isolation does not infer mechanical requirements. + +## Workflow + +Create a group around the already sketched part, then assign it: + +```json +{"action":"assign","to":"designer","node":1,"expected_revision":12, + "message":"Detail the support; preserve its shared mounting interface.", + "checks":[{"query":{"tool":"eval_expr","args":{"expr":"MountPitch"},"path":"value"}, + "op":"eq","value":40}]} +``` + +Finish the lead turn after assignment. Only one private task may be outstanding +in this Focused workflow. The specialist queries its private document and edits +using the **local** revision, initially zero: + +```json +{"action":"query","tool":"doc_info","args":{"detail":"design"}} +{"action":"apply","expected_revision":0, + "commands":[{"op":"feature.edit","id":7,"p":{"depth":9}}]} +{"action":"submit","expected_revision":1, + "message":"Local detail completed; shared expressions retained. Review required."} +``` + +Supported query tools are advertised in the schema. `preview` uses private +`doc_preview`; `apply` also accepts its prepared candidate with the local revision. +`report` with `message` requests missing inputs from the lead without publishing. +The lead may reply via `team_send` using `kind:report` to resume the designer, or +`kind:message` to retain context for its next turn. Ordinary assignment messages +cannot establish or replace private workspaces. + +Submission freezes the child. The lead reviews at the original source revision: + +```json +{"action":"review","task":"part-1","expected_revision":12} +``` + +The host derives the merge recipe and evaluates a source preview with the +immutable assignment checks. A successful review returns commands, identity +mapping, validation and `reviewed_child_sha256`. The lead integrates that digest: + +```json +{"action":"integrate","task":"part-1","expected_revision":12, + "reviewed_child_sha256":""} +``` + +Integration rechecks the merge against the current source and publishes through +ordinary atomic `doc_apply` with the same checks. Private steps and source commits +are accounted separately. Submission alone cannot satisfy global completion. +`inspect` returns task state. Lead-only `discard` abandons unpublished work; it +cannot undo an integrated task. + +## Boundaries + +The [container contract](DESIGN_CONTAINERS_023B.md) remains authoritative: +global Skeleton sources, cross-boundary mates and unsupported retained-feature +rewrites reject. Both source revision and authored provenance must match. Even +an unrelated source edit makes integration stale; explicitly discard/reassign or +handle the correction with the lead. There is no automatic rebase or concurrent +checkout merge extension. + +Private roles omit inherited preloaded guides and automatic project-memory +prefetch; they request the relevant CAD guide inside their own workspace. +Private workspaces are session-local, not crash-persistent task queues. They do +not automatically create files or copy drawing context into project memory. +Cancellation reaches isolated native workers through native request control; +noninterruptible ordinary CPU evaluation may finish privately. Existing resource, +mailbox and native-operation guards remain; no new agent turn/token budgets. + +## Comparison + +The benchmark adds `PartFocused` and explicit `part_container` selectors. The +synthetic [PD01 example](../benchmarks/part_agents_052d.json) details a parametric +definition reused twice while preserving another module. + +```powershell +out/052d-native/ark-benchmark.exe --suite benchmarks/part_agents_052d.json --preflight +out/052d-native/ark-benchmark.exe --suite benchmarks/part_agents_052d.json --config benchmarks/part_agents_offline_052d.json --out out/052d-part-offline.jsonl +``` + +Default offline PartFocused actually assigns, edits privately, submits, reviews +and integrates. Forced-delegation acceptance requires a measured private edit +and integration. +Reference commands never enter live model prompts. All strategies use the same +authored baseline and design oracle, including save/reopen and fresh authoring +reconstruction. PartFocused additionally instructs the lead to exercise the +architecture being measured; lead-only authoring cannot count as delegation. + +For a neutral decision trial, set `require_part_delegation: false`, as in +[`part_agents_neutral_sol_052d.json`](../benchmarks/part_agents_neutral_sol_052d.json). +Single and PartFocused then receive the identical task text and oracle; receipts +record `user_task_sha256` to verify this. The lead may solve a small task directly. +`delegation_integrated` still distinguishes actual specialist work from a +lead-only result. Compare total team usage and latency against Single, including +all unsuccessful attempts and tool calls. Keep forced and neutral experiments +separate: they answer different questions. The offline neutral transport is +still scripted and does not demonstrate a model's delegation judgment. + +Live runs require explicit `--live`. Compare the same model first. The +[`part_agents_sol_052d.json`](../benchmarks/part_agents_sol_052d.json) preset uses +`gpt-6.1-sol`, `medium`, and the already connected ARK ChatGPT account via +`auth_mode: "chatgpt-plan"`. It never imports another application's credentials. +Check the connected account's model catalog before running; availability is not +inferred from a preset. Default authentication remains `api-key` when omitted. +The benchmark host's time window bounds an experiment, not production agent turns. + +```powershell +out/052d-native/ark-benchmark.exe --suite benchmarks/part_agents_052d.json --config benchmarks/part_agents_sol_052d.json --out out/052d-live-sol-medium.jsonl --live +``` + +Optional +`specialist_assistant` uses the explicit provider/model/protocol/endpoint fields +of `assistant` and changes only the PartFocused designer. Receipts include role +model, effort, request bytes, provider usage, private steps and integration state. +A single lead tariff cannot price a mixed-model run: aggregate monetary cost +stays unknown. Missing usage and failed attempts remain visible. Offline success +is not evidence of model quality or savings. + +Observed verification and live pilot results: [052D](iterations/052D.md). diff --git a/docs/PROJECT_SCALE_COMMANDS_056C.md b/docs/PROJECT_SCALE_COMMANDS_056C.md new file mode 100644 index 0000000..bad3be4 --- /dev/null +++ b/docs/PROJECT_SCALE_COMMANDS_056C.md @@ -0,0 +1,119 @@ +# 056C project storage and command discovery + +Milestones **A.02 / A.04 / A.05 / D.02**: **Verificado no escopo** for the +local storage and command contracts below. Large-project, distributed-writer, +deployment and production qualification remain **Parcial**. This work does not +change the semantic `.ark` document version or declare roadmap completion. + +## Storage + +The technical compression work from PR #35 is integrated on the newer 055D +code base without adopting its older release identity. The physical container +still uses version 2 for optional derived data. One Zstandard 1.5.7 frame shares +repeated bytes across native geometry and baked-motion entries. Canonical large +base64 values travel as decoded bytes and reconstruct exactly; B-rep identities, +native validation and reference authority remain unchanged. Legacy per-entry +rows load, and readers without pack support discard the optional cache and +rebuild from authoring. Full format rules are in [FORMATS.md](FORMATS.md). + +The stored derived limit remains 128 MiB and the physical file limit remains +256 MiB. The separately bounded decoded limit is 256 MiB, tested with a 144 MiB +synthetic round trip. Unchanged valid packs avoid recompression. Reuse verifies +the decoded manifest as well as row hashes, so a valid compressed frame with a +relabelled manifest is repaired on save. Stored-capacity omissions retain a +bounded document-order prefix and are reported separately from saved authoring. + +SQLite compaction uses transactional `VACUUM` when a save frees at least 1 MiB +and a quarter of the file. It preserves SQLite locking and existing connections +instead of publishing a stale snapshot after closing the source connection. +Maintenance failure retains the preceding committed save and reports its cause. +This does not add a cross-process authoring merge contract. + +The logical document/journal limit remains 4 MiB; features remain limited to +1024 and global parameters to 256. Current scoped-sketch support already allows +256 sketches per scope and 4096 in total, with aggregate geometry resource +limits. Reusing a feature definition through assembly instances remains the +supported way to avoid repeated authored definitions. No cap is lifted merely +because storage compresses well. Compression runs on CPU; it is not a claim of +GPU simulation or arbitrary project capacity. + +Zstandard's original source/license files and provenance are retained. Windows +and Linux packaging carry its notices and the release SBOM includes the direct +dependency. ARK's own license is unchanged. + +## Parameterized command palette + +`agent_onboard` has a `commands` topic. It searches the actual current tool +registry and six parameterized recipes without expanding a document inventory: + +```json +{"topic":"commands","query":"bom","limit":3} +{"topic":"commands","command":"tool:library_source_page"} +{"topic":"commands","command":"parameter_set"} +``` + +Search results include a stable command ID, summary, kind and explicit truncation +status. An exact `tool:` returns the tool's current input schema. In the +Studio assistant it also exposes just that specialist tool on the next request, +provided the role's existing tool catalogue permits it. Topic loads and exact +selections append in first-load order. Deferred-provider tool additions use the +first actual loading call, including tools shared by BOM, vendor and component +topics; any preloaded alias makes its tools available. + +The recipes are `parameter_set`, `native_box`, `feature_parameters`, +`assembly_instance`, `material_density` and `revision_status`. A recipe publishes +its parameter schema and ordinary tool-call template. Supplying `parameters` +returns `prepared_call` with `executed:false`. Mutation recipes prepare +`doc_preview`, require an explicit observed `expected_revision`, and preserve +expression strings. Missing/unknown/type-invalid parameters reject. Preparing +a recipe does not evaluate geometry, preview, reserve a target or mutate the +document. The caller executes the returned tool, inspects its candidate and +explicitly applies it through the existing host path. Stale revisions reject +without silent rebasing. This is an agent command palette, not a new Studio +keyboard command-bar control. + +## Local evidence + +Windows Release build, Clang/LLVM-MinGW 23.1.3 and patched OCCT 8.0.1; public +synthetic fixtures only. Measurements below compare identical inputs and +criteria. They are serialized-byte/storage observations, not provider token, +cost or end-to-end latency claims. + +| Observation | Result | +| --- | --- | +| Eight synthetic derived entries, exact byte round trip | 1,665,402 decoded bytes; 645,659 bytes in one pack versus 1,246,094 in independent packs | +| Same joint pack, one local measured run | Encode 21.59 ms; decode 5.09 ms; no general performance qualification | +| Synthetic container after deleting optional cache | 18,915,328 to 20,480 physical bytes; authoring reload verified | +| Highly repetitive synthetic decoded-capacity fixture | 150,994,944 decoded bytes to 4,833 stored bytes; exact round trip; not a realistic CAD compression ratio | +| Full tool documentation versus BOM search, limit 3 | 183,120 versus 2,026 serialized bytes, including the global drawing authorization rule | +| Assistant offered tools | Core 99,687 bytes; one selected source-page tool 100,551; vendor topic 104,111 | +| Command catalog contracts | 574 checks, including native box preview/apply, all registered tool schemas, drawing authorization, parameterized execution, stale rejection and role filtering | +| Derived pack/container contracts | 142 checks, including corrupt/truncated/oversized frames, legacy migration, wrong manifest, exact order, stored-capacity omission, chunk loss, transactional compaction and existing connection visibility | + +The following ten selected CTest suites passed: `agent_contracts-032d`, +`container_snapshot-031b`, `persisted_geometry-031b`, `document-container`, +`history-compaction-051a`, `derived-pack-051a`, `command-catalog-056c`, +`assistant-connector`, `agent-tool-layer-042d`, and `distribution-fixtures`. +`release_evidence_tests.ps1` also passed notices, SBOM, package allowlist, +private-design rejection, hashes and provenance checks. The first selected run +passed nine suites and failed distribution setup because `cmake` was absent +from PATH; that suite passed after adding the configured CMake directory. +Integrated discovery testing then exposed a missing global drawing-authorization +rule in the new `commands` response and two older assertions of 109 tools where +the current registry contains 113. The command response now carries the same +authorization rule as other onboarding topics. The two tests now check unique +tool names and the actual required module/exchange or vendor-policy schema, +including policy revision and role permissions. Local reruns of +`authoring-022b-contracts`, `product-context-035b`, `modeling-workflow` and +`command-catalog-056c` all passed; the command byte measurement above includes +this correction. This verifies A.01/D.02 discovery contracts without granting +drawing writes or weakening the revision boundary. +No hosted CI, Linux runtime test, installer/OTA publication or live model task +comparison was performed by this storage/commands workstream. + +Local logs are generated under `out/scale-*.log` in the worktree; they are not +bundled in product packages. `code-context` was attempted but could not run +because `uv` is unavailable; symbol/contracts were confirmed in current source +with `rg` and direct reads. Historical memory was consulted and rechecked; +its old document-wide sketch-limit observation is superseded by current scoped +validation in `Document::validateSketchScopes`. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 0d7ecb2..5190061 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1,5 +1,74 @@ # ARK roadmap A–G +059C is **Verificado no escopo** locally for **A.02/A.04/B.01/B.03/B.04/C.04/D.02**: +editable rubber bodies, indexed patterns, derived CPU/GPU dynamics, exact face +cycling, background GPU snapshots and exact surface mirror/trim/ruled/fill with +guides and pole/glue controls. Native contracts, persistence and integrated UI +tests passed. Broader B.03/C.04 remain **Parcial**; see [059C evidence and measured +limits](iterations/059C.md). + +058A is **Verificado no escopo** locally for **A.02/A.04/D.02**: conversation +reflow after messages arrive while Studio is minimized, and clear navigation in +expanded chat. Twelve selected checks passed, including the previously failing +minimize/update/restore lifecycle; captures were inspected. See +[058A](iterations/058A.md). Broader milestones remain **Parcial**. + +057B is **Verificado no escopo** locally for **A.02/A.04/B.01/D.02**: native +conversation layout, orientation cube and grouped viewport display controls. +Fourteen final checks and inspected synthetic-fixture captures are recorded in +[057B](iterations/057B.md). Broader milestones remain **Parcial**. + +056C is **Verificado no escopo** locally for **A.02/A.04/A.05/B.01/B.04/C.04/D.02/E.01**: +integrated derived GPU rigid-body dynamics, viewport quality and +mesh reuse, lossless derived storage/compaction, parameterized agent commands +and supplier-evidence/BOM recovery. See [056C evidence](iterations/056C.md). +Broader milestones remain **Parcial**; this does not qualify structural FEA, +manufacture, arbitrary project sizes or every supplier integration. + +055D is **Verificado no escopo** locally for **A.02/B.04/C.04/D.02**: host-observed limited +task BOM review permits qualified Single/Team completion without requiring +unrelated legacy part identities. Global review, current revisions, inspection, +and detailed metadata requirements remain enforced. Native rounded cable sweeps +also handle shallow corners with explicit tighter tolerances and measured surface +error. See [055D evidence](iterations/055D.md). +Broader milestones remain **Parcial**. + +The additional 055D **A.02 / D.02** BOM recovery work is **Verificado no escopo** locally (13 selected suites): incremental +metadata patches, concrete completion diagnostics, explicit input/review-pending +states, and retained task scope on Resume. Detailed/global completion requirements +remain enforced; see [BOM recovery](BOM.md) and [055D evidence](iterations/055D.md). + +The 055D local **A.02 / D.02** UI follow-up is **Verificado no escopo** for a +readable, selectable agent conversation, pinned goal and explicit execution +states. Ten selected native suites and conversation captures passed local +verification; see [055D evidence](iterations/055D.md) and the +[conversation contract](ASSISTANT_CONVERSATION.md). Broader agent milestones +remain **Parcial**. + +The same development iteration adds scoped **A.02 / B.04 / D.02 / E.01** media +authoring: local PNG/GIF/MP4 composition, a credential-explicit Images API entry, +and session-local GIF/LED display binding to baked motion. Local composition and +playback tests are **Verificado no escopo**; live provider access depends on the +configured API key, and persistent/hardware synchronization is not claimed. +See [media authoring](MEDIA_AUTHORING.md) and [055D evidence](iterations/055D.md). + +054B is **Verificado no escopo** locally for **A.02/B.04/B.05/C.04/D.02**: editable electrical +schematics, sheet BOM/DXF, part and assembly families with Eye visibility filters, +and native cable display at baked poses. See the [054B contract](DISCIPLINES_SCHEMATICS_054B.md) +and [verification](iterations/054B.md). Broader milestones remain **Parcial**. + +053B is **Verificado no escopo** locally for **A.02/A.03/B.01/B.04/E.01**: portable parametric +parts/assemblies, explicit revision replacement and a native local graph. +See the [component contract](PARAMETRIC_COMPONENTS_053B.md) and +[053B verification](iterations/053B.md). Broader milestones remain **Parcial**. + +052D is **Verificado no escopo** locally for **A.03/B.04/D.01/D.02/D.03** through +[isolated part delegation](PART_AGENTS_052D.md): private Focused designer +workspaces, lead-owned checked integration and matched delegation measurements. +The broader milestones remain **Parcial**. The small live edit showed overhead, +not savings; larger tasks and general parallel merges remain unproven; +see [052D evidence](iterations/052D.md). + ARK aims to make an intention into an editable, inspectable design through a workspace shared by people and agents. The next features must improve dependable CAD authoring before claims of general industrial qualification. @@ -9,6 +78,14 @@ The public iteration and numeric runtime are defined in increasing sequence and its principal phase. The letter is a roadmap phase, not a month; it does not declare the phase complete. The `.ark` format evolves separately. +051A is **Verificado no escopo** locally for **A.02/A.03/A.04/B.02/B.03/B.04/D.01/D.02**: +explicit archived history compaction, part-scoped sketches, background edit +preparation, native geometry regression verification and measured agent task +outcomes. Acceptance and evidence are tracked in [051A](iterations/051A.md). +The broader milestones remain **Parcial**. Local core/native/UI verification +does not establish hosted CI, distribution, live-model savings or manufacturing +qualification. + 050B addresses **B.04/C.04/B.02/A.02**, **Parcial**, with native driven drag chains, carriage playback and a 256-sketch document limit. Integration verification and limits are recorded in [050B](iterations/050B.md). @@ -266,9 +343,9 @@ Goal: work for days without lost work, ambiguous identity or unverifiable regres | ID | Milestone | Status | Acceptance still governing the work | |---|---|---|---| | A.01 | Iteration identity and release records | Verificado no escopo | Validate `release.json`; expose one consistent identity in application, MCP, onboarding and packages. Preserve global sequence and runtime/document separation. [001A evidence](iterations/001A.md) [019B source identity](iterations/019B.md). [022B identity and compatibility](iterations/022B.md). | -| A.02 | Recovery and work protection | Parcial | Crash during save/modeling/update, disk-full and truncation tests preserve the last intact revision; recoverable autosave cannot replace the original silently. [029B local recovery and injected persistence failures](TRUST_FOUNDATION.md) retain explicit recovery choices; real power-loss qualification remains open. [045A save capacity and journal visibility](iterations/045A.md) keep an over-capacity saved-geometry cache from failing the save. [049A derived bakes](DERIVED_BAKES_049A.md) keep baked motion frames out of authoring and the journal, with an explicit backed-up journal migration. | -| A.03 | Regression corpus and release chain | Parcial | Authorized reproducible positives/negatives with seeds/hashes; native, UI, persistence and OTA suites; receipts for distributed artifacts; actual hosted CI execution. [019B hosted native/portable checks and relocated Linux package](iterations/019B.md) establish that scope, with broader release qualification still open. [022B native, persistence, consumer and viewport regression](iterations/022B.md) adds local evidence; hosted CI and user acceptance remain separate gates. | -| A.04 | Observable performance | Parcial | Measure cold/warm open, incremental save, p95 interaction and recompute at three project sizes against the same machine/baseline. [012D scope](iterations/012D.md) [022B source audit and equivalent synthetic measurements](PERFORMANCE_AUDIT_022B.md) distinguish native evaluation, pending gesture handlers, prepared commit and display work; three-size project p95 qualification remains open. 029B adds native viewport reuse and a matched native three-size control benchmark; see [029B performance](PERFORMANCE_029B.md). [043A opening/rebuild](iterations/043A.md) measures one large freeform document before and after. [046B background exact reads](ASYNC_EXACT_046B.md) keep the Studio viewport live during allow-listed exact reads on one synthetic fixture; writes and full recompute still block. | +| A.02 | Recovery and work protection | Parcial | Crash during save/modeling/update, disk-full and truncation tests preserve the last intact revision; recoverable autosave cannot replace the original silently. [029B local recovery and injected persistence failures](TRUST_FOUNDATION.md) retain explicit recovery choices; real power-loss qualification remains open. [045A save capacity and journal visibility](iterations/045A.md) keep an over-capacity saved-geometry cache from failing the save. [049A derived bakes](DERIVED_BAKES_049A.md) keep baked motion frames out of authoring and the journal, with an explicit backed-up journal migration. [051A archived compaction](HISTORY_COMPACTION_051A.md) preserves a verified complete archive, bounded undo and explicitly retained branch states. | +| A.03 | Regression corpus and release chain | Parcial | Authorized reproducible positives/negatives with seeds/hashes; native, UI, persistence and OTA suites; receipts for distributed artifacts; actual hosted CI execution. [019B hosted native/portable checks and relocated Linux package](iterations/019B.md) establish that scope, with broader release qualification still open. [022B native, persistence, consumer and viewport regression](iterations/022B.md) adds local evidence; hosted CI and user acceptance remain separate gates. [051A native evidence](NATIVE_GEOMETRY_051A.md) verifies the frozen OCCT patches with a supported LLVM-MinGW build route and unchanged regression oracles. | +| A.04 | Observable performance | Parcial | Measure cold/warm open, incremental save, p95 interaction and recompute at three project sizes against the same machine/baseline. [012D scope](iterations/012D.md) [022B source audit and equivalent synthetic measurements](PERFORMANCE_AUDIT_022B.md) distinguish native evaluation, pending gesture handlers, prepared commit and display work; three-size project p95 qualification remains open. 029B adds native viewport reuse and a matched native three-size control benchmark; see [029B performance](PERFORMANCE_029B.md). [043A opening/rebuild](iterations/043A.md) measures one large freeform document before and after. [046B background exact reads](ASYNC_EXACT_046B.md) keep the Studio viewport live during allow-listed exact reads on one synthetic fixture; write preparation was outside that scope. [051A background authoring](ASYNC_AUTHORING_051A.md) extends live navigation to ordinary geometry-changing doc_apply through private preparation, cancellation and revision/epoch-bound publication; other write paths and broad p95 qualification remain separate. | | A.05 | Security, licensing and dependencies | Parcial | Apache-2.0 source license and dependency notices are adopted; source/publication inventory, software SBOM, binary provenance, signing and vulnerability handling need evidence. Never package credentials or user designs. [019B portable image decoder provenance and notices](iterations/019B.md). | ## B — Competitive CAD authoring @@ -277,10 +354,10 @@ Goal: create and revise a complete product with clear, reliable interactions. | ID | Milestone | Status | Acceptance still governing the work | |---|---|---|---| -| B.01 | Readable navigation and editing | Parcial | Stable cube/axes, free orbit, selection/Spotlight, shortcuts and DPI; no clipped controls at supported resolutions. Measurement and display units have [013B evidence](iterations/013B.md); BOM layout has [015B evidence](iterations/015B.md). [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B native/mesh pointer selection, hover and visual authoring](iterations/019B.md). [020B exact extrusion gestures and source dimensions](iterations/020B.md). [021B direct handle and snapshot feedback](iterations/021B.md). [022B existing-solid resize, asynchronous previews, exact vertex tools and integrated sheets](iterations/022B.md). 029B adds accessible native fields, visible focus and dynamic DPI/work-area reflow; [sketch/accessibility evidence](SKETCH_ASSISTANCE_029B.md). [048B](iterations/048B.md) adds the Studio parametric HUD overlay with staged Rebuild/Auto. | -| B.02 | Everyday sketches and feature history | Parcial | Actionable constraint diagnostics, valid reorder, suppress/rollback and visible dependencies; rejection leaves the document intact. Arcs/snaps/expressions have scoped 005B/008D evidence. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact extrusion gestures and source dimensions](iterations/020B.md). [021B associative extrusion source](iterations/021B.md). [022B source-preserving edits, opaque validated preview handoff and version-37 journal checks](iterations/022B.md). 029B adds equilibrated QR solving and source/revision-bound reviewed conflict alternatives; [sketch assistance](SKETCH_ASSISTANCE_029B.md). [046B profile regions](PROFILE_REGIONS_046B.md) make multi-loop sketches with holes one extrude/revolve profile, with typed loop rejections and an optional region selection. [048B parametric HUD](PARAMETRIC_HUD_048B.md) exposes ranged named parameters and a sampled flex check. | -| B.03 | Advanced solids and surfaces | Parcial | Difficult loft/sweep/guide/patch/trim/thicken corpus, measured continuity and explicit repair; no mesh fallback concealing exact failures. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact sketch extrusion](iterations/020B.md). [021B bounded face/extrusion geometry](iterations/021B.md). [022B exact polyhedral vertex pull](NATIVE_VERTEX_PULL_022B.md) adds a bounded faceted-solid domain with input/output validity and selfinterference checks. 029B adds bounded exact orientation repair and a difficult geometry corpus; [repair evidence](SURFACE_REPAIR_029B.md). [046B hollow sweep sections](PROFILE_REGIONS_046B.md) sweep inner loops with one shared placement and a volume-conservation check. | -| B.04 | Large, configurable assemblies | Parcial | Subassemblies, reused instances, configurations, external references and selective loading; editing one definition updates all occurrences. Supported mechanisms are locally scoped. [022B source-linked component patterns](SPECIALIZED_PATTERNS_022B.md) cover inheritance, planar/spatial points, exact curve stations, chain alternation, skips and actual occurrence consumers; large configuration/loading qualification remains open. 029B adds semantic loading, measured derived-buffer/external-I/O reduction and scoped v2 configuration/pin ownership; [assembly evidence](ASSEMBLY_SCALING_029B.md). [048B exploded views](EXPLODED_VISUALIZE_048B.md) are display-only, revision-neutral and drivable by baked motions. | +| B.01 | Readable navigation and editing | Parcial | Stable cube/axes, free orbit, selection/Spotlight, shortcuts and DPI; no clipped controls at supported resolutions. Measurement and display units have [013B evidence](iterations/013B.md); BOM layout has [015B evidence](iterations/015B.md). [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B native/mesh pointer selection, hover and visual authoring](iterations/019B.md). [020B exact extrusion gestures and source dimensions](iterations/020B.md). [021B direct handle and snapshot feedback](iterations/021B.md). [022B existing-solid resize, asynchronous previews, exact vertex tools and integrated sheets](iterations/022B.md). 029B adds accessible native fields, visible focus and dynamic DPI/work-area reflow; [sketch/accessibility evidence](SKETCH_ASSISTANCE_029B.md). [048B](iterations/048B.md) adds the Studio parametric HUD overlay with staged Rebuild/Auto. [053B native graph](PARAMETRIC_COMPONENTS_053B.md) connects authored relationships, geometry selection and local navigation. | +| B.02 | Everyday sketches and feature history | Parcial | Actionable constraint diagnostics, valid reorder, suppress/rollback and visible dependencies; rejection leaves the document intact. Arcs/snaps/expressions have scoped 005B/008D evidence. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact extrusion gestures and source dimensions](iterations/020B.md). [021B associative extrusion source](iterations/021B.md). [022B source-preserving edits, opaque validated preview handoff and version-37 journal checks](iterations/022B.md). 029B adds equilibrated QR solving and source/revision-bound reviewed conflict alternatives; [sketch assistance](SKETCH_ASSISTANCE_029B.md). [046B profile regions](PROFILE_REGIONS_046B.md) make multi-loop sketches with holes one extrude/revolve profile, with typed loop rejections and an optional region selection. [048B parametric HUD](PARAMETRIC_HUD_048B.md) exposes ranged named parameters and a sampled flex check. [051A scoped sketches](SCOPED_SKETCHES_051A.md) add definition ownership, explicit references and guarded per-scope capacity. | +| B.03 | Advanced solids and surfaces | Parcial | Difficult loft/sweep/guide/patch/trim/thicken corpus, measured continuity and explicit repair; no mesh fallback concealing exact failures. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B visual and parametric authoring](iterations/019B.md). [020B exact sketch extrusion](iterations/020B.md). [021B bounded face/extrusion geometry](iterations/021B.md). [022B exact polyhedral vertex pull](NATIVE_VERTEX_PULL_022B.md) adds a bounded faceted-solid domain with input/output validity and selfinterference checks. 029B adds bounded exact orientation repair and a difficult geometry corpus; [repair evidence](SURFACE_REPAIR_029B.md). [046B hollow sweep sections](PROFILE_REGIONS_046B.md) sweep inner loops with one shared placement and a volume-conservation check. [051A native regression evidence](NATIVE_GEOMETRY_051A.md) covers shallow C0 offset classification and translated analytic C2 lofts with unchanged tolerances. | +| B.04 | Large, configurable assemblies | Parcial | Subassemblies, reused instances, configurations, external references and selective loading; editing one definition updates all occurrences. Supported mechanisms are locally scoped. [022B source-linked component patterns](SPECIALIZED_PATTERNS_022B.md) cover inheritance, planar/spatial points, exact curve stations, chain alternation, skips and actual occurrence consumers; large configuration/loading qualification remains open. 029B adds semantic loading, measured derived-buffer/external-I/O reduction and scoped v2 configuration/pin ownership; [assembly evidence](ASSEMBLY_SCALING_029B.md). [048B exploded views](EXPLODED_VISUALIZE_048B.md) are display-only, revision-neutral and drivable by baked motions. [051A definition-owned sketches](SCOPED_SKETCHES_051A.md) are shared across occurrences and remapped with component checkout/merge. [053B reusable recipes](PARAMETRIC_COMPONENTS_053B.md) embed parts/assemblies with public overrides and explicit pinned revision updates. | | B.05 | Technical drawings and exchange | Parcial | Local 022B binds part definitions, exact occurrences and root/group assemblies to source-linked views, isometric projections, planar sections/hatches, semantic dimensions and declared tolerances in the same CAD viewport. Agents author drawings only on explicit user request. 029B adds bounded exact DXF export with local readback and source metadata. Drafting standards, GD&T, PDF, independent recipient interoperability and physical qualification remain open. [Drawing contract](DRAWINGS.md) [022B viewport evidence](DRAWING_VIEWPORT_022B.md) [029B evidence](VERIFICATION_029B.md). [048B Visualize](EXPLODED_VISUALIZE_048B.md) renders exploded assembly images with balloons and a BOM table on explicit request. | ## C — Engineering and manufacturing @@ -312,8 +389,8 @@ remain **Parcial**; primitive success does not establish general design quality. | ID | Milestone | Status | Acceptance still governing the work | |---|---|---|---| -| D.01 | Quality/time/cost benchmark | Parcial | At least 30 versioned briefs, three repeats per initial configuration and blind human evaluation; cost per accepted design includes failures and coordination. Harness exists; 008D pilots were 0/9 and 4/9, 009B closed at 1/9. These results prove no savings. | -| D.02 | Responsible engineer and adaptive team | Parcial | Compare Single/Focused/Parallel; give specialists concrete useful assignments and choose concurrency by measured benefit. No default turn/token budgets. Context, completion, feedback and retained DFM proposal handoffs have scoped evidence; general quality/cost benefit remains unproven. [019B scope](iterations/019B.md) [021B proposal scope](iterations/021B.md). [022B contract/onboarding and independent performance audit](iterations/022B.md) preserve Focused defaults and explicit-request-only drawing work. [045A](iterations/045A.md) records live MCP bridge commits and failures for client feedback. [047D](iterations/047D.md) removes a CLI stdio deadlock and supersedes rejected reads of removed features. [048B](iterations/048B.md) gives agents the HUD protocol and the explicit-request explode/render rule. | +| D.01 | Quality/time/cost benchmark | Parcial | At least 30 versioned briefs, three repeats per initial configuration and blind human evaluation; cost per accepted design includes failures and coordination. Harness exists; 008D pilots were 0/9 and 4/9, 009B closed at 1/9. These results prove no savings. [051A outcome receipts](AGENT_OUTCOMES_051A.md) separate completion, postconditions and verified persistence, and account for failed attempts with explicit tariff provenance; live-model comparisons remain unmeasured. | +| D.02 | Responsible engineer and adaptive team | Parcial | Compare Single/Focused/Parallel; give specialists concrete useful assignments and choose concurrency by measured benefit. No default turn/token budgets. Context, completion, feedback and retained DFM proposal handoffs have scoped evidence; general quality/cost benefit remains unproven. [019B scope](iterations/019B.md) [021B proposal scope](iterations/021B.md). [022B contract/onboarding and independent performance audit](iterations/022B.md) preserve Focused defaults and explicit-request-only drawing work. [045A](iterations/045A.md) records live MCP bridge commits and failures for client feedback. [047D](iterations/047D.md) removes a CLI stdio deadlock and supersedes rejected reads of removed features. [048B](iterations/048B.md) gives agents the HUD protocol and the explicit-request explode/render rule. [051A task outcomes](AGENT_OUTCOMES_051A.md) add parametric edits, assembly changes and recovery after atomic rejection to the existing Single/Focused/Parallel harness. | | D.03 | Isolated part workspaces | Parcial | [023B design containers](DESIGN_CONTAINERS_023B.md) provide assembly-group checkout, explicit editable/read-only closure and atomic merge bound to parent source/revision and reviewed child digest. Conflicting ownership, unsupported cross-boundary references and stale source reject without silent rebase. Large-project scaling and general distributed collaboration remain unqualified. | | D.04 | Multimodal feedback and correction | Parcial | Shared author/reviewer diagnostics, revision-bound previews and intent-preserving correction remain the acceptance scope. 021B adds Z-up/custom snapshot cameras and guarded Studio viewport readback. [032D authored body/face colors and steady emission](SNAPSHOTS_032D.md) and [pattern-copy sampled native clearance](ASSEMBLY_MOTION_032D.md) have local checked scope; textures/stamps, continuous collision and general correction quality remain separate. [020B scope](iterations/020B.md) [021B scope](iterations/021B.md). [022B drawing curve origins, alternate-copy identities and guarded direct previews](iterations/022B.md). [046B Baked Motions clearance markers](MOTION_CLEARANCE_046B.md) show interference, below-threshold and uncertified intervals bound to the measured revision. [047D](iterations/047D.md) sends user images through the Claude Code route. [048B](iterations/048B.md) `visualize_render` returns rendered assembly images to agents. | | D.05 | Concept alternatives and reusable knowledge | Parcial | Compare alternatives against requirements, mass, process/cost and human preference using validated examples. A proposal must not be reported as a created part. | @@ -324,7 +401,7 @@ Goal: preserve design identity and evidence through explicit, versioned exchange | ID | Milestone | Status | Acceptance still governing the work | |---|---|---|---| -| E.01 | Shared identity and contracts | Parcial | Document/part/occurrence/revision IDs, units, source hash, geometry digest, provenance and idempotency; versioned schemas and compatibility tests. Local `ark.bom.v1` exists; external reconciliation is planned. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B source ownership and exact-identity selection contracts](iterations/019B.md). [022B conditional source format and occurrence/drawing identity](iterations/022B.md) retain observed revisions, atomic writes and explicit stale rejection. | +| E.01 | Shared identity and contracts | Parcial | Document/part/occurrence/revision IDs, units, source hash, geometry digest, provenance and idempotency; versioned schemas and compatibility tests. Local `ark.bom.v1` exists; external reconciliation is planned. [017B scoped evidence](iterations/017B.md). [018B editable authoring and coordination](iterations/018B.md). [019B source ownership and exact-identity selection contracts](iterations/019B.md). [022B conditional source format and occurrence/drawing identity](iterations/022B.md) retain observed revisions, atomic writes and explicit stale rejection. [053B component identity](PARAMETRIC_COMPONENTS_053B.md) adds portable definitions, digest chains, identity remapping and reviewed replacement. | | E.02 | Geometry and analysis interchange | Planeado | Publish/consume by contract; preserve original source, body, options and producer version. Display rejection without substitute geometry. | | E.03 | External BOM interchange | Planeado | Explicit authorized adapter; incremental BOM quantities/configurations and stable revision mapping. Local BOM export exists; remote import needs a published contract and end-to-end verification. | | E.04 | Manufacturing contour interchange | Planeado | Canonical contours identified by result ID/digest; placements, stock, utilization and package returned with explicit grain/kerf/units. Stock consumption remains a separate action. | diff --git a/docs/RUBBER_UI_059C.md b/docs/RUBBER_UI_059C.md new file mode 100644 index 0000000..9616dd9 --- /dev/null +++ b/docs/RUBBER_UI_059C.md @@ -0,0 +1,61 @@ +# 059C — rubber stock and local study interface + +C.04 / B.01 / A.04: implemented for integrated local verification. This interface +does not qualify material properties, large-strain behaviour or manufacturing. + +The Rubber panel creates editable exact belt, track, tire and ball stock through +native forms and one atomic revision-checked transaction. It declares a separate +material with the entered density and Young modulus. The visible defaults, +1100 kg/m3 and 3 MPa, are labelled illustrative; they are not a material database. +Stock dimensions remain CAD expressions. Creation adds an occurrence when the +document already has an assembly, without overwriting an existing material. + +Study and Environment configure a selected smooth rubber definition. GPU and CPU +reference are explicit choices. Geometry with exact relief or downstream +modification requires a separate analysis recipe and is rejected. This panel +currently submits unpinned studies with ground contact; fixed nodes and pulleys +remain available through the explicit tool contract. + +All analysis positions, gravity, ground height and initial translation use the +definition's local axes. The selected occurrence's placement only positions the +study for viewing; this is not an assembly contact solve. Cyan is the derived +surface network and the original dark stock remains exact CAD. Play, Pause, +previous/next frame, first/last frame, Fit study and Reset preview never apply +deformation or placement edits to CAD. Evidence includes the reported solver, +declared inputs, exact mass authority, reduced stiffness model and solver limits. + +`physics_inspect` runs through the background read scheduler with +`include_frames:true`, source revision, document epoch and request generation. +The decoder also verifies the exact source SHA-256 and definition ID, bounded +node/frame/index counts, finite coordinates and complete ordered time endpoints. +Cancellation, document replacement, later edits and old callbacks cannot publish +playable stale results. Closing the panel hides the preview; cancellation remains +an explicit control for a running job. + +Rendering uses a separate VAO, one dynamic packed vertex buffer and one static +index buffer. It uploads only when the displayed frame changes, does not pollute +the immutable CAD mesh cache, and does not touch CAD picking or display generation. +CPU normal generation and graphics uploads are display work; this note does not +claim all viewport preparation happens on the GPU or that GPU solving is faster +for every network size. + +## Native verification + +`rubberSelfTest059(dc, output, false)` exercises actual control clicks and native +forms for all four stock types, declared material, study/environment Apply and +Cancel, play/pause/step/fit/reset, stationary upload reuse and source immutability. +Synthetic transport adversaries cover cancellation, late callback, wrong source +hash, invalid indices, document epoch and revision changes. Synthetic frames are +explicitly labelled and are not physics evidence. + +`rubberSelfTest059(dc, output, true)` uses the production scheduler and both explicit +CPU/GPU solvers, captures the final derived mesh, and records the native reports. +Receipts use `.rubber.json`; captures include `.rubber-create-Belt.png`, +`.rubber-create-Track.png`, `.rubber-create-Tire.png`, `.rubber-create-Ball.png`, +`.rubber-study.png`, `.rubber-environment.png`, `.rubber-running.png`, +`.rubber-final.png`, `.rubber-evidence.png`, `.rubber-reset.png` and +`.rubber-stale.png` for the transport mode. + +The integrated 059C build passed both native UI tests, including the production +CPU/GPU study. Creation, study controls and final derived-frame screenshots were +inspected. No user drawing is used in this fixture. diff --git a/docs/SCOPED_SKETCHES_051A.md b/docs/SCOPED_SKETCHES_051A.md new file mode 100644 index 0000000..3b90621 --- /dev/null +++ b/docs/SCOPED_SKETCHES_051A.md @@ -0,0 +1,92 @@ +# Sketches owned by shared definitions — 051A + +B.02/B.04: component sketch ownership is **Verificado no escopo** for the local +contracts recorded below. This does not qualify manufacturing or external CAD +interchange. + +An assembly occurrence already identifies its shared definition by feature ID. +`NamedSketch.ownerFeature` uses that same stable ID. Zero is the legacy document +scope. Two definitions may each own `Profile`; repeated occurrences of either +definition reuse the same solved sketch. Ownership does not add a geometric +dependency from a sketch to the solid that consumes it. + +```json +{"op":"sketch.set","owner_feature":12,"name":"Profile", + "sketch":{"plane":"XY","entities":[ + {"kind":"circle","name":"Ring","dof":[0,0,10]}]}} +``` + +The canonical reference is `part:12::Profile`. Pass it explicitly in +`p.sketch`, native section/guide/path references, `source_sketch`, inspect +queries and context keys (`sketches:part:12::Profile`). Every sketch mutation +accepts `owner_feature` with a local `name`; an existing canonical reference +also works without that selector. No unqualified local name is searched in +other scopes. Unqualified names retain their legacy document meaning. +The C ABI exposes `ark_sketch_set_owned`; lookup, editing and removal also +accept canonical references. Ownership and capacity failures return error codes +instead of crossing the C boundary as exceptions. + +The owner must already exist. To author a result from its own sketch, create an +extrude definition with its ordinary initial profile, create the owned sketch, +then set that definition's `p.sketch` to the canonical reference. These may be +commands in one atomic batch. For a native solid, create its initial native box, +then change its native operation to extrusion once the owned profile exists. +There is no feature-type conversion or implicit reassignment of a sketch. + +Definition renames leave IDs and canonical references intact. Removing a +definition with owned sketches rejects; explicitly remove its sketches first. +Referenced sketch deletion still fails normal dependency evaluation and rolls +back the batch. Removing an occurrence does not remove definition sketches. +There is no automatic sketch rename/rebinding operation. +Sketch-to-sketch projection uses the shared definitions' authored datum frames. +It does not select an occurrence or implicitly inherit its assembly placement; +placed-source projections still use the explicit feature/instance contract. + +Each definition and the legacy global scope permit 256 sketches, with 4096 +total. Aggregate guards limit sketches to 32768 entities, 65536 constraints and +131072 scalar coordinates. Existing per-sketch and document-byte guards still +apply. Scoped local names use 1..96 characters, keeping canonical references +within the existing 128-character consumer contracts. New local/global names +cannot start with `part:`. Previously saved global names with this prefix load +unchanged; attempts to create a colliding scoped reference reject. + +Format50 persists `owner_feature`, canonical `name` and `local_name`. Loading +verifies all three agree, the owner exists, names are unique and capacities +hold before replacing the destination document. Legacy documents do not acquire +owners or format50 merely by opening/saving. Existing feature/profile/project +references remain canonical strings throughout solver evaluation, history, +serialization, native operations and context. Context graph ownership edges are +labelled `owned_by_definition`, separately from geometry source edges. + +For bounded agent context, select the definition with `object_context{ids:[12]}` +and its explicit neighborhood with `context_graph{keys:["feature:12"],depth:1}`. +Reuse only the scope/fingerprints and associated facts actually received. Shared +occurrences reuse definition context; their placement remains an occurrence +selection. This uses the live CAD context API; it does not export private drawing +content into the repository's Graphify/Obsidian code index or establish measured +provider-token savings. + +The Studio sketch browser groups local labels under shared definitions and the +Document scope. Rectangle, circle and spline authoring expose an owner chooser; +existing sketch editing and curve appending use the canonical selection. Sketch +actions have a distinct 4096-entry range, separate from constraint and mate +actions. Design-container checkout retains unused owned sketches, and merge +remaps scoped references with their definitions without interpreting arbitrary +legacy names as references. + +Verification targets: `scoped-sketches-051a` exercises 512 sketches in two +scopes, same-name isolation, self-owned extrusions, repeated occurrences, +per-scope and total overflow, aggregate resource guards, definition rename and +removal, exact persistence and legacy migration. `scoped-sketches-native-051a` +exercises cross-scope exact projection and extrusion, source edits, rejected +unqualified references/cycles/deletion, and reload. `design-containers-023b` +includes owned sketch retention and merge. Studio's `--self-test-tree-ui` +checks browser scrolling/selection; captures are local verification artifacts. + +Observed local verification: 34 scoped core/C ABI checks and 9 exact projection +checks passed; the existing kernel, agent, context-graph and design-container +suites passed. The native checks used the existing OCCT worker through its +published geometry contract. Studio built successfully; its tree fixture +selected and revealed sketch index1024 among 1025 owned sketches, with separate +constraint actions, and the top/last-row captures were visually inspected. +No production deployment or external CAD adapter qualification is claimed. diff --git a/docs/SURFACE_CONTROLS_059C.md b/docs/SURFACE_CONTROLS_059C.md new file mode 100644 index 0000000..1bdb07f --- /dev/null +++ b/docs/SURFACE_CONTROLS_059C.md @@ -0,0 +1,99 @@ +# Exact surface controls — 059C + +Scope: B.01 and A.02. Existing planar-solid `vertex_pull` remains separate. +These controls edit existing exact open, clamped, untrimmed BSpline faces with +at most 32 × 32 poles. Poles use zero-based `(u,v)` indices. Mesh vertices are +never used as production geometry. Solids, multiple faces, periodic/closed +surfaces and trimmed/holed boundaries reject explicitly. + +`surface_control` requires the current `expected_revision` and a feature `id`: + +- `inspect` returns the exact control net, face reference and B-rep SHA-256. +- `stretch_plan` requires that SHA, an explicit displacement bound and 1–128 + `{u,v,delta_mm}` edits. Duplicate poles reject. +- `candidates` requires source and target SHA-256, target feature, corner `(u,v)` + and radius ≤1000 mm. It returns at most 64 exact vertices, sorted by distance + then current exact index, with incident semantic edge references/derivatives. +- `glue_plan` requires an explicitly selected `vertex.N`, with an optional + incident `target_edge` and `tangent_axis` (`u` or `v`). It moves the corner and + optionally its adjacent handle, retaining the original handle length. It + verifies the resulting point gap ≤1e-6 mm and the declared tangent angle ≤1°. + +Coordinates are definition-local millimetres; occurrence transforms are never +inferred. All plans are read-only and return commands plus a `doc_preview` call. +Publication remains an explicit revision-guarded candidate apply. The authored +SurfaceEdit keeps the source and optional target as DAG inputs, together with +their exact fingerprints; changed geometry must be inspected and replanned. +The persisted recipe contains references, never a copied target B-rep. + +The edit copies the existing exact BSpline basis, retaining degrees, knots, +multiplicities, weights and natural parameter bounds. OCCT validates the new +face and native interference check; an additional 9 × 9 Jacobian sample rejects +observed degeneracy. Sampling is not a proof of global injectivity. Glue is one +corner point and at most one unoriented tangent line, not full boundary G1/G2, +surface sewing, or manufacturing qualification. + +Local evidence: standalone native test compiled against the patched OCCT and +current ARK native libraries passed 63 checks. It exercises a nonuniform rational +surface, basis equality, individual pole movement, valid exact results, immutable +source, bounded deterministic candidates, gap/angle/handle proofs, and rejection +of stale hashes, trim/closed/solid sources, duplicate/out-of-range poles, unknown +fields, enlarged tolerance and absent targets. The integrated 059C build also +passed host routing, preview/publication, source/target hash rejection, +save/reopen/recompute and preservation of the glue target as a separate output. + +Studio UI is supplied in `surface_edit_059c.inl`. Surface controls (49500) +asynchronously inspect the selected exact occurrence. The control cage has +pickable poles; dragging schedules coalesced private exact previews. Releasing +the pointer retains the preview. Pole / delta (49501) uses native numeric fields; +Apply (49502) atomically publishes the retained prepared candidate. Reset (49505) +discards it, and Cancel (49504) or Escape ends the edit. Source revision, document +epoch, visible occurrence and placed frame invalidate old work. No native query +runs in a paint or pointer-move handler; cage buffers upload only after changes. + +Glue hitpoint (49503) asks for a bounded radius and tangent choice, then accepts +a click on another visible exact body. Native fields require an explicit vertex +choice and, if requested, an incident semantic edge. Candidates remain in local +definition coordinates, so the UI rejects source/target occurrences with +different frames. The preview displays the chosen corner and handle together +with the exact derived surface. This does not silently reposition an occurrence. + +UI tests in `surface_edit_059c_selftest.inl` exercise real window pointer/key and +button events, asynchronous exact inspection and preview, native numeric forms, +explicit Apply, one Undo, Reset, Escape, body-target picking and stale revision. +The fixture contains only synthetic geometry. The integrated 059C Studio passed +79 UI checks, and the control-net, drag, numeric fields, hitpoint glue preview +and applied-result captures were inspected. The receipt is +`surface-edit-ui.png.surface-controls.json`. An initial target click was hidden +by the editor toolbar; Fit now reserves its space and the fixture verifies an +unobstructed target before clicking. Reference target visibility is checked +after publication. This is local native UI evidence, not external qualification. + +Integration: include `surface_deform_059c.inl` inside `surfacing.cpp` after +`surfaceEditResult`, with `Geom2d_Line.hxx`, `Geom2d_TrimmedCurve.hxx` and +`BRepAlgoAPI_Check.hxx` included at translation-unit scope. Dispatch +`surface_control_net` → `surfaceControlNet059`, `surface_glue_candidates` → +`surfaceGlueCandidates059`, and `surface_deform_poles` → `deformSurfacePoles059`. +Host exports `surfaceControlSchema059` and `surfaceControl059`. Register native +test `surface_deform_059c_tests.cpp` against `ark-occt ark`, and host test +`surface_control_059c_tests.cpp` against `ark` with the native-worker dependency. + +UI hooks (root-owned `viewer.cpp`): + +- Include after `rubber_panel_059c.inl`; forward-declare `surfaceEditAction059` + and `surfaceEditActive059` if required by earlier routing. +- Route 49500–49519 before the generic action-id ranges. Expose 49500 in the + Surface menu. Run `processSurfaceEdit059()` before drawing a frame. +- Draw `drawSurfaceEdit059()` beside the direct/cable preview passes, and + `drawSurfaceControls059(rect,button)` after ordinary viewport controls. +- While active, give `beginSurfaceDrag059(x,y)` precedence over regular body + clicks (except buttons/cube); capture the pointer. During its drag call + `moveSurfaceDrag059`; on release consume the gesture and call + `finishSurfaceDrag059`. A target click is consumed even if it did not start a + drag. Keep ordinary navigation and native text focus handling intact. +- Give `surfaceEditKey059` precedence over face Tab, after native edit focus and + sketch/direct edit precedence. Do not add the editor flag to + `faceCyclePreview059`, which the editor uses to inspect underlying scene state. +- `shutdownSurfaceEdit059()` must run before shared evaluation-pool destruction. +- Include the selftest after `drawFrame` and expose + `surfaceEditSelfTest059(hdc,shotPath)` through a native selftest flag. diff --git a/docs/SURFACE_WORKFLOW_059C.md b/docs/SURFACE_WORKFLOW_059C.md new file mode 100644 index 0000000..a9d5aa2 --- /dev/null +++ b/docs/SURFACE_WORKFLOW_059C.md @@ -0,0 +1,99 @@ +# 059C surface authoring forms + +Milestones **A.02 / B.01 / B.03 / D.02**. Status: **Verificado no escopo** in the +isolated native Studio run; final integrated Studio verification remains pending. +The forms call the exact, atomic document API and capture +both document revision and document epoch before the first interaction. + +## Operations and integration + +| Action | Form | Authored contract | +| --- | --- | --- | +| 49400 | Mirror and join | `surface_edit`, one input, `native.op:mirror`, named plane or explicit origin/normal, G0/G1 | +| 49401 | Trim by tool | `surface_edit`, source and tool inputs, `native.op:trim_tool`, explicit surface/solid/curve tool and local keep point | +| 49402 | Ruled surface | `surface_edit`, two exact curve inputs, `native.op:ruled`, explicit second-curve reversal | +| 49403 | Loft | Ordered sketch/3D-curve/datum-point names, optional sketch/curve guides, existing loft controls and sampled guide checks | +| 49404 | Supported patch | Closed sketch or exact curve boundary, optional interior curve guides, individual G1/G2 boundary support forms | + +Include `surface_workflow_059c.inl` after the existing `surfaceEditDialog`. +Dispatch creation through `surfaceWorkflowAction059(id)` and intercept feature +editing with `surfaceWorkflowEdit059(feature)` before the previous type switch. +Both return whether they handled the action. IDs outside 49400–49404 remain +available to other modules. + +Include `surface_workflow_selftest_059c.inl` with the other Studio selftests and +route `--self-test-surface-workflow-ui` to +`surfaceWorkflowSelfTest059(hdc, shotPath)` in the initialized headless GL window. +The implementation uses the shared native editor, scroll container, accessible +field labels, keyboard handling and semantic selection controls. + +## Editing and exact authority + +Every form retains a copy of the original feature. Publishing updates name, +parameters, native recipe and the complete explicit input list together. Removed +optional parameters use `p_remove`; this is necessary because `feature.edit.p` +merges values. Loft section alignment and unchanged checkbox expressions survive +editing. New, duplicate, self or forward references are validated before publish +where appropriate, then the host and native worker validate the complete result. + +The mirror form reflects and joins a valid half-surface at its boundary seam; +it does not smooth the source to force G1. Trim retains the exact region selected +by the local keep point and relies on the native report for discarded regions. +Ruled rails remain explicit; reversing a rail is a user decision. + +Loft sections use names separated by semicolons. Native curve dependencies are +included explicitly. Point tips and guide compatibility remain subject to the +existing kernel contract. Optional guide samples are 2–129 per edge and the +sampled deviation limit remains within 1e-6–0.05 mm. Existing alignment recipes +are preserved; changing the section count while retaining incompatible alignment +is rejected rather than guessed. + +Patch boundaries use `p.sketch` or `native.boundary_curve`. Interior guide IDs +are stored as `native.guide_curves` and included in inputs; at most 16 distinct +guides are accepted. They constrain G0 interior geometry. Supported edges use +the existing `native.constraints` contract with an edge index, support feature, +current semantic face and continuity 1 or 2. Unconstrained edges remain G0. +The UI checks a unique bound reference in the support's current digest-bound +producer inventory; the host resolves the exact B-rep and topology. The user +does not supply B-rep data or a fabricated topology digest. Blend requires at +least two distinct support faces. Cancelling any support form publishes nothing. + +## Verification record + +The isolated native Studio compilation and full selftest passed **106 checks** +with the guide-capable native worker on 2026-10-23. The synthetic result contains +17 native features at document revision 20. The measured interior guide error +was `4.4408920985006262e-16` mm; the test requires at least 33 checkpoints and +an observed error no greater than 1e-6 mm. + +Verified scope: all five main-form cancellations, mirror area and source +retargeting, invalid/self-source rejection, surface and curve trims with analytic +areas, ruled area, loft with exact 3D sections and a lateral guide, retained +section alignment and checkbox expressions, optional parameter removal, +sketch-to-point loft, cancellation at the second patch step, native G1/G2 +supports, unknown support-face rejection, exact closed-wire patch, interior +G0 guides, combined G1 support and guide, sketch-to-curve boundary conversion, +duplicate guide rejection, actual concurrent-publication and document-epoch +rejection, GPU scene capture, and serialized document round trip with recompute. + +An earlier worker lacked `report.guide_curve_evidence`; the UI regression failed +at check 85 rather than counting its accepted but unverified guide input as a +success. Development also exposed the fixed native mirror tolerance, rejection +of a guide through the section centroid, and the need to read the actual +producer face name. The final fixtures respect those explicit contracts. + +Native dialog screenshots and the final GPU scene were inspected. Labels and +hints were shortened after initial captures exposed clipping, including the +shared editor's automatically appended picking hint. The semantic face field +retains horizontal scrolling for full digest-bound names. + +The integrated root Studio and native worker also passed the same 106 checks; +their receipt is `surface-workflow-ui.png.surface-workflow.json`. Captures use suffixes +`.mirror-form.png`, `.trim-form.png`, `.ruled-form.png`, `.loft-form.png`, +`.fill-form.png`, `.support-form.png`, `.guided-patch-form.png` and `.surfaces.png`. +The final native dialogs and GPU scene were visually inspected after integration. + +All fixtures are synthetic. Sampled continuity and guide errors are bounded local +checks, not proofs between samples, global continuity certification or production +qualification. No external CAD integration or manufacturing qualification is +claimed. No private document is part of the tests or delivery. diff --git a/docs/THIRD_PARTY_NOTICES.md b/docs/THIRD_PARTY_NOTICES.md index b9c9fb0..336c245 100644 --- a/docs/THIRD_PARTY_NOTICES.md +++ b/docs/THIRD_PARTY_NOTICES.md @@ -103,6 +103,22 @@ This dependency's license remains separate from ARK's Apache-2.0 license. - [Official pinned license](https://github.com/nothings/stb/blob/013ac3beddff3dbffafd5177e7972067cd2b5083/LICENSE) - Provenance and exact hashes: `third_party/stb/README.md`. +## Zstandard 1.5.7 + +ARK compresses the optional derived section of `.ark` containers (saved native +geometry and baked frames) with the Zstandard library, built from unmodified +upstream sources as a static single-threaded target without legacy formats. +Authoring is not compressed by it. + +Zstandard is dual-licensed under BSD or GPLv2; ARK uses the BSD alternative. +Both unchanged upstream files are retained in `third_party/zstd` and the BSD +license is packaged as `licenses/zstd-LICENSE.txt`. This dependency's license +remains separate from ARK's Apache-2.0 license. + +- [Official v1.5.7 release](https://github.com/facebook/zstd/releases/tag/v1.5.7) +- Archive SHA-256: `eb33e51f49a15e023950cd7825ca74a4a2b43db8354825ac24fc1b7ee09e6fa3`. +- Provenance and retained files: `third_party/zstd/README.md`. + ## Microsoft Windows and Visual C++ runtime Windows APIs and system fonts remain subject to their vendor terms. Studio uses diff --git a/docs/VIEWPORT_056C.md b/docs/VIEWPORT_056C.md new file mode 100644 index 0000000..774a1fd --- /dev/null +++ b/docs/VIEWPORT_056C.md @@ -0,0 +1,88 @@ +# 056C viewport quality and representation cache + +Milestones: **A.04** responsiveness and measured resource use; **B.01** CAD +viewport quality. Status: **Verificado no escopo** for the synthetic local checks +below. This display work does not qualify **C.04** motion, collisions or manufacture. + +The viewport now offers **Off**, **FXAA** and **FXAA high quality** in System +options / Graphics, with immediate application and persisted user settings. The +pass processes the model before UI labels/widgets and leaves CPU geometry and +selection references intact. The previous attempt to select MSAA by calling +`SetPixelFormat` a second time on the same window was removed: Windows permits +that call only once per window. There is no claim of hardware MSAA support from +these controls. [Microsoft pixel-format contract](https://learn.microsoft.com/en-us/windows/win32/opengl/pixel-format-functions). + +Contact shadow strength is independently adjustable from 0 to 1. A short +screen-space ray towards the studio key light adds local contact cues. The AO +filter now weights samples by world depth difference, surface normal and screen +distance, and rejects background samples. Existing Off/Contact/Ambient/Horizon +AO modes and radius/strength controls remain available. Shadows depend on visible +depth: geometry outside the view and hidden depth layers cannot cast these +shadows. Progressive path tracing retains its own illumination. These are display +cues, not geometric clearance evidence or a new physical light solver. + +GPU display vertices retain their original float32 XYZ positions and uint32 +index order. Unit normals use signed normalized 16-bit components: the vertex +stride is 20 bytes instead of 24. The original CPU meshes, B-reps, native face +spans and picking BVHs remain unchanged. OpenGL converts the normalized integer +attribute in the vertex fetch. [Khronos vertex attribute contract](https://wikis.khronos.org/opengl/Vertex_Specification). + +Immutable GPU meshes are shared by a SHA-256 identity of their display/source +content. Re-uploading the same content reuses the existing buffers; changes to +positions, indices or source normals invalidate that identity. Reference counts +keep an active resource alive across shared handles. Released resources remain +in an LRU cache up to 32 MiB of idle buffers; active resources are not evicted. +Unloading the scene purges idle resources. Existing unchanged-definition scene +reuse still avoids tessellation, packing and upload entirely. No display cache +is written into a document or used to infer exact geometry. + +## Local validation + +Windows, LLVM MinGW, verified patched OCCT 8 SDK, NVIDIA GeForce RTX 4070 Ti, +OpenGL 4.6 NVIDIA 610.88; synthetic author-owned geometry only. The dedicated +`studio-viewport-quality-ui` check ran at 1440 × 900 and the same fixture at +1180 × 800. Captures of the model and actual Graphics controls were inspected. + +| Measurement | Observed result | +| --- | --- | +| 1,024-vertex test vertex buffer, before / after | 24,576 / 20,480 bytes, queried from the GL buffer | +| Index buffer, unchanged | 23,064 bytes | +| Total vertex + index allocation in that fixture | 47,640 → 43,544 bytes (8.60% less) | +| Maximum packed unit-normal vector error | 0.000024518 | +| Packed vs float32 raster on the same exact assembly | maximum RGB8 channel difference 1 / 255 | +| Off vs FXAA changed pixels, 1440 × 900 | 19,055 | +| FXAA vs high quality changed pixels | 5,647 | +| Contact shadow on/off changed pixels | 3,417 | + +The check also verifies shared GPU handles, reuse after release, changed-source +invalidation, active-resource protection during eviction, idle eviction, unchanged +source/revision, zero uploads on an unchanged scene, and real native control +Apply/Cancel, invalid-value rejection and settings round-trip. CPU packing and +GPU upload byte counts are separate from total driver VRAM consumption. + +Existing `studio-scene-cache-ui`, `studio-render-ui`, `studio-selection-glow-ui` +and `studio-selection-picking-ui` passed. The first scene-cache regression run +correctly failed because idle buffers survived document unloading; the unload +purge was added and the original test then passed. The original failure log was +retained locally. An additional progressive-renderer check initially exposed an +empty measured crop with the expanded assistant dock; its isolated fixture now +closes the dock before framing, so the test samples the actual model viewport. +That progressive-renderer check subsequently passed, including hidden edges, +camera/projection/visibility reset, runtime path-tracing controls and unsupported +transparency fallback. On its 10,164-triangle fixture, the completed-frame median +was 2.542 ms and p95 3.661 ms; this is a local measurement, not a before/after +performance claim. The final minimum-size quality run also exited successfully +with no competing test instance. + +The receipt records 21 completed frames per AA mode using `drawFrame` followed by +`glFinish`. These small fixtures do not establish a general frame-rate gain: +driver clocks, warm-up, CPU UI drawing and other activity affect the samples. +The validated memory reduction applies to the same vertex/index payload; +large-project responsiveness and cross-GPU performance require separate matched +workloads. No private drawing or deployment qualification is included. + +Reproduce the dedicated test with `ctest -R '^studio-viewport-quality-ui$' +from a native Studio build with `ARK_TEST_STUDIO_LIVE=ON`. Its +`ui-checks/viewport-quality-ui.png.quality.json` receipt and adjacent PNGs contain +the actual measured values and captures. The minimum-size invocation is +`ark-studio --self-test-viewport-quality-ui --shot quality-minimum.png --size 1180 800`. diff --git a/docs/VIEW_CONTROLS_057B.md b/docs/VIEW_CONTROLS_057B.md new file mode 100644 index 0000000..847f5b4 --- /dev/null +++ b/docs/VIEW_CONTROLS_057B.md @@ -0,0 +1,82 @@ +# 057B — View cube and display controls + +Milestones: **B.01** (CAD viewport/navigation), **A.04** (observable validation). +Status: **Verificado no escopo** in the local Windows Release build. Native +input checks and synthetic-fixture captures were verified on an RTX 4070 Ti; +broader hardware and CAD milestones remain **Parcial**. + +The orientation cube now has broad square faces and a shallow chamfer, with the +same 26 retained picking surfaces (six faces, twelve edges, eight corners). +Words are projected onto their actual face planes, using the existing retained +Segoe UI font atlas. The contract remains +X Right, -X Left, +Y Top, -Y Bottom, ++Z Front and -Z Back. Camera roll also rolls the face labels. Neutral matte +surfaces, restrained contours and blue hover/selection replace the larger bevels +and amber highlight. Home has a vector house icon and retains fit/isometric view. + +One grouped viewport bar provides Shaded, Shaded with edges, Wireframe, planes, +sketches, grid, projection, Fit, selected-source drawing and More. Mode selection +is visible beside independent overlay toggles. The group title identifies the +current display style; hover explains each action. The bar uses the existing +OpenGL vector icon system and moves beside the Cartesian triad when space allows. +The cube leaves room for it in short viewports. The separate top-right style +dropdown is removed; More opens its existing settings and named-view menu. +The navigation toggle expands Orbit, Pan, Zoom and ambient occlusion as an +optional group in this same bar. Fit, edges and projection are not duplicated. +At constrained widths, direct styles and More remain; More explicitly includes +overlays, navigation, named views and selected-source drawing. A reference-mode +hint banner collapses only where it would cover the display bar; the ribbon's +selection mode and all selection behavior remain available. +Grid scale captions follow the same intersection rule. Contextual sheet/tube +and suspension playback uses a 44-pixel display bar with the same 32-pixel hit +targets and tooltips, omitting group captions so the full bar clears playback. +Descriptors and local hit-zone storage use fixed arrays rather than allocating +collections on each frame. This does not claim the complete draw path is free +of allocations or demonstrate a frame-time reduction. + +Explicit raster style selection turns off path tracing and saves the style. +Projection keeps its existing persisted preference. Display/navigation controls +and neutral toolbar padding preserve inertial playback. Opening a drawing remains +explicit and retains the selected part/container source contract. CAD geometry, +document revision, file format, mesh authority and production tolerances are +unchanged. + +## Observed validation and source review + +- `git diff --check`: passed for the integrated source. +- `studio-navigation-036a`: passed 208 real face/edge/corner clicks across four + physical sizes and two rolls, 48 cardinal text pixel checks, antialias coverage, + Home/orbit/padding and retained allocations. Independent camera-normal + agreement is checked for every clicked facet so a self-consistent but wrong + named view cannot pass. At 1180x800 and 1600x1000, actual style clicks passed + with Assistant and navigation controls both open, requiring a cube at least 96 pixels + across and disjoint control rectangles. A real occurrence of the public startup + fixture keeps Appearance, Opacity and Move visible; all three must remain + disjoint from the bar. Orbit/Pan/Zoom/AO passed through the same Win32 path. + Toolbar, cube and triad share placement geometry; wide, short viewports retain + readable face labels. +- `studio-viewport-dock-ui` and compact counterpart passed actual Win32 clicks for + all raster styles, projection, overlays and Fit; settings reload; neutral + padding; bounds and triad separation; selected part/container drawings, + explicit creation and Assistant layout. Each style and More hover were captured. +- Overview, cardinal/diagonal/hover, compact-layout and full viewport captures + were inspected. The compact controls and selected-style captures were also + independently reviewed by the viewport agent. + Native text is reused; no generated image asset or private drawing fixture is + introduced. +- The final source `eb1856e` passed 14 selected tests in 28.47 seconds, including + action icons, inertial UI, drawings, render and picking. An intermediate build + also passed asynchronous exact-work Cancel priority. Context and suspension + self-tests passed with the full display bar checked against the playback panel, + rather than only checking one navigation button. The test and capture receipts + are recorded in the [iteration evidence](iterations/057B.md). + +This change does not claim faster frame time: retained geometry/font/target +allocation assertions remain, and paint timings are receipts rather than a +before/after benchmark. Supersampling still uses the existing 3x target and +fallback; no graphics backend or hardware qualification is added. + +A preexisting limitation remains outside this change: at a 160-pixel-high +suspension viewport, its legacy full-width physical panel can intersect the cube +and Appearance panel. Source comparison confirmed the intersection on the 056C +base. The display bar now clears playback, but this is not a claim that every +legacy contextual panel has been redesigned or qualified at that height. diff --git a/docs/iterations/051A.md b/docs/iterations/051A.md new file mode 100644 index 0000000..380ea43 --- /dev/null +++ b/docs/iterations/051A.md @@ -0,0 +1,63 @@ +# 051A - project scale, responsive authoring and task outcomes + +Runtime 0.9.52 and iteration identity come from `release.json`. The principal +phase is **A**. Implementation status: **Verificado no escopo** locally. The broader milestones +**A.02/A.03/A.04/B.02/B.03/B.04/D.01/D.02** remain **Parcial**. + +## Implementation and acceptance + +| Scope | Milestones | Implemented behavior and contract | +|---|---|---| +| Explicit history compaction | A.02 | [history_compact](../HISTORY_COMPACTION_051A.md) verifies a complete new archive before replacing the active journal, retains bounded undo and selected branch states, and never overwrites archives. Capacity, stale revisions and archive failures reject atomically. | +| Part-scoped sketches | B.02/B.04 | [Definition ownership](../SCOPED_SKETCHES_051A.md), local names and explicit canonical references; shared occurrences reuse sketches. Each scope allows 256 sketches, with 4096 total and aggregate resource guards. Legacy global sketches remain valid. Studio, C ABI, context and component merge preserve ownership. | +| Background reconstruction | A.04 | [Private authoring preparation](../ASYNC_AUTHORING_051A.md) keeps orbit, zoom and body selection live for ordinary geometry-changing doc_apply. Progress, cancellation and native pool cancellation are available; publication checks revision, document epoch and original recipe. No-op prepared edits preserve journal/undo, and publication failures roll back. | +| Native offset and loft | A.03/B.03 | [Verified LLVM-MinGW SDK route](../NATIVE_GEOMETRY_051A.md) applies the existing frozen OCCT fixes. The same test binaries reproduce the two unpatched failures and pass with the patched SDK. Geometric oracles and tolerances are unchanged. | +| Agent task outcomes | D.01/D.02 | [Versioned benchmark cases](../AGENT_OUTCOMES_051A.md) cover parametric edits, assembly changes and atomic rejection/recovery. Completion, postconditions and real save/reopen are separate acceptance gates. Failed attempts remain in accounting; missing costs stay unknown. | + +Document format **50** is conditional on persisted ownership/compaction +semantics, independently of the application iteration. Ordinary legacy documents +do not change format just by opening/saving. There are **109** discoverable tools. +Synthetic fixtures are used throughout. User drawings and live Studio sessions +are preserved. + +## Verification + +LLVM-MinGW Release, with the frozen patched OCCT 8.0.1 SDK. The fresh native +configuration uses `ARK_ALLOW_UNPATCHED_OCCT=OFF`, empty C/C++ extra flags and +no external forced-include workaround. Application metadata reports 051A/0.9.52. + +- Core CTest: **109/109 passed**, including ownership/history integration, + async authoring, persistence, release identity, updates and agent contracts. +- Native CTest: **156/158 passed in the full run**. `authoring-extensions` and + `ota-updates` encountered filesystem access/publication failures in temporary + fixtures; **both passed on an isolated rerun**, with unchanged code and + assertions. All 158 test cases therefore have a passing result; the initial + failures remain in the full-run report. `native-solid` and `native-surface`, + which failed against the old unpatched SDK, passed in this integrated run. +- Native Studio: **8/8 selftests passed**: async authoring, history compaction, + tree, sketch dialogs, parametric HUD, async exact reads, feature-editor picking + and drag chains. Captures were inspected for the new ownership chooser, + 1025-sketch selection, live navigation/publication and archive controls. + The existing exact-read UI test also exercised concurrent writes and retained + revision labels; its cancel completed in 51.56 ms on this synthetic fixture. +- Outcome CLI: **3/3 native preflights and 9/9 offline attempts accepted and + persisted**, across Single/Focused/Parallel. Costs remain unknown for offline + transport; this does not establish live-model quality, speed or savings. + +The core suite was also run before final integration. Four environment-dependent +failures there were resolved by supplying CMake on PATH, an explicit workspace +temporary directory and Windows user DPAPI access for synthetic authentication +fixtures. The final core run above passed all 109 in one run. + +Local logs and receipts: `out/051a-core-tests-verified.{log,xml}`, +`out/051a-native-tests-verified.{log,xml}`, `out/051a-native-recheck.{log,xml}`, +`out/051a-ui-native/results.json` and `out/051a-outcomes.jsonl`. +The local executable is `out/051a-native/ark-studio.exe`; its SHA-256 is +`1a11b38e5534e23748a0b0f8258b519e7be44e0a2481b0bbb59ece11e1ef0339`. + +GitHub Actions, paid providers, packaging, installation and deployment were not +run. CPU work without an interruption point can still finish privately after +cancellation; other write operations keep their existing execution contracts. +Archive retention, native geometry and agent outcomes have the bounded domains +described in their contracts above. No manufacturing or general performance +qualification follows from these local fixtures. diff --git a/docs/iterations/052D.md b/docs/iterations/052D.md new file mode 100644 index 0000000..f514519 --- /dev/null +++ b/docs/iterations/052D.md @@ -0,0 +1,98 @@ +# 052D — isolated part agents + +Technical version: **0.9.53**. Milestones: **A.03/B.04/D.01/D.02/D.03**. +Implementation: **Verificado no escopo** locally. The broader milestones remain +**Parcial**; only the synthetic detail task below has live-model evidence. + +Focused Studio teams delegate existing part containers into real private +documents. Designers receive local context and read-only dependencies, retain +parametric expressions and submit frozen results. Lead review and atomic +integration require the original source revision, provenance and reviewed child +digest. No global prompt/image is automatically sent to part designers. + +The [workflow contract](../PART_AGENTS_052D.md) describes capabilities, current +container boundaries and the lack of automatic rebase or persistent task queues. +Parallel remains optional with its previous workflow. + +The benchmark adds actual scoped delegation, optional explicit designer models, +per-role measurements and a synthetic reused-part fixture. A separate neutral +mode gives Single and PartFocused identical user task text and records its hash; +the lead may decide to perform a small edit directly. Actual delegation remains +separately identified. Authentication is explicit, including the connected ARK +ChatGPT account without importing another application's credentials. + +## Local verification + +- Native CTest: release metadata, agent team, isolated parts and benchmark passed + **4/4** on the final runtime. Design-container contracts also passed. The + standalone part suite passed **349 assertions across five workflows**: accepted + integration, stale source, rejected acceptance condition, omitted optional + checks and wrong reviewed digest. All also exercise private context, immutable + shared parameters, frozen submission and persistence. +- Neutral benchmark regression proves identical task hashes, accepts valid + lead-only work and keeps `delegation_integrated` false for that result. +- Core release/team/part checks passed **3/3** before the final guard that clears + inherited guide/memory prefetch; that guard is covered by the final native run. +- Studio assistant selftest reached its success capture; model/effort controls + and the final UI capture were inspected. Tests used disposable synthetic + documents and settings. No user Studio session was replaced. +- Native PD01 reference preflight passed all six checks. Offline comparison + passed **9/9** across Single/Focused/PartFocused. The initial offline run had + three failed delegated attempts caused by an empty optional check array; + that defect was fixed and its regression is covered. Initial receipts remain + retained separately. + +## Live pilot: forced delegation + +2026-10-22, `gpt-6.1-sol`, `medium`, ARK ChatGPT-plan Responses route. Two +repetitions, alternating strategy order; the same synthetic baseline, model, +effort and geometric/persistence oracle. The task changes a reused part's depth +from 6 to 9 mm, preserves the `SharedWidth` expression and the other module. +PartFocused explicitly requires a private edit and lead integration. + +| Strategy | Accepted | Reported total tokens, both attempts | Median attempt time | +|---|---:|---:|---:| +| Single | 2/2 | 157,654 | 38.91 s | +| Forced PartFocused | 1/2 | at least 759,815 | 165.37 s | + +Both delegated attempts produced valid, integrated geometry that survived +save/reopen. The second was conservatively rejected as a completed outcome after +an HTTP 504 during lead completion. Its failed request has missing usage; it is +not zero-cost. Tool failures were 0/0 for Single and 3/5 for delegated attempts. +The first successful delegated trial alone used 384,259 tokens versus 85,234 for +its Single control. This small edit does not establish savings from delegation. + +Receipts: `out/052d-live-sol-medium.jsonl`, SHA-256 +`3a9225e76a980a1a9b0003d7a8f9750a5e60260b6e2bf69a129d98539f75eb89`. +Each attempt also records executable and case fingerprints and a retained +synthetic `.ark` artifact. No account billing amount was returned; monetary cost +remains unknown. These are local task results, not general CAD competence, +manufacturing qualification, distribution or production evidence. + +## Live pilot: neutral decision + +The separate neutral preset ran two repetitions with the same model, effort, +baseline, criteria and identical user-task hash in both strategies: +`9bac307ed2532094274d99f6d6af89c3ed44b08a7b92c7f470414953b528c2d9`. +The lead was free to choose delegation; no private-edit requirement was added. + +| Strategy | Accepted and reopened | Mean tokens per attempt | Mean attempt time | +|---|---:|---:|---:| +| Single | 2/2 | 72,630.5 | 35.19 s | +| Neutral PartFocused | 2/2 | 244,286 | 96.94 s | + +All four attempts had complete provider usage and zero tool failures. In both +team attempts, the engineer edited directly and used the reviewer; the designer +remained inactive. This measures the current team's coordination/review overhead, +not context savings from private part editing. The neutral team used **3.36x** +the reported tokens and **2.75x** the elapsed time of Single on this small edit. +Neither the neutral trial nor the forced trial supports a savings claim. + +Neutral receipts: `out/052d-live-neutral-sol-medium.jsonl`, SHA-256 +`d6a3c93f0829106da4806deb5bf5a35dfde20f807d696ca40c0ed2a625dfa5f8`. +The executable fingerprint was +`35f209aeb4bfa77ff2b1f3d0be539cde008061b1d1a7e99f23b40fc802dfda25`. +The two experiments used separately recorded builds; do not pool their results +as a single identical-build sample. Failed forced trials remain in their report. +Account billing is unknown. No Luna capability trial or large-assembly economic +claim is established. These few repetitions qualify this example only. diff --git a/docs/iterations/053B.md b/docs/iterations/053B.md new file mode 100644 index 0000000..6ad060b --- /dev/null +++ b/docs/iterations/053B.md @@ -0,0 +1,47 @@ +# 053B — reusable parametric components and graph navigation + +Technical version: **0.9.54**. Milestones: **A.02/A.03/B.01/B.04/E.01**. +Status: **Verificado no escopo** locally. The broader milestones remain **Parcial**. + +`.arkprt` and `.arktop` store authored reusable definitions with stable identity, +explicit revision chains and public parameter/datum interfaces. A project embeds +the selected revision and remaps its source into an independent namespace. +Updates use checked candidates, retain root placement and reject local divergence +or structural identity changes. Conditional semantic format 51 persists bindings; +the owned binary container and `.arkops` replay meaning remain unchanged. + +Neural Parametric View is a native modeless window over the local authored graph. +It connects geometry selection, parameter dependants, groups and embedded reuse. +Search, focus, folding, layout, pan and zoom do not issue model calls or edit the +document. The index's incomplete dependency coverage remains explicit. + +See the [contract and boundaries](../PARAMETRIC_COMPONENTS_053B.md). + +## Local verification — 2026-10-22 + +- Patched OCCT native build, Windows llvm-mingw: **94 component assertions** pass. + Evidence covers independently calculated B-rep volume, portable reopen without + the original file, expression/ID/owned-sketch remapping, preserved existing + output bodies, independent overrides and placements, explicit revision chains, + undo/redo, scoped checkout isolation, mate endpoints/expressions and solved pose. + Rejections cover invalid geometry, private overrides, local divergence, stale + candidates, overwritten files, tampered hashes and structural revision changes. +- **18 distinct selected CTest suites passed**: parametric components, context + graph, datum authoring, release metadata, binary container, history compaction, + iteration history, agent, profile regions, native graph UI, agent team, scoped + part agents, design containers, agent features, assembly manipulation and the + 023B/024B/029B authoring contracts. The first batch passed 12/13 and exposed an + obsolete 109-tool count. All six affected discovery suites passed after the + assertions were updated to the newly published 110-tool catalog. +- Native UI test passed export of both file types, insertion, configuration, + reviewed revision update, selection of the real 3D object, parameter dependants, + group folding, search, zoom, focus, revision refresh and cancelled forms. Source + authoring and revision stay unchanged during navigation. Final captures were + inspected at 1400×850 and 1080×680; fitted card text and controls remain readable. +- A synthetic bearing example retains a `.arkprt`, assembly revisions 1 and 2, + and a portable `.ark` project. It is generated in the isolated UI artifact + directory, never taken from a user's drawing. The existing Studio was preserved. + +This is local evidence; no hosted CI, distribution, token saving or manufacturing +qualification is claimed. Independently updateable nested library bindings and +structural revision reconciliation remain outside the delivered v1 contract. diff --git a/docs/iterations/054B.md b/docs/iterations/054B.md new file mode 100644 index 0000000..75d61dd --- /dev/null +++ b/docs/iterations/054B.md @@ -0,0 +1,74 @@ +# 054B — design families, editable electrical sheets and flexible cable playback + +Technical version: **0.9.55**. Milestones: **A.02/B.04/B.05/C.04/D.02**. +Status: **Verificado no escopo**, local verification; broader milestones remain +**Parcial**. + +The [054B contract](../DISCIPLINES_SCHEMATICS_054B.md) defines editable native +schematics with explicit pins/nets, sheet-specific BOM and DXF/SVG/CSV exports; +classification metadata and local Eye visibility filters; and native cable +preparation at baked poses. Conditional semantic format 52 preserves the new +metadata without changing the owned binary container. Three discovery tools +extend the catalog to 113. + +## Local evidence — 2026-10-22 + +- Windows llvm-mingw, patched native OCCT build: **23 distinct selected CTest + suites passed**. A final batch passed 22/22 in 74.49 seconds; the assistant + connector and discipline tests passed after the final onboarding correction. + Coverage includes release metadata, binary persistence, iteration history, + compaction, source containers, reusable components, agent/authoring contracts, + datum/profile geometry, rigid motion and clearance, drag chains, schematics, + agent tool discovery and four native UI suites. +- **518 discipline checks** cover scoped classification queries, inheritance, + explicit occurrence overrides, schema discovery, atomic rejections, stale + revisions, prepared publication, undo/redo, conditional format 52, sheet/net/BOM + reopen, BOM annotation exclusion, exclusive exports and DXF group-pair readback. + Readback checks declared layers, entity subclass markers, text style and known + wire endpoint coordinates after sheet-to-DXF Y conversion. +- **99 component assertions** include preservation of definition/group families + during `.arktop` reuse. Tags matching a parameter name remain metadata and do + not become expressions or geometric dependencies. +- Native Schematic Designer tests passed sheet creation, symbols, connections, + pins, linked CAD selection, a single-revision drag, cancelled forms, export, + family editing and Eye visibility. Captures were inspected at 1400×850 and + 1150×680, with the main ribbon at 1440×900. Native action icons and the existing + rigid motion UI passed. The synthetic electrical example is generated locally + with `.ark`, DXF, SVG and its own BOM CSV. +- A 25-link synthetic carrier with a moving prismatic carriage passed native + cable preparation at five recorded poses, lossless display-cache roundtrip, + duplicate-request reuse, cancellation, source neutrality, cable-edit staleness, + classification-neutral motion fingerprints and rejection of rigid clearance + scopes containing flexible cables. Studio tests inspect the two stroke ends + and verify that Stop restores both original mesh and source revision. Alternate + links are hidden locally in the captures to expose the cable inside the chain. + +### Long cable preparation measurement + +With `ARK_CABLE_LONG_TEST=1`, `ark-drag-chain-050b-tests` additionally prepares a +14-second synthetic motion at 30 fps: **421 frames**, **419 distinct native +requests**, **424.201 seconds** of initial preparation and **406235888 bytes** +(387.42 MiB) of retained display cache. Decoding the 421 cached frames took +**2708.89 ms** (6.43 ms/frame). This excludes GPU upload, BVH updates and rendering; +it is not evidence of achieved 30 fps playback. Local compilation/UI checks also +ran during parts of this single measurement, so it is not an isolated performance +benchmark. Preparation remains expensive and the cache is process-local. The +512 MiB cache cap was not reached. Fewer baked frames reduce preparation work. + +The test validates native sweeps at the sampled poses; it does not establish +constant cable length, mechanical strain, fatigue or continuous clearance. + +### Issues found and resolved + +Integration tests caught omitted metadata publication fields and loading a sheet +after history validation; both paths now retain complete authoring before the +history check. Discovery tests caught an omitted onboarding allowlist entry; +schematic guide loading and deferred tool activation now pass. Classification +lookup remains a core tool. An initial restriction on all stale playback was +narrowed to flexible cables, preserving the existing rigid-only inspection +contract. A native worker held open by the long test prevented an intermediate +relink; the completed final build ran after the test exited. + +Synthetic fixtures were used throughout; no user drawing was edited or included +in source artifacts. Hosted CI, external DXF recipient interoperability and +electrical/manufacturing qualification are not claimed. diff --git a/docs/iterations/055D.md b/docs/iterations/055D.md new file mode 100644 index 0000000..5a06aaa --- /dev/null +++ b/docs/iterations/055D.md @@ -0,0 +1,191 @@ +# 055D — limited task completion and stable rounded cable sweeps + +Technical version: **0.9.56**. Milestones: **A.02/B.04/C.04/D.02**. +Status: **Verificado no escopo**, local verification; broader milestones remain +**Parcial**. + +A completed cable edit or motion refresh could be withheld by the Single +assistant's global BOM gate because preexisting unrelated definitions lacked +internal part numbers or descriptions. An accepted specialist review did not +satisfy that gate; repeated finalization ended as an interrupted run. + +Studio now establishes a host-owned baseline before a Single task or a new Team +goal. `bom_inspect.task_scope` reports changed/new counted definitions and +removals. Coverage compares authored definitions, BOM rows, referenced materials, +occurrences/placements and evaluated geometry. Native B-rep hashes bind native +geometry; evaluation keys conservatively cover other evaluated dependencies. +Models cannot reset the baseline through a tool or narrow the coverage by passing +`ids`. Steering remains within the existing task boundary. + +For an explicitly limited user task, `bom_review` accepts `completion:"task"` +together with selected `ids`. The selection must cover every affected counted +definition, and the normal current-revision inspection, identity, scope, +pending-note and fastening rules still apply. The receipt is ephemeral and bound +to the current authoring digest. Later edits or another task invalidate it. +Single and Team append a host qualification that the global project/BOM remains +pending. Ordinary selected reviews and default project review retain their +previous authority. Do not downgrade a requested whole-project/detailed result. + +Removal of a counted definition, unavailable baseline or more than 64 affected +definitions conservatively requires project review. This mechanism governs BOM +finalization, not geometric acceptance or a proof that all user requirements were +met. It does not add electrical ratings, suppliers, materials, fasteners or other +unrequested metadata. No document-format change, dependency or agent turn/token +budget is introduced. + +Full-frame cable preparation also exposed a native rounded sweep failure at a +nearly straight waypoint (`BRepAdaptor_Curve::No geometry`). Rounded arcs now use +their known circle/plane directly. An explicitly configured pipe-shell builder +uses **1e-7 mm** geometric/boundary tolerance and **1e-7 rad** angular tolerance, +with a measured surface-error check before the existing B-rep/solid validation. +This replaces the convenience sweep builder's coarse defaults. No corner is +discarded, no obstacle/solid check is bypassed, and tolerances are not enlarged. +The electronics receipt reports the sweep tolerance and measured surface error. + +## Local verification — 2026-10-22 + +- Patched native OCCT / Windows LLVM-MinGW Release build succeeded. +- `ctest --test-dir out/055d-native --output-on-failure -R + '^(bom-completion|agent-workflow-033d|assistant-connector|agent-team|release-metadata|studio-assistant-ui|studio-assistant-steering-ui)$'` + passed **7/7** selected suites in **43.91 seconds**. +- The regression fixture contains a changed identified part beside an unchanged + unidentified part. Limited completion succeeds with explicit global-pending + qualification in Single and Team; global completion still rejects. Tests cover + missing host boundaries, ordinary specialist reviews, detailed metadata + rejection, omitted affected definitions, stale receipts, new task boundaries, + prepared publication, parameter dependants, deletion and reset. +- Existing specialist/global authority tests and assistant steering/UI fixtures + passed. This is selected local verification, not a full suite, hosted CI or a + live provider quality/cost comparison. +- A new synthetic rounded-cable regression reproduced the native exception + before the sweep correction. **20** cases (five shallow bend angles, both + directions, at the origin and translated) now verify a valid single solid, + analytic route length/volume and the explicit surface-error bound. Existing + electronics invalid-input/obstacle checks also pass. +- After the native correction, `electronics`, `drag-chain-050b`, + `studio-drag-chain-ui` and `release-metadata` passed **4/4 in 22.64 seconds**; + this brings coverage to **10 distinct selected suites**. Native UI captures + were inspected. Initial attempts that changed arc construction alone still + reproduced the sweep exception; explicit pipe-shell tolerances resolved it. + +Private live diagnostics are kept outside committed artifacts. Motion display +preparation retains the 054B display cache contract and gains the rounded-sweep +correction above. A pose edit can stale a bake and requires an explicit +revision-checked refresh before playback. Sampled poses do not qualify physical +cable fatigue or continuous flexible clearance. + +### BOM recovery and incremental metadata — A.02 / D.02 + +**Verificado no escopo** locally: an offline regression reproduced the generic BOM completion +exception even when the final reply explicitly requested a missing user input. +The recovery path now distinguishes input requests and repeated unchanged review +stops from completed work. Rejections carry current inspection and missing-field +evidence; task reviews can select their host-observed scope without manually +copying IDs, including an empty scope for display-only work. Global and detailed +review requirements remain enforced. + +`feature.edit part_patch` preserves omitted metadata, validates the merged record +and keeps revision checks, atomic publication and native geometry. Bare resume +requests preserve the current Single goal/BOM baseline. Visible qualifications +are concise; detailed review notes remain in receipts. See [BOM](../BOM.md). + +Local Windows/MSVC validation passed **13 distinct suites**: `bom-completion`, +`bom-contract`, `agent-workflow-033d`, `agent`, `agent-features`, +`assistant-connector`, `agent-team`, `release-metadata`, native +`studio-assistant-steering-ui`, `studio-assistant-ui`, both normal and compact +`studio-assistant-chat-ui`, and `studio-bom-ui`. The eight core suites passed in +23.03 s; the five native UI fixtures passed in 22.46 s. A strengthened completion +fixture then also passed with explicit checks for offered recovery tools and +Team diagnostics. The review-pending, compact pinned-goal and BOM table captures +were inspected. The initial input-request regression failed with the reported +BOM exception before the fix. + +Metadata tests verify retained fields, selected-source validation, atomic invalid +patch rejection, required revision, prepared publication, persistence and unchanged +native B-reps. Completion tests retain stale/detailed/global rejection and test +empty host task coverage, same-revision inspection progress, interrupted-task +baseline retention and concise qualification. Provider reasoning/quality is not +established by the scripted transports; no reduction in user failure rate is +claimed. Studio was linked as `ark-studio-bom.exe` to preserve the two running +instances. No public release, full-suite or hosted CI claim. + + +### Windows MSVC launch verification + +For A.02/B.04, a local Visual Studio 2022 build exposed a Windows SDK `small` +macro collision in the graph and schematic panels. Their font members were +renamed to `smallFont`, preserving UI behavior. Studio, CLI and the native worker +then built successfully. `release-metadata`, `studio-parametric-graph-ui` and +`studio-design-disciplines-ui` passed 3/3; the two overview captures were inspected. +The launcher started a responding 055D / 0.9.56 window. This is selected local +build and launch evidence, not full-suite or hosted CI qualification. + +### Readable agent conversation — A.02 / D.02 + +**Verificado no escopo** locally: the Assistant now uses native read-only, +selectable conversation bubbles, an 18 px body/composer, a pinned goal with +measured text height, explicit activity states, Copy chat, Latest and expanded +reading. Team settings remain available through Agents; Single run metrics are +available through Run info. Conversation history is retained for the open +document session and native controls are virtualized. See +[conversation behavior and limits](../ASSISTANT_CONVERSATION.md). + +Windows MSVC Release Studio built successfully. Ten selected CTest suites passed: +`release-metadata`, `studio-connectors-ui`, `studio-viewport-dock-ui` and its +compact variant, `studio-assistant-steering-ui` and its compact variant, +`studio-assistant-chat-ui` and its compact variant, `studio-assistant-ui`, and +`studio-media-044b-ui`. The final chat pair passed 2/2 in 0.98 s; the remaining +eight passed 8/8 in 28.70 s. Native conversation captures at 1440x900 and +1100x760, including expanded mode, were inspected. + +The first regression runs exposed hidden Team controls, compact viewport/card +layout conflicts and insufficient goal line height. These were corrected before +the passing runs. A hidden-child PrintWindow capture initially returned black; +the test now renders the actual native child controls and checks text layout. +Tests additionally cover long replies, more than 200 messages, native selection, +scroll retention, pinned goal, cancellation, interruption, explicit needs-input +and the distinction between an idle agent and declared completion. + +The media regression observed changing GIF frames, H.264 frames at two times, +three live playback colors and a paused clock while minimized. This is synthetic +local display evidence. Live window inspection additionally caught a native +header repaint issue after hidden-start document loading; explicit repainting +resolved it. The expanded conversation now starts below the ribbon. After those +final adjustments, the conversation and assistant integration self-tests passed +again against the final local executable. The last executable was linked under +the separate development name `ark-studio-chat.exe` because the earlier preview +was still open; no running window was forcibly closed. No hosted CI, full-suite, public package or manufacturing +qualification is claimed by this UI change. + +### Scroll repair and agent media authoring — A.02 / B.04 / D.02 / E.01 + +**Verificado no escopo** locally: scrolling moves RichEdit controls without +reusing old pixels and repaints all visible text children after the layout settles. +The regression exercises real WM_PAINT after mouse-wheel and scrollbar movement +with a long reply, and verifies that repainting preserves text selection. + +`image_asset` now discovers capabilities, generates PNG through an explicit +OpenAI Images API request, composes local PNG/GIF/MP4 layers, imports portable +generated media and controls a revision-bound Studio display preview. Its catalog +identity is unchanged. OpenAI key setup has a separate dialog that preserves the +assistant's model and ChatGPT login. Generation never grants geometry authority. +The local compositor uses an adaptive GIF palette, delta rectangles, explicit +resource limits, decode verification and exclusive output publication. See +[the media contract](../MEDIA_AUTHORING.md). + +The provider request/response path was verified with an offline transport fixture, +including invalid image rejection and preservation of an existing output without +another request. No live Images API success is claimed without a configured key. +Local generation produced and re-opened real 14-second GIF and H.264 files. The +live Studio fixture verified binding, play, pause, seek, stop, stale-revision +rejection, and atomic rejection of invalid bindings. GIF and LED appearance use +the same discrete baked clock; bindings remain session-local, and MP4 clock +synchronization and physical hardware triggering are explicitly excluded. + +Selected verification covered the conversation/UI suites above, `media-authoring`, +`assistant-connector`, `agent`, `agent-features`, `media-044b`, +`stamps-appearance-024b` and `authoring-024b-contract`. A legacy appearance test +incorrectly treated format 51 as unsupported although the serializer already +accepts 52; its rejection probe now uses a deliberately unsupported format number. +The actual document format was not changed. Public tests use synthetic images and +geometry; private drawings and generated demonstration assets remain excluded. diff --git a/docs/iterations/056C.md b/docs/iterations/056C.md new file mode 100644 index 0000000..64558be --- /dev/null +++ b/docs/iterations/056C.md @@ -0,0 +1,75 @@ +# 056C — inertial studies, viewport quality and reliable project workflows + +Technical version **0.9.57**, sourced from `release.json`. Milestones: +**A.02/A.04/A.05/B.01/B.04/C.04/D.02/E.01**. Status: **Verificado no escopo** for the +local integrated runtime, native contracts and Studio controls. Broader milestones +remain **Parcial**. + +## Implemented scope + +- [Inertial dynamics](../INERTIAL_SIMULATION_056C.md): revision-bound derived + rigid-body studies with hardware GPU integration/contact/joint solving and an + explicit CPU reference. Native CAD mass/inertia remains authoritative; + supported collision geometry is a validated convex display mesh. The + [Studio panel](../INERTIAL_UI_056C.md) exposes settings, occurrence loads, + background Run/Cancel and derived playback/reset through Inspect > Simulation. +- [Viewport](../VIEWPORT_056C.md): actual Off/FXAA/high-quality FXAA controls, + screen-space contact shadows, bilateral AO and shared GPU meshes with packed + normals. Exact geometry, source positions and picking identities are retained. +- [Project storage and commands](../PROJECT_SCALE_COMMANDS_056C.md): integrated + derived compression from PR #35 with transactional compaction and stronger + manifest checks; searchable parameterized command discovery and exact-tool + activation through existing onboarding and preview contracts. +- [BOM and public research](../BOM_RESEARCH_056C.md): supplier search-to-page + handoff, bounded product evidence, actionable per-part recovery and direct + exposure of sourcing tools in BOM workflows. + +The base includes PR #39 and its #36–#38 ancestry. The technical compression +change from #35 is integrated without its obsolete release identity. Public +release/OTA publication is separate from this local development runtime. + +## Evidence and limits + +Windows Release, LLVM-MinGW 23.1.3, patched OCCT 8.0.1, RTX 4070 Ti. Component +observations and initial failed attempts are in the linked contracts. + +- The integrated build completed. Of 165 non-Studio CTest suites, 162 passed + initially. Three discovery failures identified an omitted drawing-authorization + rule in command onboarding and two obsolete tool-count assertions. The rule + was restored; assertions now inspect actual tools, schemas and permissions. + All 11 affected/relevant suites then passed, including the three failures, + command discovery, assistant/tool layers, BOM, simulation and release evidence. +- The native inertial suite passes 60 checks across CPU reference and hardware + GPU, including analytic mechanics, momentum, peripheral support, inertia, + hinge drift, mesh reuse, invalid scopes and unchanged CAD. Fixed poses remain + exact rather than round-tripping through float32 display state. +- Actual Studio CPU/GPU studies passed at 1440x900 and 1180x800, including native + mass, occurrence loads, scheduling, playback and reset without authoring changes. + The minimum-size process exited 0. Captures of controls, evidence and model + display were inspected. This is local synthetic-fixture integration evidence. +- Nine of ten selected Studio regressions passed initially: scene cache, + inertial controls, viewport quality, selection glow/picking, render, action + icons, baked motions and exploded views. The additional background exact-read + test found a real hit-priority conflict: the floating dock intercepted the + visible Cancel button in a short viewport. The overlay now owns foreground + input and consumes background clicks within its card. All four follow-up + regressions passed: background exact reads, inertial controls, viewport dock + and drawing viewport (125.60 s total). The exact-read fixture retained live + navigation and source/revision checks and measured cancellation at 52.24 ms; + the original assertion and expanded assistant dock were preserved. + +Logs are local under `out/056c-*.log`; UI receipts/captures are under +`out/056c-native/ui-checks`. Initial failures remain recorded. The base runtime +055D/0.9.56 from PR #39 was built and opened during development. The integrated +056C runtime is local; no remote PR merge, installer or OTA publication is claimed. +The complete non-Studio run, targeted rechecks, nine initial passing UI checks, +four final UI checks and two actual engine/UI sizes are distinct observations; +the failed attempts are included rather than presented as one all-green run. + +No private drawing/session, generated demonstration media or credential is +included. There is no claim of general provider cost savings, superior design, +arbitrary project size, all-supplier access or manufacturing qualification. + +The document semantic version is unchanged by the application identity. The +optional derived container pack preserves the documented legacy-read/rebuild +contract. Zstandard's source provenance and license notices are included. diff --git a/docs/iterations/057B.md b/docs/iterations/057B.md new file mode 100644 index 0000000..24d0d6c --- /dev/null +++ b/docs/iterations/057B.md @@ -0,0 +1,87 @@ +# 057B — conversation layout and viewport controls + +Technical version **0.9.58**, sourced from `release.json`. Milestones: +**A.02/A.04/B.01/D.02**. Status: **Verificado no escopo** in the local Windows +native build, input checks and inspected synthetic-fixture captures. + +Follow-up: the reported blank conversation also occurs after messages arrive +while Studio is minimized. That lifecycle was absent from these checks; +[058A](058A.md) records its reproduction and correction. The results below are +historical evidence for the tested scope, not proof that this later case passed. + +## Scope + +The [conversation](../ASSISTANT_CONVERSATION.md) measures response height using +native text positions and font metrics. Latest lands on readable text, message +updates preserve selection and the reading anchor, and short split views retain +space for messages while the complete goal has its own scrollbar. Unchanged +frames no longer force a composer/header repaint. + +The [orientation cube and display bar](../VIEW_CONTROLS_057B.md) use larger square +faces, shallow chamfers, face-aligned labels and a restrained blue hover. A +single toolbar groups explicit raster modes, overlays, projection, Fit, +selected-source drawing and further display options. Home has its own icon. + +This iteration follows the locally integrated 056C runtime. Document geometry, +document format and agent completion/permission contracts are unchanged. The +validation uses synthetic fixtures, without user drawings or conversations. + +## Evidence + +Windows Release, LLVM-MinGW 23.1.3, patched OCCT 8.0.1, RTX 4070 Ti. + +- The existing 056C conversation self-test passed. A strengthened test then + reproduced a failure before the correction: Latest placed the final line of + an 18,000-character response at y=-14, above the visible message page. The + capture confirmed clipped text; retaining the full string was insufficient. +- After the correction, the new regression passed, including actual window + pixels after 12 OpenGL swaps and the native message loop. Inspection confirmed + visible final text and all four conversation actions. A capture taken before + pumping native paint messages showed blank buttons; the live regression now + dispatches those messages and checks both labels and backgrounds. +- Six integrated suites passed initially: camera contracts, cube navigation, + normal/compact display bar and normal/compact conversation. Conversation checks + include 1100/1180/1440/3556-wide layouts, selection during updates to current, + earlier and later messages, more than 200 messages, goal scrolling, Latest, + expanded view and Team states. Release metadata and evidence suites also pass. +- Navigation currently passes 208 face/edge/corner click-and-roll checks and 48 + cardinal label pixel checks. Geometry/font allocation remains retained; these + are scoped observations, not a before/after speed claim. +- Source and capture review identified a further compact-layout issue: the cube + became too small and the display bar could disappear with compact navigation + and Assistant open. Shared placement retains a readable cube, combines the + optional navigation controls into the display bar and keeps Appearance, + Opacity and Move clear. Face hints and grid captions yield where they would + cover that bar. Final captures at 1180x800 and 1600x1000 confirm readable labels + and disjoint cube, display bar and contextual controls. +- An intermediate integrated runtime passed 11 Studio suites (138.77 seconds): + navigation, asynchronous exact-work cancellation, inertial UI, normal/compact + display bar and conversation, drawings, picking, render and action icons. + Context and suspension self-tests also exited 0; their captures exposed an + existing weakness in the old checks, which compared buttons rather than full + panels. The final checks now include the entire bar/playback intersection. + The scoped remaining legacy suspension-panel limitation is recorded in the + [view-controls contract](../VIEW_CONTROLS_057B.md). +- The final runtime source `eb1856e` passed 14 selected checks in 28.47 seconds: + release metadata, camera, navigation, inertial UI, normal/compact display bar, + context, suspension, normal/compact conversation, drawings, picking, rendering + and action icons. The final build succeeded and `git diff --check` passed. + Conversation captures show the actual final response text and native controls; + cube, style and compact-layout captures were inspected by both implementing + agents. These are local synthetic-fixture results, not provider-session or + hardware-independent qualification. +- The local executable was opened on 2026-10-23 as **ARK 057B**, version + **0.9.58**, and reported a responding window. No installer or OTA publication + was performed. Runtime SHA-256: + `92f998d18b3adce13da1d50ab13d4bfe0cd82a129c6b257a6bad85d87461dc36`. + +Build logs and synthetic captures are local under `out/057b-native/ui-checks` +and `out/057b-*.log`. The baseline failure is retained in +`out/057b-chat-baseline.log`; initial integrated results are in +`out/057b-integrated-ui-first.log`. Final results are in +`out/057b-ui-final.log`; the final build is recorded in +`out/057b-build-controls-final.log`. + +Local runtime delivery is separate from installer/OTA publication. Broader +milestones remain **Parcial**; this work does not claim general project-size, +provider reliability or hardware-independent graphics qualification. diff --git a/docs/iterations/058A.md b/docs/iterations/058A.md new file mode 100644 index 0000000..cdb7db0 --- /dev/null +++ b/docs/iterations/058A.md @@ -0,0 +1,76 @@ +# 058A — conversation layout after background progress + +Technical version **0.9.59**, sourced from `release.json`. Milestones: +**A.02/A.04/D.02**. Status: **Verificado no escopo** in the local Windows +native build and inspected synthetic-fixture captures. + +## Problem and scope + +The 057B checks did not cover messages arriving while Studio was minimized. +Read-only inspection of the reported running 057B window found a response with +approximately 2,000 characters and 30 native display lines in a roughly +29,000-pixel-high child window (coordinates observed from a DPI-virtualized +probe). No private message text or drawing was collected into the fixture. + +A standalone synthetic RichEdit probe reproduced the mechanism: while its root +window was minimized, resizing a newly populated 1-pixel control to 972 pixels +left 1,890 cached lines and a final-line position of 47,225. Restoring the window +can reflow the text without invalidating the application's cached bubble height. +`EM_REQUESTRESIZE` alone did not correct this in the probe. Setting the target +device back to the current screen width with `EM_SETTARGETDEVICE(NULL, 0)` did: +18 display lines and a final-line position of 425 for the same text and width. + +The fix explicitly refreshes screen-width wrapping before reading native line +positions. It retains selectable text, complete message contents, native font +metrics and the outer conversation's reading anchor. This changes presentation, +not agent requests, execution, completion, document format or geometry. +When chat takes the whole workspace, the cube, triad, motion, appearance and grid +controls from the collapsed viewport no longer paint over its Single/Team row. + +## Verification + +The native conversation regression adds actual minimize/background-message/ +restore transitions and compares the cached bubble height with the rendered +text. Existing selection, long-message, Unicode, goal, compact/wide and live +OpenGL/native-paint checks remain required. Tests use synthetic conversations +and separate settings, preserving the user's running session. + +The strengthened Studio test reproduced the failure before the fix: a synthetic +2,188-character reply retained a cached height of **47,833** although its actual +19-line text measured **483**. Check 844 failed and the capture showed the blank +bubble. This failed attempt is retained in `out/058a-chat-baseline.log` and +`out/058a-chat-background-before.png`. + +The existing 057B session was repaired without restarting it: a temporary narrow +window placement forced fresh measurement, then its original maximized placement +was restored. A second read-only bounds inspection found the same response's +native child at approximately **505** rather than **29,089** pixels high, with +the same character/line counts. This was a temporary layout recovery, not an +in-place binary upgrade; the minimized-window fix requires the new runtime. + +The corrected runtime passed **12/12** selected suites in **34.00 seconds**: +release metadata/evidence, navigation, inertial UI, context, suspension, +normal/compact display bar, normal/compact assistant steering and normal/compact +conversation. `git diff --check` also passed. The build used Windows Release, +LLVM-MinGW 23.1.3, patched OCCT and an RTX 4070 Ti. + +The background reply measured **483 cached / 483 actual** in the normal fixture +and **508 / 508** in the compact fixture. Three subsequent minimized updates +retained the same text control and selection. Both live captures found **700** +light glyph pixels in the final-line region after OpenGL swaps and native paint +dispatch. The before/fixed/live/expanded captures were inspected; the fixed +captures show the response end rather than an oversized blank tail. Expanded +chat also passes the assertion that cube/Home/appearance targets are absent. +Existing long reply, Unicode, reading-anchor, goal and Team checks passed. + +Receipts are local in `out/058a-final-tests.log`, +`out/058a-native/Testing/Temporary/LastTest.log`, `out/058a-fixed-build.log` and +`out/058a-native/ui-checks`. These are synthetic lifecycle tests and a read-only +inspection plus layout recovery of the reported session, not general provider, +all-monitor-DPI or every chat-session qualification. Broader milestones remain +**Parcial**. No private drawing or conversation was added to the repository. + +The local **ARK 058A / 0.9.59** runtime was opened on 2026-10-23 and reported a +responding window; the older running session was retained. No installer or OTA +publication was performed. Runtime SHA-256: +`cb2f4ca06637c6bd18654174851a33c5069b7449f14037d96772100bba1ae0ee`. diff --git a/docs/iterations/059C.md b/docs/iterations/059C.md new file mode 100644 index 0000000..31726d7 --- /dev/null +++ b/docs/iterations/059C.md @@ -0,0 +1,194 @@ +# 059C — rubber dynamics, exact surfacing and background GPU inspection + +Technical version **0.9.60**, sourced from `release.json`. Milestones +**A.02/A.04/B.01/B.03/B.04/C.04/D.02**. Status: **Verificado no escopo**, locally +on Windows with the native worker. Broader surfacing and engineering milestones +remain **Parcial**; this is not a published installer or OTA qualification. + +## Implementation scope + +- Exact editable `native_solid` operation `rubber_body`: belt/track racetrack, + elliptical tire and solid/hollow ball. Numeric expressions remain authored + parameters. Optional bounded exact relief fuses reusable motifs and rejects + invalid/disconnected results atomically. +- Indexed procedural placement on cylinder, torus, sphere and racetrack, + including circular, helical, chevron, braided and spherical distributions. + Dense visual pebble/traction/chevron detail is distinct from exact geometry. +- Derived XPBD surface network, CPU reference and hardware D3D11 compute, + ground/pulley contact, friction, explicit anchors and material inputs. + Native CAD supplies total volume/mass. Link stiffness is a reduced model; + it is not a calibrated continuum rubber or tire handling law. +- Agent `rubber_plan`, lazy rubber onboarding and parameterized command recipe. +- Native body click followed by Tab/Shift+Tab cycles exact canonical faces of + the same occurrence while preserving editing/text-control precedence. +- GPU viewport snapshots use an owned framebuffer and the shared scene renderer, + including bloom, occlusion and antialiasing, while Studio is minimized or the + chat covers the viewport. Capture does not show, move or resize the window. +- Associative half-surface mirror with G0/G1 seam evidence; trim by a bounded + surface, solid or exact open 3D wire with an explicit retained-region point; + ruled surfaces between two exact single-edge rails; closed 3D-wire fills. +- Exact BSpline control-net inspection, bounded pole displacement and nearby + exact vertex candidates for corner/tangent glue. Source/target hashes remain + guarded; no sampled mesh positions become production geometry. +- Native forms expose surface workflows and control-net manipulation. Guided + patch fill measures its internal guide error and G1/G2 support conditions. + Reference cutters, glue targets and tangent-support bodies remain separate + visible outputs; they are not consumed as if sewn into the new surface. + +## Acceptance and limits + +Verify analytic native volumes, invalid-input rejection and atomic rollback, +recipe persistence, deterministic frames and bounded pattern paging, material +and mass authority, CPU/GPU solver agreement, anchors/contact/friction, +revision/cancellation guards, and inspect actual native UI captures. + +No pressure/volume conservation, self-contact, fatigue, thermal coupling, +calibrated tire contact or manufacturing qualification is claimed. Runtime +comparisons below apply only to their identical synthetic workloads. No change +to the `.ark` document version is required by the release identity. + +Surface mirror checks continuity at the symmetry seam; it does not automatically +fair the input half. Trim retains one explicitly selected connected region and +accounts for removed regions. The cutter is finite. Pole edits preserve the +existing exact BSpline basis and reject unsupported trimmed, holed, closed, +periodic or solid inputs. Corner/tangent glue is not full-edge G1/G2 sewing. +Loft's internal continuity setting does not establish end-support tangency. + +## Observed local evidence + +- Patched OCCT native build, Windows, NVIDIA RTX 4070 Ti. No user drawing is used + in the synthetic fixtures or included in this iteration's commits. +- Indexed pattern suite: 156,299 mathematical/contract checks, including a + million-placement recipe with constant allocation and allocation-free indexed + frame lookup. These are placement checks, not a million-solid benchmark. +- Rubber solver: 119 checks, CPU/GPU agreement, explicit anchors, contact, + friction and link forces. For the same 256-node/930-link, 0.2 s study, measured + CPU time was 3.24 ms and GPU time 14.38 ms; cached GPU run 13.86 ms. Maximum + sampled difference was 4.12 micrometres. The second GPU run uploaded zero link + bytes from the 29,760-byte constraint cache. GPU was slower for this workload. + The separate integrated ball fixture (130 nodes, 720 links, 23 colours, + 48 steps, 8 iterations) measured CPU 3.04 ms and GPU 245.37 ms, with 9,312 + dispatches. These different fixtures must not be compared as a speedup. +- Native rubber authoring/preview/apply/persistence checks passed, as did the + Rubber UI and real CPU/GPU engine UI tests. Creation, study and derived-frame + captures were inspected. UI transport adversaries separately exercise stale + revisions/epochs, cancellation, late callbacks and malformed frame payloads. +- Offscreen capture: 32 checks; hidden, minimized and expanded-chat captures + produced identical pixels in the fixed fixture. Bloom changed 19,717 pixels. + Window/camera/layout/document and framebuffer state were preserved, including + a write failure after rendering. The GPU capture was visually inspected. +- Surfacing native tests passed 112 checks for mirror, cutter types, exact ruled + rails, closed-wire fills and guided patches. Exact spline deformation passed + 63 native checks. Integration also passed source edits, dependency + regeneration, save/reopen/recompute and atomic rejection. Integrated surface + workflow UI passed 106 checks; the control-net UI passed 79 checks, including + real pointer drag, numeric fields, explicit Apply/Undo/Cancel, hitpoint choice, + target preservation and stale rejection. Dialogs, previews and applied results + were visually inspected. Host surface-control passed 38 checks and the + authoring/persistence workflow passed 44 checks. +- Media patterns, face cycling, native surface repair, direct authoring, + viewport quality and assistant chat regressions passed. Actual pebble pattern + and rubber-study captures were inspected. +- Failures retained in the development record: Windows `near` macro collided + with native test helper names; JSON object-order comparison was corrected to + compare canonical objects. Stock-preview face rejection initially reported + visibility before preview mode. Sketch edit also failed on 058A because Fit + placed an anchor behind the toolbar; the fit now reserves its actual height, + and the sketch-edit, viewport-dock and viewport-quality regressions now pass. +- The final runtime passed 14 selected integration suites: release identity, + rubber solver/authoring/UI/engine, inertial solver, both surfacing UIs, + offscreen capture, viewport quality/dock, chat, picking and sketch editing. + Four further host suites passed: surface controls/workflow and BOM + completion/contract. These are selected tests, not a claim that every test in + the repository ran. The synthetic benchmark executable also completed with + the same scalar digest and maximum CPU/GPU difference of 0.295482 micrometres. +- A separate support-visibility suite passed 38 checks: an adjacent G1 support + and its patch both retain visible rendered pixels, unchanged support B-rep, + dependency-order independence and save/reopen/recompute. Its headless + software capture was inspected; it is not additional GPU evidence. +- Studio 059C / 0.9.60 was launched locally and its window responded. Binary + SHA-256: `b4354f6820f14d0831cfca085142fa4e70d8f0999808c8b9a8df2ee3e8219fa9`. + Existing sessions were preserved; no installer or OTA publication occurred. + +## Measured GPU binding optimization + +The same 130-node, 720-link, 23-colour, 48-step, 8-iteration fixture was run in +five alternating baseline/candidate pairs on the RTX 4070 Ti: five cold and +15 warm measurements per version. All 40 GPU runs succeeded, with byte-identical +scalar positions, velocities and link forces. The baseline kernel is +`cc0b44f93ff231a36b357fee8f051f560d38c405`; the candidate uses the optimization +in `5b63793` (the measured executable precedes a field-only reserved-name rename). + +| Transfer-inclusive time, ms | Baseline min / median / max | Candidate min / median / max | +|---|---|---| +| Cold, initialization included | 287.10 / 306.72 / 344.22 | 286.00 / 301.44 / 358.46 | +| Warm, device and constraints reused | 27.76 / 31.06 / 36.18 | 22.06 / 24.34 / 28.91 | + +Warm median time decreased 21.6% in this fixture. Cold ranges overlap; no cold +gain is established. CPU reference remained approximately 2.5 ms and faster. +Dispatch count stayed at 9,312; per-step constant updates fell from 9,312 to 48, +with immutable colour constants and bindings reused across a frame. This does +not claim a general GPU-over-CPU speedup or change solver accuracy. + +The opt-in target `ark-rubber-runtime-059c-benchmark` builds +`benchmarks/rubber_runtime_059c.cpp`. The comparison artifact SHA-256 is +`bc5a6527253c3e9b1dd50af33b0a6b99854dec9c5be684d92dd0806ef0412826`; +the scalar result digest is +`6a8e4fcd8903abd57cffd3516ddcaceb09996276fa6ea1fc8fde13e1ba461eed`. +The final integrated executable separately reproduced that digest in all four +GPU runs, with cold 324.80 ms and warm 23.51–27.37 ms. + +Retained preparation failures: one launch lacked runtime DLLs in PATH; one +preliminary process (four GPU runs) could not establish digest equivalence +because raw Vec3 padding was included. Hashing scalar values fixed the method +before the alternating series. A bindings-only trial gave a small, inconclusive +difference; the constant-upload change produced the comparison above. + +Studio must remain running and connected for GPU snapshots. Named/custom views +still use their separate software path; this work does not make a disconnected +application available or remove the existing Visualize export UI restrictions. + +## Local audit-history correction (2026-10-25) + +**A.02 / D.02 — verified in scope.** A BOM review note of at least 1,024 +bytes could make subsequent previews, edits and saves fail: persistence tried +to resolve audit strings through the CAD history blob dictionary even though +audit records are deliberately excluded from CAD iteration authoring. The +Studio queue then replaced the exception with a misleading cancellation reply. + +Persistence now retains `agent_activity` and `usage` inline, without truncating +them or changing CAD history. Authored large payloads still require their +journal blobs; document capacity, history hashes and revision guards remain. +Previously packed audit strings remain readable. The Studio tool-dispatch +exception boundary returns `STUDIO_TOOL_FAILED`, the original diagnostic and +the observed revision, without asserting that execution never started or that +the document is unchanged. Genuine queued cancellation keeps its own response. + +The synthetic regression first failed with the original unjournaled-payload +exception. After the correction, iteration-history, reactivity-activity, +async-authoring-051a, document-container, history-compaction-051a, +feature-history-authoring and recovery-protection passed. The Studio +`--self-test-async-authoring-ui` also passed, exercising actual queued exception +and cancellation paths. Coverage includes exact long-note retention, +preview/prepared apply, undo/redo, JSON and binary reopen, legacy packed-audit +reads, and rejection of unjournaled large CAD payloads. This is local evidence; +no hosted CI, installer, OTA publication or full-suite result is claimed. + +## Technical sources + +- [XPBD paper](https://matthias-research.github.io/pages/publications/XPBD.pdf): + compliant position constraints and their relationship to energy. +- [Project Chrono tire models](https://api.projectchrono.org/development/wheeled_tire.html): + distinguishes rigid, handling and deformable tire model scopes. ARK does not + claim a Chrono integration or implement its calibrated tire models here. +- [GPU Gems procedural terrain](https://developer.nvidia.com/gpugems/gpugems3/part-i-geometry/chapter-1-generating-complex-procedural-terrains-using-gpu): + procedural surface detail and triplanar texture blending as rendering techniques. + +- [OCCT BSpline surface controls](https://occt3d.com/dev/doc/refman/html/class_geom___b_spline_surface.html): + exact pole/weight editing within an existing spline basis. +- [OCCT constrained filling](https://occt3d.com/dev/doc/refman/html/class_b_rep_offset_a_p_i___make_filling.html): + boundary support and internal curve constraints; ARK additionally checks its + result and rejects unmet declared tolerances. + +The pattern combinations are ARK options, not a claim of scientific novelty or +state-of-the-art superiority. diff --git a/include/ark/agent.hpp b/include/ark/agent.hpp index 80b266e..781e1ef 100644 --- a/include/ark/agent.hpp +++ b/include/ark/agent.hpp @@ -5,6 +5,7 @@ #include "ark/failure_record.hpp" #include #include +#include namespace ark { struct Image; bool metadataOnlyApply(const Document&,const arkjson::Value& args); @@ -41,9 +42,12 @@ class AgentSession { arkjson::Value call(const std::string& tool,const arkjson::Value& args); arkjson::Value info() const; arkjson::Value reviewBom(const arkjson::Value& args); - arkjson::Value bomCompletionCheck(bool onlyIfAuthored=false) const; + arkjson::Value bomCompletionCheck(bool onlyIfAuthored=false,bool allowTaskReview=false) const; + // Host-owned boundary, never resettable through an agent tool. + void beginBomTask(bool continuation=false); + arkjson::Value bomTaskScope() const; void markBomAuthored(){bomAuthored_=true;} - void resetBomReview(){bomAuthored_=false;bomReview_={};bomInspectedHash_.clear();bomInspectedItems_.clear();bomInspectedRevision_=~u64(0);} + void resetBomReview(){bomAuthored_=false;bomReview_={};bomTaskReview_={};bomTaskActive_=false;bomTaskBaseline_.clear();bomTaskError_.clear();bomInspectedHash_.clear();bomInspectedItems_.clear();bomInspectedRevision_=~u64(0);} void observeBomInspection(const arkjson::Value& bom); static arkjson::Value tools(bool detailed=false); arkjson::Value preparePreview(const arkjson::Value& args); @@ -53,6 +57,9 @@ class AgentSession { arkjson::Value snapshotCandidate(const arkjson::Value& args); std::unique_ptr takePreparedCandidate(const std::string& id); void adoptPreparedCandidate(PreparedTransfer&&, u64 expectedRevision); + // Host-only completion: run the original request through normal transaction, + // history and failure guards while dispatch consumes a private worker receipt. + arkjson::Value completePreparedApply(const arkjson::Value& originalArgs,std::unique_ptr transfer,const arkjson::Value& rejection={}); arkjson::Value failureInfo(const arkjson::Value& args) const; arkjson::Value failureExport(const arkjson::Value& args) const; arkjson::Value failureReplay(const arkjson::Value& args); @@ -62,6 +69,10 @@ class AgentSession { private: bool bomAuthored_=false; arkjson::Value bomReview_; + arkjson::Value bomTaskReview_; + bool bomTaskActive_=false; + std::map bomTaskBaseline_; + std::string bomTaskError_; std::string bomInspectedHash_; u64 bomInspectedRevision_=~u64(0); std::set bomInspectedItems_; @@ -74,6 +85,8 @@ class AgentSession { std::vector failures_; arkjson::Value captureFailure(const std::string&,const arkjson::Value&,const arkjson::Value&,const std::string&,u64,arkjson::Value); size_t callDepth_=0; + std::string hostPreparedApplyId_; + arkjson::Value hostPreparedApplyRejection_; struct Prepared { std::string id, baseline; u64 revision=0; diff --git a/include/ark/agent_benchmark.hpp b/include/ark/agent_benchmark.hpp index e23c384..3313d59 100644 --- a/include/ark/agent_benchmark.hpp +++ b/include/ark/agent_benchmark.hpp @@ -11,6 +11,8 @@ struct AgentBenchmarkCase { arkjson::Value baseline=arkjson::Value::makeArr(); arkjson::Value reference=arkjson::Value::makeArr(); arkjson::Value checks=arkjson::Value::makeArr(); + arkjson::Value rejectedCommands=arkjson::Value::makeArr(); + arkjson::Value partContainer; // Explicit synthetic existing container for delegated trials. }; struct AgentBenchmarkSuite { std::string id; @@ -19,11 +21,21 @@ struct AgentBenchmarkSuite { }; struct AgentBenchmarkConfig { AssistantConfig assistant; + AssistantConfig specialistAssistant; // Explicit optional role model; otherwise inherit assistant. + bool hasSpecialistAssistant=false; + bool requirePartDelegation=true; // False: identical user task; lead chooses whether to delegate. unsigned repetitions=3,deadlineSeconds=120; std::vector strategies={"Single","Focused","Parallel"}; std::vector caseIds; + std::string artifactDirectory; // Empty uses a unique temporary directory per attempt. + arkjson::Value tariff; // Explicit flat input/output estimate with provenance, never inferred. + std::function offlineBeforeReopen; // Persistence fault injection; forbidden live. AssistantTransport offlineTransport; // Test seam only; --live rejects it. }; +// Pure accounting seam: only complete live usage under the supplied tariff is estimable. +arkjson::Value estimateAgentBenchmarkCost(const arkjson::Value& tariff, const AssistantConfig&, + const AssistantUsage&, const AssistantPerformance&, bool live); +arkjson::Value summarizeAgentBenchmarkAttempts(const arkjson::Value& attempts); AgentBenchmarkSuite parseAgentBenchmarkSuite(const arkjson::Value& value); AgentBenchmarkConfig parseAgentBenchmarkConfig(const arkjson::Value& value); // Evaluates every supplied baseline and reference with the production C++ CAD diff --git a/include/ark/agent_team.hpp b/include/ark/agent_team.hpp index 50e0f8e..9ac1c15 100644 --- a/include/ark/agent_team.hpp +++ b/include/ark/agent_team.hpp @@ -22,6 +22,9 @@ struct AgentTeamConfig { unsigned maxWorkers=8, maxTurnsPerRole=0; // Zero means no turn budget. bool orchestratedStart=false; // Specialists await explicit assignments. bool focusedWorkflow=false; // One conversation at a time; the lead starts and delegates specific tasks. + // Focused part designers receive isolated design-container workspaces and + // only the lead can review/publish their results into the source document. + bool isolatePartDesigners=false; bool requireLeadAuthoringCheckpoint=false; // Parallel empty-document startup: defer other writers until the lead commits a sketch/feature. // Strict 038D/041D contract: any retained failed read also blocks completion // until its exact recovery. Off while agents stabilize: failed reads stay @@ -66,6 +69,8 @@ struct AgentTeamRoleSnapshot { bool canWrite=false; unsigned turns=0; std::uint64_t stepsApplied=0; + std::string partTask,partState; + std::uint64_t privateStepsApplied=0; // Private revisions, never source commits. bool needsInspection=false; unsigned unresolvedToolErrors=0; // Opt-in bounded diagnostics; never a CAD/prompt/provider-history payload. diff --git a/include/ark/api.h b/include/ark/api.h index b90a625..deba62a 100644 --- a/include/ark/api.h +++ b/include/ark/api.h @@ -63,6 +63,11 @@ int ark_feature_set_param(ArkDoc*, uint64_t id, const char* key, const char * ark_sketch_json returns malloc'd UTF-8 (free via ark_free) or nullptr. */ int ark_sketch_set (ArkDoc*, const char* name, const char* entitiesJson, const char* constraintsJson /*may be null*/); +/* Explicit shared-definition scope; ownerFeature=0 retains the legacy global + * contract. Other sketch APIs accept part:::. Errors: -1 invalid + * arguments, -2 malformed sketch JSON, -3 owner/name/capacity rejection. */ +int ark_sketch_set_owned(ArkDoc*, uint64_t ownerFeature, const char* localName, + const char* entitiesJson, const char* constraintsJson); char* ark_sketch_json(ArkDoc*, const char* name); int ark_sketch_remove(ArkDoc*, const char* name); diff --git a/include/ark/assembly.hpp b/include/ark/assembly.hpp index aac0606..188c41d 100644 --- a/include/ark/assembly.hpp +++ b/include/ark/assembly.hpp @@ -20,6 +20,7 @@ struct AssemblyNode { bool visible=true; bool fixed=false; // Grounded instance; its authored placement is retained by the mate solver. AssemblyPattern pattern; + arkjson::Value classification; // explicit occurrence/group families and tags }; struct AssemblyJointLimits { bool enabled=false; diff --git a/include/ark/async_authoring.hpp b/include/ark/async_authoring.hpp new file mode 100644 index 0000000..b596150 --- /dev/null +++ b/include/ark/async_authoring.hpp @@ -0,0 +1,31 @@ +#pragma once +#include "ark/agent.hpp" +#include +#include +#include +#include +#include +#include +namespace ark { +// Host captures and publishes under its session serialization. Evaluation owns +// only a private snapshot; no host document, UI or GL access is permitted. +class AsyncAuthoringWorker { +public: + struct Progress {u64 job=0,feature=0;size_t index=0,total=0;std::string name;bool completed=false,reused=false;}; + struct Result {u64 job=0,revision=0,epoch=0;double milliseconds=0;arkjson::Value arguments,rejection;std::unique_ptr transfer;}; + explicit AsyncAuthoringWorker(std::function beforeEvaluation={}); + ~AsyncAuthoringWorker(); + u64 start(const Document&,u64 revision,u64 epoch,const arkjson::Value& args); + void cancel(); + void shutdown(); + Progress progress() const; + std::optional take(); + static arkjson::Value publish(Result&&,AgentSession&,u64 currentEpoch,bool cancelled=false); +private: + struct Request {u64 job=0,revision=0,epoch=0;arkjson::Value arguments;std::shared_ptr snapshot;std::shared_ptr cancelled;}; + mutable std::mutex mutex_;std::condition_variable ready_;bool stopping_=false;u64 serial_=0; + std::optional pending_,current_;std::optional result_;Progress progress_; + std::function beforeEvaluation_;std::thread thread_; + void run(); +}; +} diff --git a/include/ark/bom.hpp b/include/ark/bom.hpp index faf3f31..459827e 100644 --- a/include/ark/bom.hpp +++ b/include/ark/bom.hpp @@ -3,6 +3,7 @@ namespace ark { // Caller-declared commercial/engineering data. Geometry never certifies it. arkjson::Value validatePartMetadata(const arkjson::Value& value); +arkjson::Value patchPartMetadata(const arkjson::Value& current,const arkjson::Value& patch); arkjson::Value partMetadataSchema(); std::string newBomDocumentId(); bool validBomDocumentId(const std::string& value); diff --git a/include/ark/command_catalog.hpp b/include/ark/command_catalog.hpp new file mode 100644 index 0000000..b0dfe45 --- /dev/null +++ b/include/ark/command_catalog.hpp @@ -0,0 +1,7 @@ +#pragma once +#include "ark/json.hpp" +namespace ark { +// Read-only command palette. Recipes produce ordinary host tool arguments; +// execution, revisions, permissions and geometry validation stay with that tool. +arkjson::Value agentCommandCatalog(const arkjson::Value& args); +} diff --git a/include/ark/component_sources.hpp b/include/ark/component_sources.hpp index 124a980..829a82a 100644 --- a/include/ark/component_sources.hpp +++ b/include/ark/component_sources.hpp @@ -21,10 +21,10 @@ ComponentResource fetchComponentResource(const std::string& url,ComponentResourc arkjson::Value componentSources(); // Public web search and paged KiCad discovery. Search results are candidates; // read the actual product page before recording supplier metadata. -arkjson::Value searchComponentSource(const arkjson::Value& args); +arkjson::Value searchComponentSource(const arkjson::Value& args,const ComponentHttpTransport& transport={}); arkjson::Value parseComponentWebSearch(const std::string& html,const std::string& query); -arkjson::Value componentSourcePage(const arkjson::Value& args); -arkjson::Value parseComponentSourcePage(const std::string& html,const std::string& requestedUrl,const std::string& finalUrl); +arkjson::Value componentSourcePage(const arkjson::Value& args,const ComponentHttpTransport& transport={}); +arkjson::Value parseComponentSourcePage(const std::string& html,const std::string& requestedUrl,const std::string& finalUrl,const arkjson::Value& readArgs={}); std::string componentPageText(const std::string& html); // Public HTTPS STEP only, bounded to 64 MiB and 90 seconds per resource. No account // credentials, cookies or background crawling. Destination is owned diff --git a/include/ark/derived_pack.hpp b/include/ark/derived_pack.hpp new file mode 100644 index 0000000..4f99090 --- /dev/null +++ b/include/ark/derived_pack.hpp @@ -0,0 +1,32 @@ +#pragma once +#include "ark/document_container.hpp" +#include +#include + +namespace ark { + +// 051A: the optional derived section is one zstd frame (a "pack") over every +// entry in caller order, split across rows named pack1... +// Long canonical base64 JSON strings travel as their decoded bytes, so B-rep +// text shared by successive feature bodies compresses across entries. Decoding +// reproduces each entry byte for byte; derived data stays an optional cache. +inline constexpr char derivedPackRowPrefix[]="pack1."; +inline constexpr size_t derivedPackChunkBytes=16*1024*1024; +inline constexpr size_t derivedPackMinimumSplice=1024; + +struct DerivedPackReport { + size_t entries=0,decodedBytes=0,storedBytes=0,splicedStrings=0,splicedBytes=0; + size_t omittedEntries=0,omittedBytes=0; +}; + +// SHA-256 over the keys, lengths and per-entry digests of the first `count` +// records in order; it names the pack rows and is checked again after decoding. +std::string derivedPackManifest(const DocumentDerivedPayloads& records,size_t count); +// Encodes a bounded record prefix whose pack fits `storedLimit`; the report +// counts the omitted tail. The retry heuristic does not promise a maximal prefix. +// An empty result means the attempted prefixes did not fit. +std::string encodeDerivedPack(const DocumentDerivedPayloads& records,size_t storedLimit,DerivedPackReport* report=nullptr); +// Rejects truncated, trailing, oversized or inconsistent packs by throwing. +DocumentDerivedPayloads decodeDerivedPack(const std::string& stored,DerivedPackReport* report=nullptr); + +} // namespace ark diff --git a/include/ark/design_disciplines.hpp b/include/ark/design_disciplines.hpp new file mode 100644 index 0000000..a533081 --- /dev/null +++ b/include/ark/design_disciplines.hpp @@ -0,0 +1,22 @@ +#pragma once +#include "ark/model.hpp" +#include +namespace ark { +class AgentSession; +arkjson::Value validateClassification(const arkjson::Value&); +std::set effectiveFamilies(const Document&,u64 feature,u64 node=0); +bool matchesFamilyFilter(const Document&,u64 feature,u64 node,const std::set&); +void validateDesignDisciplines(const Document&); +bool requiresDesignDisciplines054B(const Document&); +bool applyDesignDisciplineCommand(Document&,const arkjson::Value&); +const arkjson::Value* findSchematic(const Document&,const std::string&); +arkjson::Value inspectSchematic(const Document&,u64,const std::string&); +arkjson::Value inspectClassifications(const Document&,u64); +struct SchematicLine {Vec2 a,b;std::string layer;}; +struct SchematicLabel {Vec2 point;std::string text;}; +struct SchematicPin {Vec2 point;std::string symbol,pin;}; +struct SchematicDrawing {std::vector lines;std::vector labels;std::vector pins;}; +SchematicDrawing schematicDrawing(const Document&,const arkjson::Value& sheet); +bool callDesignDisciplineTool(AgentSession&,const std::string&,const arkjson::Value&,arkjson::Value&); +void appendDesignDisciplineTools(arkjson::Value&); +} diff --git a/include/ark/document_container.hpp b/include/ark/document_container.hpp index 661cca5..e77c304 100644 --- a/include/ark/document_container.hpp +++ b/include/ark/document_container.hpp @@ -13,7 +13,9 @@ inline constexpr int documentContainerApplicationId=0x41524b31; // ARK1 inline constexpr size_t maxDocumentContainerBytes=256*1024*1024; inline constexpr size_t maxDocumentValueBytes=16*1024*1024; inline constexpr size_t maxDocumentDerivedEntryBytes=64*1024*1024; -inline constexpr size_t maxDocumentDerivedBytes=128*1024*1024; +// 051A: decoded entry bytes (memory) and compressed pack bytes (file) are bounded separately. +inline constexpr size_t maxDocumentDerivedBytes=256*1024*1024; +inline constexpr size_t maxDocumentDerivedStoredBytes=128*1024*1024; inline constexpr size_t maxDocumentDerivedEntries=8192; struct DocumentDerivedPayload {std::string key,bytes;}; using DocumentDerivedPayloads=std::vector; @@ -26,8 +28,25 @@ struct DocumentContainerWriteStats { size_t slotsRemoved=0; size_t physicalBytes=0; bool stagedReplacement=false; + // 051A derived pack: entries written, their decoded and stored bytes, and the + // tail omitted when the compressed pack would exceed its stored capacity. + size_t derivedEntries=0,derivedDecodedBytes=0,derivedStoredBytes=0,derivedOmittedEntries=0,derivedOmittedBytes=0; + bool derivedRewritten=false; + // 051A compaction: an incremental save that leaves at least a quarter of the + // file free is compacted by transactional SQLite VACUUM, preserving writer locks. + bool compacted=false; + size_t bytesBeforeCompaction=0; + std::string compactionSkipped; }; +struct DocumentContainerReadStats { + std::string derivedEncoding="none"; // none, entries (container v2 before 051A) or zstd_pack + size_t derivedStoredBytes=0,derivedDecodedBytes=0; +}; + +// SHA-256 used by the container for payloads and derived rows. +std::string documentContainerDigest(const std::string& bytes); + // This identifies any SQLite file. Ownership/version/schema checks happen on load. bool documentContainerFile(const char* path); bool saveDocumentContainer(const arkjson::Value& root,const char* path, @@ -36,7 +55,8 @@ bool saveDocumentContainer(const arkjson::Value& root,const char* path, // Derived bytes are optional transport, never validated geometry. A damaged // derived section is discarded independently of strictly checked authoring. bool loadDocumentContainer(const char* path,arkjson::Value& root,std::string* error=nullptr, - DocumentDerivedPayloads* derived=nullptr,std::string* derivedDiscardedReason=nullptr); + DocumentDerivedPayloads* derived=nullptr,std::string* derivedDiscardedReason=nullptr, + DocumentContainerReadStats* readStats=nullptr); // Deterministic typed codec, useful to other owned persistence components. // Object keys are sorted, numbers retain their exact finite double value. diff --git a/include/ark/geometry_storage_032d.hpp b/include/ark/geometry_storage_032d.hpp index 19d20d9..bf77238 100644 --- a/include/ark/geometry_storage_032d.hpp +++ b/include/ark/geometry_storage_032d.hpp @@ -5,6 +5,10 @@ #include namespace ark { +// Process-local lossless derived caches. Empty compressed output means that the +// optional codec is unavailable or gives no saving; callers retain raw bytes. +std::string compressDerivedBytes(const std::string&); +std::string expandDerivedBytes(const std::string&,size_t originalBytes); // Value semantics over immutable derived geometry. Copies share storage; edits // publish a separate value and cannot mutate an evaluated cache owner. class NativePayload { diff --git a/include/ark/inertial_simulation.hpp b/include/ark/inertial_simulation.hpp new file mode 100644 index 0000000..0d4393f --- /dev/null +++ b/include/ark/inertial_simulation.hpp @@ -0,0 +1,45 @@ +#pragma once +#include "ark/agent.hpp" +#include + +namespace ark { +// Derived simulation only. CAD coordinates are mm; solver coordinates are SI. +// No pose in this module is an authored placement or manufacturing evidence. +struct InertialShape { + std::vector vertices, normals, edges; // local metres, unit directions + std::vector> segments; // actual non-coplanar boundary edges + std::string digest; + size_t sourceVertices=0; +}; +struct InertialBody { + u64 feature=0,node=0; int copy=0; std::string name; + size_t shape=0; double mass=1; + std::array inertia{1,0,0,0,1,0,0,0,1}; + Vec3 localCenterMm, position, velocity, omega, force, torque; + std::array orientation{0,0,0,1}; + bool fixed=false; +}; +struct InertialJoint { + size_t a=0,b=0; Vec3 anchorA,anchorB,axisA,axisB; + bool hinge=false; +}; +struct InertialOptions { + double duration=1, step=1.0/240, restitution=.1, friction=.5; + Vec3 gravity{0,0,-9.80665}; + bool ground=false,contacts=true; double groundZ=0; + unsigned iterations=16, outputFps=30; + std::string backend="gpu"; +}; +struct InertialResult { + std::vector> frames; + std::vector times; + arkjson::Value diagnostics; +}; +InertialShape prepareInertialShape(const Mesh&,Vec3 localCenterMm); +InertialResult simulateInertial(const std::vector&, + const std::vector&,const std::vector&,const InertialOptions&); +arkjson::Value inertialCapabilities(); +arkjson::Value inertialSimulationSchema(); +arkjson::Value inspectInertial(AgentSession&,const arkjson::Value&); +Mat4 inertialDisplayPose(const InertialBody&); +} diff --git a/include/ark/iteration_history.hpp b/include/ark/iteration_history.hpp index ffe3c85..67b0ec5 100644 --- a/include/ark/iteration_history.hpp +++ b/include/ark/iteration_history.hpp @@ -4,6 +4,7 @@ #include #include #include +#include namespace ark { class Document; inline constexpr size_t maxDocumentBytes=4u*1024u*1024u; @@ -25,4 +26,8 @@ void iterationInlineBakePayloads(const arkjson::Value& history,size_t& reference // transform and rebuilds deltas, the blob dictionary, digests and node ids with the same // topology and node metadata. ids maps every old node and baseline id to its new id. arkjson::Value iterationRewrite(const arkjson::Value& history,const std::function& transform,std::map& ids); +// Explicit archive-backed compaction. Retains the current-head ancestor suffix; +// undo keeps only its contiguous retained targets, redo is cleared. No auto pruning. +arkjson::Value iterationCompact(const Document& source,size_t keepRecent,const arkjson::Value& receipt,const arkjson::Value& retainIds=arkjson::Value::makeArr()); +arkjson::Value historyCompactTool(Document& document,std::uint64_t& revision,const arkjson::Value& args); } diff --git a/include/ark/media_044b.hpp b/include/ark/media_044b.hpp index 06178db..6be2586 100644 --- a/include/ark/media_044b.hpp +++ b/include/ark/media_044b.hpp @@ -13,7 +13,7 @@ namespace ark { // Procedural patterns are scalar fields in pattern periods, sampled triplanar // in part-local millimetres. Studio's GLSL mirrors these formulas. -int appearancePatternKind044B(const std::string& name); // 0 none, 1..7 known, -1 unknown +int appearancePatternKind044B(const std::string& name); // 0 none, 1..10 known, -1 unknown double appearancePatternField044B(int kind,double u,double v); double appearancePatternTriplanar044B(const Appearance& appearance,const Vec3& localPoint,const Vec3& localNormal); Vec3 appearancePatternColor044B(const Appearance& appearance,const Vec3& color,double field); diff --git a/include/ark/media_authoring.hpp b/include/ark/media_authoring.hpp new file mode 100644 index 0000000..7e5e367 --- /dev/null +++ b/include/ark/media_authoring.hpp @@ -0,0 +1,17 @@ +#pragma once +#include "ark/model.hpp" +#include "ark/assistant.hpp" +namespace ark { +// File-producing display tools. They never publish document/geometry changes. +arkjson::Value mediaAuthoringCapabilities(); +arkjson::Value generateDisplayImage(const arkjson::Value&,const AssistantTransport& offline={}); +arkjson::Value composeDisplayMedia(const Document&,const arkjson::Value&); +arkjson::Value requestDisplayImage(const arkjson::Value&,const AssistantTransport& offline={},const std::atomic_bool* cancel=nullptr); +struct MediaAuthoringCancellation { + explicit MediaAuthoringCancellation(const std::atomic_bool*); + ~MediaAuthoringCancellation(); + MediaAuthoringCancellation(const MediaAuthoringCancellation&)=delete; + MediaAuthoringCancellation& operator=(const MediaAuthoringCancellation&)=delete; +private: const std::atomic_bool* previous_; +}; +} diff --git a/include/ark/model.hpp b/include/ark/model.hpp index 76307ef..b0ddafb 100644 --- a/include/ark/model.hpp +++ b/include/ark/model.hpp @@ -128,6 +128,7 @@ struct Feature { int opInt = 0; // Boolean: 0 union 1 cut 2 intersect bool suppressed = false; // history and parameters stay; recompute skips the body arkjson::Value part; // explicit BOM metadata, independent of geometry + arkjson::Value classification; // explicit families/tags; navigation, never geometry authority std::string material; // named document material, empty uses default std::string manufacturingRoute; // explicit intent; empty is undeclared arkjson::Value manufacturingProcess; // bounded caller-declared route-specific process inputs @@ -267,7 +268,10 @@ struct NamedSketch { f64 residual = 0; // max |residual| after the last solve std::string error; int freeDofs=0, rank=0; + u64 ownerFeature=0; // Stable shared definition ID; zero retains legacy global scope. + std::string localName() const; }; +std::string sketchReference(u64 ownerFeature,const std::string& localName); struct DatumPlane { std::string name, parent="XY"; @@ -313,8 +317,9 @@ class Document { std::vector imageAssets; std::vector stamps; NamedSketch* findSketch(const std::string& name); - void setSketch(const std::string& name, Sketch sk); // create or replace + void setSketch(const std::string& name, Sketch sk,u64 ownerFeature=0); // local name with explicit owner, otherwise canonical/global reference bool removeSketch(const std::string& name); + bool validateSketchScopes(std::string& error) const; // features ---------------------------------------------------------------- std::vector features; @@ -324,6 +329,9 @@ class Document { std::string bomDocumentId; // assigned on explicit BOM authoring; stable across edits/save arkjson::Value iterationHistory; // immutable authoring journal; no evaluated geometry or usage snapshots arkjson::Value designContainerCheckout; // scoped workspace ownership and merge baseline; no derived geometry + arkjson::Value parametricComponents; // embedded immutable .arkprt/.arktop definitions and explicit instance bindings + arkjson::Value schematics; // independent editable 2D circuit sheets, symbols, pins and explicit wires + std::vector componentBindingsToSeal; // transient, only a component command can request a new evaluated baseline arkjson::Value skeleton; // native declarative source, input overrides and stable ownership manifest std::vector drawings; // authored associative technical drawings; derived curves are never persisted u64 historyTip=0; // inclusive feature prefix; zero resumes the full authored history @@ -400,7 +408,8 @@ std::string featureOperation(const Feature& feature); // Face extrusion inputs are geometric references for a separate body; their // source/limit bodies remain physical outputs until an actual modeling recipe consumes them. bool featureConsumesInputBodies(const Feature& feature); -// Per input: a 044B curve-pattern support (third input) stays a visible reference. +// Per input: curve-pattern supports and surface cutter/glue/tangent supports +// stay visible references; constructing a result does not consume these bodies. bool featureConsumesInputBody(const Feature& feature,size_t index); ManufacturingLineage featureManufacturingLineage(const Document& document,const Feature& feature); bool validateManufacturingRoutes(const Document& document,std::string& error); diff --git a/include/ark/motion_cables.hpp b/include/ark/motion_cables.hpp new file mode 100644 index 0000000..da2f24e --- /dev/null +++ b/include/ark/motion_cables.hpp @@ -0,0 +1,23 @@ +#pragma once +#include "ark/motion_graph.hpp" +#include +#include +namespace ark { +// Derived display meshes from native cable sweeps at the recorded rigid frame +// poses. These are not authored geometry, continuous collision or fatigue evidence. +class MotionCableMesh { + std::string bytes_;size_t positions_=0,indices_=0;bool compressed_=false; +public: + explicit MotionCableMesh(const Mesh&); + Mesh mesh() const; + size_t bytes() const{return sizeof(*this)+bytes_.capacity()+1;} +}; +struct MotionCableDisplay { + std::vector features; + std::vector> meshes; // frame-major + size_t frameCount=0,bytes=0,nativeRequests=0; +}; +std::vector motionCableFeatures(const Document&,const BakedMotionFrames&); +MotionCableDisplay prepareMotionCableDisplay(Document&,const BakedMotionFrames&, + const std::atomic_bool& cancelled,const std::function& progress={}); +} diff --git a/include/ark/native_backend.hpp b/include/ark/native_backend.hpp index bcbc686..fcf41be 100644 --- a/include/ark/native_backend.hpp +++ b/include/ark/native_backend.hpp @@ -43,6 +43,9 @@ int setNativeThreadBudget(int threads); // predicate stops the isolated worker (polled every 50 ms) and throws an error // containing NATIVE_CANCELLED; limitMs replaces the default 30000 ms per-request // watchdog only inside the scope. A timeout keeps the "worker limit" wording. +// Evaluation children inherit a copy of this policy. The predicate may run +// concurrently on those threads: captured state must be thread-safe and live +// until all requests using the policy have finished. class NativeRequestControlScope { const std::function* previousCancel;unsigned previousLimit;std::function cancel; public: @@ -51,6 +54,10 @@ class NativeRequestControlScope { NativeRequestControlScope(const NativeRequestControlScope&)=delete; NativeRequestControlScope& operator=(const NativeRequestControlScope&)=delete; }; +// Own a copy of the calling thread's policy for a child evaluation task. The +// scope on that task restores the pool thread's previous policy on every exit. +struct NativeRequestControl {std::function cancelled;unsigned limitMs=30000;}; +NativeRequestControl captureNativeRequestControl(); unsigned nativeRequestLimitMs(); // effective per-request limit on this thread arkjson::Value exportNativeBrep(const std::string& brep,const std::string& path); Mesh nativeResultMesh(const arkjson::Value& result); diff --git a/include/ark/parametric_components.hpp b/include/ark/parametric_components.hpp new file mode 100644 index 0000000..5fe6eaa --- /dev/null +++ b/include/ark/parametric_components.hpp @@ -0,0 +1,18 @@ +#pragma once +#include "ark/agent.hpp" + +namespace ark { +// Portable authored definitions, independent of the STEP snapshot library. +arkjson::Value componentSourceClosure(const Document&, const arkjson::Value&); +arkjson::Value makeParametricComponent(const Document&, const arkjson::Value&); +arkjson::Value loadParametricComponent(const std::string& path); +void saveParametricComponent(const arkjson::Value&, const std::string& path); +std::string parametricComponentHash(const arkjson::Value&); +void validateParametricComponents(const arkjson::Value&); +bool applyParametricComponentCommand(Document&, const arkjson::Value&); +void sealParametricComponentBindings(Document&); +bool callParametricComponentTool(AgentSession&, const std::string&, const arkjson::Value&, arkjson::Value&); +void appendParametricComponentTools(arkjson::Value&); +// Same authored relation index as context_graph, without its agent response cap. +arkjson::Value parametricGraphSnapshot(const Document&, u64 revision); +} diff --git a/include/ark/rubber.hpp b/include/ark/rubber.hpp new file mode 100644 index 0000000..1884cc4 --- /dev/null +++ b/include/ark/rubber.hpp @@ -0,0 +1,11 @@ +#pragma once +#include "ark/agent.hpp" + +namespace ark { +// Authored exact profiles, procedural decoration and derived dynamics are separate contracts. +arkjson::Value rubberCapabilities(); +arkjson::Value rubberPlanSchema(); +arkjson::Value rubberStudySchema(); +arkjson::Value planRubber(AgentSession&, const arkjson::Value&); +arkjson::Value inspectRubber(AgentSession&, const arkjson::Value&); +} diff --git a/include/ark/rubber_dynamics.hpp b/include/ark/rubber_dynamics.hpp new file mode 100644 index 0000000..f9f51c6 --- /dev/null +++ b/include/ark/rubber_dynamics.hpp @@ -0,0 +1,45 @@ +#pragma once +#include "ark/core.hpp" +#include "ark/json.hpp" + +namespace ark { +// Derived, reduced spring-network dynamics. All quantities are SI (m, kg, s, N). +// A distance constraint has energy (length-restLength)^2/(2*compliance). +// This is not a calibrated constitutive rubber model or manufacturing evidence. +struct RubberNode { + Vec3 position, velocity, force; + double mass=1; + bool fixed=false; +}; +struct RubberLink { + uint32_t a=0,b=0; + double restLength=1,compliance=0; // m, m/N; zero is an inextensible link +}; +struct RubberPulley { + Vec3 center,axis{0,0,1}; + double radius=1,angularVelocity=0; // infinite cylinder, m and rad/s +}; +struct RubberDynamicsOptions { + double duration=1,step=1.0/240; + unsigned iterations=8; + Vec3 gravity{0,0,-9.80665}; + bool ground=true; + double groundZ=0,friction=.7,damping=.02,contactRadius=0; + // damping is velocity decay in s^-1; friction is the Coulomb coefficient. + unsigned outputFps=30; + std::string backend="gpu"; + std::vector pulleys; +}; +struct RubberDynamicsResult { + std::vector> frames; + std::vector times; + std::vector finalVelocities; + // Original input link order; positive=tension, negative=compression. + // XPBD -lambda/dt^2 estimate, not continuum stress or qualification data. + std::vector finalLinkForces_N; + arkjson::Value diagnostics; +}; +RubberDynamicsResult simulateRubber(const std::vector&, + const std::vector&,const RubberDynamicsOptions&); +arkjson::Value rubberDynamicsCapabilities(); +} diff --git a/include/ark/rubber_patterns.hpp b/include/ark/rubber_patterns.hpp new file mode 100644 index 0000000..b17a5b0 --- /dev/null +++ b/include/ark/rubber_patterns.hpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 +#pragma once +#include "ark/core.hpp" +#include "ark/json.hpp" + +namespace ark { + +inline constexpr uint32_t RUBBER_PATTERN_MAX_COUNT = 1000000; +inline constexpr uint32_t RUBBER_PATTERN_MAX_PREVIEW = 256; + +struct RubberPatternFrame { + uint32_t index = 0; + Vec3 position_mm, tangent, bitangent, normal; + Mat4 transform; // Columns: tangent (x), bitangent (y), outward normal (z), position. + double u_rad = 0, v_rad = 0; + // Surface coordinates before placement/offset. u is wrapped to [0, 2*pi). + // v is torus section angle or sphere polar angle; zero on cylinder/racetrack. + double transverse_mm = 0; // Cylinder axial / racetrack width coordinate; otherwise zero. +}; + +// Immutable, compact analytical recipe. Construction and indexed access do not +// enumerate instances or build geometry. frame() is constant work and allocates +// no memory. Copying the plan shares immutable data, safe for concurrent reads. +// Invalid inputs throw std::invalid_argument; an invalid index throws +// std::out_of_range. No implicit field coercion or ignored unsupported fields. +class RubberPatternPlan { +public: + explicit RubberPatternPlan(const arkjson::Value& recipe); + uint32_t count() const; + RubberPatternFrame frame(uint32_t index) const; + arkjson::Value diagnostics() const; +private: + struct Impl; + std::shared_ptr impl_; +}; + +// Schema/capabilities describe placement recipes only. The caller must bind a +// recipe to an authored surface and choose visual instances or explicit geometry +// with its normal revision/atomic-publication contract. Motif names are semantic +// hints; this module does not create solids or qualify rubber manufacturing. +arkjson::Value rubberPatternSchema(); +arkjson::Value rubberPatternCapabilities(); +arkjson::Value rubberPatternFrameJson(const RubberPatternFrame& frame); +arkjson::Value previewRubberPattern(const arkjson::Value& recipe, + uint32_t offset = 0, uint32_t limit = 64); + +} // namespace ark diff --git a/include/ark/serialize.hpp b/include/ark/serialize.hpp index e9c43ae..f098d39 100644 --- a/include/ark/serialize.hpp +++ b/include/ark/serialize.hpp @@ -26,6 +26,10 @@ struct DocumentSaveReport { size_t derivedEntries=0,derivedBytes=0,derivedOmittedEntries=0,derivedOmittedBytes=0,derivedCapacityBytes=0; // 049A cached baked frames of current receipts; not cached or omitted frames re-bake on demand. size_t motionFrameEntries=0,motionFrameBytes=0,motionFrameOmittedEntries=0,motionFrameOmittedBytes=0,motionFrameNotCached=0; + // 051A: compressed bytes of the whole derived pack (geometry and frames) and the file after saving. + size_t derivedStoredBytes=0,physicalBytes=0,bytesBeforeCompaction=0; + bool derivedRewritten=false,compacted=false; + std::string compactionSkipped; }; // Binary by default; .arkjson/.json select text export. Loads detect the signature. diff --git a/include/ark/surface_edit_059c.hpp b/include/ark/surface_edit_059c.hpp new file mode 100644 index 0000000..fea6c30 --- /dev/null +++ b/include/ark/surface_edit_059c.hpp @@ -0,0 +1,8 @@ +#pragma once +#include "ark/agent.hpp" + +namespace ark { +arkjson::Value surfaceControlSchema059(); +// Read-only exact inspection and explicit revision-bound SurfaceEdit plans. +arkjson::Value surfaceControl059(AgentSession&, const arkjson::Value&); +} diff --git a/release.json b/release.json index 7df588e..8cb79aa 100644 --- a/release.json +++ b/release.json @@ -1,12 +1,15 @@ { - "sequence": 50, - "phase": "B", - "code": "050B", - "version": "0.9.51", + "sequence": 59, + "phase": "C", + "code": "059C", + "version": "0.9.60", "milestones": [ + "A.02", + "A.04", + "B.01", + "B.03", "B.04", "C.04", - "B.02", - "A.02" + "D.02" ] } diff --git a/scripts/Ark.ReleaseEvidence.psm1 b/scripts/Ark.ReleaseEvidence.psm1 index 98e57a7..da852fc 100644 --- a/scripts/Ark.ReleaseEvidence.psm1 +++ b/scripts/Ark.ReleaseEvidence.psm1 @@ -69,7 +69,7 @@ function New-ArkReleaseEvidence([string]$Repository,[string]$PackageDirectory,[s $sourceRelease = $release if ($UseRuntimeIdentity) { $release = @{version=$metadata.version;code=$metadata.iteration_code;sequence=$metadata.sequence;phase=$metadata.phase} } elseif ($metadata.version -ne $release.version -or $metadata.iteration_code -ne $release.code -or $metadata.sequence -ne $release.sequence -or $metadata.phase -ne $release.phase) { throw 'Package identity differs from release.json.' } - foreach ($notice in @('LICENSE','NOTICE','licenses/mapbox-earcut-ISC.txt','licenses/stb-image-LICENSE.txt','licenses/sqlite-provenance.txt','licenses/LICENSE_LGPL_21.txt','licenses/OCCT_LGPL_EXCEPTION.txt')) { + foreach ($notice in @('LICENSE','NOTICE','licenses/mapbox-earcut-ISC.txt','licenses/stb-image-LICENSE.txt','licenses/sqlite-provenance.txt','licenses/zstd-LICENSE.txt','licenses/LICENSE_LGPL_21.txt','licenses/OCCT_LGPL_EXCEPTION.txt')) { if (-not (Test-Path -LiteralPath (Join-Path $PackageDirectory $notice) -PathType Leaf)) { throw "Required package notice missing: $notice" } } $inventory = Get-ArkPackageInventory $PackageDirectory @@ -81,6 +81,7 @@ function New-ArkReleaseEvidence([string]$Repository,[string]$PackageDirectory,[s @('mapbox-earcut','2.2.4','ISC','third_party/mapbox/earcut.hpp','https://github.com/mapbox/earcut.hpp/tree/v2.2.4'), @('stb_image','2.30','MIT','third_party/stb/stb_image.h','https://github.com/nothings/stb/tree/013ac3beddff3dbffafd5177e7972067cd2b5083'), @('SQLite','3.54.0','LicenseRef-SQLite-Public-Domain','third_party/sqlite/sqlite3.c','https://www.sqlite.org/2026/sqlite-amalgamation-3540000.zip'), + @('zstd','1.5.7','BSD-3-Clause','third_party/zstd/lib/zstd.h','https://github.com/facebook/zstd/tree/v1.5.7'), @('Open-CASCADE-Technology','8.0.1','LGPL-2.1-only WITH OCCT-exception-1.0','','https://github.com/Open-Cascade-SAS/OCCT/tree/V8_0_1') ) $components = @(foreach ($definition in $definitions) { diff --git a/scripts/build-occt.ps1 b/scripts/build-occt.ps1 index c64d242..6ad345e 100644 --- a/scripts/build-occt.ps1 +++ b/scripts/build-occt.ps1 @@ -1,7 +1,9 @@ param( [ValidateRange(1, 16)][int]$Jobs = 4, [switch]$ConfigureOnly, - [switch]$AllowCandidatePatchset + [switch]$AllowCandidatePatchset, + [ValidateSet('MSVC', 'LLVMMinGW')][string]$Toolchain = 'MSVC', + [string]$CompilerDirectory ) $ErrorActionPreference = 'Stop' @@ -12,8 +14,9 @@ $patchHelper = Join-Path $PSScriptRoot 'ApplyOcctPatch.cmake' $cache = Join-Path $deps 'cache' $archive = Join-Path $cache 'OCCT-V8_0_1.zip' $source = Join-Path $deps "source-$patchset" -$build = Join-Path $deps "build-msvc-$patchset" -$install = Join-Path $deps "install-msvc-$patchset" +$toolchainSuffix = if ($Toolchain -eq 'LLVMMinGW') { 'mingw' } else { 'msvc' } +$build = Join-Path $deps "build-$toolchainSuffix-$patchset" +$install = Join-Path $deps "install-$toolchainSuffix-$patchset" $sourceStamp = Join-Path $source '.ark-source-sha256' $expectedSha256 = '7C033D917EE8F040C0512D289DCC5F02C148889D5BAC17C3E25639ACCB44F0DA' $archiveUrl = 'https://github.com/Open-Cascade-SAS/OCCT/archive/refs/tags/V8_0_1.zip' @@ -48,8 +51,9 @@ if (-not (Test-Path -LiteralPath $sourceStamp) -or (Get-Content -LiteralPath $so if ($LASTEXITCODE -ne 0) { throw 'Exact OCCT patch preparation failed' } $configure = @( - '-S', $source, '-B', $build, '-G', 'Visual Studio 17 2022', '-A', 'x64', + '-S', $source, '-B', $build, "-DINSTALL_DIR=$install", + '-DCMAKE_EXPORT_NO_PACKAGE_REGISTRY=ON', '-DBUILD_MODULE_FoundationClasses=ON', '-DBUILD_MODULE_ModelingData=ON', '-DBUILD_MODULE_ModelingAlgorithms=ON', @@ -69,6 +73,20 @@ $configure = @( '-DINSTALL_DOC_Overview=OFF', '-DINSTALL_TEST_CASES=OFF' ) +if ($Toolchain -eq 'LLVMMinGW') { + if (-not $CompilerDirectory) { throw 'LLVMMinGW requires -CompilerDirectory pointing to the LLVM-MinGW bin directory' } + foreach ($tool in @('clang.exe', 'clang++.exe', 'mingw32-make.exe')) { + if (-not (Test-Path -LiteralPath (Join-Path $CompilerDirectory $tool) -PathType Leaf)) { throw "Missing LLVM-MinGW tool: $tool" } + } + $CompilerDirectory = (Resolve-Path -LiteralPath $CompilerDirectory).Path.Replace('\','/') + $env:PATH = "$CompilerDirectory;$env:PATH" + $configure += @('-G', 'MinGW Makefiles', '-DCMAKE_BUILD_TYPE=Release', + "-DCMAKE_C_COMPILER=$CompilerDirectory/clang.exe", + "-DCMAKE_CXX_COMPILER=$CompilerDirectory/clang++.exe", + "-DCMAKE_MAKE_PROGRAM=$CompilerDirectory/mingw32-make.exe") +} else { + $configure += @('-G', 'Visual Studio 17 2022', '-A', 'x64') +} & cmake @configure if ($LASTEXITCODE -ne 0) { throw 'OCCT configuration failed' } if ($ConfigureOnly) { return } @@ -80,10 +98,12 @@ if ($LASTEXITCODE -ne 0) { throw 'OCCT install failed' } $config = Get-ChildItem -LiteralPath $install -Filter OpenCASCADEConfig.cmake -File -Recurse | Select-Object -First 1 -$stepLib = Get-ChildItem -LiteralPath $install -Filter TKDESTEP.lib -File -Recurse | +$libraryPattern = if ($Toolchain -eq 'LLVMMinGW') { 'libTKDESTEP.dll.a' } else { 'TKDESTEP.lib' } +$stepLib = Get-ChildItem -LiteralPath $install -Filter $libraryPattern -File -Recurse | Select-Object -First 1 if (-not $config -or -not $stepLib) { throw 'Installed OCCT SDK lacks CMake config or STEP library' } -$igesLib = Get-ChildItem -LiteralPath $install -Filter TKDEIGES.lib -File -Recurse | Select-Object -First 1 +$igesPattern = if ($Toolchain -eq 'LLVMMinGW') { 'libTKDEIGES.dll.a' } else { 'TKDEIGES.lib' } +$igesLib = Get-ChildItem -LiteralPath $install -Filter $igesPattern -File -Recurse | Select-Object -First 1 if (-not $igesLib) { throw 'Installed OCCT SDK lacks IGES library' } $licenses=Join-Path $install 'licenses';[IO.Directory]::CreateDirectory($licenses)|Out-Null foreach($notice in @('LICENSE_LGPL_21.txt','OCCT_LGPL_EXCEPTION.txt')){Copy-Item -LiteralPath (Join-Path $source $notice) -Destination $licenses} diff --git a/scripts/package-linux.sh b/scripts/package-linux.sh index 3d29683..17f47f4 100755 --- a/scripts/package-linux.sh +++ b/scripts/package-linux.sh @@ -41,6 +41,8 @@ cp -- "$root/third_party/mapbox/LICENSE" "$package/licenses/mapbox-earcut-ISC.tx cp -- "$root/third_party/stb/LICENSE" "$package/licenses/stb-image-LICENSE.txt" cp -- "$root/third_party/stb/README.md" "$package/licenses/stb-image-provenance.md" cp -- "$root/third_party/sqlite/README.md" "$package/licenses/sqlite-provenance.txt" +cp -- "$root/third_party/zstd/LICENSE" "$package/licenses/zstd-LICENSE.txt" +cp -- "$root/third_party/zstd/README.md" "$package/licenses/zstd-provenance.md" cp -- "$root/third_party/sqlite/sqlite3.h" "$package/licenses/sqlite3.h" cp -- "$root/docs/THIRD_PARTY_NOTICES.md" "$package/licenses/THIRD_PARTY_NOTICES.md" cp -- "$root/assets/ui/README.md" "$package/licenses/ark-ui-assets.txt" diff --git a/scripts/package-release.ps1 b/scripts/package-release.ps1 index 87fca13..cf77feb 100644 --- a/scripts/package-release.ps1 +++ b/scripts/package-release.ps1 @@ -134,6 +134,8 @@ it is for manual evaluation and is excluded from the stable automatic updater. Copy-Item -LiteralPath (Join-Path $repository 'third_party/stb/LICENSE') -Destination (Join-Path $licenses 'stb-image-LICENSE.txt') Copy-Item -LiteralPath (Join-Path $repository 'third_party/stb/README.md') -Destination (Join-Path $licenses 'stb-image-provenance.md') Copy-Item -LiteralPath (Join-Path $repository 'third_party/sqlite/README.md') -Destination (Join-Path $licenses 'sqlite-provenance.txt') + Copy-Item -LiteralPath (Join-Path $repository 'third_party/zstd/LICENSE') -Destination (Join-Path $licenses 'zstd-LICENSE.txt') + Copy-Item -LiteralPath (Join-Path $repository 'third_party/zstd/README.md') -Destination (Join-Path $licenses 'zstd-provenance.md') Copy-Item -LiteralPath (Join-Path $repository 'third_party/sqlite/sqlite3.h') -Destination (Join-Path $licenses 'sqlite3.h') Copy-Item -LiteralPath (Join-Path $repository 'assets/ui/README.md') -Destination (Join-Path $licenses 'ark-ui-assets.txt') Copy-Item -LiteralPath (Join-Path $repository 'docs/THIRD_PARTY_NOTICES.md') -Destination (Join-Path $licenses 'THIRD_PARTY_NOTICES.md') diff --git a/scripts/prepare-test-preview.ps1 b/scripts/prepare-test-preview.ps1 index 5dabb9d..b25e8fb 100644 --- a/scripts/prepare-test-preview.ps1 +++ b/scripts/prepare-test-preview.ps1 @@ -31,7 +31,7 @@ foreach ($folderName in @('assets')) { } $licensesRoot = Join-Path $previewRoot 'licenses' New-Item -ItemType Directory -Path $licensesRoot | Out-Null -foreach ($noticeFile in @('third_party/mapbox/LICENSE','third_party/sqlite/README.md','third_party/stb/LICENSE','third_party/stb/README.md','docs/THIRD_PARTY_NOTICES.md')) { +foreach ($noticeFile in @('third_party/mapbox/LICENSE','third_party/sqlite/README.md','third_party/stb/LICENSE','third_party/stb/README.md','third_party/zstd/LICENSE','third_party/zstd/README.md','docs/THIRD_PARTY_NOTICES.md')) { $source = Join-Path $repoRoot $noticeFile Copy-Item -LiteralPath $source -Destination (Join-Path $licensesRoot ($noticeFile -replace '/', '_')) } diff --git a/src/agent.cpp b/src/agent.cpp index 7276ecf..1d7a5b3 100644 --- a/src/agent.cpp +++ b/src/agent.cpp @@ -15,6 +15,8 @@ #include "ark/drawings.hpp" #include "ark/authoring_023b.hpp" #include "ark/design_containers.hpp" +#include "ark/parametric_components.hpp" +#include "ark/design_disciplines.hpp" #include "ark/holes_orchestrator.hpp" #include "ark/collision.hpp" #include "ark/mesh_model.hpp" @@ -217,6 +219,7 @@ void editNode(AssemblyNode& n,const V& j,const Document& doc){ if(auto p=j.find("visible")){if(p->t!=V::Bool)throw std::runtime_error("visible must be boolean");n.visible=p->b;} if(auto p=j.find("fixed")){if(p->t!=V::Bool)throw std::runtime_error("fixed must be boolean");n.fixed=p->b;} if(j.find("name"))n.name=str(j,"name"); + if(const auto* classification=j.find("classification"))n.classification=classification->isNull()?V{}:validateClassification(*classification); if(auto p=j.find("p")){if(p->t!=V::Obj)throw std::runtime_error("p must be object");for(auto& kv:p->obj)n.p[kv.first]=expression(kv.second);} if(auto pattern=j.find("pattern")){ readAssemblyPattern(n.pattern,*pattern); @@ -226,8 +229,10 @@ void editNode(AssemblyNode& n,const V& j,const Document& doc){ } V result(V data,bool error=false){V r=V::makeObj(),content=V::makeArr(),item=V::makeObj();item.set("type",V::makeStr("text"));item.set("text",V::makeStr(data.dump()));content.arr.push_back(item);r.set("content",content);r.set("structuredContent",data);r.set("isError",V::makeBool(error));return r;} void validatedMaterials(const Document& d){ + validateDesignDisciplines(d); validateAppearanceAuthoring024B(d,false); - if(d.features.size()>1024||d.params.size()>256||d.sketches.size()>256||d.planes.size()>128||d.canvases.size()>8||d.materials.size()>256)throw std::runtime_error("Document capacity exceeded"); + if(d.features.size()>1024||d.params.size()>256||d.planes.size()>128||d.canvases.size()>8||d.materials.size()>256)throw std::runtime_error("Document capacity exceeded"); + {std::string error;if(!d.validateSketchScopes(error))throw std::runtime_error(error);} for(const auto& material:d.materials){std::string reason;if(!validateMaterial(material,reason))throw std::runtime_error(reason);} for(const auto& feature:d.features){ if(!feature.material.empty()&&std::none_of(d.materials.begin(),d.materials.end(),[&](const Material& material){return material.name==feature.material;}))throw std::runtime_error("Feature references a missing material: "+feature.material); @@ -248,6 +253,7 @@ void validated(Document& d){ for(auto& sk:d.sketches)if(!sk.error.empty()||!std::isfinite(sk.residual)||sk.residual>1e-6)throw std::runtime_error("Sketch '"+sk.name+"': "+sk.error); validateAppearanceAuthoring024B(d,true); std::vector placements;std::string error;if(!resolveAssembly(d,placements,error))throw std::runtime_error(error); + sealParametricComponentBindings(d); } std::set consumed(const Document& d){return consumedFeatureInputs(d);} struct MeshSelection { u64 feature=0; u64 node=0; int copy=-1; std::string nodeName; bool useNode=false; u64 cacheKey=0; }; @@ -493,7 +499,7 @@ bool metadataOnlyApply(const Document& document,const V& args){ if(command.t!=V::Obj)return false; const V* operation=command.find("op");if(!operation||operation->t!=V::Str)return false; const std::string& op=operation->str; - if(op=="light_up")return true; + if(op=="light_up"||op=="classification.set"||op=="schematic.set"||op=="schematic.remove")return true; if(op=="bom.initialize")return command.obj.size()==1; if(op=="image_asset.set"||op=="image_asset.remove"||op=="stamp.set"||op=="stamp.remove"||op=="face_appearance.set"||op=="face_appearance.remove")return true; if(op!="material.set"&&op!="material.remove"&&op!="feature.edit")return false; @@ -504,7 +510,7 @@ bool metadataOnlyApply(const Document& document,const V& args){ if(key=="op")continue; if(op=="material.set"&&(key=="name"||key=="density"||key=="density_kg_m3"||key=="physical"||key=="appearance"))continue; if(op=="material.remove"&&key=="name")continue; - if(op=="feature.edit"&&(key=="id"||key=="material"||key=="appearance"||key=="part"))continue; + if(op=="feature.edit"&&(key=="id"||key=="material"||key=="appearance"||key=="part"||key=="part_patch"||key=="classification"))continue; return false; } return true; @@ -570,7 +576,7 @@ V designView(const Document& document,u64 revision){ features.arr.push_back(row); } for(const auto& sketch:document.sketches){ - V row=V::makeObj(),entities=V::makeArr();row.set("name",V::makeStr(sketch.name));row.set("plane",V::makeStr(sketch.sk.plane));row.set("profile_ready",V::makeBool(profileReady(document,sketch))); + V row=V::makeObj(),entities=V::makeArr();row.set("name",V::makeStr(sketch.name));row.set("local_name",V::makeStr(sketch.localName()));row.set("owner_feature",V::makeNum((double)sketch.ownerFeature));row.set("reference",V::makeStr(sketch.name));row.set("plane",V::makeStr(sketch.sk.plane));row.set("profile_ready",V::makeBool(profileReady(document,sketch))); for(size_t index=0;indexarr)if(used.str==sketch.name)consumers.arr.push_back(*feature.find("id"));row.set("consumers",consumers); row.set("entities",entities);sketches.arr.push_back(row); @@ -608,7 +614,7 @@ V designDigest(const Document& document,u64 revision,const V& args){ } for(const auto& row:design.find("sketches")->arr){ if(known_("sketch:"+row.find("name")->str,row))continue; - V out=V::makeObj();copy(row,out,{"name","plane","profile_ready","consumers"});out.set("entities",V::makeNum((double)row.find("entities")->arr.size()));sketches.arr.push_back(std::move(out)); + V out=V::makeObj();copy(row,out,{"name","local_name","owner_feature","reference","plane","profile_ready","consumers"});out.set("entities",V::makeNum((double)row.find("entities")->arr.size()));sketches.arr.push_back(std::move(out)); } for(const auto& row:design.find("assembly")->arr){if(!known_("node:"+std::to_string((u64)row.find("id")->num),row))nodes.arr.push_back(row);} r.set("features",features);r.set("sketches",sketches);r.set("assembly",nodes); @@ -672,6 +678,7 @@ V selectedDesignView(const Document& document,u64 revision,const V& args){ static std::atomic_size_t contextGraphAuthoringSerializationsCount{0}; size_t contextGraphAuthoringSerializations(){return contextGraphAuthoringSerializationsCount.load(std::memory_order_relaxed);} #include "context_graph_034d.inl" +V parametricGraphSnapshot(const Document& document,u64 revision){V root;if(!arkjson::parse(documentToJson(document,false,false),root))throw std::runtime_error("Cannot read authored graph");auto graph=buildProjectGraph(root,"studio");graph.set("revision",V::makeNum((double)revision));graph.set("partial_dependencies",V::makeBool(true));return graph;} int wholeIndex(const V& value,const char* what){ if(value.t!=V::Num||!std::isfinite(value.num)||value.num<0||value.num>1024||value.num!=std::floor(value.num))throw std::runtime_error(std::string(what)+" must be a nonnegative integer"); return (int)value.num; @@ -767,7 +774,7 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ if(!(tool=="import_step"||tool=="import_sheet_step")||!replace||replace->t!=V::Bool||!replace->b) throw std::runtime_error("Resume full feature history before appending imported definitions or library components"); } - static const std::set custodyTools{"export_step","export_iges","export_mesh","drawing_export","drawing_inspect","bom_export_parts","snapshot","geometry_query","native_inspect","collision_inspect","assembly_info","assembly_motion","motion_info","explode_info","drag_chain_info","visualize_render","mesh_inspect","mesh_raycast","physics_inspect","manufacturing_inspect","reference_inspect","frame_inspect","electronics_inspect","pcb_export"}; + static const std::set custodyTools{"surface_control","export_step","export_iges","export_mesh","drawing_export","drawing_inspect","bom_export_parts","snapshot","geometry_query","native_inspect","collision_inspect","assembly_info","assembly_motion","motion_info","explode_info","drag_chain_info","visualize_render","mesh_inspect","mesh_raycast","physics_inspect","manufacturing_inspect","reference_inspect","frame_inspect","electronics_inspect","pcb_export"}; if(custodyTools.count(tool))verifyAssemblyExternalReferences(document); // Older direct clients may omit this field. When supplied (mandatory // for agent teams), every document replacement/history/import path @@ -777,7 +784,7 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ if(expected->t!=V::Num||expected->num!=(double)revision) throw std::runtime_error("Revision conflict; the current revision is in this result. Inspect only what your edit depends on and retry"); if(tool=="context_graph")return result(projectContextGraph(document,revision,args,contextGraphCache_,contextGraphSource_,contextGraphStamp_)); - V extension;if(callProjectMemoryTool(*this,tool,args,extension))return result(extension);if(callAuthoring023Tool(*this,tool,args,extension))return result(extension);if(callComponentLibraryTool(*this,tool,args,extension))return result(extension);if(callAgentFeature(*this,tool,args,extension))return result(extension);if(callParametricHudTool(*this,tool,args,extension))return result(extension); + V extension;if(callDesignDisciplineTool(*this,tool,args,extension))return result(extension);if(callParametricComponentTool(*this,tool,args,extension))return result(extension);if(callProjectMemoryTool(*this,tool,args,extension))return result(extension);if(callAuthoring023Tool(*this,tool,args,extension))return result(extension);if(callComponentLibraryTool(*this,tool,args,extension))return result(extension);if(callAgentFeature(*this,tool,args,extension))return result(extension);if(callParametricHudTool(*this,tool,args,extension))return result(extension); {V out;if(callAuthoring024Tool(*this,tool,args,out))return result(out);if(callMotionTool(*this,tool,args,out))return result(out);if(callDragChainTool(*this,tool,args,out))return result(out);Image image;if(callExplodedViewTool(*this,tool,args,out,&image))return image.w?snapshotImageResult(image,out,std::string()):result(out);} if(tool=="collision_inspect"||tool=="skeleton_inspect"||tool=="skeleton_compile"){ if(const auto* expected=args.find("expected_revision"))if(expected->t!=V::Num||expected->num!=(double)revision)throw std::runtime_error("Revision conflict; inspect the current document before querying"); @@ -1263,13 +1270,17 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ for(const auto& command:commands.arr)if(const auto* op=command.find("op");op&&op->t==V::Str&&op->str.rfind("motion.",0)==0&&!args.find("expected_revision"))throw std::runtime_error("Motion authoring requires expected_revision from current doc_info"); for(const auto& command:commands.arr)if(const auto* op=command.find("op");op&&op->t==V::Str&&op->str.rfind("explode.",0)==0&&!args.find("expected_revision"))throw std::runtime_error("Exploded view authoring requires expected_revision from current doc_info"); for(const auto& command:commands.arr)if(const auto* op=command.find("op");op&&op->t==V::Str&&op->str.rfind("drag_chain.",0)==0&&!args.find("expected_revision"))throw std::runtime_error("Drag chain authoring requires expected_revision from current doc_info"); - for(const auto& command:commands.arr)if((command.find("part")||(command.find("op")&&command.find("op")->asStr()=="bom.initialize"))&&!args.find("expected_revision"))throw std::runtime_error("BOM authoring requires expected_revision from current doc_info"); + for(const auto& command:commands.arr)if((command.find("part")||command.find("part_patch")||(command.find("op")&&command.find("op")->asStr()=="bom.initialize"))&&!args.find("expected_revision"))throw std::runtime_error("BOM authoring requires expected_revision from current doc_info"); + for(const auto& command:commands.arr)if(command.find("classification")&&!args.find("expected_revision"))throw std::runtime_error("Classification authoring requires expected_revision from current doc_info"); for(const auto& command:commands.arr)if(!args.find("expected_revision")){ const auto* op=command.find("op"),*type=command.find("type"); if(op&&op->t==V::Str&&(op->str=="feature.move"||op->str=="feature.rollback"||op->str.rfind("configuration.",0)==0||op->str=="assembly.load"||op->str.rfind("assembly.external.",0)==0))throw std::runtime_error("History and configuration authoring require expected_revision from current doc_info"); if((op&&op->t==V::Str&&op->str.rfind("skeleton.",0)==0)||(type&&type->t==V::Str&&type->str=="mesh_edit"))throw std::runtime_error("Skeleton and indexed mesh authoring require expected_revision from current doc_info"); } for(const auto& command:commands.arr)if(const auto* op=command.find("op");op&&op->t==V::Str&&(op->str=="light_up"||op->str=="sheet.vent"||op->str.rfind("stamp.",0)==0||op->str.rfind("image_asset.",0)==0||op->str.rfind("face_appearance.",0)==0)&&!args.find("expected_revision"))throw std::runtime_error("Image and face authoring require expected_revision"); + for(const auto& command:commands.arr)if(command.find("part_patch")){ + if(!command.find("op")||command.find("op")->asStr()!="feature.edit"||command.find("part"))throw std::runtime_error("part_patch requires feature.edit and cannot be combined with part replacement"); + } const bool appearanceOnly=metadataOnlyApply(document,args); Document next;std::string error; if(appearanceOnly)next=document.authoringCopy(); @@ -1280,9 +1291,12 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ for(auto& c:commands.arr){ applying=true;commandIndex=(size_t)(&c-commands.arr.data());commandOp=c.find("op")?c.find("op")->asStr():""; auto op=str(c,"op"); + const auto sketchName=op.rfind("sketch.",0)==0&&c.find("name")?sketchReference(c.find("owner_feature")?featureRef(next,*c.find("owner_feature")):0,str(c,"name")):std::string(); if(next.historyTip&&(op=="feature.add"||op=="sheet.create"||op=="skeleton.set"))throw std::runtime_error("Resume full feature history before adding features or changing Skeleton source"); if(op=="feature.move"&&skeletonOwnsFeature(next,featureRef(next,field(c,"id"))))throw std::runtime_error("Skeleton pattern is source-owned; change its source instead of reordering generated features"); - if(applyFeatureHistoryCommand(next,c)){} + if(op.rfind("component.",0)==0){if(!args.find("expected_revision"))throw std::runtime_error("Parametric component commands require expected_revision");if(!applyParametricComponentCommand(next,c))throw std::runtime_error("Unknown component command");validated(next);} + else if(op=="classification.set"||op.rfind("schematic.",0)==0){if(!args.find("expected_revision"))throw std::runtime_error("Classification and schematic commands require expected_revision");if(!applyDesignDisciplineCommand(next,c))throw std::runtime_error("Unknown discipline command");} + else if(applyFeatureHistoryCommand(next,c)){} else if(applyAssemblyAuthoringCommand(next,c,error)){if(!error.empty())throw std::runtime_error(error);} else if(op.rfind("motion.",0)==0){if(op=="motion.graph.set"||op=="motion.bake")validated(next);if(!applyMotionCommand(next,c,revision,error))throw std::runtime_error("Unknown operation: "+op);if(!error.empty())throw std::runtime_error(error);} else if(op.rfind("explode.",0)==0){if(!applyExplodedViewCommand(next,c,error))throw std::runtime_error("Unknown operation: "+op);if(!error.empty())throw std::runtime_error(error);} @@ -1341,6 +1355,7 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ if(auto mode=c.find("mode")){if(mode->t!=V::Num||mode->num<0||mode->num>2||mode->num!=std::floor(mode->num))throw std::runtime_error("mode must be 0, 1 or 2");f.opInt=(int)mode->num;} featureAppearance(f,c); if(const auto* part=c.find("part")){f.part=part->isNull()?V{}:validatePartMetadata(*part);if(f.part.t==V::Obj&&next.bomDocumentId.empty())next.bomDocumentId=newBomDocumentId();} + if(const auto* classification=c.find("classification"))f.classification=classification->isNull()?V{}:validateClassification(*classification); if(f.type==FeatureType::NativeSolid&&f.inputs.size()==2){ const auto* operation=f.nativeSpec.find("op"); if(operation&&operation->t==V::Str&&operation->str=="tube_end_fit"){ @@ -1377,6 +1392,8 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ if(c.find("name"))f->name=str(c,"name"); featureAppearance(*f,c); if(const auto* part=c.find("part")){f->part=part->isNull()?V{}:validatePartMetadata(*part);if(f->part.t==V::Obj&&next.bomDocumentId.empty())next.bomDocumentId=newBomDocumentId();} + if(const auto* patch=c.find("part_patch")){f->part=patchPartMetadata(f->part,*patch);if(next.bomDocumentId.empty())next.bomDocumentId=newBomDocumentId();} + if(const auto* classification=c.find("classification"))f->classification=classification->isNull()?V{}:validateClassification(*classification); if(auto flag=c.find("suppressed")){if(flag->t!=V::Bool)throw std::runtime_error("suppressed must be boolean");f->suppressed=flag->b;} } else if(op=="feature.remove"){const auto target=featureRef(next,field(c,"id"));if(target==next.historyTip)throw std::runtime_error("Resume full history before removing its rollback tip");if(!next.remove(target))throw std::runtime_error("Feature not found");} @@ -1397,12 +1414,13 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ else if(op=="sketch.set"){ V sketch=field(c,"sketch");bindSketchProjects(next,sketch); Sketch sk;if(!sketchFromJson(sketch.dump(),sk,&error))throw std::runtime_error(error); - next.setSketch(str(c,"name"),std::move(sk)); + const auto* owner=c.find("owner_feature"); + next.setSketch(str(c,"name"),std::move(sk),owner?featureRef(next,*owner):0); } - else if(op=="sketch.remove"){if(!next.removeSketch(str(c,"name")))throw std::runtime_error("Sketch not found");} - else if(op=="sketch.patch"){auto* sketch=next.findSketch(str(c,"name"));if(!sketch)throw std::runtime_error("Sketch not found");patchSketch(*sketch,c,error);} + else if(op=="sketch.remove"){if(!next.removeSketch(sketchName))throw std::runtime_error("Sketch not found");} + else if(op=="sketch.patch"){auto* sketch=next.findSketch(sketchName);if(!sketch)throw std::runtime_error("Sketch not found");patchSketch(*sketch,c,error);} else if(op=="sketch.entity.set"){ - auto* sk=next.findSketch(str(c,"name"));if(!sk)throw std::runtime_error("Sketch not found"); + auto* sk=next.findSketch(sketchName);if(!sk)throw std::runtime_error("Sketch not found"); V entity=field(c,"entity");bindProjectFeature(next,entity);auto name=str(entity,"name");V wrapper=V::makeObj(),entities=V::makeArr();entities.arr.push_back(entity);wrapper.set("entities",entities);Sketch single; if(!sketchFromJson(wrapper.dump(),single,&error))throw std::runtime_error(error); auto it=std::find_if(sk->sk.ents.begin(),sk->sk.ents.end(),[&](const SketchEnt& e){return e.name==name;}); @@ -1410,7 +1428,7 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ Sketch checked;if(!sketchFromJson(sketchToJson(sk->sk),checked,&error))throw std::runtime_error(error);sk->sk=std::move(checked); } else if(op=="sketch.fillet"||op=="sketch.chamfer"){ - auto* sk=next.findSketch(str(c,"name"));if(!sk)throw std::runtime_error("Sketch not found"); + auto* sk=next.findSketch(sketchName);if(!sk)throw std::runtime_error("Sketch not found"); const bool chamfer=op=="sketch.chamfer"; const std::string entity=str(c,"entity"); const V& index=field(c,"corner"); @@ -1460,8 +1478,8 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ next.evalBodies=document.evalBodies;next.lastResults=document.lastResults; validatedMaterials(next);validateAppearanceAuthoring024B(next,true); if(appearance024BNeedsVersion39(next)&&documentToJson(next,true,false).size()>maxDocumentBytes)throw std::runtime_error("Embedded image document exceeds 4 MiB; reduce image dimensions/size"); - remember();document.materials=std::move(next.materials);document.bomDocumentId=std::move(next.bomDocumentId);document.imageAssets=std::move(next.imageAssets);document.stamps=std::move(next.stamps); - for(size_t i=0;istr=="changes"?revisionReceipt032D(document,revision):info();r.set("created_ids",created);r.set("created_node_ids",createdNodes);r.set("created_mate_ids",createdMates);r.set("sheet_edits",sheetEdits);r.set("geometry_recomputed",V::makeBool(!appearanceOnly));if(args.find("checks"))r.set("conditions",conditionReport);return result(r); @@ -1481,8 +1499,14 @@ V AgentSession::dispatch(const std::string& tool,const V& args){ if(saved.derivedGeometry){ // Optional geometry cache receipt; omitted bodies recompute from authoring on open. V geometry=V::makeObj();geometry.set("status",V::makeStr(saved.derivedOmittedEntries?"partial":"saved"));geometry.set("entries_saved",V::makeNum((double)saved.derivedEntries));geometry.set("bytes_saved",V::makeNum((double)saved.derivedBytes));geometry.set("entries_omitted",V::makeNum((double)saved.derivedOmittedEntries));geometry.set("bytes_omitted",V::makeNum((double)saved.derivedOmittedBytes));geometry.set("capacity_bytes",V::makeNum((double)saved.derivedCapacityBytes)); - if(saved.derivedOmittedEntries)geometry.set("omitted_reason",V::makeStr("Saved geometry is an optional cache with a 128 MiB capacity. Authoring was saved in full; omitted bodies are evaluated from authoring on the next open.")); + // 051A: one zstd pack holds geometry and baked frames; stored_bytes is its compressed size. + geometry.set("encoding",V::makeStr("zstd_pack"));geometry.set("stored_bytes",V::makeNum((double)saved.derivedStoredBytes));geometry.set("stored_capacity_bytes",V::makeNum((double)maxDocumentDerivedStoredBytes)); + if(saved.derivedOmittedEntries)geometry.set("omitted_reason",V::makeStr("Saved geometry is an optional cache with a 256 MiB decoded and 128 MiB compressed capacity. Authoring was saved in full; omitted bodies are evaluated from authoring on the next open.")); r.set("saved_geometry",geometry); + V file=V::makeObj();file.set("physical_bytes",V::makeNum((double)saved.physicalBytes));file.set("compacted",V::makeBool(saved.compacted)); + if(saved.compacted)file.set("bytes_before_compaction",V::makeNum((double)saved.bytesBeforeCompaction)); + if(!saved.compactionSkipped.empty())file.set("compaction_skipped",V::makeStr(saved.compactionSkipped)); + r.set("container",file); if(motionReceiptsRequireDocumentVersion49(document)){V frames=V::makeObj();frames.set("entries_saved",V::makeNum((double)saved.motionFrameEntries));frames.set("bytes_saved",V::makeNum((double)saved.motionFrameBytes));frames.set("entries_omitted",V::makeNum((double)saved.motionFrameOmittedEntries));frames.set("entries_not_cached",V::makeNum((double)saved.motionFrameNotCached)); frames.set("note",V::makeStr("Baked frames are derived data saved in the optional derived section. Omitted or uncached frames are re-baked on demand and verified against each receipt's frames_sha256."));r.set("saved_motion_frames",frames);} } @@ -1603,6 +1627,7 @@ V AgentSession::tools(bool detailed){ const Def defs[]={ {"history_info","Inspect persistent immutable iteration metadata and branch heads. limit 1..64, newest first. before_id excludes that anchor and pages older nodes; has_more/next_before_id indicate continuation. Baseline represents only the first observed authoring state. Actor identity is caller-declared. No geometry or token ledger snapshots are returned.",R"({"type":"object","properties":{"limit":{"type":"integer","minimum":1,"maximum":64},"before_id":{"type":"string"}}})",true}, {"iteration_restore","Restore saved authoring as a new branch iteration, preserving all prior nodes, current usage receipts and monotonic revision. Exact geometry is re-evaluated; any failure or total 4 MiB capacity violation rejects atomically. Actor is declared provenance.",R"({"type":"object","properties":{"id":{"type":"string"},"expected_revision":{"type":"integer","minimum":0},"motivation":{"type":"string","maxLength":4096},"actor":{"type":"object","properties":{"kind":{"type":"string"},"id":{"type":"string"},"role":{"type":"string"}},"required":["kind","id"]}},"required":["id","expected_revision"]})",false}, + {"history_compact","Explicit recoverable history compaction, only on user instruction. Writes the complete current document to a NEW archive_path .ark and verifies reopening before publication. Retains at most keep_recent current-head ancestors and a baseline; optional retain_ids explicitly preserves other selected states (combined nodes at most 256), rewrites their ids, retains only contiguous available undo targets and clears redo. Other branches and older history remain in the archive, recoverable using doc_load. No authoring, geometry or usage is removed. Never overwrites archives; stale revision or archive failure leaves current document unchanged. Save the compacted document afterwards with doc_save.",R"({"type":"object","additionalProperties":false,"properties":{"archive_path":{"type":"string"},"keep_recent":{"type":"integer","minimum":0,"maximum":256},"retain_ids":{"type":"array","maxItems":256,"items":{"type":"string"}},"expected_revision":{"type":"integer","minimum":0},"confirm":{"type":"boolean","const":true},"motivation":{"type":"string","maxLength":4096},"actor":{"type":"object"}},"required":["archive_path","keep_recent","expected_revision","confirm"]})",false}, {"history_migrate_derived","049A explicit journal rewrite; only on the user's explicit instruction. Removes 044B-048B inline baked-motion frames (derived data) from the current authoring, the journal baseline, deltas and blobs, keeping receipts with frames_sha256. First writes the complete document beside path as .pre-049A.ark (never overwriting) and verifies it reopens; then rebuilds the journal (schema 2, new node ids and digests, same actors, tools, times and branches), records the migration in history_info migrations and advances revision. Rejects without confirm:true, a saved .ark path or inline payloads. Save afterwards with doc_save.",R"({"type":"object","properties":{"path":{"type":"string","description":"Saved .ark document; the backup is written beside it."},"expected_revision":{"type":"integer","minimum":0},"confirm":{"type":"boolean","const":true},"motivation":{"type":"string","maxLength":4096},"actor":{"type":"object","properties":{"kind":{"type":"string"},"id":{"type":"string"},"role":{"type":"string"},"model":{"type":"string"}},"required":["kind","id"]}},"required":["path","expected_revision","confirm"]})",false}, {"suspension_inspect","Solve a double-wishbone suspension preview at jounce_mm, rack_mm and wheel_spin_deg, returning hardpoints, link closure residuals, toe/camber, spring stroke and declared-rate force. Read-only kinematics, not dynamic/inertia/contact simulation or native B-rep authority.",R"({"type":"object","properties":{"id":{"type":["integer","string"]},"jounce_mm":{"type":"number"},"rack_mm":{"type":"number"},"wheel_spin_deg":{"type":"number"}},"required":["id"]})",true}, {"usage_info","Read persisted drawing token receipts and reported lower-bound totals. External MCP consumption may remain unknown; client receipts cover only reported calls. detail receipts includes provenance; no estimate is invented.",R"({"type":"object","properties":{"detail":{"type":"string","enum":["summary","receipts"]}}})",true}, @@ -1614,12 +1639,12 @@ V AgentSession::tools(bool detailed){ {"electronics_inspect","Read PCB layers, net connectivity, clearance DRC and BOM, or a cable route's bend radius, exact length and independently checked obstacle clearance. Does not certify electrical or manufacturing performance.",R"({"type":"object","properties":{"id":{"type":["integer","string"]}},"required":["id"]})",true}, {"pcb_export","Export PCB copper and outline Gerbers, plated/non-plated Excellon drill files and JSON netlist as a fabrication preview. Run electronics_inspect for incomplete nets and DRC scope first.",R"({"type":"object","properties":{"id":{"type":["integer","string"]},"path_prefix":{"type":"string"}},"required":["id","path_prefix"]})",false}, {"export_iges","Export a selected exact B-rep as IGES in millimetres, with independent readback bounds/area checks and solid-topology status. Default pose formed; flat is available only for sheet features.",R"({"type":"object","properties":{"id":{"type":["integer","string"]},"path":{"type":"string"},"pose":{"type":"string","enum":["flat","formed"]}},"required":["id","path"]})",false}, - {"agent_onboard","START HERE. Discover current document/revision, supported modeling workflows, reusable component library, examples and validation limits. Read-only; choose a topic before modeling.",R"({"type":"object","properties":{"topic":{"type":"string","enum":["bom","fasteners","components","vendors","plastics","motion","manufacturing","physics","automation","overview","sketch","tube","assembly","surfacing","sheet","solids","mesh","materials","frames","electronics","routing","suspension","skeleton","drawings","holes","cad_import","containers","stamps","planes","history","configurations","wood","networks","lighting","hud"]}}})",true}, + {"agent_onboard","START HERE. Discover current document/revision, supported modeling workflows, reusable component library, examples and validation limits. Read-only; choose a topic before modeling.",R"({"type":"object","properties":{"topic":{"type":"string","enum":["bom","fasteners","components","vendors","plastics","motion","manufacturing","physics","automation","overview","sketch","tube","assembly","surfacing","sheet","solids","mesh","materials","frames","electronics","routing","suspension","skeleton","drawings","holes","cad_import","containers","stamps","planes","history","configurations","wood","networks","lighting","hud","schematics"]}}})",true}, {"doc_info","Document summary/inventory. detail design returns feature operations/dependencies/roles, sketch names, origins, manufacturing declarations and measured volume/bounds. ids/sections require detail design or omitted detail (inferred design); explicit summary cannot use either filter. Examples: {detail:summary}, {detail:design,sections:[features,assembly]}. Optional ids selects 1..64 feature ids or unique names (default section features); sections selects features|sketches|parameters|assembly|materials. With ids, sketches/assembly/materials are direct associations; parameters stay document-wide. Selected reads expose partial, scope, section_scopes and total_counts. detail digest returns compact feature/sketch/node rows, parameters and a fingerprints map; send that map back as known_fingerprints to receive only changed rows plus removed keys. No meshes/native payloads; read-only.",R"({"type":"object","anyOf":[{"properties":{"detail":{"enum":["design"]}}},{"not":{"anyOf":[{"required":["ids"]},{"required":["sections"]}]}}],"properties":{"detail":{"type":"string","enum":["summary","design"]},"ids":{"type":"array","minItems":1,"maxItems":64,"items":{"oneOf":[{"type":"integer","minimum":1},{"type":"string","minLength":1,"maxLength":128}]}},"sections":{"type":"array","minItems":1,"maxItems":5,"uniqueItems":true,"items":{"type":"string","enum":["features","sketches","parameters","assembly","materials"]}}}})",true}, {"doc_new","Start an empty document only when requested. Clears the active model with undo and a monotonically increasing revision; does not overwrite saved files.",R"({"type":"object","properties":{"expected_revision":{"type":"integer","minimum":0}},"required":["expected_revision"]})",false}, {"doc_get","Read full parametric document, including expressions and revision.",R"({"type":"object"})",true}, {"object_context","Compact existing-object CAD context and change tokens. Select ids (feature ids/unique names), or node/copy for one part occurrence; otherwise discover by query substring/type and after_id. expected_revision rejects stale reads. depth 0..2 expands dependencies/dependents; limit 1..64 bounds rows. known_fingerprints maps returned document-scoped keys to change tokens; unchanged rows keep identity but omit details. Covers authored recipes, dependency/parameter/sketch/datum resources, connected assembly and available measured evidence. Source/mesh/B-rep buffers stay local; fingerprints are change detection, never identity/security/geometry equivalence. Read-only; partial/truncated and omitted fields are explicit.",R"({"type":"object","properties":{"ids":{"type":"array","minItems":1,"maxItems":64,"items":{"type":["integer","string"]}},"node":{"type":["integer","string"]},"copy":{"type":"integer","minimum":0,"maximum":31},"query":{"type":"string","minLength":1,"maxLength":128},"type":{"type":"string"},"expected_revision":{"type":"integer","minimum":0},"known_fingerprints":{"type":"object","maxProperties":1024,"additionalProperties":{"type":"string","maxLength":64}},"depth":{"type":"integer","minimum":0,"maximum":2},"limit":{"type":"integer","minimum":1,"maximum":64},"after_id":{"type":"integer","minimum":1}},"additionalProperties":false})",true}, - {"doc_apply","Atomic batch; evaluate once, roll back on any failure. BOM: bom.initialize{} assigns persistent document identity; feature.add/edit part:{part_number,description,part_revision,category,procurement:make|buy|unspecified,manufacturer,manufacturer_part_number,supplier,supplier_part_number,source_url,datasheet_url,standard,specification,representation,sourcing_status} replaces declared metadata; null clears it. Requires expected_revision; metadata-only edits do not recompute geometry. Use bom_inspect to check quantities/missing fields. Technical drawings: drawing.set{drawing:{name,feature,units:mm|in,scale,paper_mm:[width,height],views:[{name,type:orthographic|section,direction:front|back|top|bottom|right|left,offset_mm:[x,y],origin_mm:[x,y,z] for section}],dimensions:[{name,view,kind:linear|horizontal|vertical|radius|diameter,reference_a,reference_b? (linear only),fraction_a?,fraction_b?,position_mm:[x,y],tolerance?:{lower,upper,units}}]}}, drawing.refresh{name}, drawing.remove{name}. Requires expected_revision. One feature-local exact solid; changed B-rep invalidates the binding. Radius/diameter use an exact circular axis viewed along that axis. Operations: param.set{name,expr}, material.set{name,density?,appearance?}, material.remove{name}, feature.add{type,name,p,native,inputs,mode,material?,appearance?}, feature.edit{id,p,native,name,material?,appearance?}, feature.remove{id} where id is a number or a unique feature name, plane.set{name,kind?:plane|axis|frame|point,parent,p:{ox,oy,oz,rx,ry,rz},support?:{kind:face|midplane|normal_to_curve|tube_path|on_curve|on_face|offset_plane|angle_plane|plane_three_points|plane_axis_point|plane_point_normal|axis_points|axis_planes|point|between_points,feature,reference,second_feature?,second_reference?,fraction?,station?,u?,v?}}, plane.remove{name}, sketch.set{name,sketch:{plane,tolerance,entities,constraints}}, sketch.entity.set{name,entity}, sketch.patch{name,entity,anchor?,x?,y?,r?,a0?,a1?,segment?,role?}, sketch.remove{name}, sketch.fillet{name,entity,corner,radius}, sketch.chamfer{name,entity,corner,distance}, assembly.add{name,parent,feature,p,visible}, assembly.edit{id,parent,feature,p,visible}, assembly.remove{id}, assembly.drive{driver,mate?,mode?:rotate|translate,delta}. Drive requires expected_revision; delta is degrees for rotate or mm for translate and accepts expressions. It moves the connected side of a grounded joint, retains internal passive coordinates and rechecks every mate; unsupported, ambiguous or unsatisfied motion rejects atomically. Grounded closed linkages and transmission boundaries use measured constrained continuation in the verified domain. id and parent accept a unique node name or a number; parent 0 stays the root. feature=0 is a group; feature and feature inputs accept a unique name or an id, and the saved document stores the id. placements are rigid tx/ty/tz/rx/ry/rz. assembly pattern is type linear or circular with count and dx/dy/dz or step/axis. It repeats one part, a mate moves that pattern rigidly, and degrees of freedom count the node once. Tube feature accepts p{section:round|rect,od,width,height,wall,tail,chord_tol,sides} plus bends:[{feed,radius,angle,roll}] in mm/degrees. A round section is also an exact annular sweep along the centerline, initially +X, and can enter union, cut, common and a concentric axis mate. A rectangular section is an exact hollow sweep along the centerline, initially +X, with width along the normal and height along the binormal, and can enter a boolean. The display mesh remains the viewport tessellation. Sketch entities: kind point|line|circle|spline|arc|wire|recipe (typed recipe source, editable fields; inspect sketch onboarding for defaults), optional unique name, dof numbers or expression strings (strings are driven), construction. Spline dof is 2..64 XY anchor pairs flattened; closed wraps without repeated first point, tension 0..1. Arc entity optionally uses recipe:{type:three_point,start:[x,y],through:[x,y],end:[x,y]} or recipe:{type:tangent,start:[x,y],end:[x,y],tangent:[tx,ty]}; expressions persist and derive driven center/radius/angles, including major/clockwise arcs. Edit the recipe via sketch.entity.set; resolved dof patches reject. Spatial curve arc mode three_point/tangent uses XYZ through/to/tangent; omitted tangent inherits previous exact edge, first requires tangent. Optional normal validates coplanarity; radius arcs allow major:true. Recipes/modes save v30. Constraints val/val2 accept expressions. Entity edits replace one named entity. Mates: revolute aligns origins and +Z, leaving axial rotation; rigid aligns full reference frames and locks all six DOFs (no retain-offset capture). Both save document version29. mate.add{a,b,type,reference_a,reference_b,value}, mate.edit, mate.remove. Mechanical types chain and gear use motion:{teeth_a,teeth_b,phase_deg?}; shaft locks rotational ratio 1:1; rack_pinion uses motion:{pitch_radius,direction?:1|-1}; cam uses harmonic motion:{lift,phase_deg?}. Expressions are persisted in v22. Endpoints are driver a/driven b instance IDs. Mechanical couplings retain independent static geometric positioning; inspect assembly_motion for validated read-only matrices/speeds. Cycles, multiple incoming drivers, fixed/pattern endpoints and incompatible semantic axes reject. Mate ids stay numeric. Pass that id, or omit it and pass endpoints a and b, names or ids, in either order, to select the unique mate. Endpoints a and b accept a unique instance name or an id; the saved mate stores ids. ground instances with assembly.edit{id,fixed:true}. assembly_info candidate probes a mate without saving it. Manufacturing intent: feature.add/edit accepts manufacturing:{route:sheet_metal|machined|frame|purchased|unspecified|injection_molding|additive,process?:object} or null to clear both. This object replaces the full process plan. Injection/additive and nonempty typed process settings save as version23. Call manufacturing onboarding for route-specific field contracts and manufacturing_inspect for exact evidence, blockers and unknowns; declarations do not certify production. Sheet/frame declarations require matching actual authoring lineage, retained by rigid transforms. Declaring purchased identifies a supplier envelope, not supplier validation. Frame endpoint tools: frame.trim_extend{id,joint:{member,end:start|end,against,max_extension}}, frame.trim_plane{id,joint:{member,end,origin,normal}}, frame.joint.remove{id,member,end}, frame.weld.add{id,weld:{id,member_a,member_b,path:[[x,y,z],[x,y,z]],normal:[x,y,z],leg_a,leg_b,material?|density_g_cm3?}}, frame.weld.edit/remove{id,entity,values?}. Exact separate triangular fillet beads are declared geometry; fusion and strength remain unverified. Sheet internal forming: sheet.jog.add{id,jog:{id?,station,height,angle,inner_radius,k_factor?}} and sheet.sketch_bend.add{id,bend:{id?,sketch,entity,angle,inner_radius,k_factor?}}; edit/remove use values. Current domain one original unperforated rectangular blank; full-width XZ sketch line; preserve original flat length. These operations save v25. Sheet edits: sheet.create{name,p:{width,thickness,k_factor},base:{id,length}}, sheet.base.edit{id,values}, sheet.flange.add{id,flange:{id?,parent,edge:u_min|u_max|v_min|v_max,length,width?,offset?,inner_radius,angle,k_factor?}}, sheet.opening.add{id,opening:{id?,panel,kind:circle|slot|window|polygon,x,y,radius,length,width,height,angle,points}}, sheet.opening.pattern{id,opening,count,dx,dy} creates named parametric copies. sheet.flange.edit/sheet.opening.edit{id,entity,values}, sheet.flange.remove/sheet.opening.remove{id,entity,cascade?}. sheet.hem.add{id,hem:{id?,parent,edge,length,inner_radius,direction,width?,offset?,k_factor?}}, sheet.hem.edit/remove{id,entity,values?}. sheet.stamp.add{id,stamp:{id?,panel,kind:circular_emboss,x,y,radius,top_radius,depth}}, sheet.stamp.edit/remove{id,entity,values?}. Hem/stamp and manufacturing intent save as version21. Stamped sheets have an unqualified nominal flat reference; flat STEP/IGES/DXF export rejects. Local expressions: panel_length/panel_width/thickness in openings, parent_length/parent_width/edge_length/thickness in flanges. Native feature types: native_solid{native:{op:box|cylinder|sphere|cone|torus|extrude|union|cut|common|hole|fillet|chamfer|draft|linear_pattern|circular_pattern|mirror|shell|transform,...},inputs,p} exact ops. Fillet/chamfer take native.edges or native.selection sharp|convex|concave|all plus p.min_angle. Draft takes p.angle and native.direction/neutral/faces; freeform faces reject. Patterns take p.count and p.dx/dy/dz or p.step plus native.axis; mirror takes native.plane XY|XZ|YZ or a datum name, or native.face naming one planar face; p.copy_only=1 keeps only the reflected body. split_plane accepts a native.plane or native.face, or native.normal plus optional native.origin, and native.keep positive|negative|both. p.fuse defaults to 0. A Boolean tool may be a compound of those solids. loft{native:{sections:[sketch names],guides?:[1..8 sketch or curve names]},p:{solid,ruled,max_degree?,smooth?,compatible?,continuity?}}. Guides are open curves the sections follow. A one-point sketch is a first or last tip. A smooth loft that fuses sides also lists side. with status merged and the surviving face; native.faces, native.edges and plane support.reference accept that alias, and the document keeps the authored name. Loft edges are edge.start/end. and rail., surface_fill{p:{sketch} or native:{profile}}, bspline_surface{native:{poles,weights?},p:{u_degree,v_degree}}, thicken{inputs:[native surface],p:{thickness}}, sheet_metal{p:{width,leg_a,leg_b,thickness,inner_radius,angle,k_factor},native:{openings?}}. Feature types: sketch_cut{inputs:[base],p:{sketch,depth,offset}}, notched_tube{p:{width_mm,height_mm,wall_mm,length_mm,hinge_offset_mm},notches:[{station,angle,face:bottom|top|left|right}]}, tube, box{dx,dy,dz}, cylinder{r,h}, sphere{r}, cone{rb,rt,h}, torus{R,r}, extrude{shape,w,d,height,sketch}, revolve{shape,w,d,angle,sketch}, transform{tx,ty,tz,rx,ry,rz}, boolean{mode:0 union/1 cut/2 intersect}, pattern{count,dx,dy,dz}, surface{x,y,z,u0,u1,v0,v1,nu,nv,wrap_u,wrap_v}. Geometry parameters belong in p and accept math expressions. Transforms and solid patterns take one input. native_solid union, cut or common accepts 2..16 feature inputs and/or native.instances of placed parts, including every pattern copy, and returns one exact solid. Two-input booleans keep the previous document version. Instance patterns, native.instances, and unions of more than two exact solids save as document version 10. shell, with signed p.thickness and optional native.faces to open, and a loft with native.guides, save as document version 11. A point datum, on_curve or on_face support, a sketch arc or wire, a tangent constraint, and curve, intersection_curve or bridge save as document version 12. feature.edit accepts suppressed: a true value leaves that feature out of recomputation and keeps its history and parameters. Sketch kinds also include project{feature,reference,mode:normal,source_instance?,source_copy?} and offset{source,distance}. Normal projection is an exact associative B-rep; derived display samples are not profile authority. Alternatively project{source_sketch,source_entity,mode:normal} selects one earlier named sketch entity without feature/reference; sources are exclusive. type curve native:{op:project,mode:3d,source_sketch,source_entity} needs no feature inputs. Source-sketch self/future references and cycles reject. Native edge or one planar face boundary sources also supported; curved faces, holes/multiple wires and collapsed geometry reject. Source instance/copy selects solved world placement. Projected entities remain driven; edit their source. type curve with inputs:[source] and native:{op:project,mode:3d,reference,source_instance?,source_copy?} includes the exact spatial edge/wire preserving XYZ, usable as sweep path/loft guide. This is a spatial curve feature, not a general 3D constraint solver. New projection modes/instance fields save version 28. feature is an id or a unique name bound to an id at apply. distance is signed millimetres, positive to the left of the directed curve. Project and offset entities are driven, and sketch.patch rejects them. canvas.set{name,path,plane?,width,height,opacity?} and canvas.remove{name} store a photo rectangle on a plane. The kernel does not decode the image. A plane canvas, a suppressed feature, or a projected or offset sketch entity saves as document version 13. sketch.fillet and sketch.chamfer trim one wire corner; the sharp wire stays the authority and the size stays an expression. A mate across assembly groups moves each immediate parent group and its descendants as one rigid body. Either of those saves document version 14. p.density in grams per cubic centimetre overrides a named material density. material.set assigns density 0..100 g/cm3 (0 means unspecified) and appearance {base_color:[sRGB display values 0..1], metallic:0..1, roughness:0..1, opacity:0..1, texture_path:string, texture_scale:[positive U,V], pattern:twill|weave|carbon|leather|brushed|knurl|perforated|none, pattern_scale_mm, pattern_angle_deg, pattern_contrast, pattern_color (044B display-only procedural patterns, version 47)}; feature appearance is a partial override. Named materials and appearance save as version 15. split_plane and mirror copy_only also save as version 15. An appearance-only batch reports geometry_recomputed:false and retains evaluated geometry. A loft section accepts a point datum. A loft guide and a sweep path accept a curve feature name. Engineering modules construction_frame, pcb and cable_route store editable native programs and save version 16. Call agent_onboard frames or electronics for their contracts. Use expected_revision to reject stale writes. Angles in degrees except trig expressions in radians. Surface coordinates use u,v; periodic seams are checked. Exact surfaces also include sweep{native:{section,path} sketch names or profiles,p:{solid,correction,contact}}, extrude_surface{p:{sketch,distance,solid} or native.profile}, revolve_surface{p:{sketch,angle,solid},native:{axis:X|Y|Z default Y}}, offset_surface{inputs:[one face or shell],p:{distance}}, and sew{inputs:[2..16 faces or shells],p:{solid}}. Mesh features are sampled authority and never become a B-rep: mesh_body{mesh:{positions,indices}}, mesh_weld{inputs,p:{epsilon}}, mesh_smooth{inputs,p:{iterations,lambda,pin_boundary}}, mesh_decimate{inputs,p:{ratio}}, mesh_offset{inputs,p:{distance}}, mesh_fill{inputs}; mesh_edit{inputs,native:{op:displace|extrude,vertices?|triangles?,source_topology},p:{dx,dy,dz}}. Read mesh_inspect.topology_fingerprint before indexed edits. skeleton.set{source} persists native input/relation/array/pattern code; skeleton_compile previews relations and doc_preview validates geometry. An exact B-rep input needs p.sample=1, which opts into the display tessellation. import_mesh reads an STL or OBJ snapshot under the triangle cap.",R"({"type":"object","properties":{"expected_revision":{"type":"integer","minimum":0},"commands":{"type":"array","minItems":1,"maxItems":128,"items":{"type":"object","properties":{"op":{"type":"string","enum":["drawing.set","drawing.refresh","drawing.remove","param.set","material.set","material.remove","feature.add","feature.edit","feature.remove","sketch.set","sketch.entity.set","sketch.patch","sketch.remove","sketch.fillet","sketch.chamfer","canvas.set","canvas.remove","skeleton.set","skeleton.remove","plane.set","plane.remove","assembly.add","assembly.edit","assembly.remove","assembly.drive","mate.add","mate.edit","mate.remove","sheet.create","sheet.base.edit","sheet.flange.add","sheet.flange.edit","sheet.flange.remove","sheet.opening.add","sheet.opening.pattern","sheet.opening.edit","sheet.opening.remove","sheet.hem.add","sheet.hem.edit","sheet.hem.remove","sheet.stamp.add","sheet.stamp.edit","sheet.stamp.remove","frame.trim_extend","frame.trim_plane","frame.joint.remove","frame.weld.add","frame.weld.edit","frame.weld.remove","sheet.jog.add","sheet.jog.edit","sheet.jog.remove","sheet.sketch_bend.add","sheet.sketch_bend.edit","sheet.sketch_bend.remove"]},"entity":{"oneOf":[{"type":"string"},{"type":"object","properties":{"source_sketch":{"type":"string","minLength":1,"maxLength":128},"source_entity":{"type":"string","minLength":1,"maxLength":128},"source_instance":{"type":"integer","minimum":1},"source_copy":{"type":"integer","minimum":0,"maximum":31},"reference":{"type":"string","minLength":1,"maxLength":128},"kind":{"type":"string","enum":["point","line","circle","spline","arc","wire","project","offset"]},"name":{"type":"string","minLength":1,"maxLength":128},"feature":{"oneOf":[{"type":"integer","minimum":1},{"type":"string","minLength":1,"maxLength":128}]},"mode":{"type":"string","enum":["normal"]},"dof":{"type":"array","items":{"oneOf":[{"type":"number"},{"type":"string"}]}},"construction":{"type":"boolean"},"recipe":{"type":"object","properties":{"type":{"type":"string","enum":["three_point","tangent"]},"start":{"type":"array","minItems":2,"maxItems":2,"items":{"type":["number","string"]}},"through":{"type":"array","minItems":2,"maxItems":2,"items":{"type":["number","string"]}},"end":{"type":"array","minItems":2,"maxItems":2,"items":{"type":["number","string"]}},"tangent":{"type":"array","minItems":2,"maxItems":2,"items":{"type":["number","string"]}}},"required":["type","start","end"],"additionalProperties":false}}}]},"native":{"type":"object","properties":{"source_sketch":{"type":"string","minLength":1,"maxLength":128},"source_entity":{"type":"string","minLength":1,"maxLength":128},"source_instance":{"type":"integer","minimum":1},"source_copy":{"type":"integer","minimum":0,"maximum":31},"reference":{"type":"string","minLength":1,"maxLength":128},"op":{"type":"string"},"mode":{"type":"string"}}}},"required":["op"]}}},"required":["commands"]})",false}, + {"doc_apply","Atomic batch; evaluate once, roll back on any failure. BOM: bom.initialize{} assigns persistent document identity; feature.add/edit part:{part_number,description,part_revision,category,procurement:make|buy|unspecified,manufacturer,manufacturer_part_number,supplier,supplier_part_number,source_url,datasheet_url,standard,specification,representation,sourcing_status} replaces declared metadata; null clears it. Prefer feature.edit part_patch:{...} for individual fields: omitted fields are preserved, merged sourcing is validated; cannot combine part and part_patch. Requires expected_revision; metadata-only edits do not recompute geometry. Use bom_inspect to check quantities/missing fields. Technical drawings: drawing.set{drawing:{name,feature,units:mm|in,scale,paper_mm:[width,height],views:[{name,type:orthographic|section,direction:front|back|top|bottom|right|left,offset_mm:[x,y],origin_mm:[x,y,z] for section}],dimensions:[{name,view,kind:linear|horizontal|vertical|radius|diameter,reference_a,reference_b? (linear only),fraction_a?,fraction_b?,position_mm:[x,y],tolerance?:{lower,upper,units}}]}}, drawing.refresh{name}, drawing.remove{name}. Requires expected_revision. One feature-local exact solid; changed B-rep invalidates the binding. Radius/diameter use an exact circular axis viewed along that axis. Operations: param.set{name,expr}, material.set{name,density?,appearance?}, material.remove{name}, feature.add{type,name,p,native,inputs,mode,material?,appearance?}, feature.edit{id,p,native,name,material?,appearance?}, feature.remove{id} where id is a number or a unique feature name, plane.set{name,kind?:plane|axis|frame|point,parent,p:{ox,oy,oz,rx,ry,rz},support?:{kind:face|midplane|normal_to_curve|tube_path|on_curve|on_face|offset_plane|angle_plane|plane_three_points|plane_axis_point|plane_point_normal|axis_points|axis_planes|point|between_points,feature,reference,second_feature?,second_reference?,fraction?,station?,u?,v?}}, plane.remove{name}, sketch.set{name,sketch:{plane,tolerance,entities,constraints}}, sketch.entity.set{name,entity}, sketch.patch{name,entity,anchor?,x?,y?,r?,a0?,a1?,segment?,role?}, sketch.remove{name}, sketch.fillet{name,entity,corner,radius}, sketch.chamfer{name,entity,corner,distance}, assembly.add{name,parent,feature,p,visible}, assembly.edit{id,parent,feature,p,visible}, assembly.remove{id}, assembly.drive{driver,mate?,mode?:rotate|translate,delta}. Drive requires expected_revision; delta is degrees for rotate or mm for translate and accepts expressions. It moves the connected side of a grounded joint, retains internal passive coordinates and rechecks every mate; unsupported, ambiguous or unsatisfied motion rejects atomically. Grounded closed linkages and transmission boundaries use measured constrained continuation in the verified domain. id and parent accept a unique node name or a number; parent 0 stays the root. feature=0 is a group; feature and feature inputs accept a unique name or an id, and the saved document stores the id. placements are rigid tx/ty/tz/rx/ry/rz. assembly pattern is type linear or circular with count and dx/dy/dz or step/axis. It repeats one part, a mate moves that pattern rigidly, and degrees of freedom count the node once. Tube feature accepts p{section:round|rect,od,width,height,wall,tail,chord_tol,sides} plus bends:[{feed,radius,angle,roll}] in mm/degrees. A round section is also an exact annular sweep along the centerline, initially +X, and can enter union, cut, common and a concentric axis mate. A rectangular section is an exact hollow sweep along the centerline, initially +X, with width along the normal and height along the binormal, and can enter a boolean. The display mesh remains the viewport tessellation. Sketch entities: kind point|line|circle|spline|arc|wire|recipe (typed recipe source, editable fields; inspect sketch onboarding for defaults), optional unique name, dof numbers or expression strings (strings are driven), construction. Spline dof is 2..64 XY anchor pairs flattened; closed wraps without repeated first point, tension 0..1. Arc entity optionally uses recipe:{type:three_point,start:[x,y],through:[x,y],end:[x,y]} or recipe:{type:tangent,start:[x,y],end:[x,y],tangent:[tx,ty]}; expressions persist and derive driven center/radius/angles, including major/clockwise arcs. Edit the recipe via sketch.entity.set; resolved dof patches reject. Spatial curve arc mode three_point/tangent uses XYZ through/to/tangent; omitted tangent inherits previous exact edge, first requires tangent. Optional normal validates coplanarity; radius arcs allow major:true. Recipes/modes save v30. Constraints val/val2 accept expressions. Entity edits replace one named entity. Mates: revolute aligns origins and +Z, leaving axial rotation; rigid aligns full reference frames and locks all six DOFs (no retain-offset capture). Both save document version29. mate.add{a,b,type,reference_a,reference_b,value}, mate.edit, mate.remove. Mechanical types chain and gear use motion:{teeth_a,teeth_b,phase_deg?}; shaft locks rotational ratio 1:1; rack_pinion uses motion:{pitch_radius,direction?:1|-1}; cam uses harmonic motion:{lift,phase_deg?}. Expressions are persisted in v22. Endpoints are driver a/driven b instance IDs. Mechanical couplings retain independent static geometric positioning; inspect assembly_motion for validated read-only matrices/speeds. Cycles, multiple incoming drivers, fixed/pattern endpoints and incompatible semantic axes reject. Mate ids stay numeric. Pass that id, or omit it and pass endpoints a and b, names or ids, in either order, to select the unique mate. Endpoints a and b accept a unique instance name or an id; the saved mate stores ids. ground instances with assembly.edit{id,fixed:true}. assembly_info candidate probes a mate without saving it. Manufacturing intent: feature.add/edit accepts manufacturing:{route:sheet_metal|machined|frame|purchased|unspecified|injection_molding|additive,process?:object} or null to clear both. This object replaces the full process plan. Injection/additive and nonempty typed process settings save as version23. Call manufacturing onboarding for route-specific field contracts and manufacturing_inspect for exact evidence, blockers and unknowns; declarations do not certify production. Sheet/frame declarations require matching actual authoring lineage, retained by rigid transforms. Declaring purchased identifies a supplier envelope, not supplier validation. Frame endpoint tools: frame.trim_extend{id,joint:{member,end:start|end,against,max_extension}}, frame.trim_plane{id,joint:{member,end,origin,normal}}, frame.joint.remove{id,member,end}, frame.weld.add{id,weld:{id,member_a,member_b,path:[[x,y,z],[x,y,z]],normal:[x,y,z],leg_a,leg_b,material?|density_g_cm3?}}, frame.weld.edit/remove{id,entity,values?}. Exact separate triangular fillet beads are declared geometry; fusion and strength remain unverified. Sheet internal forming: sheet.jog.add{id,jog:{id?,station,height,angle,inner_radius,k_factor?}} and sheet.sketch_bend.add{id,bend:{id?,sketch,entity,angle,inner_radius,k_factor?}}; edit/remove use values. Current domain one original unperforated rectangular blank; full-width XZ sketch line; preserve original flat length. These operations save v25. Sheet edits: sheet.create{name,p:{width,thickness,k_factor},base:{id,length}}, sheet.base.edit{id,values}, sheet.flange.add{id,flange:{id?,parent,edge:u_min|u_max|v_min|v_max,length,width?,offset?,inner_radius,angle,k_factor?}}, sheet.opening.add{id,opening:{id?,panel,kind:circle|slot|window|polygon,x,y,radius,length,width,height,angle,points}}, sheet.opening.pattern{id,opening,count,dx,dy} creates named parametric copies. sheet.flange.edit/sheet.opening.edit{id,entity,values}, sheet.flange.remove/sheet.opening.remove{id,entity,cascade?}. sheet.hem.add{id,hem:{id?,parent,edge,length,inner_radius,direction,width?,offset?,k_factor?}}, sheet.hem.edit/remove{id,entity,values?}. sheet.stamp.add{id,stamp:{id?,panel,kind:circular_emboss,x,y,radius,top_radius,depth}}, sheet.stamp.edit/remove{id,entity,values?}. Hem/stamp and manufacturing intent save as version21. Stamped sheets have an unqualified nominal flat reference; flat STEP/IGES/DXF export rejects. Local expressions: panel_length/panel_width/thickness in openings, parent_length/parent_width/edge_length/thickness in flanges. Native feature types: native_solid{native:{op:box|cylinder|sphere|cone|torus|extrude|union|cut|common|hole|fillet|chamfer|draft|linear_pattern|circular_pattern|mirror|shell|transform,...},inputs,p} exact ops. Fillet/chamfer take native.edges or native.selection sharp|convex|concave|all plus p.min_angle. Draft takes p.angle and native.direction/neutral/faces; freeform faces reject. Patterns take p.count and p.dx/dy/dz or p.step plus native.axis; mirror takes native.plane XY|XZ|YZ or a datum name, or native.face naming one planar face; p.copy_only=1 keeps only the reflected body. split_plane accepts a native.plane or native.face, or native.normal plus optional native.origin, and native.keep positive|negative|both. p.fuse defaults to 0. A Boolean tool may be a compound of those solids. loft{native:{sections:[sketch names],guides?:[1..8 sketch or curve names]},p:{solid,ruled,max_degree?,smooth?,compatible?,continuity?}}. Guides are open curves the sections follow. A one-point sketch is a first or last tip. A smooth loft that fuses sides also lists side. with status merged and the surviving face; native.faces, native.edges and plane support.reference accept that alias, and the document keeps the authored name. Loft edges are edge.start/end. and rail., surface_fill{p:{sketch} or native:{profile}}, bspline_surface{native:{poles,weights?},p:{u_degree,v_degree}}, thicken{inputs:[native surface],p:{thickness}}, sheet_metal{p:{width,leg_a,leg_b,thickness,inner_radius,angle,k_factor},native:{openings?}}. Feature types: sketch_cut{inputs:[base],p:{sketch,depth,offset}}, notched_tube{p:{width_mm,height_mm,wall_mm,length_mm,hinge_offset_mm},notches:[{station,angle,face:bottom|top|left|right}]}, tube, box{dx,dy,dz}, cylinder{r,h}, sphere{r}, cone{rb,rt,h}, torus{R,r}, extrude{shape,w,d,height,sketch}, revolve{shape,w,d,angle,sketch}, transform{tx,ty,tz,rx,ry,rz}, boolean{mode:0 union/1 cut/2 intersect}, pattern{count,dx,dy,dz}, surface{x,y,z,u0,u1,v0,v1,nu,nv,wrap_u,wrap_v}. Geometry parameters belong in p and accept math expressions. Transforms and solid patterns take one input. native_solid union, cut or common accepts 2..16 feature inputs and/or native.instances of placed parts, including every pattern copy, and returns one exact solid. Two-input booleans keep the previous document version. Instance patterns, native.instances, and unions of more than two exact solids save as document version 10. shell, with signed p.thickness and optional native.faces to open, and a loft with native.guides, save as document version 11. A point datum, on_curve or on_face support, a sketch arc or wire, a tangent constraint, and curve, intersection_curve or bridge save as document version 12. feature.edit accepts suppressed: a true value leaves that feature out of recomputation and keeps its history and parameters. Sketch kinds also include project{feature,reference,mode:normal,source_instance?,source_copy?} and offset{source,distance}. Normal projection is an exact associative B-rep; derived display samples are not profile authority. Alternatively project{source_sketch,source_entity,mode:normal} selects one earlier named sketch entity without feature/reference; sources are exclusive. type curve native:{op:project,mode:3d,source_sketch,source_entity} needs no feature inputs. Source-sketch self/future references and cycles reject. Native edge or one planar face boundary sources also supported; curved faces, holes/multiple wires and collapsed geometry reject. Source instance/copy selects solved world placement. Projected entities remain driven; edit their source. type curve with inputs:[source] and native:{op:project,mode:3d,reference,source_instance?,source_copy?} includes the exact spatial edge/wire preserving XYZ, usable as sweep path/loft guide. This is a spatial curve feature, not a general 3D constraint solver. New projection modes/instance fields save version 28. feature is an id or a unique name bound to an id at apply. distance is signed millimetres, positive to the left of the directed curve. Project and offset entities are driven, and sketch.patch rejects them. canvas.set{name,path,plane?,width,height,opacity?} and canvas.remove{name} store a photo rectangle on a plane. The kernel does not decode the image. A plane canvas, a suppressed feature, or a projected or offset sketch entity saves as document version 13. sketch.fillet and sketch.chamfer trim one wire corner; the sharp wire stays the authority and the size stays an expression. A mate across assembly groups moves each immediate parent group and its descendants as one rigid body. Either of those saves document version 14. p.density in grams per cubic centimetre overrides a named material density. material.set assigns density 0..100 g/cm3 (0 means unspecified) and appearance {base_color:[sRGB display values 0..1], metallic:0..1, roughness:0..1, opacity:0..1, texture_path:string, texture_scale:[positive U,V], pattern:twill|weave|carbon|leather|brushed|knurl|perforated|none, pattern_scale_mm, pattern_angle_deg, pattern_contrast, pattern_color (044B display-only procedural patterns, version 47)}; feature appearance is a partial override. Named materials and appearance save as version 15. split_plane and mirror copy_only also save as version 15. An appearance-only batch reports geometry_recomputed:false and retains evaluated geometry. A loft section accepts a point datum. A loft guide and a sweep path accept a curve feature name. Engineering modules construction_frame, pcb and cable_route store editable native programs and save version 16. Call agent_onboard frames or electronics for their contracts. Use expected_revision to reject stale writes. Angles in degrees except trig expressions in radians. Surface coordinates use u,v; periodic seams are checked. Exact surfaces also include sweep{native:{section,path} sketch names or profiles,p:{solid,correction,contact}}, extrude_surface{p:{sketch,distance,solid} or native.profile}, revolve_surface{p:{sketch,angle,solid},native:{axis:X|Y|Z default Y}}, offset_surface{inputs:[one face or shell],p:{distance}}, and sew{inputs:[2..16 faces or shells],p:{solid}}. Mesh features are sampled authority and never become a B-rep: mesh_body{mesh:{positions,indices}}, mesh_weld{inputs,p:{epsilon}}, mesh_smooth{inputs,p:{iterations,lambda,pin_boundary}}, mesh_decimate{inputs,p:{ratio}}, mesh_offset{inputs,p:{distance}}, mesh_fill{inputs}; mesh_edit{inputs,native:{op:displace|extrude,vertices?|triangles?,source_topology},p:{dx,dy,dz}}. Read mesh_inspect.topology_fingerprint before indexed edits. skeleton.set{source} persists native input/relation/array/pattern code; skeleton_compile previews relations and doc_preview validates geometry. An exact B-rep input needs p.sample=1, which opts into the display tessellation. import_mesh reads an STL or OBJ snapshot under the triangle cap.",R"({"type":"object","properties":{"expected_revision":{"type":"integer","minimum":0},"commands":{"type":"array","minItems":1,"maxItems":128,"items":{"type":"object","properties":{"op":{"type":"string","enum":["drawing.set","drawing.refresh","drawing.remove","param.set","material.set","material.remove","feature.add","feature.edit","feature.remove","sketch.set","sketch.entity.set","sketch.patch","sketch.remove","sketch.fillet","sketch.chamfer","canvas.set","canvas.remove","skeleton.set","skeleton.remove","plane.set","plane.remove","assembly.add","assembly.edit","assembly.remove","assembly.drive","mate.add","mate.edit","mate.remove","sheet.create","sheet.base.edit","sheet.flange.add","sheet.flange.edit","sheet.flange.remove","sheet.opening.add","sheet.opening.pattern","sheet.opening.edit","sheet.opening.remove","sheet.hem.add","sheet.hem.edit","sheet.hem.remove","sheet.stamp.add","sheet.stamp.edit","sheet.stamp.remove","frame.trim_extend","frame.trim_plane","frame.joint.remove","frame.weld.add","frame.weld.edit","frame.weld.remove","sheet.jog.add","sheet.jog.edit","sheet.jog.remove","sheet.sketch_bend.add","sheet.sketch_bend.edit","sheet.sketch_bend.remove"]},"entity":{"oneOf":[{"type":"string"},{"type":"object","properties":{"source_sketch":{"type":"string","minLength":1,"maxLength":128},"source_entity":{"type":"string","minLength":1,"maxLength":128},"source_instance":{"type":"integer","minimum":1},"source_copy":{"type":"integer","minimum":0,"maximum":31},"reference":{"type":"string","minLength":1,"maxLength":128},"kind":{"type":"string","enum":["point","line","circle","spline","arc","wire","project","offset"]},"name":{"type":"string","minLength":1,"maxLength":128},"feature":{"oneOf":[{"type":"integer","minimum":1},{"type":"string","minLength":1,"maxLength":128}]},"mode":{"type":"string","enum":["normal"]},"dof":{"type":"array","items":{"oneOf":[{"type":"number"},{"type":"string"}]}},"construction":{"type":"boolean"},"recipe":{"type":"object","properties":{"type":{"type":"string","enum":["three_point","tangent"]},"start":{"type":"array","minItems":2,"maxItems":2,"items":{"type":["number","string"]}},"through":{"type":"array","minItems":2,"maxItems":2,"items":{"type":["number","string"]}},"end":{"type":"array","minItems":2,"maxItems":2,"items":{"type":["number","string"]}},"tangent":{"type":"array","minItems":2,"maxItems":2,"items":{"type":["number","string"]}}},"required":["type","start","end"],"additionalProperties":false}}}]},"native":{"type":"object","properties":{"source_sketch":{"type":"string","minLength":1,"maxLength":128},"source_entity":{"type":"string","minLength":1,"maxLength":128},"source_instance":{"type":"integer","minimum":1},"source_copy":{"type":"integer","minimum":0,"maximum":31},"reference":{"type":"string","minLength":1,"maxLength":128},"op":{"type":"string"},"mode":{"type":"string"}}}},"required":["op"]}}},"required":["commands"]})",false}, {"plane_inspect","Read a named construction datum world transform. Built-ins: Origin (point at world zero), XY, XZ (normal -Y), YZ (normal +X). Origin stays kind point. Offsets/XYZ Euler rotations are relative to parent.",R"({"type":"object","properties":{"name":{"type":"string"}},"required":["name"]})",true}, {"sketch_inspect","Read resolved sketch coordinates, local constraint rank/remaining DOFs, profile readiness and sampling counts. Optional samples:true includes local/world polylines. Optional entity returns that entity's length, bbox and end tangents without every coordinate. Spline chord tolerance bounds curve approximation, not manufacturing accuracy.",R"({"type":"object","properties":{"name":{"type":"string"},"samples":{"type":"boolean"},"entity":{"type":"string"}},"required":["name"]})",true}, {"sketch_diagnose","Diagnose a named sketch or an uncommitted sketch candidate. Evaluates dimensions, attempts solve, reports each constraint residual and local rank/redundancy even if inconsistent. Does not mutate the document; no minimal conflict-set claim.",R"({"type":"object","properties":{"name":{"type":"string"},"sketch":{"type":"object"}},"oneOf":[{"required":["name"]},{"required":["sketch"]}]})",true}, @@ -1665,7 +1690,12 @@ V AgentSession::tools(bool detailed){ if(std::string(d.name)=="native_inspect"){V props=*schema.find("properties"),detail;arkjson::parse(R"({"type":"string","enum":["full","report","properties"],"description":"properties projects current native validity, volume/area/bounds and authority flags; operation diagnostics/openings/topology omitted. report retains operation diagnostics; full includes topology/panels/bends."})",detail);props.set("detail",detail);schema.set("properties",props);} if(std::string(d.name)=="doc_info"){V props=*schema.find("properties"),detail,known;arkjson::parse(R"({"type":"string","enum":["summary","design","revision","digest"],"description":"revision returns current revision/status without any object inventory; summary preserves the legacy catalog; design supports ids/sections; digest returns compact per-revision rows with fingerprints."})",detail);props.set("detail",detail); arkjson::parse(R"({"type":"object","maxProperties":4096,"additionalProperties":{"type":"string","maxLength":64},"description":"detail digest only: the fingerprints map from an earlier digest. Unchanged rows are then omitted and removed keys listed."})",known);props.set("known_fingerprints",known);schema.set("properties",props);} - if(std::string(d.name)=="agent_onboard"){V props=*schema.find("properties"),detail;arkjson::parse(R"({"type":"string","enum":["full","guide"],"description":"guide returns reusable static guidance without document state; full preserves document inventory. Prefer guide plus doc_info detail revision and selected object_context."})",detail);props.set("detail",detail);schema.set("properties",props);} + if(std::string(d.name)=="agent_onboard"){ + V props=*schema.find("properties"),detail,fields;arkjson::parse(R"({"type":"string","enum":["full","guide"],"description":"guide returns reusable static guidance without document state; full preserves document inventory. The commands topic always excludes document state."})",detail);props.set("detail",detail); + V topic=*props.find("topic"),topics=*topic.find("enum");topics.arr.push_back(V::makeStr("commands"));topics.arr.push_back(V::makeStr("rubber"));topic.set("enum",topics);props.set("topic",topic); + arkjson::parse(R"({"query":{"type":"string","maxLength":128,"description":"commands topic only: find tools and parameterized recipes by words."},"limit":{"type":"integer","minimum":1,"maximum":16},"command":{"type":"string","minLength":1,"maxLength":128,"description":"commands topic only: recipe ID or tool: for its exact contract. An exact tool selection also exposes that tool if allowed by this agent's catalogue."},"parameters":{"type":"object","description":"commands topic only: values matching the chosen recipe parameter_schema. Produces a prepared_call without executing it; expected_revision is explicit."}})",fields); + for(const auto& field:fields.obj)props.set(field.first,field.second);schema.set("properties",props);t.set("description",V::makeStr(t.find("description")->str+" Use topic:commands with query for compact command discovery, or command plus parameters for a prepared call.")); + } if(std::string(d.name)=="assembly_info"){V props=*schema.find("properties"),detail;arkjson::parse(R"({"type":"string","enum":["full","result"],"description":"result requires exactly one measure/clearance/drive/sweep and returns its evidence plus revision, without document inventory/BOM/mass/interference. full/default preserves legacy inspection."})",detail);props.set("detail",detail);schema.set("properties",props);} if(std::string(d.name)=="doc_apply"){ {V props=*schema.find("properties"),detail;arkjson::parse(R"({"type":"string","enum":["full","design","changes"],"description":"changes returns revision/evaluation/created-ID/check receipts without a document inventory; full/default and design retain the legacy response."})",detail);props.set("detail",detail);schema.set("properties",props);} @@ -1678,6 +1708,7 @@ if(std::string(d.name)=="doc_apply"){ "id":{"type":["integer","string","null"],"description":"Required target for feature.edit/remove and assembly.edit/remove: positive id or unique name. feature.rollback accepts null to resume all history. Mate ids are numeric; mate endpoints a/b may select a unique mate instead."}, "type":{"type":"string","description":"Feature type on feature.add; mate type on mate.add/edit."}, "name":{"type":"string","minLength":1,"description":"Feature/instance label, parameter name, sketch name or datum name for the selected operation."}, + "owner_feature":{"type":["integer","string"],"description":"Sketch commands only: existing shared feature definition ID or unique name; name is local to this owner. Omit for legacy globals or an existing canonical part::: reference. Occurrences reuse definition sketches. New scoped names are 1..96 characters."}, "p":{"type":"object","additionalProperties":{"type":["number","string"]},"description":"Editable parameters, each a finite number or expression string. Use actual authored keys from object_context: native_solid box uses width/depth/height; legacy box uses dx/dy/dz. feature.edit uses id plus p, not entity. Rigid placements use tx/ty/tz/rx/ry/rz."}, "inputs":{"type":"array","items":{"type":["integer","string"]},"description":"Feature inputs as positive ids or unique feature names, in operation order."}, "expr":{"type":["number","string"],"description":"param.set value or one sketch.patch coordinate expression."}, @@ -1706,12 +1737,16 @@ if(std::string(d.name)=="doc_apply"){ {V operation=*commandProps.find("op"),choices=*operation.find("enum");for(const char* op:{"feature.move","feature.rollback","configuration.set","configuration.apply","configuration.remove","assembly.load","assembly.external.set","assembly.external.remove","motion.graph.set","motion.bake","motion.rename","motion.remove"})choices.arr.push_back(V::makeStr(op));operation.set("enum",choices);commandProps.set("op",operation); V fields;arkjson::parse(R"({"parameters":{"type":"object","additionalProperties":{"type":["number","string"]}},"visibility":{"type":"object","additionalProperties":{"type":"boolean"}},"roots":{"type":["array","null"],"items":{"type":"integer","minimum":1},"uniqueItems":true},"source_sha256":{"type":"string","pattern":"^[0-9a-f]{64}$"},"source_revision":{"type":"string","minLength":1},"graph":{"type":"object","description":"motion.graph.set vector motion graph {channels:[{name,mate,from?,curve|expr}],duration_s?,allow_jumps?}; agent_onboard motion has the node grammar."},"fps":{"type":"integer","minimum":1,"maximum":240},"new_name":{"type":"string","minLength":1,"maxLength":128}})",fields);for(const auto& entry:fields.obj)commandProps.set(entry.first,entry.second);} commandProps.set("drawing",drawingAuthoringSchema()); + {V operation=*commandProps.find("op"),choices=*operation.find("enum");for(const char* op:{"classification.set","schematic.set","schematic.remove"})choices.arr.push_back(V::makeStr(op));operation.set("enum",choices);commandProps.set("op",operation); + V fields;arkjson::parse(R"({"node":{"type":"integer","minimum":1},"families":{"type":"array","maxItems":6,"uniqueItems":true,"items":{"enum":["electrical","electronics","mechanical","bodywork","sheet_metal","plastics"]}},"tags":{"type":"array","maxItems":16,"uniqueItems":true,"items":{"type":"string","minLength":1,"maxLength":64}},"classification":{"type":["object","null"],"description":"Optional definition/occurrence metadata {families:[published family],tags:[short label]}; null clears. Requires expected_revision."},"sheet":{"type":"object","description":"Editable electrical sheet; agent_onboard schematics and schematic_inspect describe symbols, pins, explicit nets and BOM. Crossings do not connect wires.","properties":{"name":{"type":"string","minLength":1,"maxLength":128},"title":{"type":"string"},"width":{"type":"number","minimum":50,"maximum":2000},"height":{"type":"number","minimum":50,"maximum":2000},"symbols":{"type":"array","maxItems":512,"items":{"type":"object","description":"{id,ref,kind:block|connector|resistor|switch|ground|power,x,y,pins:[{id,x,y,label?}],label?,rotation?:0|90|180|270,width?,height?,feature?|node?,copy?,part_number?,manufacturer?,description?,bom?:boolean}"}},"wires":{"type":"array","maxItems":2048,"items":{"type":"object","description":"{id,net,from:{symbol,pin},to:{symbol,pin},points?:[[x,y],...]}; coordinates in sheet mm"}}},"required":["name","symbols","wires"],"additionalProperties":false}})",fields);for(const auto& field:fields.obj)commandProps.set(field.first,field.second);} {V pattern;arkjson::parse(R"({"oneOf":[{"type":"null"},{"type":"object","properties":{"type":{"type":"string","enum":["linear","circular","pattern_driven","sketch_driven","curve_driven","chain"]},"count":{"type":["number","string"],"description":"2..32 for curve/chain; pattern/sketch may infer stable slots."},"dx":{"type":["number","string"]},"dy":{"type":["number","string"]},"dz":{"type":["number","string"]},"step":{"type":["number","string"]},"axis":{"type":"string","enum":["X","Y","Z"]},"skips":{"type":"array","items":{"type":"integer","minimum":1,"maximum":31},"uniqueItems":true,"maxItems":31},"source":{"type":"object","description":"Bound source recipe. Onboard assembly for actual points, guide, inheritance and chain contracts.","properties":{"node":{"type":["integer","string"]},"feature":{"type":["integer","string"]},"sketch":{"type":"string"},"points":{"type":"array","items":{"type":"string"}},"reference":{"type":"string"},"spacing":{"enum":["equal","pitch"]},"pitch":{"type":["number","string"]},"margin":{"type":["number","string"]},"alignment":{"enum":["fixed","tangent"]},"normal":{"type":"array","minItems":3,"maxItems":3,"items":{"type":["number","string"]}},"closed":{"type":"boolean"},"endpoint":{"enum":["exclude","include"]},"max_source_error":{"type":["number","string"]},"alternate_feature":{"type":["integer","string"]},"alternate_node":{"type":["integer","string"]},"alternate_angle":{"type":["number","string"]}},"additionalProperties":false}},"required":["type"],"additionalProperties":false}]})",pattern);commandProps.set("pattern",pattern);} {V pattern=*commandProps.find("pattern"),variants=*pattern.find("oneOf"),shape=variants.arr[1],props=*shape.find("properties"),carry;arkjson::parse(R"({"type":"array","minItems":16,"maxItems":16,"items":{"type":"number"},"description":"Optional proper rigid column-major transform carrying the entire pattern before node placement; identity when omitted."})",carry);props.set("carry_frame",carry);shape.set("properties",props);variants.arr[1]=shape;pattern.set("oneOf",variants);commandProps.set("pattern",pattern);} {V operation=*commandProps.find("op"),choices=*operation.find("enum");for(const char* family:{"miter","swept_flange","corner","rip","tab"})for(const char* action:{"add","edit","remove"})choices.arr.push_back(V::makeStr(std::string("sheet.")+family+"."+action));choices.arr.push_back(V::makeStr("sheet.bend_table.set"));choices.arr.push_back(V::makeStr("sheet.bend_table.remove"));operation.set("enum",choices);commandProps.set("op",operation); V object;arkjson::parse(R"({"type":"object","description":"Editable authored sheet operation; agent_onboard sheet supplies exact operation-specific required fields. Unknown geometry fields reject at runtime."})",object);for(const char* field:{"miter","swept_flange","corner","rip","tab","table","base","flange","opening","hem","stamp"})if(std::string(field)=="corner"){V options=V::makeArr();options.arr.push_back(*commandProps.find("corner"));options.arr.push_back(object);V combined=V::makeObj();combined.set("oneOf",options);commandProps.set(field,combined);}else commandProps.set(field,object); } V part=V::makeObj(),partChoices=V::makeArr(),empty=V::makeObj();empty.set("type",V::makeStr("null"));partChoices.arr.push_back(partMetadataSchema());partChoices.arr.push_back(empty);part.set("oneOf",partChoices);commandProps.set("part",part); + {V patch=partMetadataSchema();patch.obj.erase(std::remove_if(patch.obj.begin(),patch.obj.end(),[](const auto& entry){return entry.first=="anyOf";}),patch.obj.end());patch.set("minProperties",V::makeNum(1));patch.set("description",V::makeStr("feature.edit only: merge these fields into existing declared metadata; all omitted fields are preserved. Cannot combine with part. Merged sourcing is validated atomically. Use part for intentional full replacement."));commandProps.set("part_patch",patch);} + if(auto entity=commandProps.find("entity");entity&&entity->find("oneOf")){ V variants=*entity->find("oneOf"); if(variants.arr.size()>1){V shape=variants.arr[1],properties=*shape.find("properties"),kind=*properties.find("kind"),choices=*kind.find("enum");choices.arr.push_back(V::makeStr("recipe"));kind.set("enum",choices);properties.set("kind",kind); @@ -1734,7 +1769,12 @@ if(std::string(d.name)=="doc_apply"){ enrichModeling031BSchemas(list); {V tool=V::makeObj(),schema,annotations=V::makeObj();tool.set("name",V::makeStr("context_graph"));tool.set("description",V::makeStr("Retrieve a small linked project context by query or exact keys. Includes authored dependencies/backlinks and attributed saved feedback; no geometry evaluation. Use known_scope and known_fingerprints to omit unchanged facts. Read object_context/native evidence before editing; this graph grants no write or manufacturing authority."));arkjson::parse(R"({"type":"object","properties":{"query":{"type":"string","maxLength":256},"keys":{"type":"array","minItems":1,"maxItems":64,"items":{"type":"string","maxLength":256}},"depth":{"type":"integer","minimum":0,"maximum":2},"limit":{"type":"integer","minimum":1,"maximum":64},"history_limit":{"type":"integer","minimum":0,"maximum":8},"expected_revision":{"type":"integer","minimum":0},"known_scope":{"type":"string","maxLength":256},"known_fingerprints":{"type":"object","additionalProperties":{"type":"string","maxLength":64}}},"additionalProperties":false})",schema);tool.set("inputSchema",schema);annotations.set("readOnlyHint",V::makeBool(true));tool.set("annotations",annotations);list.arr.push_back(tool);} for(auto& tool:list.arr)if(tool.find("name")->str=="doc_apply"){V schema=*tool.find("inputSchema"),props=*schema.find("properties"),flag=V::makeObj();flag.set("type",V::makeStr("boolean"));props.set("refresh_candidate",flag);schema.set("properties",props);tool.set("inputSchema",schema);} - appendProjectMemoryTools(list); + appendProjectMemoryTools(list);appendParametricComponentTools(list);appendDesignDisciplineTools(list); + for(auto& tool:list.arr)if(tool.find("name")->str=="doc_apply"||tool.find("name")->str=="doc_preview"){ + V schema=*tool.find("inputSchema"),props=*schema.find("properties"),commands=*props.find("commands"),items=*commands.find("items"),cp=*items.find("properties"),op=*cp.find("op"),en=*op.find("enum"); + for(const auto* name:{"component.insert","component.update","component.configure"})en.arr.push_back(V::makeStr(name));op.set("enum",en);cp.set("op",op); + for(const auto* key:{"package","overrides"}){V shape=V::makeObj();shape.set("type",V::makeStr("object"));cp.set(key,shape);}for(const auto* key:{"namespace","package_sha256","expected_package_sha256"}){V shape=V::makeObj();shape.set("type",V::makeStr("string"));cp.set(key,shape);}items.set("properties",cp);commands.set("items",items);props.set("commands",commands);schema.set("properties",props);tool.set("inputSchema",schema); + } return list; } Document makeDemoDocument(){ diff --git a/src/agent_benchmark.cpp b/src/agent_benchmark.cpp index cfa41d2..0acb30b 100644 --- a/src/agent_benchmark.cpp +++ b/src/agent_benchmark.cpp @@ -1,6 +1,15 @@ #include "ark/agent_benchmark.hpp" #include "ark/agent.hpp" #include "ark/agent_team.hpp" +#include "ark/iteration_history.hpp" +#include "ark/version.hpp" +#include +#include +#include +#include +#ifdef _WIN32 +#include +#endif #include #include #include @@ -27,34 +36,109 @@ V usageJson(const AssistantUsage& u){V v=V::makeObj();v.set("input_tokens",V::ma V performanceJson(const AssistantPerformance& p){V v=V::makeObj();v.set("provider_requests",V::makeNum((double)p.providerRequests));v.set("provider_ms",V::makeNum((double)p.providerMilliseconds));v.set("tool_calls",V::makeNum((double)p.toolCalls));v.set("tool_ms",V::makeNum((double)p.toolMilliseconds));v.set("request_bytes",V::makeNum((double)p.requestBytes));v.set("input_bytes",V::makeNum((double)p.inputBytes));v.set("tool_schema_bytes",V::makeNum((double)p.toolSchemaBytes));v.set("max_request_bytes",V::makeNum((double)p.maxRequestBytes));return v;} V offlineCall(unsigned n,const std::string& name,const V& args){V r=json(R"({"status":"completed","output":[]})"),call=V::makeObj();call.set("type",V::makeStr("function_call"));call.set("call_id",V::makeStr("benchmark-"+std::to_string(n)));call.set("name",V::makeStr(name));call.set("arguments",V::makeStr(args.dump()));r.find("output");auto out=need(r,"output");out.arr.push_back(call);r.set("output",out);return r;} AssistantTransport scripted(const AgentBenchmarkCase& test,AgentSession& session,bool lead,bool writer,bool team){auto stage=std::make_shared(0);return [&,stage,lead,writer,team](const AssistantConfig&,const V&,const std::atomic_bool*){auto n=++*stage;if(n==1)return offlineCall(n,"doc_info",json(R"({"detail":"design"})"));if(writer&&n==2){V args=V::makeObj();args.set("expected_revision",V::makeNum(session.revision));args.set("commands",test.reference);return offlineCall(n,"doc_apply",args);}if(lead&&team&&n==3)return offlineCall(n,"team_finish_goal",json(R"({"state":"completed","summary":"Scripted native reference executed; benchmark acceptance remains external. No LLM quality or manufacture claim."})"));return json(R"({"status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Scripted harness turn complete."}]}]})");};} -V selectedTools(){V tools=V::makeArr();const std::set names={"doc_info","doc_apply","object_context","native_inspect","sketch_inspect","assembly_info","eval_expr","agent_onboard","query_batch","reference_inspect"};for(const auto& tool:AgentSession::tools().arr)if(names.count(word(tool,"name")))tools.arr.push_back(tool);return tools;} +V selectedTools(){V tools=V::makeArr();const std::set names={"doc_info","doc_get","doc_apply","object_context","native_inspect","sketch_inspect","assembly_info","eval_expr","agent_onboard","query_batch","reference_inspect"};for(const auto& tool:AgentSession::tools().arr)if(names.count(word(tool,"name")))tools.arr.push_back(tool);return tools;} const char* protocolName(AssistantProtocol p){return p==AssistantProtocol::Responses?"responses":p==AssistantProtocol::ChatCompletions?"chat_completions":"messages";} -V strategyTotals(const V& attempts){V totals=V::makeArr();for(const auto* strategy:{"Single","Focused","Parallel"}){unsigned count=0,accepted=0,usageMissing=0,usageReported=0,unknown=0;std::uint64_t tokens=0,providerMs=0,toolMs=0,bytes=0;std::vector elapsed;for(const auto& row:attempts.arr)if(need(row,"strategy").str==strategy){++count;accepted+=need(row,"accepted").b?1:0;if(auto duration=row.find("elapsed_ms"))elapsed.push_back(duration->num);if(auto usage=row.find("usage")){tokens+=(std::uint64_t)need(*usage,"total_tokens").num;usageMissing+=(unsigned)need(*usage,"missing_responses").num;usageReported+=(unsigned)need(*usage,"reported_responses").num;}else ++unknown;if(auto performance=row.find("performance")){providerMs+=(std::uint64_t)need(*performance,"provider_ms").num;toolMs+=(std::uint64_t)need(*performance,"tool_ms").num;bytes+=(std::uint64_t)need(*performance,"request_bytes").num;}}if(!count)continue;std::sort(elapsed.begin(),elapsed.end());V row=V::makeObj();row.set("strategy",V::makeStr(strategy));row.set("attempt_count",V::makeNum(count));row.set("accepted_count",V::makeNum(accepted));row.set("failed_attempt_count",V::makeNum(count-accepted));row.set("reported_total_tokens",V::makeNum((double)tokens));row.set("reported_responses",V::makeNum(usageReported));row.set("missing_responses",V::makeNum(usageMissing));row.set("attempts_without_usage",V::makeNum(unknown));row.set("provider_ms",V::makeNum((double)providerMs));row.set("tool_ms",V::makeNum((double)toolMs));row.set("request_bytes",V::makeNum((double)bytes));row.set("median_attempt_ms",elapsed.empty()?V{}:V::makeNum(elapsed.size()%2?elapsed[elapsed.size()/2]:(elapsed[elapsed.size()/2-1]+elapsed[elapsed.size()/2])/2));row.set("cost_per_accepted_design",V{});totals.arr.push_back(row);}return totals;} -V attempt(const AgentBenchmarkSuite& suite,const AgentBenchmarkCase& test,const AgentBenchmarkConfig& config,const std::string& strategy,unsigned repetition,bool live){ - V result=V::makeObj();result.set("type",V::makeStr("attempt"));result.set("suite",V::makeStr(suite.id));result.set("suite_version",V::makeNum(suite.version));result.set("case",V::makeStr(test.id));result.set("case_version",V::makeNum(test.version));result.set("strategy",V::makeStr(strategy));result.set("repetition",V::makeNum(repetition));result.set("transport",V::makeStr(live?"live_provider":"offline_scripted_harness"));result.set("provider",V::makeStr(config.assistant.provider));result.set("model",V::makeStr(config.assistant.model));result.set("reasoning_effort",V::makeStr(config.assistant.reasoningEffort));result.set("configured_protocol",V::makeStr(protocolName(config.assistant.protocol)));result.set("effective_protocol",V::makeStr(live?protocolName(config.assistant.protocol):"responses"));result.set("brief",V::makeStr(test.brief));result.set("criteria",test.checks);result.set("baseline_commands",test.baseline);result.set("human_blind_review",V::makeStr("pending"));result.set("cost",V{});result.set("cost_reason",V::makeStr("No verified tariff/payment receipt supplied; missing usage is unknown, never zero-cost evidence.")); +V strategyTotals(const V& attempts){V totals=V::makeArr();for(const auto* strategy:{"Single","Focused","Parallel","PartFocused"}){double cost=0;std::string costContext;unsigned costUnknown=0;unsigned count=0,accepted=0,completed=0,persisted=0,usageMissing=0,usageReported=0,unknown=0;std::uint64_t tokens=0,providerMs=0,toolMs=0,bytes=0;std::vector elapsed;for(const auto& row:attempts.arr)if(need(row,"strategy").str==strategy){++count;completed+=row.find("completed")&&row.find("completed")->b;persisted+=row.find("persisted")&&row.find("persisted")->b;if(auto value=row.find("cost");value&&value->t==V::Num){ + const auto& tariff=need(row,"tariff");if(tariff.t!=V::Obj||word(tariff,"provider")!=word(row,"provider")||word(tariff,"model")!=word(row,"model")||!std::isfinite(value->num)||value->num<0)throw std::runtime_error("Invalid priced benchmark attempt provenance"); + const auto context=tariff.dump();if(!costContext.empty()&&costContext!=context)throw std::runtime_error("Cannot aggregate benchmark costs across different tariffs, currencies or model provenance");costContext=context;cost+=value->num; + }else ++costUnknown;accepted+=need(row,"accepted").b?1:0;if(auto duration=row.find("elapsed_ms"))elapsed.push_back(duration->num);if(auto usage=row.find("usage")){tokens+=(std::uint64_t)need(*usage,"total_tokens").num;usageMissing+=(unsigned)need(*usage,"missing_responses").num;usageReported+=(unsigned)need(*usage,"reported_responses").num;}else ++unknown;if(auto performance=row.find("performance")){providerMs+=(std::uint64_t)need(*performance,"provider_ms").num;toolMs+=(std::uint64_t)need(*performance,"tool_ms").num;bytes+=(std::uint64_t)need(*performance,"request_bytes").num;}}if(!count)continue;std::sort(elapsed.begin(),elapsed.end());V row=V::makeObj();row.set("strategy",V::makeStr(strategy));row.set("attempt_count",V::makeNum(count));row.set("accepted_count",V::makeNum(accepted));row.set("completed_count",V::makeNum(completed));row.set("persisted_count",V::makeNum(persisted));row.set("failed_attempt_count",V::makeNum(count-accepted));row.set("reported_total_tokens",V::makeNum((double)tokens));row.set("reported_responses",V::makeNum(usageReported));row.set("missing_responses",V::makeNum(usageMissing));row.set("attempts_without_usage",V::makeNum(unknown));row.set("provider_ms",V::makeNum((double)providerMs));row.set("tool_ms",V::makeNum((double)toolMs));row.set("request_bytes",V::makeNum((double)bytes));row.set("median_attempt_ms",elapsed.empty()?V{}:V::makeNum(elapsed.size()%2?elapsed[elapsed.size()/2]:(elapsed[elapsed.size()/2-1]+elapsed[elapsed.size()/2])/2));row.set("cost_unknown_attempts",V::makeNum(costUnknown));row.set("known_attempt_cost",count>costUnknown?V::makeNum(cost):V{});row.set("cost_per_accepted_design",!costUnknown&&accepted?V::makeNum(cost/accepted):V{});totals.arr.push_back(row);}return totals;} +V buildIdentity(){ + V result=V::makeObj();result.set("version",V::makeStr(ARK_APP_VERSION));result.set("iteration",V::makeStr(ARK_ITERATION_CODE));result.set("executable_sha256",V{}); + std::filesystem::path executable; +#ifdef _WIN32 + std::wstring path(32768,L'\0');auto size=GetModuleFileNameW(nullptr,path.data(),(DWORD)path.size());if(size&&size