From bb184334f74edd3ebc61200850ba08049ff0345d Mon Sep 17 00:00:00 2001 From: Bruno Santos Date: Thu, 22 Oct 2026 08:46:34 +0100 Subject: [PATCH 01/69] docs(051A): define five implementation scopes and acceptance gates [skip ci] --- docs/ROADMAP.md | 6 ++++++ docs/iterations/051A.md | 24 ++++++++++++++++++++++++ release.json | 18 +++++++++++------- 3 files changed, 41 insertions(+), 7 deletions(-) create mode 100644 docs/iterations/051A.md diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 0d7ecb2..d1357ad 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -9,6 +9,12 @@ 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 **Em curso** 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** while integration is in progress. + 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). diff --git a/docs/iterations/051A.md b/docs/iterations/051A.md new file mode 100644 index 0000000..38cbdcb --- /dev/null +++ b/docs/iterations/051A.md @@ -0,0 +1,24 @@ +# 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: **Em curso**. 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 | Required behavior and evidence | +|---|---|---| +| Explicit history compaction | A.02 | Archive and reopen-verify the complete history before replacing the active journal; retain explicit bounded undo, reject stale revisions and archive failures without changing authoring; continue editing after the old node limit. | +| Part-scoped sketches | B.02/B.04 | Stable definition ownership, local names and explicit cross-scope references; shared occurrences reuse the same sketch; legacy global sketches remain valid; bounded larger projects save/reopen and reject overflow atomically. | +| Background reconstruction | A.04 | Prepare expensive edits on a private snapshot while navigation stays live; expose progress/cancellation; publish only against the same document and revision; test cancellation, concurrent edits, document replacement and shutdown. | +| Native offset and loft | A.03/B.03 | Reproduce the two known unpatched-SDK failures and verify the repository's exact geometry fixes with an attested patched SDK; no widened tolerances or omitted solids. | +| Agent task outcomes | D.01/D.02 | Extend the existing versioned benchmark with parametric edits, assembly changes, rejection/recovery and actual save/reopen; separate completion from accepted postconditions, include failed attempts and leave unmeasured cost unknown. | + +The document format advances only for new persisted ownership/compaction +semantics, independently of the application iteration. Synthetic fixtures are +used throughout. User drawings and live Studio sessions are preserved. + +## Verification + +Integration checks are pending. No completed-scope, hosted CI, provider-quality, +distribution or manufacturing claim is made by this implementation plan. diff --git a/release.json b/release.json index 7df588e..cbc6e45 100644 --- a/release.json +++ b/release.json @@ -1,12 +1,16 @@ { - "sequence": 50, - "phase": "B", - "code": "050B", - "version": "0.9.51", + "sequence": 51, + "phase": "A", + "code": "051A", + "version": "0.9.52", "milestones": [ - "B.04", - "C.04", + "A.02", + "A.03", + "A.04", "B.02", - "A.02" + "B.03", + "B.04", + "D.01", + "D.02" ] } From 04b84025d89ee2bc9461cebffbcbd283cf5a31b7 Mon Sep 17 00:00:00 2001 From: Bruno Santos Date: Thu, 22 Oct 2026 08:49:58 +0100 Subject: [PATCH 02/69] Fix optional compression declarations for MinGW builds [skip ci] --- src/geometry_storage_032d.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/geometry_storage_032d.cpp b/src/geometry_storage_032d.cpp index a074cb9..26a3f22 100644 --- a/src/geometry_storage_032d.cpp +++ b/src/geometry_storage_032d.cpp @@ -9,7 +9,13 @@ #ifdef _WIN32 #define NOMINMAX #include +// Request the optional API declarations locally. The product's minimum Windows +// target is unchanged: every symbol is still resolved dynamically below. +#pragma push_macro("NTDDI_VERSION") +#undef NTDDI_VERSION +#define NTDDI_VERSION 0x06020000 #include +#pragma pop_macro("NTDDI_VERSION") #endif namespace ark { @@ -20,12 +26,16 @@ const V& empty(){static const V v;return v;} V* member(V& v,const char* name){for(auto& p:v.obj)if(p.first==name)return &p.second;return nullptr;} #ifdef _WIN32 struct MetadataCodec { + // Windows documents both source buffers as const. Some MinGW headers declare + // PVOID instead; use the documented ABI for these dynamically loaded symbols + // without redeclaring imported functions or casting away source constness. + using Transform = BOOL (WINAPI *)(COMPRESSOR_HANDLE,LPCVOID,SIZE_T,PVOID,SIZE_T,PSIZE_T); HMODULE module=LoadLibraryExW(L"cabinet.dll",nullptr,LOAD_LIBRARY_SEARCH_SYSTEM32); decltype(&CreateCompressor) create=module?reinterpret_cast(GetProcAddress(module,"CreateCompressor")):nullptr; - decltype(&Compress) compress=module?reinterpret_cast(GetProcAddress(module,"Compress")):nullptr; + Transform compress=module?reinterpret_cast(GetProcAddress(module,"Compress")):nullptr; decltype(&CloseCompressor) close=module?reinterpret_cast(GetProcAddress(module,"CloseCompressor")):nullptr; decltype(&CreateDecompressor) createDecoder=module?reinterpret_cast(GetProcAddress(module,"CreateDecompressor")):nullptr; - decltype(&Decompress) decompress=module?reinterpret_cast(GetProcAddress(module,"Decompress")):nullptr; + Transform decompress=module?reinterpret_cast(GetProcAddress(module,"Decompress")):nullptr; decltype(&CloseDecompressor) closeDecoder=module?reinterpret_cast(GetProcAddress(module,"CloseDecompressor")):nullptr; ~MetadataCodec(){if(module)FreeLibrary(module);} bool available() const{return create&&compress&&close&&createDecoder&&decompress&&closeDecoder;} From 5ae03c87cbe0722e5d4783193851cd17cc563f5d Mon Sep 17 00:00:00 2001 From: Bruno Santos Date: Thu, 22 Oct 2026 08:50:18 +0100 Subject: [PATCH 03/69] Add explicit archive-backed history compaction for A.02 [skip ci] --- CMakeLists.txt | 8 ++- docs/HISTORY_COMPACTION_051A.md | 74 ++++++++++++++++++++++++ include/ark/iteration_history.hpp | 5 ++ src/agent.cpp | 1 + src/agent_team.cpp | 2 +- src/agent_transactions.cpp | 8 +-- src/assistant.cpp | 2 +- src/history_compaction_051a.cpp | 60 +++++++++++++++++++ src/iteration_history.cpp | 42 ++++++++++++-- src/view/history_compaction_selftest.inl | 14 +++++ src/view/viewer.cpp | 40 +++++++++---- tests/history_compaction_051a_tests.cpp | 50 ++++++++++++++++ 12 files changed, 281 insertions(+), 25 deletions(-) create mode 100644 docs/HISTORY_COMPACTION_051A.md create mode 100644 src/history_compaction_051a.cpp create mode 100644 src/view/history_compaction_selftest.inl create mode 100644 tests/history_compaction_051a_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0a74d12..4fa52d7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -46,7 +46,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 @@ -344,6 +344,10 @@ 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) 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) @@ -546,7 +550,7 @@ 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 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 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() diff --git a/docs/HISTORY_COMPACTION_051A.md b/docs/HISTORY_COMPACTION_051A.md new file mode 100644 index 0000000..d43bc00 --- /dev/null +++ b/docs/HISTORY_COMPACTION_051A.md @@ -0,0 +1,74 @@ +# Recoverable history compaction — 051A + +Milestone **A.02**. Implementation and synthetic verification targets are present; +execution evidence is recorded in the iteration verification notes after running them. + +`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. + +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. 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, 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. + +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/include/ark/iteration_history.hpp b/include/ark/iteration_history.hpp index ffe3c85..ae78c76 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); +arkjson::Value historyCompactTool(Document& document,std::uint64_t& revision,const arkjson::Value& args); } diff --git a/src/agent.cpp b/src/agent.cpp index 7276ecf..698237e 100644 --- a/src/agent.cpp +++ b/src/agent.cpp @@ -1603,6 +1603,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, 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},"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}, diff --git a/src/agent_team.cpp b/src/agent_team.cpp index 2d2f530..041b8b9 100644 --- a/src/agent_team.cpp +++ b/src/agent_team.cpp @@ -23,7 +23,7 @@ bool identifier(const std::string& id){return !id.empty()&&id.size()<=64&&std::a bool hasText(const std::string& text){return text.find_first_not_of(" \r\n\t")!=std::string::npos;} std::string userMessageText(const V& value){const auto* content=value.find("content");if(!content)return {};if(content->t==V::Str)return content->str;std::string text;for(const auto& part:content->arr)if(field(part,"type")=="input_text"){if(!text.empty())text+='\n';text+=field(part,"text");}return text;} bool userMessageHasImage(const V& value){const auto* content=value.find("content");return content&&content->t==V::Arr&&std::any_of(content->arr.begin(),content->arr.end(),[](const auto& part){return field(part,"type")=="input_image";});} -bool documentMutation(const std::string& name){static const std::set names={"doc_apply","doc_new","doc_load","doc_undo","doc_redo","import_step","import_sheet_step","import_mesh","import_cad","design_containers","library_insert","iteration_restore","history_migrate_derived","team_apply_step"};return names.count(name)!=0;} +bool documentMutation(const std::string& name){static const std::set names={"doc_apply","doc_new","doc_load","doc_undo","doc_redo","import_step","import_sheet_step","import_mesh","import_cad","design_containers","library_insert","iteration_restore","history_migrate_derived","history_compact","team_apply_step"};return names.count(name)!=0;} bool revision(const V& args){auto p=args.find("expected_revision");return p&&p->t==V::Num&&std::isfinite(p->num)&&p->num>=0&&p->num<=9007199254740991.0&&std::floor(p->num)==p->num;} bool receiptRevision(const V& value,std::uint64_t& result){auto p=value.find("revision");if(p&&p->t==V::Num&&std::isfinite(p->num)&&p->num>=0&&p->num<=9007199254740991.0&&std::floor(p->num)==p->num){result=(std::uint64_t)p->num;return true;}return false;} bool samePreparedRecipe(const V& a,const V& b){const auto* ac=a.find("commands"),*bc=b.find("commands"),*at=a.find("checks"),*bt=b.find("checks");return ac&&bc&&ac->t==V::Arr&&bc->t==V::Arr&&ac->dump()==bc->dump()&&((!at&&!bt)||(at&&bt&&at->dump()==bt->dump()));} diff --git a/src/agent_transactions.cpp b/src/agent_transactions.cpp index d988fd1..e5398ca 100644 --- a/src/agent_transactions.cpp +++ b/src/agent_transactions.cpp @@ -132,10 +132,10 @@ arkjson::Value AgentSession::call(const std::string& tool,const V& args){ const bool mutating=tool=="doc_apply"||tool=="doc_new"||tool=="doc_load"||tool=="doc_undo"||tool=="doc_redo"||tool=="iteration_restore"||tool=="import_step"||tool=="import_sheet_step"||tool=="import_mesh"||tool=="import_cad"||(tool=="design_containers"&&args.find("action")&&args.find("action")->asStr()=="merge"&&!(args.find("preview")&&args.find("preview")->t==V::Bool&&args.find("preview")->b))||(tool=="image_asset"&&args.find("action")&&args.find("action")->asStr()=="import")||tool=="usage_record"||tool=="library_insert"; struct Depth {size_t& value;Depth(size_t& n):value(n){++value;}~Depth(){--value;}} depth(callDepth_); // 049A explicit journal rewrite: its own atomic path (backup, migrate, then publish); never an iteration node. - if(tool=="history_migrate_derived"){V out;bool failed=false; - try{out=historyMigrateDerivedTool(document,revision,args);prepared_.clear();cache_.clear();cacheRevision_=~u64(0);motionRevision_=~u64(0);} + if(tool=="history_migrate_derived"||tool=="history_compact"){V out;bool failed=false; + try{out=tool=="history_compact"?historyCompactTool(document,revision,args):historyMigrateDerivedTool(document,revision,args);undo_.clear();redo_.clear();prepared_.clear();cache_.clear();cacheRevision_=~u64(0);motionRevision_=~u64(0);} catch(const std::exception& e){failed=true;const std::string message=e.what();out=V::makeObj();out.set("error",V::makeStr(message));const auto end=message.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ_"); - out.set("error_code",V::makeStr(message.find("Revision conflict")!=std::string::npos?"REVISION_CONFLICT":message.rfind("HISTORY_MIGRATION_",0)==0?message.substr(0,end):"HISTORY_MIGRATION_FAILED"));out.set("tool",V::makeStr(tool));out.set("revision",V::makeNum((double)revision));out.set("document_unchanged",V::makeBool(true));} + out.set("error_code",V::makeStr(message.find("Revision conflict")!=std::string::npos?"REVISION_CONFLICT":(message.rfind("HISTORY_MIGRATION_",0)==0||message.rfind("HISTORY_COMPACTION_",0)==0)?message.substr(0,end):"HISTORY_MIGRATION_FAILED"));out.set("tool",V::makeStr(tool));out.set("revision",V::makeNum((double)revision));out.set("document_unchanged",V::makeBool(true));} V response=V::makeObj(),content=V::makeArr(),item=V::makeObj();item.set("type",V::makeStr("text"));item.set("text",V::makeStr(out.dump()));content.arr.push_back(item);response.set("content",content);response.set("structuredContent",out);response.set("isError",V::makeBool(failed));return finish(std::move(response));} const bool planeMutation=tool=="plane_authoring"&&!(args.find("preview")&&args.find("preview")->t==V::Bool&&args.find("preview")->b); if((!mutating&&!planeMutation)||callDepth_>1||suppressHistory_)return finish(dispatch(tool,clean)); @@ -163,7 +163,7 @@ arkjson::Value AgentSession::call(const std::string& tool,const V& args){ return finish(std::move(response)); }catch(const std::exception& exception){rollback();V error=V::makeObj();error.set("error",V::makeStr(exception.what()));error.set("error_code",V::makeStr(std::string(exception.what()).find("capacity")!=std::string::npos?"HISTORY_CAPACITY_EXCEEDED":"HISTORY_FAILED"));error.set("tool",V::makeStr(tool));error.set("revision",V::makeNum((double)revision));error.set("document_unchanged",V::makeBool(true)); // 049A: name the reclaimable derived bytes when old inline baked frames fill the journal. - if(error.find("error_code")->str=="HISTORY_CAPACITY_EXCEEDED"){size_t references=0,bytes=0;iterationInlineBakePayloads(document.iterationHistory,references,bytes);if(references){V hint=V::makeObj();hint.set("inline_bake_payload_bytes",V::makeNum((double)bytes));hint.set("hint",V::makeStr("The journal holds 044B-048B baked frames, which are derived data. With the user's explicit approval, history_migrate_derived{path,expected_revision,confirm:true} backs up the saved document and removes them; then save."));error.set("derived_bakes",hint);}} + if(error.find("error_code")->str=="HISTORY_CAPACITY_EXCEEDED"){error.set("compaction_hint",V::makeStr("With explicit user instruction, history_compact{archive_path,keep_recent,expected_revision,confirm:true} verifies a complete new .ark archive and retains a bounded recent ancestor range. Never auto-prune. Save afterwards."));size_t references=0,bytes=0;iterationInlineBakePayloads(document.iterationHistory,references,bytes);if(references){V hint=V::makeObj();hint.set("inline_bake_payload_bytes",V::makeNum((double)bytes));hint.set("hint",V::makeStr("The journal holds 044B-048B baked frames, which are derived data. With the user's explicit approval, history_migrate_derived{path,expected_revision,confirm:true} backs up the saved document and removes them; then save."));error.set("derived_bakes",hint);}} return finish(envelope(error,true));} } arkjson::Value AgentSession::preparedRecipe(const std::string& id) const{ diff --git a/src/assistant.cpp b/src/assistant.cpp index fef8efc..119c2ab 100644 --- a/src/assistant.cpp +++ b/src/assistant.cpp @@ -411,7 +411,7 @@ const std::vector>>& assistantSpe {"skeleton",{"skeleton_inspect","skeleton_compile"}},{"automation",{"skeleton_inspect","skeleton_compile","design_solve"}}, {"planes",{"plane_authoring"}},{"sketch",{"sketch_repair"}},{"containers",{"design_containers"}},{"hud",{"hud_info","hud_flex_check"}}, {"cad_import",{"import_step","import_cad","step_inspect","cad_inspect","image_asset","export_step","export_iges","doc_new","doc_load"}}, - {"history",{"feature_history","history_info","iteration_restore","history_migrate_derived","failure_replay","failure_export","usage_info","usage_record","memory_maintain"}}}; + {"history",{"feature_history","history_info","iteration_restore","history_migrate_derived","history_compact","failure_replay","failure_export","usage_info","usage_record","memory_maintain"}}}; return topics; } V assistantActiveTools(const V& tools,const V& conversation,const std::string& onboardingPack){ diff --git a/src/history_compaction_051a.cpp b/src/history_compaction_051a.cpp new file mode 100644 index 0000000..d54c6c3 --- /dev/null +++ b/src/history_compaction_051a.cpp @@ -0,0 +1,60 @@ +#include "ark/iteration_history.hpp" +#include "ark/serialize.hpp" +#include +#include +#include +#include +#include +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#else +#include +#endif +namespace ark { +namespace { +using V=arkjson::Value;namespace fs=std::filesystem; +void require(bool valid,const std::string& reason){if(!valid)throw std::runtime_error(reason);} +std::string utf8(const fs::path& path){const auto value=path.u8string();return {value.begin(),value.end()};} +std::string bytes(const fs::path& path){std::ifstream input(path,std::ios::binary);require(bool(input),"HISTORY_COMPACTION_ARCHIVE_FAILED: cannot read archive");return {std::istreambuf_iterator(input),{}};} +bool publishNew(const fs::path& from,const fs::path& to){ +#ifdef _WIN32 + return MoveFileExW(from.c_str(),to.c_str(),MOVEFILE_WRITE_THROUGH)!=0; +#else + if(::link(from.c_str(),to.c_str())!=0)return false;std::error_code ec;fs::remove(from,ec);return true; +#endif +} +} +V historyCompactTool(Document& document,u64& revision,const V& args){ + require(args.t==V::Obj,"HISTORY_COMPACTION_INVALID: arguments must be an object"); + for(const auto& field:args.obj)require(field.first=="archive_path"||field.first=="keep_recent"||field.first=="expected_revision"||field.first=="confirm"||field.first=="actor"||field.first=="motivation","HISTORY_COMPACTION_INVALID: unknown field "+field.first); + const auto* expected=args.find("expected_revision");require(expected&&expected->t==V::Num&&expected->num==(double)revision,"Revision conflict; read history_info before compacting"); + const auto* confirm=args.find("confirm");require(confirm&&confirm->t==V::Bool&&confirm->b,"HISTORY_COMPACTION_CONFIRM_REQUIRED: archive and compact only on explicit instruction with confirm:true"); + const auto* count=args.find("keep_recent");require(count&&count->t==V::Num&&count->num>=0&&count->num<=256&&count->num==std::floor(count->num),"HISTORY_COMPACTION_INVALID: keep_recent must be an integer 0..256"); + const V actor=iterationActor(args);std::string motivation;if(const auto* m=args.find("motivation")){require(m->t==V::Str&&m->str.size()<=4096,"HISTORY_COMPACTION_INVALID: motivation must be text of at most 4096 bytes");motivation=m->str;} + const auto* path=args.find("archive_path");require(path&&path->t==V::Str&&!path->str.empty()&&path->str.size()<=4096,"HISTORY_COMPACTION_INVALID: archive_path must name a new .ark file"); + const fs::path archive=fs::absolute(fs::u8path(path->str));auto extension=archive.extension().string();std::transform(extension.begin(),extension.end(),extension.begin(),[](unsigned char c){return (char)std::tolower(c);}); + require(extension==".ark"&&fs::is_directory(archive.parent_path())&&!fs::exists(archive),"HISTORY_COMPACTION_ARCHIVE_FAILED: archive must be a new .ark file in an existing directory; nothing was changed"); + require(document.iterationHistory.t==V::Obj,"HISTORY_COMPACTION_INVALID: no persistent history to compact"); + const std::string original=documentToJson(document);std::string error;require(iterationValidate(document,document.iterationHistory,error),"HISTORY_COMPACTION_INVALID: "+error); + // Reserve a unique directory atomically, so concurrent calls cannot overwrite staging. + fs::path stagingDirectory;for(int attempt=0;attempt<100&&stagingDirectory.empty();++attempt){auto candidate=archive.parent_path()/fs::u8path(".ark-compact-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())+"-"+std::to_string(attempt));std::error_code ec;if(fs::create_directory(candidate,ec))stagingDirectory=candidate;} + require(!stagingDirectory.empty(),"HISTORY_COMPACTION_ARCHIVE_FAILED: cannot reserve archive staging directory"); + struct Cleanup {fs::path directory;~Cleanup(){std::error_code ec;fs::remove(directory/"archive.ark",ec);fs::remove(directory,ec);}} cleanup{stagingDirectory};const auto staging=stagingDirectory/"archive.ark"; + DocumentSaveReport saved;require(saveDocument(document,utf8(staging).c_str(),&saved),"HISTORY_COMPACTION_ARCHIVE_FAILED: "+saved.error); + Document reopened;require(loadDocument(utf8(staging).c_str(),reopened,&error)&&documentToJson(reopened)==original,"HISTORY_COMPACTION_ARCHIVE_FAILED: staged archive did not reopen identically: "+error); + V archiveInfo=V::makeObj();archiveInfo.set("path",V::makeStr(utf8(archive)));archiveInfo.set("bytes",V::makeNum((double)fs::file_size(staging)));archiveInfo.set("verified",V::makeBool(true));archiveInfo.set("document_sha256",V::makeStr(iterationSha256(original)));archiveInfo.set("file_sha256",V::makeStr(iterationSha256(bytes(staging)))); + V record=V::makeObj();record.set("archive",archiveInfo);record.set("actor",actor);record.set("provenance",V::makeStr("caller_declared"));record.set("motivation",V::makeStr(motivation));record.set("revision_before",V::makeNum((double)revision)); + Document next=document;next.iterationHistory=iterationCompact(document,(size_t)count->num,record);const std::string persisted=documentToJson(next); + require(persisted.size()<=maxDocumentBytes,"HISTORY_COMPACTION_CAPACITY: retained history still exceeds 4 MiB; request fewer retained nodes"); + require(iterationValidate(next,next.iterationHistory,error)&&documentFromJson(persisted,reopened,&error)&&documentToJson(reopened)==persisted,"HISTORY_COMPACTION_INVALID: compacted document did not reopen identically: "+error); + require(iterationAuthoring(next).dump()==iterationAuthoring(document).dump(),"HISTORY_COMPACTION_INVALID: compaction changed authoring"); + // Prepare all receipts before publication. Only archive publication may fail after this. + V out=V::makeObj();out.set("compacted",V::makeBool(true));out.set("revision",V::makeNum((double)(revision+1)));out.set("archive",archiveInfo);out.set("compaction",*next.iterationHistory.find("compaction"));out.set("capacity_before",iterationInfo(document,1));out.set("capacity_after",iterationInfo(next,1));out.set("document_bytes_before",V::makeNum(original.size()));out.set("document_bytes_after",V::makeNum(persisted.size()));out.set("next_step",V::makeStr("Save the compacted document with doc_save. Open archive.path with doc_load to recover complete previous branches and undo history; archive is never replaced. Re-read history_info: retained node ids changed.")); + require(publishNew(staging,archive),"HISTORY_COMPACTION_ARCHIVE_FAILED: archive publication refused (existing destination or I/O failure); document unchanged"); + document=std::move(next);++revision;return out; +} +} diff --git a/src/iteration_history.cpp b/src/iteration_history.cpp index 3e4f236..63162b5 100644 --- a/src/iteration_history.cpp +++ b/src/iteration_history.cpp @@ -147,13 +147,13 @@ V iterationInfo(const Document& document,size_t limit,const std::string& beforeI size_t end=nodes.size();if(!beforeId.empty()){if(beforeId==text(h,"baseline_id"))end=0;else{auto found=std::find_if(nodes.begin(),nodes.end(),[&](const V& n){return text(n,"id")==beforeId;});if(found==nodes.end())throw std::runtime_error("History before_id cursor not found");end=(size_t)(found-nodes.begin());}} for(size_t i=end;i>0&&rows.arr.size()rows.arr.size();out.set("has_more",V::makeBool(more));out.set("next_before_id",V::makeStr(more?text(rows.arr.back(),"id"):""));out.set("node_count",V::makeNum(nodes.size()));out.set("storage_bytes",V::makeNum(h.dump().size())); }else{if(!beforeId.empty())throw std::runtime_error("History before_id cursor not found");out.set("has_more",V::makeBool(false));out.set("next_before_id",V::makeStr(""));out.set("node_count",V::makeNum(0));out.set("storage_bytes",V::makeNum(0));} - if(h.t==V::Obj){out.set("schema",*h.find("schema"));if(const auto* migrations=h.find("migrations"))out.set("migrations",*migrations);size_t references=0,bytes=0;iterationInlineBakePayloads(h,references,bytes); + if(h.t==V::Obj){out.set("schema",*h.find("schema"));if(const auto* receipt=h.find("compaction"))out.set("compaction",*receipt);out.set("undo_count",V::makeNum(need(h,"undo_ids").arr.size()));out.set("redo_count",V::makeNum(need(h,"redo_ids").arr.size()));if(const auto* migrations=h.find("migrations"))out.set("migrations",*migrations);size_t references=0,bytes=0;iterationInlineBakePayloads(h,references,bytes); V payloads=V::makeObj();payloads.set("references",V::makeNum((double)references));payloads.set("bytes",V::makeNum((double)bytes));if(references)payloads.set("hint",V::makeStr("These 044B-048B baked frames are derived data. history_migrate_derived{path,expected_revision,confirm:true} removes them from the journal after writing a backup."));out.set("inline_bake_payloads",payloads);} out.set("nodes",rows);out.set("branch_heads",heads);out.set("max_nodes",V::makeNum(maxNodes));out.set("max_document_bytes",V::makeNum(maxDocumentBytes));out.set("document_bytes",V::makeNum(documentToJson(document).size()));out.set("actor_identity_verified",V::makeBool(false));return out; } void iterationRestore(const Document& source,const std::string& id,Document& target){if(source.iterationHistory.t!=V::Obj)throw std::runtime_error("No iteration history available");V state=replay(source.iterationHistory,id);std::string error;if(!documentFromJson(state.dump(),target,&error))throw std::runtime_error("Iteration authoring invalid: "+error);target.usage=source.usage;target.agentActivity=source.agentActivity;target.iterationHistory=source.iterationHistory;target.nextFeatureId_=std::max(target.nextFeatureId_,source.nextFeatureId_);target.nextAssemblyId_=std::max(target.nextAssemblyId_,source.nextAssemblyId_);target.nextMateId_=std::max(target.nextMateId_,source.nextMateId_);} std::string iterationUndoTarget(const Document& document,bool redo){const V& h=document.iterationHistory;if(h.t!=V::Obj)throw std::runtime_error("No iteration history available");const V& ids=need(h,redo?"redo_ids":"undo_ids");if(ids.t!=V::Arr||ids.arr.empty())throw std::runtime_error("No iteration history available");return ids.arr.back().str;} -void iterationPersist(V& root,const Document& document){if(document.iterationHistory.t!=V::Obj)return;V blobs=need(document.iterationHistory,"blobs"),packed=pack(root,blobs);if(blobs.dump()!=need(document.iterationHistory,"blobs").dump())throw std::runtime_error("Current document has unjournaled large authoring payload");root=std::move(packed);root.set("version",V::makeNum(std::max(27.,root.find("version")?root.find("version")->asNum():27.)));root.set("iteration_history",document.iterationHistory);} +void iterationPersist(V& root,const Document& document){if(document.iterationHistory.t!=V::Obj)return;V blobs=need(document.iterationHistory,"blobs"),packed=pack(root,blobs);if(blobs.dump()!=need(document.iterationHistory,"blobs").dump())throw std::runtime_error("Current document has unjournaled large authoring payload");root=std::move(packed);root.set("version",V::makeNum(std::max(document.iterationHistory.find("compaction")?50.:27.,root.find("version")?root.find("version")->asNum():27.)));root.set("iteration_history",document.iterationHistory);} void iterationInlineBakePayloads(const V& h,size_t& references,size_t& bytes){ references=bytes=0;if(h.t!=V::Obj)return;const V* blobs=h.find("blobs");std::set counted; auto charge=[&](const V& value){++references;if(value.t==V::Str)bytes+=value.str.size();else if(const auto* ref=value.find("$ark_history_blob");ref&&ref->t==V::Str&&blobs&&counted.insert(ref->str).second)if(const auto* blob=blobs->find(ref->str.c_str());blob&&blob->t==V::Str)bytes+=blob->str.size();}; @@ -179,12 +179,44 @@ V iterationRewrite(const V& h,const std::function& transform,std::map< } out.set("head_id",V::makeStr(ids.at(text(h,"head_id"))));out.set("nodes",nodes);out.set("blobs",newBlobs); for(const char* key:{"undo_ids","redo_ids"}){V list=V::makeArr();for(const auto& id:need(h,key).arr)list.arr.push_back(V::makeStr(ids.at(id.str)));out.set(key,list);} - if(const auto* migrations=h.find("migrations"))out.set("migrations",*migrations);return out; -} -bool iterationExpand(V& root,V& history,std::string& error){try{if(auto h=root.find("iteration_history")){if(!root.find("version")||(root.find("version")->num<27||root.find("version")->num>49))throw std::runtime_error("Iteration history requires a supported document version 27 or later");history=*h;erase(root,"iteration_history");root=unpack(root,need(history,"blobs"));}else if(root.find("version")&&root.find("version")->num==27)throw std::runtime_error("Version 27 requires iteration history");return true;}catch(const std::exception& e){error=e.what();return false;}} + if(const auto* migrations=h.find("migrations"))out.set("migrations",*migrations);if(const auto* receipt=h.find("compaction")){out.set("compaction",*receipt);out.set("compacted",V::makeBool(true));}return out; +} +V iterationCompact(const Document& source,size_t keepRecent,const V& receipt){ + if(keepRecent>256)throw std::runtime_error("HISTORY_COMPACTION_INVALID: keep_recent must be 0..256"); + const V& h=source.iterationHistory;std::string error; + if(!iterationValidate(source,h,error))throw std::runtime_error("HISTORY_COMPACTION_INVALID: "+error); + std::vector chain;std::string cursor=text(h,"head_id"); + while(cursor!=text(h,"baseline_id")&&chain.size() ids{{cursor,text(out,"baseline_id")}}; + V mapping=V::makeArr();auto mapped=[&](const std::string& old,const std::string& current){V item=V::makeObj();item.set("original_id",V::makeStr(old));item.set("id",V::makeStr(current));mapping.arr.push_back(item);};mapped(cursor,text(out,"baseline_id")); + for(auto it=chain.rbegin();it!=chain.rend();++it){const V& n=**it;V next=state;apply(next,need(n,"delta"),need(h,"blobs"));V delta=V::makeArr();diff(state,next,V::makeArr(),delta,member(out,"blobs")); + V m=n;erase(m,"id");erase(m,"restored_from_id");m.set("original_id",need(n,"id"));m.set("original_parent_id",need(n,"parent_id"));m.set("original_previous_head_id",need(n,"previous_head_id")); + m.set("parent_id",need(out,"head_id"));m.set("previous_head_id",need(out,"head_id"));m.set("before_sha256",V::makeStr(iterationSha256(state.dump())));m.set("delta",delta);m.set("ordinal",V::makeNum(need(out,"nodes").arr.size()+1)); + const std::string id=nodeId(m);m.set("id",V::makeStr(id));member(out,"nodes").arr.push_back(m);out.set("head_id",V::makeStr(id));ids[text(n,"id")]=id;mapped(text(n,"id"),id);state=std::move(next); + } + // Undo means previous active state (including across branches), not parent. + // Keep only the contiguous suffix; never silently skip an omitted target. + V undo=V::makeArr();const auto& oldUndo=need(h,"undo_ids").arr; + for(auto it=oldUndo.rbegin();it!=oldUndo.rend();++it){auto found=ids.find(it->str);if(found==ids.end())break;undo.arr.insert(undo.arr.begin(),V::makeStr(found->second));} + out.set("undo_ids",undo);V record=receipt;record.set("format",V::makeStr("ark.history_compaction.v1"));record.set("utc",V::makeStr(utc()));record.set("previous_head_id",need(h,"head_id"));record.set("previous_baseline_id",need(h,"baseline_id"));record.set("baseline_id",need(out,"baseline_id"));record.set("head_id",need(out,"head_id"));record.set("retained_ids",mapping); + record.set("nodes_before",V::makeNum(need(h,"nodes").arr.size()));record.set("nodes_retained",V::makeNum(chain.size()));record.set("undo_retained",V::makeNum(undo.arr.size()));record.set("redo_cleared",V::makeNum(need(h,"redo_ids").arr.size())); + size_t omittedHeads=0;const V sourceInfo=iterationInfo(source);for(const auto& head:need(sourceInfo,"branch_heads").arr)if(!ids.count(head.str))++omittedHeads; + record.set("archived_branch_heads",V::makeNum(omittedHeads));record.set("policy",V::makeStr("head_ancestor_suffix_contiguous_undo_clear_redo")); + V signedRecord=record;canonical(signedRecord);record.set("sha256",V::makeStr(iterationSha256(signedRecord.dump())));out.set("compaction",record);out.set("compacted",V::makeBool(true));return out; +} +bool iterationExpand(V& root,V& history,std::string& error){try{if(auto h=root.find("iteration_history")){if(!root.find("version")||(root.find("version")->num<27||root.find("version")->num>50))throw std::runtime_error("Iteration history requires a supported document version 27 or later");if(h->find("compaction")&&root.find("version")->num<50)throw std::runtime_error("Compacted history requires document version 50");history=*h;erase(root,"iteration_history");root=unpack(root,need(history,"blobs"));}else if(root.find("version")&&root.find("version")->num==27)throw std::runtime_error("Version 27 requires iteration history");return true;}catch(const std::exception& e){error=e.what();return false;}} bool iterationValidate(const Document& document,const V& h,std::string& error){ try{if(h.t!=V::Obj||need(h,"schema").t!=V::Num||(need(h,"schema").num!=1&&need(h,"schema").num!=2))throw std::runtime_error("Unsupported iteration history schema");const V& blobs=need(h,"blobs"),nodes=need(h,"nodes");if(blobs.t!=V::Obj||nodes.t!=V::Arr||nodes.arr.size()>maxNodes)throw std::runtime_error("Invalid history blob/node storage"); const bool derivedOnly=need(h,"schema").num==2;if(derivedOnly)validateMigrations(h);else if(h.find("migrations"))throw std::runtime_error("History migration records require schema 2"); + if((h.find("compacted")!=nullptr)!=(h.find("compaction")!=nullptr)||(h.find("compacted")&&(h.find("compacted")->t!=V::Bool||!h.find("compacted")->b)))throw std::runtime_error("Missing history compaction receipt or marker"); + if(const auto* record=h.find("compaction")){ + V signedRecord=*record;erase(signedRecord,"sha256");canonical(signedRecord); + if(record->t!=V::Obj||record->dump().size()>131072||text(*record,"format")!="ark.history_compaction.v1"||text(*record,"sha256")!=iterationSha256(signedRecord.dump())||text(*record,"policy")!="head_ancestor_suffix_contiguous_undo_clear_redo")throw std::runtime_error("Invalid history compaction receipt fingerprint or policy"); + validateActor(need(*record,"actor"));const V& archive=need(*record,"archive"); + if(text(archive,"path").empty()||!digest(text(archive,"document_sha256"))||!digest(text(archive,"file_sha256"))||need(archive,"verified").t!=V::Bool||!need(archive,"verified").b||need(archive,"bytes").t!=V::Num||need(archive,"bytes").num<=0||need(*record,"retained_ids").t!=V::Arr||need(*record,"retained_ids").arr.empty()||need(*record,"retained_ids").arr.size()>257)throw std::runtime_error("Invalid history compaction archive or lineage"); + } auto noPayload=[&](const V& s){if(derivedOnly&&inlineBakeState(s))throw std::runtime_error("Schema 2 history state contains inline baked-frame payloads");}; for(const auto& blob:blobs.obj)if(!digest(blob.first)||blob.second.t!=V::Str||blob.second.str.size()<1024||iterationSha256(blob.second.str)!=blob.first)throw std::runtime_error("History blob digest mismatch"); V state=unpack(need(h,"baseline"),blobs);noPayload(state);std::string stateBytes=state.dump();const std::string base=text(h,"baseline_id"),baseHash=iterationSha256(stateBytes);if(base!="baseline-"+baseHash||text(h,"baseline_sha256")!=baseHash)throw std::runtime_error("History baseline digest mismatch"); diff --git a/src/view/history_compaction_selftest.inl b/src/view/history_compaction_selftest.inl new file mode 100644 index 0000000..50c9c54 --- /dev/null +++ b/src/view/history_compaction_selftest.inl @@ -0,0 +1,14 @@ +if(historyCompactionUiTest){ + using V=arkjson::Value;auto fail=[&](const char* why){fprintf(stderr,"History compaction UI: %s / %s\n",why,g_status.c_str());return 951;}; + const auto directory=std::filesystem::temp_directory_path()/("ark-history-compact-ui-"+std::to_string(GetCurrentProcessId()));std::filesystem::create_directory(directory); + runTool("doc_new",V::makeObj());V args;arkjson::parse(R"({"commands":[{"op":"feature.add","type":"box","name":"Archive fixture","p":{"dx":"5","dy":"6","dz":"7"}}]})",args);runTool("doc_apply",args);if(g_error)return fail("fixture rejected"); + V save=V::makeObj();save.set("path",V::makeStr((directory/"drawing.ark").string()));runTool("doc_save",save);if(g_error)return fail("fixture save failed"); + const auto before=documentToJson(g_doc);const auto revision=g_session.revision;const auto archive=directory/("drawing.history-"+std::to_string(revision)+".ark"); + g_historySmokeCompact=true;g_historyCompactAnswer=IDNO;g_dialogSmoke=2;g_dialogShot=shotPath+".history-compact.png";uiAction(493); + if(g_error||g_session.revision!=revision||documentToJson(g_doc)!=before||std::filesystem::exists(archive))return fail("declined compaction changed drawing"); + g_historyCompactAnswer=IDYES;uiAction(493);g_dialogSmoke=0;g_historySmokeCompact=false;g_historyCompactAnswer=0; + if(g_error||g_session.revision!=revision+1||!g_doc.iterationHistory.find("compaction"))return fail("compaction control failed"); + Document original,saved;std::string error;if(!loadDocument(archive.string().c_str(),original,&error)||documentToJson(original)!=before||!loadDocument((directory/"drawing.ark").string().c_str(),saved,&error)||!saved.iterationHistory.find("compaction"))return fail("saved archive or compacted drawing failed reopen"); + g_dialogSmoke=2;g_dialogShot=shotPath+".history-compacted.png";uiAction(493);g_dialogSmoke=0;if(g_error)return fail("compacted history inspection failed"); + std::filesystem::remove_all(directory);g_status="History compaction UI passed / decline / archive / explicit retained range / save / reopen"; +} diff --git a/src/view/viewer.cpp b/src/view/viewer.cpp index 96d8348..6967d7a 100644 --- a/src/view/viewer.cpp +++ b/src/view/viewer.cpp @@ -1448,8 +1448,8 @@ static arkjson::Value runTool(const std::string& tool,const arkjson::Value& args size_t previousVisibleBodies=g_bodyIds.size(); g_progressTiming030={}; flushPendingUsage(); - auto effectiveArgs=args;static const std::set mutations{"doc_apply","doc_new","doc_load","doc_undo","doc_redo","iteration_restore","history_migrate_derived","import_step","import_sheet_step","import_mesh","import_cad","design_containers","image_asset","plane_authoring","library_insert"};const bool documentWrite=mutations.count(tool)&&(tool!="design_containers"||containerWrite)&&(tool!="image_asset"||!args.find("action")||args.find("action")->asStr()!="inspect");if(documentWrite&&!effectiveArgs.find("actor")){using V=arkjson::Value;V actor=V::makeObj();actor.set("kind",V::makeStr("human"));actor.set("id",V::makeStr("studio"));effectiveArgs.set("actor",actor);} - bool potentiallySlow=tool=="wood_inspect"||tool=="hud_flex_check"||tool=="sketch_repair"||tool=="plane_authoring"||tool=="import_cad"||tool=="cad_inspect"||tool=="design_containers"||tool.rfind("library_",0)==0||tool=="failure_replay"||tool=="failure_export"||tool=="manufacturing_inspect"||tool=="doc_load"||tool=="iteration_restore"||tool=="history_migrate_derived"||tool=="doc_apply"||tool=="doc_preview"||tool=="design_solve"||tool=="placement_plan"||tool=="pattern_plan"||tool=="query_batch"||tool=="geometry_query"||tool=="physics_inspect"||tool=="native_inspect"||tool=="step_inspect"||tool=="reference_inspect"||tool=="assembly_info"||tool=="kernel_info"||tool=="doc_undo"||tool=="doc_redo"||tool=="import_step"||tool=="import_sheet_step"||tool=="import_mesh"||tool=="export_step"||tool=="export_iges"||tool=="export_mesh"||tool=="export_flat_dxf"||tool=="bom_export_parts"||tool=="reference_navigate"||tool=="selection_set"; + auto effectiveArgs=args;static const std::set mutations{"doc_apply","doc_new","doc_load","doc_undo","doc_redo","iteration_restore","history_migrate_derived","history_compact","import_step","import_sheet_step","import_mesh","import_cad","design_containers","image_asset","plane_authoring","library_insert"};const bool documentWrite=mutations.count(tool)&&(tool!="design_containers"||containerWrite)&&(tool!="image_asset"||!args.find("action")||args.find("action")->asStr()!="inspect");if(documentWrite&&!effectiveArgs.find("actor")){using V=arkjson::Value;V actor=V::makeObj();actor.set("kind",V::makeStr("human"));actor.set("id",V::makeStr("studio"));effectiveArgs.set("actor",actor);} + bool potentiallySlow=tool=="wood_inspect"||tool=="hud_flex_check"||tool=="sketch_repair"||tool=="plane_authoring"||tool=="import_cad"||tool=="cad_inspect"||tool=="design_containers"||tool.rfind("library_",0)==0||tool=="failure_replay"||tool=="failure_export"||tool=="manufacturing_inspect"||tool=="doc_load"||tool=="iteration_restore"||tool=="history_migrate_derived"||tool=="history_compact"||tool=="doc_apply"||tool=="doc_preview"||tool=="design_solve"||tool=="placement_plan"||tool=="pattern_plan"||tool=="query_batch"||tool=="geometry_query"||tool=="physics_inspect"||tool=="native_inspect"||tool=="step_inspect"||tool=="reference_inspect"||tool=="assembly_info"||tool=="kernel_info"||tool=="doc_undo"||tool=="doc_redo"||tool=="import_step"||tool=="import_sheet_step"||tool=="import_mesh"||tool=="export_step"||tool=="export_iges"||tool=="export_mesh"||tool=="export_flat_dxf"||tool=="bom_export_parts"||tool=="reference_navigate"||tool=="selection_set"; if(tool=="doc_apply"&&!effectiveArgs.find("checks")&&metadataOnlyApply(g_doc,effectiveArgs))potentiallySlow=false; bool viewportSnapshot=tool=="snapshot"&&!effectiveArgs.find("candidate_id")&&effectiveArgs.find("view")&&effectiveArgs.find("view")->asStr()=="viewport"; auto result=viewportSnapshot?captureViewportSnapshot(effectiveArgs):potentiallySlow&&g_uiReady&&(!g_headless||g_busyTestMode)?callSessionWithProgress(tool,effectiveArgs):g_session.call(tool,effectiveArgs);g_error=result.find("isError")->b; @@ -3612,7 +3612,20 @@ static void editDrivingSketch(){ } #include "feature_history.inl" #include "configuration_workspace.inl" -struct HistoryEditor {arkjson::Value nodes;HWND list=nullptr,details=nullptr;std::string head,selected;bool migrate=false;}; +struct HistoryEditor {arkjson::Value nodes;HWND list=nullptr,details=nullptr;std::string head,selected,archive;bool migrate=false,compact=false;}; +static bool g_historySmokeCompact=false;static int g_historyCompactAnswer=0; +static void compactHistoryStudio(u64 observedRevision){ + using V=arkjson::Value;if(g_path.empty()){g_status="Save the drawing first to choose an archive beside it.";return;} + const auto path=std::filesystem::u8path(g_path);const auto stem=path.stem().u8string();const auto archive=path.parent_path()/std::filesystem::u8path(std::string(stem.begin(),stem.end())+".history-"+std::to_string(observedRevision)+".ark");const auto archiveText=archive.u8string(); + std::vector fields{{"New archive .ark path",std::string(archiveText.begin(),archiveText.end())},{"Recent ancestor nodes to keep (0..256)","64"}}; + if(!g_historyCompactAnswer&&!editFields("Archive and compact iteration history","Full history is archived first. Retained undo stops at the first unavailable target; redo is cleared. Other branches remain in the archive.",fields))return; + const double keep=formNumber(fields[1].value);if(keep<0||keep>256||keep!=std::floor(keep)){g_error=true;g_status="Keep recent must be an integer from 0 to 256";return;} + const std::string prompt="Archive the complete current drawing and compact its iteration history?\n\nArchive: "+fields[0].value+"\n\nARK verifies that the new archive reopens and never replaces an existing archive. The current drawing keeps its authoring and geometry, up to "+fields[1].value+" recent ancestors and their baseline. Undo retains only consecutive available targets; it may stop immediately after a branch restore. Redo is cleared. All older states and other branches stay recoverable by opening the archive with File > Open.\n\nARK then saves the compacted drawing to its current path."; + const int answer=g_historyCompactAnswer?g_historyCompactAnswer:MessageBoxA(g_window,prompt.c_str(),"Archive and compact history",MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2);if(answer!=IDYES){g_status="History compaction cancelled / nothing changed";return;} + V args=V::makeObj();args.set("archive_path",V::makeStr(fields[0].value));args.set("keep_recent",V::makeNum(keep));args.set("confirm",V::makeBool(true));args.set("expected_revision",V::makeNum((double)observedRevision));args.set("motivation",V::makeStr("Archive and compact from Studio Iterations")); + const auto response=runTool("history_compact",args);if(g_error)return;const auto* receipt=response.find("structuredContent");V save=V::makeObj();save.set("path",V::makeStr(g_path));runTool("doc_save",save);if(g_error){g_status="History compacted in memory; Save failed. Complete archive: "+fields[0].value+" / "+g_status;return;} + const auto* compact=receipt->find("compaction");g_status="History archived and compacted / "+std::to_string((int)compact->find("nodes_retained")->num)+" nodes / "+std::to_string((int)compact->find("undo_retained")->num)+" undo targets / archive "+fields[0].value; +} static int g_historySmokeIndex=0;static bool g_historySmokeMigrate=false;static int g_historyMigrateAnswer=0; // selftests: press Reclaim and answer the prompt // 049A: explicit, confirmed journal rewrite that removes derived baked frames. The // tool writes and verifies .pre-049A.ark beside the saved file first; Studio @@ -3624,30 +3637,31 @@ static void migrateDerivedBakesStudio(u64 observedRevision){ const std::string prompt="Rewrite this drawing's iteration journal without its derived baked-motion frames?\n\nARK first writes the complete current document beside it as "+stem+".pre-049A.ark (an existing file is never replaced) and checks that it reopens. Every iteration keeps its actor, tool, time and branch; iteration ids and SHA-256 values are recomputed. Baked motions keep a receipt and their frames are re-created on demand and checked against it.\n\nThe migrated document is then saved to "+file+"."; const int answer=g_historyMigrateAnswer?g_historyMigrateAnswer:MessageBoxA(g_window,prompt.c_str(),"Reclaim derived baked frames",MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2);if(answer!=IDYES){g_status="Journal migration cancelled / nothing changed";return;} V args=V::makeObj();args.set("path",V::makeStr(g_path));args.set("expected_revision",V::makeNum((double)observedRevision));args.set("confirm",V::makeBool(true));args.set("motivation",V::makeStr("Reclaim derived baked-motion frames from the iteration journal")); - const auto response=runTool("history_migrate_derived",args);if(g_error)return;const auto* r=response.find("structuredContent");if(!r||!r->find("backup")||!r->find("document_bytes_after")){g_status="Journal migration returned no receipt";g_error=true;return;}const std::string backup=r->find("backup")->find("path")->asStr(); + const auto response=runTool("history_migrate_derived","history_compact",args);if(g_error)return;const auto* r=response.find("structuredContent");if(!r||!r->find("backup")||!r->find("document_bytes_after")){g_status="Journal migration returned no receipt";g_error=true;return;}const std::string backup=r->find("backup")->find("path")->asStr(); V save=V::makeObj();save.set("path",V::makeStr(g_path));runTool("doc_save",save);if(g_error){g_status="Journal migrated in memory but not saved: "+g_status+" / original kept in "+backup;return;} char text[600];std::snprintf(text,sizeof text,"Journal migrated and saved: %.2f MB to %.2f MB of 4 MB / backup %s",r->find("document_bytes_before")->num/1e6,r->find("document_bytes_after")->num/1e6,backup.c_str());g_status=text; } static void selectHistoryNode(HistoryEditor& editor){ using V=arkjson::Value;auto selected=SendMessage(editor.list,LB_GETCURSEL,0,0);editor.selected.clear();if(selected<0||(size_t)selected>=editor.nodes.arr.size()){EnableWindow(GetDlgItem(g_dialog,1),FALSE);return;}const auto& node=editor.nodes.arr[(size_t)selected];auto text=[&](const V& object,const char* key){auto* value=object.find(key);return value?value->asStr():std::string{};};editor.selected=text(node,"id"); - std::ostringstream detail;detail<<"Iteration: "< Open to recover earlier states and branches.";SetWindowTextA(editor.details,detail.str().c_str());EnableWindow(GetDlgItem(g_dialog,1),!editor.selected.empty()); } -static LRESULT CALLBACK historyEditorProc(HWND hwnd,UINT message,WPARAM wp,LPARAM lp){auto* editor=(HistoryEditor*)GetWindowLongPtr(hwnd,GWLP_USERDATA);if(editor&&message==WM_COMMAND&&LOWORD(wp)==101&&HIWORD(wp)==LBN_SELCHANGE){selectHistoryNode(*editor);return 0;}if(editor&&message==WM_COMMAND&&LOWORD(wp)==3){editor->migrate=true;g_dialogAccept=false;g_dialogDone=true;return 0;}if(editor&&message==WM_TIMER&&wp==901){SendMessage(editor->list,LB_SETCURSEL,(WPARAM)g_historySmokeIndex,0);selectHistoryNode(*editor);if(g_historySmokeMigrate&&IsWindowEnabled(GetDlgItem(hwnd,3)))editor->migrate=true;}if(editor&&message==WM_COMMAND&&LOWORD(wp)==1&&editor->selected.empty())return 0;return editorProc(hwnd,message,wp,lp);} +static LRESULT CALLBACK historyEditorProc(HWND hwnd,UINT message,WPARAM wp,LPARAM lp){auto* editor=(HistoryEditor*)GetWindowLongPtr(hwnd,GWLP_USERDATA);if(editor&&message==WM_COMMAND&&LOWORD(wp)==101&&HIWORD(wp)==LBN_SELCHANGE){selectHistoryNode(*editor);return 0;}if(editor&&message==WM_COMMAND&&LOWORD(wp)==4){editor->compact=true;g_dialogAccept=false;g_dialogDone=true;return 0;}if(editor&&message==WM_COMMAND&&LOWORD(wp)==3){editor->migrate=true;g_dialogAccept=false;g_dialogDone=true;return 0;}if(editor&&message==WM_TIMER&&wp==901){SendMessage(editor->list,LB_SETCURSEL,(WPARAM)g_historySmokeIndex,0);selectHistoryNode(*editor);if(g_historySmokeMigrate&&IsWindowEnabled(GetDlgItem(hwnd,3)))editor->migrate=true;if(g_historySmokeCompact)editor->compact=true;}if(editor&&message==WM_COMMAND&&LOWORD(wp)==1&&editor->selected.empty())return 0;return editorProc(hwnd,message,wp,lp);} static void iterationHistoryDialog(){ - using V=arkjson::Value;if(g_chatBusy||(g_teamStarted&&g_agentTeam.snapshot().running)){g_status="Finish or cancel active assistant work before restoring an iteration.";return;}V args=V::makeObj();args.set("limit",V::makeNum(64));auto response=runTool("history_info",args);if(g_error)return;auto* info=response.find("structuredContent"),*nodes=info?info->find("nodes"):nullptr;if(!nodes||nodes->t!=V::Arr||nodes->arr.empty()){g_status="No persistent iterations have been recorded for this drawing.";return;}u64 observedRevision=g_session.revision; + using V=arkjson::Value;if(g_chatBusy||(g_teamStarted&&g_agentTeam.snapshot().running)){g_status="Finish or cancel active assistant work before restoring an iteration.";return;}V args=V::makeObj();args.set("limit",V::makeNum(64));auto response=runTool("history_info",args);if(g_error)return;auto* info=response.find("structuredContent"),*nodes=info?info->find("nodes"):nullptr;if(!nodes||nodes->t!=V::Arr||!info->find("baseline_id")||info->find("baseline_id")->asStr().empty()){g_status="No persistent iterations have been recorded for this drawing.";return;}u64 observedRevision=g_session.revision; V allNodes=*nodes;const V* pageInfo=info;std::set cursors;V page; while(auto* more=pageInfo->find("has_more")){if(more->t!=V::Bool||!more->b)break;auto* cursor=pageInfo->find("next_before_id");if(!cursor||cursor->t!=V::Str||cursor->str.empty()||!cursors.insert(cursor->str).second||allNodes.arr.size()>=512)throw std::runtime_error("History pagination is unavailable or exceeds the retained node bound");V pageArgs=V::makeObj();pageArgs.set("limit",V::makeNum(64));pageArgs.set("before_id",*cursor);page=runTool("history_info",pageArgs);if(g_error)return;pageInfo=page.find("structuredContent");auto* older=pageInfo?pageInfo->find("nodes"):nullptr;if(!older||older->t!=V::Arr||older->arr.empty()||allNodes.arr.size()+older->arr.size()>512)throw std::runtime_error("History page is empty or exceeds the retained node bound");allNodes.arr.insert(allNodes.arr.end(),older->arr.begin(),older->arr.end());} - if(auto* baseline=info->find("baseline_id");baseline&&baseline->t==V::Str&&!baseline->str.empty()){V node=V::makeObj();node.set("id",*baseline);node.set("summary",V::makeStr("Initial drawing state before the first recorded edit"));node.set("tool",V::makeStr("baseline"));if(!allNodes.arr.empty())if(auto* hash=allNodes.arr.back().find("before_sha256"))node.set("after_sha256",*hash);allNodes.arr.push_back(node);} - HistoryEditor editor;editor.nodes=std::move(allNodes);if(auto* head=info->find("head_id"))editor.head=head->asStr();WNDCLASSA cls{};cls.lpfnWndProc=historyEditorProc;cls.hInstance=GetModuleHandle(nullptr);cls.lpszClassName="ARK_ITERATION_HISTORY";cls.hbrBackground=dialogBrush;cls.hCursor=LoadCursor(nullptr,IDC_ARROW);RegisterClassA(&cls); + if(auto* baseline=info->find("baseline_id");baseline&&baseline->t==V::Str&&!baseline->str.empty()){V node=V::makeObj();node.set("id",*baseline);node.set("summary",V::makeStr(info->find("compaction")?"Retained baseline / older history is in the archive":"Initial drawing state before the first recorded edit"));node.set("tool",V::makeStr("baseline"));if(!allNodes.arr.empty())if(auto* hash=allNodes.arr.back().find("before_sha256"))node.set("after_sha256",*hash);allNodes.arr.push_back(node);} + HistoryEditor editor;if(const auto* receipt=info->find("compaction"))editor.archive=receipt->find("archive")->find("path")->asStr();editor.nodes=std::move(allNodes);if(auto* head=info->find("head_id"))editor.head=head->asStr();WNDCLASSA cls{};cls.lpfnWndProc=historyEditorProc;cls.hInstance=GetModuleHandle(nullptr);cls.lpszClassName="ARK_ITERATION_HISTORY";cls.hbrBackground=dialogBrush;cls.hCursor=LoadCursor(nullptr,IDC_ARROW);RegisterClassA(&cls); RECT parent;GetWindowRect(g_window,&parent);int width=1000,height=620;RECT outer{0,0,width,height};AdjustWindowRectEx(&outer,WS_CAPTION|WS_SYSMENU,FALSE,WS_EX_DLGMODALFRAME);int ow=outer.right-outer.left,oh=outer.bottom-outer.top;g_dialog=CreateWindowExA(WS_EX_DLGMODALFRAME,cls.lpszClassName,"Persistent drawing iterations / restore a branch",WS_CAPTION|WS_SYSMENU,parent.left+(parent.right-parent.left-ow)/2,parent.top+(parent.bottom-parent.top-oh)/2,ow,oh,g_window,nullptr,cls.hInstance,nullptr);if(!g_dialog)throw std::runtime_error("Could not open iteration history.");HFONT font=CreateFontA(-16,0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,"Segoe UI");BOOL dark=TRUE;DwmSetWindowAttribute(g_dialog,20,&dark,sizeof dark); auto control=[&](const char* kind,const char* text,DWORD style,int x,int y,int w,int h,int id){auto window=CreateWindowExA(0,kind,text,WS_CHILD|WS_VISIBLE|style,x,y,w,h,g_dialog,(HMENU)(INT_PTR)id,cls.hInstance,nullptr);SendMessage(window,WM_SETFONT,(WPARAM)font,TRUE);return window;}; - control("STATIC","Newest first. Select an iteration to inspect its actor, motivation and measured document hashes.",0,24,18,952,28,0);editor.list=control("LISTBOX","",WS_TABSTOP|WS_BORDER|WS_VSCROLL|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,24,52,952,218,101);editor.details=control("EDIT","",WS_BORDER|WS_VSCROLL|ES_MULTILINE|ES_READONLY|ES_AUTOVSCROLL,24,286,952,258,102);control("BUTTON","Close",WS_TABSTOP|BS_OWNERDRAW,660,570,100,34,2);control("BUTTON","Restore selected",WS_TABSTOP|BS_OWNERDRAW,776,570,200,34,1); + const std::string capacity="History: "+std::to_string((int)info->find("node_count")->num)+" / 512 nodes, "+std::to_string((int)(info->find("document_bytes")->num/1024))+" / 4096 KiB. Select an iteration to inspect or restore.";control("STATIC",capacity.c_str(),0,24,18,952,28,0);editor.list=control("LISTBOX","",WS_TABSTOP|WS_BORDER|WS_VSCROLL|LBS_NOTIFY|LBS_NOINTEGRALHEIGHT,24,52,952,218,101);editor.details=control("EDIT","",WS_BORDER|WS_VSCROLL|ES_MULTILINE|ES_READONLY|ES_AUTOVSCROLL,24,286,952,258,102);control("BUTTON","Close",WS_TABSTOP|BS_OWNERDRAW,660,570,100,34,2);control("BUTTON","Restore selected",WS_TABSTOP|BS_OWNERDRAW,776,570,200,34,1); // 049A: offered only while the journal still holds inline baked frames. {const V* payloads=info->find("inline_bake_payloads");const V* refs=payloads?payloads->find("references"):nullptr;const bool reclaimable=refs&&refs->t==V::Num&&refs->num>0;char label[96];std::snprintf(label,sizeof label,reclaimable?"Reclaim baked frames (%.1f MB)...":"No baked frames to reclaim",reclaimable?payloads->find("bytes")->num/1e6:0.); auto reclaim=control("BUTTON",label,WS_TABSTOP|BS_OWNERDRAW,24,570,320,34,3);EnableWindow(reclaim,reclaimable);} + control("BUTTON","Archive and compact...",WS_TABSTOP|BS_OWNERDRAW,356,570,280,34,4); for(const auto& node:editor.nodes.arr){auto string=[&](const char* key){auto* value=node.find(key);return value?value->asStr():std::string{};};std::string row=(string("id")==editor.head?"HEAD ":" ")+string("id").substr(0,18)+" / "+string("utc")+" / ";if(auto* actor=node.find("actor")){auto* role=actor->find("role"),*id=actor->find("id");row+=(role&&!role->asStr().empty()?role->asStr():id?id->asStr():"unknown")+" / ";}row+=string("summary");if(!string("motivation").empty())row+=" / "+string("motivation");for(char& c:row)if(c=='\r'||c=='\n')c=' ';SendMessageA(editor.list,LB_ADDSTRING,0,(LPARAM)row.c_str());} SetWindowLongPtr(g_dialog,GWLP_USERDATA,(LONG_PTR)&editor);SendMessage(editor.list,LB_SETCURSEL,0,0);selectHistoryNode(editor);g_edit=editor.list;g_dialogDone=g_dialogAccept=false;EnableWindow(g_window,FALSE);ShowWindow(g_dialog,SW_SHOW);SetFocus(editor.list);if(g_dialogSmoke)SetTimer(g_dialog,901,200,nullptr);MSG msg;while(!g_dialogDone&&GetMessage(&msg,nullptr,0,0)>0){if(msg.message==WM_KEYDOWN&&msg.wParam==VK_ESCAPE){SendMessage(g_dialog,WM_COMMAND,2,0);continue;}if(!IsDialogMessage(g_dialog,&msg)){TranslateMessage(&msg);DispatchMessage(&msg);}} - bool restore=g_dialogAccept&&!editor.selected.empty();EnableWindow(g_window,TRUE);DestroyWindow(g_dialog);g_dialog=nullptr;DeleteObject(font);if(!g_headless)SetForegroundWindow(g_window);if(editor.migrate){migrateDerivedBakesStudio(observedRevision);return;}if(!restore)return;args=V::makeObj();args.set("id",V::makeStr(editor.selected));args.set("expected_revision",V::makeNum((double)observedRevision));args.set("motivation",V::makeStr("Restore selected iteration from ARK history"));V actor=V::makeObj();actor.set("kind",V::makeStr("human"));actor.set("id",V::makeStr("studio"));args.set("actor",actor);runTool("iteration_restore",args);if(!g_error)g_status="Restored iteration as a new branch / revision "+std::to_string(g_session.revision); + bool restore=g_dialogAccept&&!editor.selected.empty();EnableWindow(g_window,TRUE);DestroyWindow(g_dialog);g_dialog=nullptr;DeleteObject(font);if(!g_headless)SetForegroundWindow(g_window);if(editor.compact){compactHistoryStudio(observedRevision);return;}if(editor.migrate){migrateDerivedBakesStudio(observedRevision);return;}if(!restore)return;args=V::makeObj();args.set("id",V::makeStr(editor.selected));args.set("expected_revision",V::makeNum((double)observedRevision));args.set("motivation",V::makeStr("Restore selected iteration from ARK history"));V actor=V::makeObj();actor.set("kind",V::makeStr("human"));actor.set("id",V::makeStr("studio"));args.set("actor",actor);runTool("iteration_restore",args);if(!g_error)g_status="Restored iteration as a new branch / revision "+std::to_string(g_session.revision); } static void motionDriverDialog(){ auto coupled=[&](u64 node){return node&&std::any_of(g_doc.mates.begin(),g_doc.mates.end(),[&](const AssemblyMate& mate){return isMechanicalMate(mate.type)&&(mate.a==node||mate.b==node);});};u64 candidate=g_motionActive&&coupled(g_motionDriver)?g_motionDriver:0; @@ -6111,7 +6125,7 @@ int WINAPI WinMain(HINSTANCE hi,HINSTANCE,LPSTR cmdLine,int){ if(!setDpiContext||!setDpiContext(reinterpret_cast(-4)))SetProcessDPIAware(); bool plasticsUiTest=false,electronicsWorkspaceUiTest=false,cableGuideUiTest=false; bool nativeProductPerformanceUiTest=false,sceneCacheUiTest=false,authoringAssistanceUiTest=false,featureEditorPickingUiTest=false; - bool featureHistoryUiTest=false,recoveryUiTest=false,editorScrollUiTest=false,configurationWorkspaceUiTest=false,interactionPerformanceUiTest=false;bool startupUiTest=false;bool stampsUiTest=false;bool media044bUiTest=false;bool planesSectionsUiTest=false; + bool historyCompactionUiTest=false;bool featureHistoryUiTest=false,recoveryUiTest=false,editorScrollUiTest=false,configurationWorkspaceUiTest=false,interactionPerformanceUiTest=false;bool startupUiTest=false;bool stampsUiTest=false;bool media044bUiTest=false;bool planesSectionsUiTest=false; bool specializedPatternUiTest=false;bool advancedSheetmetalUiTest=false;bool nativeVertexPullUiTest=false;bool cadImportUiTest=false;bool holesOrchestratorUiTest=false;bool designContainerUiTest=false; bool directAuthoringUiTest=false,parametricAuthoringUiTest=false,skeletonEditorUiTest=false,imageAttachmentUiTest=false,assistantSteeringUiTest=false; bool localModelsUiTest=false;bool viewportDockUiTest=false;bool bakedMotionsUiTest=false;bool parametricHudUiTest=false;bool explodedViewsUiTest=false;bool dragChainUiTest=false;bool bomUiTest=false;bool drawingWorkspaceUiTest=false;bool drawingViewportUiTest=false;bool measurementUiTest=false;bool authoringUiTest=false; @@ -6125,6 +6139,7 @@ int WINAPI WinMain(HINSTANCE hi,HINSTANCE,LPSTR cmdLine,int){ else if(a=="--self-test-plastics-ui"){plasticsUiTest=true;g_headless=true;} else if(a=="--self-test-electronics-workspace-ui"){electronicsWorkspaceUiTest=true;g_headless=true;} else if(a=="--self-test-startup-ui"){startupUiTest=true;g_headless=true;} + else if(a=="--self-test-history-compaction-ui"){historyCompactionUiTest=true;g_headless=true;} else if(a=="--self-test-history-ui"){featureHistoryUiTest=true;g_headless=true;} else if(a=="--self-test-recovery-ui"){recoveryUiTest=true;g_headless=true;} else if(a=="--self-test-team-blockers-ui"){teamBlockersUiTest=true;g_headless=true;} @@ -7030,6 +7045,7 @@ int WINAPI WinMain(HINSTANCE hi,HINSTANCE,LPSTR cmdLine,int){ #include "datum_authoring_selftest.inl" #include "typed_sketch_selftest.inl" #include "history_recovery_selftest.inl" +#include "history_compaction_selftest.inl" #include "editor_scroll_selftest.inl" #include "feature_editor_picking_selftest.inl" #include "configuration_workspace_selftest.inl" diff --git a/tests/history_compaction_051a_tests.cpp b/tests/history_compaction_051a_tests.cpp new file mode 100644 index 0000000..c231515 --- /dev/null +++ b/tests/history_compaction_051a_tests.cpp @@ -0,0 +1,50 @@ +#include "ark/agent.hpp" +#include "ark/iteration_history.hpp" +#include +#include +#include +#include +#include +namespace { +using V=arkjson::Value;namespace fs=std::filesystem; +void check(bool ok,const std::string& message){if(!ok)throw std::runtime_error(message);} +V parse(const std::string& text){V result;check(arkjson::parse(text,result),"fixture parses");return result;} +V result(const V& response){check(!response.find("isError")->b,response.dump());return *response.find("structuredContent");} +V edit(ark::AgentSession& session,int number){V args=parse(R"({"commands":[{"op":"param.set","name":"length","expr":"1"}]})");args.obj.front().second.arr.front().set("expr",V::makeStr(std::to_string(number)));args.set("expected_revision",V::makeNum(session.revision));return result(session.call("doc_apply",args));} +V compactArgs(ark::AgentSession& session,const fs::path& file,int keep){V args=V::makeObj();args.set("archive_path",V::makeStr(file.string()));args.set("keep_recent",V::makeNum(keep));args.set("confirm",V::makeBool(true));args.set("expected_revision",V::makeNum(session.revision));return args;} +std::string bytes(const fs::path& file){std::ifstream input(file,std::ios::binary);return {std::istreambuf_iterator(input),{}};} +V& member(V& value,const char* key){for(auto& field:value.obj)if(field.first==key)return field.second;throw std::runtime_error(key);} +} +int main(){try{ + const fs::path directory=fs::temp_directory_path()/("ark-compaction-synthetic-"+std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));fs::create_directory(directory); + ark::AgentSession session;result(session.call("doc_apply",parse(R"({"expected_revision":0,"commands":[{"op":"feature.add","type":"box","name":"Retained geometry","p":{"dx":"5","dy":"6","dz":"7"}}]})"))); + for(int i=1;i<=511;++i)edit(session,i); + const auto original=ark::documentToJson(session.document);const auto originalAuthoring=ark::iterationAuthoring(session.document).dump();const auto revision=session.revision; + auto args=compactArgs(session,directory/"first.ark",16);auto stale=args;stale.set("expected_revision",V::makeNum(0));check(session.call("history_compact",stale).find("isError")->b&&!fs::exists(directory/"first.ark"),"stale rejection precedes archive writes"); + auto unconfirmed=args;unconfirmed.set("confirm",V::makeBool(false));check(session.call("history_compact",unconfirmed).find("isError")->b,"explicit confirmation required"); + auto badPath=compactArgs(session,directory/"missing"/"archive.ark",16);check(session.call("history_compact",badPath).find("isError")->b&&session.revision==revision&&ark::documentToJson(session.document)==original,"failed archive leaves source unchanged"); + const auto receipt=result(session.call("history_compact",args));check(session.revision==revision+1&&ark::iterationAuthoring(session.document).dump()==originalAuthoring,"compaction retains exact authoring and revision advances"); + check(receipt.find("compaction")->find("nodes_retained")->num==16&&receipt.find("compaction")->find("undo_retained")->num==16,"explicit recent range retained"); + const auto archiveBytes=bytes(directory/"first.ark");check(ark::iterationSha256(archiveBytes)==receipt.find("archive")->find("file_sha256")->str,"receipt fingerprints real binary archive bytes"); + ark::Document archived;std::string error;check(ark::loadDocument((directory/"first.ark").string().c_str(),archived,&error)&&ark::documentToJson(archived)==original,"full 512-node archive reopens identically"); + auto collision=compactArgs(session,directory/"first.ark",0);const auto beforeCollision=ark::documentToJson(session.document);check(session.call("history_compact",collision).find("isError")->b&&bytes(directory/"first.ark")==archiveBytes&&ark::documentToJson(session.document)==beforeCollision,"archive never overwritten"); + check(ark::saveDocument(session.document,(directory/"compacted.ark").string().c_str()),"compacted file saves");ark::AgentSession reopened;check(ark::loadDocument((directory/"compacted.ark").string().c_str(),reopened.document,&error),error);reopened.revision=1000; + for(int i=0;i<16;++i)result(reopened.call("doc_undo",V::makeObj()));check(reopened.document.getParam("length")==495,"retained undo range survives reopen");check(reopened.call("doc_undo",V::makeObj()).find("isError")->b,"undo stops at explicit compaction boundary");result(reopened.call("doc_redo",V::makeObj()));check(reopened.document.getParam("length")==496,"redo works for post-compaction undo"); + // Continue beyond the former project-wide 512-node stop, then compact again. + for(int i=512;i<=600;++i)edit(session,i);check(session.document.getParam("length")==600&&session.document.features.size()==1,"continued edits preserve geometry authoring"); + const auto second=result(session.call("history_compact",compactArgs(session,directory/"second.ark",4)));check(second.find("compaction")->find("nodes_retained")->num==4,"repeat compaction has bounded latest receipt"); + ark::Document previous;check(ark::loadDocument((directory/"second.ark").string().c_str(),previous,&error)&&previous.iterationHistory.find("compaction")->find("archive")->find("file_sha256")->str==ark::iterationSha256(archiveBytes),"archive chain retains preceding archive lineage"); + auto tampered=parse(ark::documentToJson(session.document));member(member(tampered,"iteration_history"),"compaction").set("policy",V::makeStr("silent pruning"));check(!ark::documentFromJson(tampered.dump(),previous,&error),"receipt tampering rejects"); + tampered=parse(ark::documentToJson(session.document));auto& journal=member(tampered,"iteration_history");journal.obj.erase(std::remove_if(journal.obj.begin(),journal.obj.end(),[](const auto& p){return p.first=="compaction";}),journal.obj.end());check(!ark::documentFromJson(tampered.dump(),previous,&error),"missing receipt rejects"); + tampered=parse(ark::documentToJson(session.document));tampered.set("version",V::makeNum(49));check(!ark::documentFromJson(tampered.dump(),previous,&error),"legacy format cannot silently accept compacted history"); + // Restore archive through the public tool; its complete old branch set is usable. + ark::AgentSession restore;V load=V::makeObj();load.set("path",V::makeStr((directory/"first.ark").string()));result(restore.call("doc_load",load));check(restore.document.iterationHistory.find("nodes")->arr.size()==512,"public doc_load restores full archive"); + // Free archive capacity explicitly before further mutation at the old bound. + result(restore.call("history_compact",compactArgs(restore,directory/"restored-full.ark",8)));result(restore.call("doc_undo",V::makeObj()));check(restore.document.getParam("length")==510,"archive restore + explicit compaction recovers old undo"); + ark::AgentSession branches;const auto first=edit(branches,1);edit(branches,2);edit(branches,3);V pick=V::makeObj();pick.set("id",*first.find("iteration_id"));pick.set("expected_revision",V::makeNum(branches.revision));result(branches.call("iteration_restore",pick)); + const auto branchOriginal=ark::documentToJson(branches.document);const auto branchReceipt=result(branches.call("history_compact",compactArgs(branches,directory/"branches.ark",8))); + check(branchReceipt.find("compaction")->find("archived_branch_heads")->num==1&&branchReceipt.find("compaction")->find("undo_retained")->num==0,"branch compaction honestly bounds cross-branch undo without skipping target"); + check(ark::loadDocument((directory/"branches.ark").string().c_str(),previous,&error)&&ark::documentToJson(previous)==branchOriginal,"archive retains alternate branch topology"); + result(branches.call("history_compact",compactArgs(branches,directory/"baseline.ark",0)));check(branches.document.iterationHistory.find("nodes")->arr.empty()&&branches.document.getParam("length")==1,"zero-retention keeps full current state as baseline");edit(branches,7); + fs::remove_all(directory);std::cout<<"history compaction 051A tests passed: 601 edits, archives, reopen, undo, branches, failures, lineage\n";return 0; +}catch(const std::exception& error){std::cerr< Date: Thu, 22 Oct 2026 08:53:30 +0100 Subject: [PATCH 04/69] Retain explicitly selected archived branch states at history capacity [skip ci] --- docs/HISTORY_COMPACTION_051A.md | 16 +++++++++++++--- include/ark/iteration_history.hpp | 2 +- src/agent.cpp | 2 +- src/agent_transactions.cpp | 2 +- src/history_compaction_051a.cpp | 4 ++-- src/iteration_history.cpp | 19 ++++++++++++++++--- tests/history_compaction_051a_tests.cpp | 14 +++++++++++++- 7 files changed, 47 insertions(+), 12 deletions(-) diff --git a/docs/HISTORY_COMPACTION_051A.md b/docs/HISTORY_COMPACTION_051A.md index d43bc00..080f144 100644 --- a/docs/HISTORY_COMPACTION_051A.md +++ b/docs/HISTORY_COMPACTION_051A.md @@ -24,7 +24,10 @@ Retention follows the current head's **ancestor path**, keeping at most 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. +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 @@ -51,7 +54,12 @@ 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. Studio **Iterations → Archive and compact…** shows current +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 @@ -62,7 +70,9 @@ 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, zero retention, stale/no-confirm/archive failure/no-overwrite and + 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. diff --git a/include/ark/iteration_history.hpp b/include/ark/iteration_history.hpp index ae78c76..67b0ec5 100644 --- a/include/ark/iteration_history.hpp +++ b/include/ark/iteration_history.hpp @@ -28,6 +28,6 @@ void iterationInlineBakePayloads(const arkjson::Value& history,size_t& reference 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); +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/src/agent.cpp b/src/agent.cpp index 698237e..cdba2f9 100644 --- a/src/agent.cpp +++ b/src/agent.cpp @@ -1603,7 +1603,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, 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},"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_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}, diff --git a/src/agent_transactions.cpp b/src/agent_transactions.cpp index e5398ca..b420d69 100644 --- a/src/agent_transactions.cpp +++ b/src/agent_transactions.cpp @@ -135,7 +135,7 @@ arkjson::Value AgentSession::call(const std::string& tool,const V& args){ if(tool=="history_migrate_derived"||tool=="history_compact"){V out;bool failed=false; try{out=tool=="history_compact"?historyCompactTool(document,revision,args):historyMigrateDerivedTool(document,revision,args);undo_.clear();redo_.clear();prepared_.clear();cache_.clear();cacheRevision_=~u64(0);motionRevision_=~u64(0);} catch(const std::exception& e){failed=true;const std::string message=e.what();out=V::makeObj();out.set("error",V::makeStr(message));const auto end=message.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ_"); - out.set("error_code",V::makeStr(message.find("Revision conflict")!=std::string::npos?"REVISION_CONFLICT":(message.rfind("HISTORY_MIGRATION_",0)==0||message.rfind("HISTORY_COMPACTION_",0)==0)?message.substr(0,end):"HISTORY_MIGRATION_FAILED"));out.set("tool",V::makeStr(tool));out.set("revision",V::makeNum((double)revision));out.set("document_unchanged",V::makeBool(true));} + out.set("error_code",V::makeStr(message.find("Revision conflict")!=std::string::npos?"REVISION_CONFLICT":(message.rfind("HISTORY_MIGRATION_",0)==0||message.rfind("HISTORY_COMPACTION_",0)==0)?message.substr(0,end):(tool=="history_compact"?"HISTORY_COMPACTION_FAILED":"HISTORY_MIGRATION_FAILED")));out.set("tool",V::makeStr(tool));out.set("revision",V::makeNum((double)revision));out.set("document_unchanged",V::makeBool(true));} V response=V::makeObj(),content=V::makeArr(),item=V::makeObj();item.set("type",V::makeStr("text"));item.set("text",V::makeStr(out.dump()));content.arr.push_back(item);response.set("content",content);response.set("structuredContent",out);response.set("isError",V::makeBool(failed));return finish(std::move(response));} const bool planeMutation=tool=="plane_authoring"&&!(args.find("preview")&&args.find("preview")->t==V::Bool&&args.find("preview")->b); if((!mutating&&!planeMutation)||callDepth_>1||suppressHistory_)return finish(dispatch(tool,clean)); diff --git a/src/history_compaction_051a.cpp b/src/history_compaction_051a.cpp index d54c6c3..6ac7002 100644 --- a/src/history_compaction_051a.cpp +++ b/src/history_compaction_051a.cpp @@ -30,7 +30,7 @@ bool publishNew(const fs::path& from,const fs::path& to){ } V historyCompactTool(Document& document,u64& revision,const V& args){ require(args.t==V::Obj,"HISTORY_COMPACTION_INVALID: arguments must be an object"); - for(const auto& field:args.obj)require(field.first=="archive_path"||field.first=="keep_recent"||field.first=="expected_revision"||field.first=="confirm"||field.first=="actor"||field.first=="motivation","HISTORY_COMPACTION_INVALID: unknown field "+field.first); + for(const auto& field:args.obj)require(field.first=="archive_path"||field.first=="keep_recent"||field.first=="retain_ids"||field.first=="expected_revision"||field.first=="confirm"||field.first=="actor"||field.first=="motivation","HISTORY_COMPACTION_INVALID: unknown field "+field.first); const auto* expected=args.find("expected_revision");require(expected&&expected->t==V::Num&&expected->num==(double)revision,"Revision conflict; read history_info before compacting"); const auto* confirm=args.find("confirm");require(confirm&&confirm->t==V::Bool&&confirm->b,"HISTORY_COMPACTION_CONFIRM_REQUIRED: archive and compact only on explicit instruction with confirm:true"); const auto* count=args.find("keep_recent");require(count&&count->t==V::Num&&count->num>=0&&count->num<=256&&count->num==std::floor(count->num),"HISTORY_COMPACTION_INVALID: keep_recent must be an integer 0..256"); @@ -48,7 +48,7 @@ V historyCompactTool(Document& document,u64& revision,const V& args){ Document reopened;require(loadDocument(utf8(staging).c_str(),reopened,&error)&&documentToJson(reopened)==original,"HISTORY_COMPACTION_ARCHIVE_FAILED: staged archive did not reopen identically: "+error); V archiveInfo=V::makeObj();archiveInfo.set("path",V::makeStr(utf8(archive)));archiveInfo.set("bytes",V::makeNum((double)fs::file_size(staging)));archiveInfo.set("verified",V::makeBool(true));archiveInfo.set("document_sha256",V::makeStr(iterationSha256(original)));archiveInfo.set("file_sha256",V::makeStr(iterationSha256(bytes(staging)))); V record=V::makeObj();record.set("archive",archiveInfo);record.set("actor",actor);record.set("provenance",V::makeStr("caller_declared"));record.set("motivation",V::makeStr(motivation));record.set("revision_before",V::makeNum((double)revision)); - Document next=document;next.iterationHistory=iterationCompact(document,(size_t)count->num,record);const std::string persisted=documentToJson(next); + Document next=document;next.iterationHistory=iterationCompact(document,(size_t)count->num,record,args.find("retain_ids")?*args.find("retain_ids"):V::makeArr());const std::string persisted=documentToJson(next); require(persisted.size()<=maxDocumentBytes,"HISTORY_COMPACTION_CAPACITY: retained history still exceeds 4 MiB; request fewer retained nodes"); require(iterationValidate(next,next.iterationHistory,error)&&documentFromJson(persisted,reopened,&error)&&documentToJson(reopened)==persisted,"HISTORY_COMPACTION_INVALID: compacted document did not reopen identically: "+error); require(iterationAuthoring(next).dump()==iterationAuthoring(document).dump(),"HISTORY_COMPACTION_INVALID: compaction changed authoring"); diff --git a/src/iteration_history.cpp b/src/iteration_history.cpp index 63162b5..380bc5c 100644 --- a/src/iteration_history.cpp +++ b/src/iteration_history.cpp @@ -181,13 +181,14 @@ V iterationRewrite(const V& h,const std::function& transform,std::map< for(const char* key:{"undo_ids","redo_ids"}){V list=V::makeArr();for(const auto& id:need(h,key).arr)list.arr.push_back(V::makeStr(ids.at(id.str)));out.set(key,list);} if(const auto* migrations=h.find("migrations"))out.set("migrations",*migrations);if(const auto* receipt=h.find("compaction")){out.set("compaction",*receipt);out.set("compacted",V::makeBool(true));}return out; } -V iterationCompact(const Document& source,size_t keepRecent,const V& receipt){ +V iterationCompact(const Document& source,size_t keepRecent,const V& receipt,const V& retainIds){ if(keepRecent>256)throw std::runtime_error("HISTORY_COMPACTION_INVALID: keep_recent must be 0..256"); + if(retainIds.t!=V::Arr||retainIds.arr.size()>256)throw std::runtime_error("HISTORY_COMPACTION_INVALID: retain_ids must be an array of at most 256 iteration ids"); const V& h=source.iterationHistory;std::string error; if(!iterationValidate(source,h,error))throw std::runtime_error("HISTORY_COMPACTION_INVALID: "+error); std::vector chain;std::string cursor=text(h,"head_id"); while(cursor!=text(h,"baseline_id")&&chain.size() ids{{cursor,text(out,"baseline_id")}}; V mapping=V::makeArr();auto mapped=[&](const std::string& old,const std::string& current){V item=V::makeObj();item.set("original_id",V::makeStr(old));item.set("id",V::makeStr(current));mapping.arr.push_back(item);};mapped(cursor,text(out,"baseline_id")); @@ -196,12 +197,24 @@ V iterationCompact(const Document& source,size_t keepRecent,const V& receipt){ m.set("parent_id",need(out,"head_id"));m.set("previous_head_id",need(out,"head_id"));m.set("before_sha256",V::makeStr(iterationSha256(state.dump())));m.set("delta",delta);m.set("ordinal",V::makeNum(need(out,"nodes").arr.size()+1)); const std::string id=nodeId(m);m.set("id",V::makeStr(id));member(out,"nodes").arr.push_back(m);out.set("head_id",V::makeStr(id));ids[text(n,"id")]=id;mapped(text(n,"id"),id);state=std::move(next); } + // Explicit selected states can be preserved even when they are on another + // branch or older than the ancestor suffix. They do not change the head. + for(const auto& selected:retainIds.arr){ + if(selected.t!=V::Str||selected.str.empty())throw std::runtime_error("HISTORY_COMPACTION_INVALID: retain_ids requires iteration ids"); + if(ids.count(selected.str))continue; + if(need(out,"nodes").arr.size()>=256)throw std::runtime_error("HISTORY_COMPACTION_INVALID: combined retained nodes exceed 256"); + const V selectedState=replay(h,selected.str);V delta=V::makeArr();diff(baselineState,selectedState,V::makeArr(),delta,member(out,"blobs")); + const V* original=node(h,selected.str);V m=original?*original:V::makeObj();erase(m,"id");erase(m,"restored_from_id"); + if(!original){m.set("actor",need(receipt,"actor"));m.set("provenance",V::makeStr("caller_declared"));m.set("tool",V::makeStr("history_compact"));m.set("motivation",V::makeStr("Explicitly retained archived baseline"));m.set("utc",V::makeStr(utc()));m.set("summary",V::makeStr("Explicitly retained archived baseline"));} + m.set("original_id",selected);m.set("original_parent_id",original?need(*original,"parent_id"):selected);m.set("original_previous_head_id",original?need(*original,"previous_head_id"):selected);m.set("parent_id",need(out,"baseline_id"));m.set("previous_head_id",need(out,"baseline_id"));m.set("before_sha256",need(out,"baseline_sha256"));m.set("after_sha256",V::makeStr(iterationSha256(selectedState.dump())));m.set("delta",delta);m.set("ordinal",V::makeNum(need(out,"nodes").arr.size()+1)); + const auto id=nodeId(m);m.set("id",V::makeStr(id));member(out,"nodes").arr.push_back(m);ids[selected.str]=id;mapped(selected.str,id); + } // Undo means previous active state (including across branches), not parent. // Keep only the contiguous suffix; never silently skip an omitted target. V undo=V::makeArr();const auto& oldUndo=need(h,"undo_ids").arr; for(auto it=oldUndo.rbegin();it!=oldUndo.rend();++it){auto found=ids.find(it->str);if(found==ids.end())break;undo.arr.insert(undo.arr.begin(),V::makeStr(found->second));} out.set("undo_ids",undo);V record=receipt;record.set("format",V::makeStr("ark.history_compaction.v1"));record.set("utc",V::makeStr(utc()));record.set("previous_head_id",need(h,"head_id"));record.set("previous_baseline_id",need(h,"baseline_id"));record.set("baseline_id",need(out,"baseline_id"));record.set("head_id",need(out,"head_id"));record.set("retained_ids",mapping); - record.set("nodes_before",V::makeNum(need(h,"nodes").arr.size()));record.set("nodes_retained",V::makeNum(chain.size()));record.set("undo_retained",V::makeNum(undo.arr.size()));record.set("redo_cleared",V::makeNum(need(h,"redo_ids").arr.size())); + record.set("nodes_before",V::makeNum(need(h,"nodes").arr.size()));record.set("nodes_retained",V::makeNum(need(out,"nodes").arr.size()));record.set("ancestor_nodes_retained",V::makeNum(chain.size()));record.set("selected_extra_nodes",V::makeNum(need(out,"nodes").arr.size()-chain.size()));record.set("undo_retained",V::makeNum(undo.arr.size()));record.set("redo_cleared",V::makeNum(need(h,"redo_ids").arr.size())); size_t omittedHeads=0;const V sourceInfo=iterationInfo(source);for(const auto& head:need(sourceInfo,"branch_heads").arr)if(!ids.count(head.str))++omittedHeads; record.set("archived_branch_heads",V::makeNum(omittedHeads));record.set("policy",V::makeStr("head_ancestor_suffix_contiguous_undo_clear_redo")); V signedRecord=record;canonical(signedRecord);record.set("sha256",V::makeStr(iterationSha256(signedRecord.dump())));out.set("compaction",record);out.set("compacted",V::makeBool(true));return out; diff --git a/tests/history_compaction_051a_tests.cpp b/tests/history_compaction_051a_tests.cpp index c231515..44343a0 100644 --- a/tests/history_compaction_051a_tests.cpp +++ b/tests/history_compaction_051a_tests.cpp @@ -5,6 +5,7 @@ #include #include #include +#include namespace { using V=arkjson::Value;namespace fs=std::filesystem; void check(bool ok,const std::string& message){if(!ok)throw std::runtime_error(message);} @@ -46,5 +47,16 @@ int main(){try{ check(branchReceipt.find("compaction")->find("archived_branch_heads")->num==1&&branchReceipt.find("compaction")->find("undo_retained")->num==0,"branch compaction honestly bounds cross-branch undo without skipping target"); check(ark::loadDocument((directory/"branches.ark").string().c_str(),previous,&error)&&ark::documentToJson(previous)==branchOriginal,"archive retains alternate branch topology"); result(branches.call("history_compact",compactArgs(branches,directory/"baseline.ark",0)));check(branches.document.iterationHistory.find("nodes")->arr.empty()&&branches.document.getParam("length")==1,"zero-retention keeps full current state as baseline");edit(branches,7); - fs::remove_all(directory);std::cout<<"history compaction 051A tests passed: 601 edits, archives, reopen, undo, branches, failures, lineage\n";return 0; + // A full archive must also recover an intermediate state on an old branch, + // which is not an ancestor of its active head. + ark::AgentSession fullBranch;result(fullBranch.call("doc_apply",parse(R"({"expected_revision":0,"commands":[{"op":"feature.add","type":"box","name":"Branch geometry","p":{"dx":"5","dy":"6","dz":"7"}}]})"))); + const auto branchA=edit(fullBranch,1),branchB=edit(fullBranch,2);edit(fullBranch,3);pick.set("id",*branchA.find("iteration_id"));pick.set("expected_revision",V::makeNum(fullBranch.revision));result(fullBranch.call("iteration_restore",pick)); + for(int i=4;i<=510;++i)edit(fullBranch,i);check(fullBranch.document.iterationHistory.find("nodes")->arr.size()==512,"branched fixture reaches exact capacity"); + check(ark::saveDocument(fullBranch.document,(directory/"full-branches.ark").string().c_str()),"full branched archive saves");ark::AgentSession recoveredBranch;load.set("path",V::makeStr((directory/"full-branches.ark").string()));result(recoveredBranch.call("doc_load",load)); + const auto branchAuthoring=ark::iterationAuthoring(recoveredBranch.document).dump();auto retain=compactArgs(recoveredBranch,directory/"full-branches-copy.ark",0);V selected=V::makeArr();selected.arr.push_back(*branchB.find("iteration_id"));selected.arr.push_back(*branchB.find("iteration_id"));selected.arr.push_back(*recoveredBranch.document.iterationHistory.find("head_id"));retain.set("retain_ids",selected); + const auto selectedReceipt=result(recoveredBranch.call("history_compact",retain));check(ark::iterationAuthoring(recoveredBranch.document).dump()==branchAuthoring&&selectedReceipt.find("compaction")->find("selected_extra_nodes")->num==1,"selected old branch retained without changing authoring or duplicating nodes"); + std::string selectedId;for(const auto& row:selectedReceipt.find("compaction")->find("retained_ids")->arr)if(row.find("original_id")->str==branchB.find("iteration_id")->str)selectedId=row.find("id")->str;check(!selectedId.empty(),"selected branch receipt maps old id"); + pick.set("id",V::makeStr(selectedId));pick.set("expected_revision",V::makeNum(recoveredBranch.revision));result(recoveredBranch.call("iteration_restore",pick));check(recoveredBranch.document.getParam("length")==2&&recoveredBranch.document.features.size()==1&&recoveredBranch.document.features[0].name=="Branch geometry","full archive arbitrary old branch state restores correct authoring and geometry"); + auto invalid=compactArgs(recoveredBranch,directory/"invalid-target.ark",0);selected.arr={V::makeStr("missing-iteration")};invalid.set("retain_ids",selected);const auto unchanged=ark::documentToJson(recoveredBranch.document);check(recoveredBranch.call("history_compact",invalid).find("isError")->b&&ark::documentToJson(recoveredBranch.document)==unchanged&&!fs::exists(directory/"invalid-target.ark"),"unknown retained id fails without publication or mutation"); + fs::remove_all(directory);std::cout<<"history compaction 051A tests passed: 601 edits, full branched archive recovery, reopen, undo, failures, lineage\n";return 0; }catch(const std::exception& error){std::cerr< Date: Thu, 22 Oct 2026 08:53:09 +0100 Subject: [PATCH 05/69] Verify agent outcomes through rejection recovery and cold persistence [skip ci] --- CMakeLists.txt | 2 +- benchmarks/agent_outcomes_v2.json | 302 ++++++++++++++++++++++++++++++ docs/AGENT_OUTCOMES_051A.md | 60 ++++++ include/ark/agent_benchmark.hpp | 8 + src/agent_benchmark.cpp | 103 +++++++++- tests/agent_benchmark_tests.cpp | 36 +++- 6 files changed, 499 insertions(+), 12 deletions(-) create mode 100644 benchmarks/agent_outcomes_v2.json create mode 100644 docs/AGENT_OUTCOMES_051A.md diff --git a/CMakeLists.txt b/CMakeLists.txt index 4fa52d7..b621538 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -177,7 +177,7 @@ 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/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) 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/docs/AGENT_OUTCOMES_051A.md b/docs/AGENT_OUTCOMES_051A.md new file mode 100644 index 0000000..a96cf96 --- /dev/null +++ b/docs/AGENT_OUTCOMES_051A.md @@ -0,0 +1,60 @@ +# Agent outcomes, 051A + +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. + +Each attempt 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. It compares authoring and checks file bytes +again after reopen. `persistence.saved` means writing succeeded; `persisted` also +requires the cold 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. + +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 changed benchmark and test translation units were compiled +with LLVM-MinGW and linked against the existing ARK baseline library for this local +check; this is not a new packaged runtime or a live-model speed/cost comparison. diff --git a/include/ark/agent_benchmark.hpp b/include/ark/agent_benchmark.hpp index e23c384..b2321c8 100644 --- a/include/ark/agent_benchmark.hpp +++ b/include/ark/agent_benchmark.hpp @@ -11,6 +11,7 @@ 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(); }; struct AgentBenchmarkSuite { std::string id; @@ -22,8 +23,15 @@ struct AgentBenchmarkConfig { 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/src/agent_benchmark.cpp b/src/agent_benchmark.cpp index cfa41d2..57c8125 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,19 +36,73 @@ 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"}){double cost=0;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)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