MySmartRouter.comVantage Product LabsProduct Architecture OverviewV6 Architecture · Updated October 3, 2026
Vantage Product Labs • Multi-Model AI Workspace

One workspace.
Every model.
Real control.

MySmartRouter V6 brings exact model choice, Auto Router, connected context, sessions and cost visibility into one governed workspace. Its Build experience uses the unified V6 GPT WORK process and the approved Dark B product shell. As of October 3, 2026, the architecture and persistence requirements are locked; the build is paused at persistence/runtime proof. The recorded source checkpoint is preserved, with runtime, full regression and release work still open.

Core Architecture Thesis
Intent → Govern → Route → Execute → Review → Cost → Resume
Keep decisions, source identity, evidence, cost and next actions visible. GPT coordinates bounded work; independent review and owner authorization remain distinct. Product V6 development does not imply an installed autonomous control plane.
Choose the Work
→
Select or Route
→
Execute Bounded Work
→
Review / Continue
→
Save / Hand Off
→
Resume Saved State
Framework evidence informing MySmartRouter · September 28, 2026

Independent AI Architecture Assessments

Two assessments of architecture capability—not two ratings of MySmartRouter’s runtime. The first concerns the governed system architecture; the second concerns Peter DeCaro’s applied-AI architectural judgment.

AI Systems Architecture Capability

95.00

Gemini · 10-Dimension Systems Architecture Assessment

Measures the architecture: how well the system is designed, governed, tested, recovered, and controlled.

Applied-AI Architecture Capability

99.50

Gemini · Informed 9-Dimension Applied-AI Architect Assessment

Measures the architect: how effectively complex objectives are translated into governed AI systems while human judgment and control remain authoritative.

Gemini / Magai · September 28, 2026. The ten-dimension frozen baseline was 94.50; the historical V3 nine-dimension result was 97.00. The 99.50 successor is informed/non-blind, with partial comparability—not a repeat of the original blinded product assessment. The framework-only evidence did not raise the Product/System Integration scores.

Evidence-based assessments using Google Gemini; not vendor certifications, endorsements, product completion percentages, throughput benchmarks or deployment approvals.

Assessment delivery

magai logoMagai · Gemini assessment delivery

Assessment workflow

Delivery surface for the accepted Gemini architecture assessments. Magai is not an additional evaluator, and the route does not independently attest the serving model version.

V6
V6 · October 3, 2026

MySmartRouter V6: one workspace, one saved build.

The current product requirements combine model routing and creation with a governed Build workflow. Architecture, source verification and installed behavior are reported separately.

Pause checkpoint · October 3, 2026. V6 architecture is FINAL. Persistence requirements are locked; production persistence is not qualified. The build remains at stage 1 of 7. The signer is unprovisioned and fail-closed; runtime Attempt 1 has not been issued. No merge or deployment is authorized by this website update.

Unified Build

GPT WORK is the common process for direct GPT and qualified partners. MySmartRouter coordinates the same saved project and current stage.

Explicit model choice

Model Direct keeps the chosen canonical model/version or fails closed. Auto Router records the approved dispatcher and actual served provider/model.

Current UX baseline

The approved Dark B shell and shared navigation remain the product design baseline. Historical multi-pane and old mode proposals do not reopen it.

Preserved earlier reference · historical wording and evidence

History only. The earlier text below retains its original scope and dates. The V6 requirements and October 3 checkpoint above govern this page’s current description. Earlier modes, retry allowances, timer-only refresh and startup paths do not redefine V6.

01
Executive Architecture Summary

What MySmartRouter.com Is

MySmartRouter is a governed AI workspace built around distinct work modes, explicit model/provider routing, persistent sessions, cost visibility and controlled handoffs. The early multi-pane concept remains an architectural direction; the later V6 evidence is a source/CI record, not proof that every feature shown on this page is installed or accepted in production.

The product's defensible operating layer is not the model itself. It is the governed experience around model choice, routing, context, provenance, persistence, cost visibility, cross-model work, and deliberate handoff.
The Problem MySmartRouter.com Solves

AI work is powerful, but increasingly fragmented.

The operating problem

Serious AI users increasingly work across multiple models, providers, projects and conversations. That creates repeated manual copying, duplicated context, uncertain model/provider selection, fragmented history, inconsistent project authority, and poor visibility into what each request actually cost.

  • Separate AI products become disconnected work silos.
  • The user repeatedly rebuilds context when moving between models.
  • Provider/model choice can become technical overhead instead of productive work.
  • Comparing several models often means opening several apps and manually coordinating them.
  • Project files, authority and AI conversation state are difficult to keep aligned.

How the product architecture addresses it

The architecture brings work modes, routing configuration, context provenance and usage records into one operator-controlled surface. The preserved multi-pane and cross-chat concepts extend that direction, while the V6 source/CI record strengthens the boundary between an authorized task, a returned result and the evidence needed to accept it.

  • Exact-model choice and Smart Select remain distinct routing concepts; provider eligibility and configuration must be explicit.
  • Auto Router delegates model choice where its configured route supports it; provider execution needs its own proof.
  • Multi-pane comparison and concurrent fan-out remain separately identified design horizons.
  • Drive, projects and attachments supply context with provenance; canonical framework loading has stricter completeness rules.
  • Usage records expose reported costs, while durable reservations and partial-delivery rules aim to avoid accidental duplicate work.

1 · Model and provider choice

Keep the requested route, configured credentials, eligible capability and served-route metadata distinct. OpenRouter is part of the product’s routing history, not the entire multi-provider product identity.

2 · Work-mode boundaries

Build, creation, media and later routing modes must retain explicit scope and credential boundaries. The V6 source extends this separation; feature availability still depends on the accepted product version.

3 · Governed continuity

Keep the accepted checkpoint, candidate, Recovery Anchor, directives and returned evidence visible. An output marked PASS does not establish independent acceptance.

4 · V5-informed Build control

Apply complete authority loading, fact-derived applicability, verified handoffs and invocation-bound persistence through an authorized product wave. See the detailed framework improvements.

V6
V6 · October 3, 2026

The V6 framework inside MySmartRouter.

Shared framework rules belong to one release; product-specific requirements remain in the product ledger.

Complete continuity

Load governing rules, operating instructions and cumulative build content at equal priority. Capture the actual delivered request, source revisions and capacity checks; a digest or shortened summary alone is insufficient.

Every return and turn

Perform a full refresh on each actor return and on required hard-refresh events. Ordinary exchanges retain project/release/state binding and response validation. Drift or a changed authority triggers another full refresh.

Protected execution

Bind actions to an immediate challenge/proof receipt and a protected action broker. The application must not control the signer, private key, journal or trusted reader. Instructional-only routes must be labeled.

Durable state

Keep immutable revisions and one authoritative mutable project pointer. Use expected-version updates, durable reservations, idempotency keys and fencing; stale writers cannot advance the current state.

Uncertain outcomes

Timeout, lost acknowledgement or expired lease does not prove an operation failed. Hold the reservation, reconcile actual effect and record the decision before any newly authorized attempt.

Recovery

Restore application, data, configuration and environment under separate checks. Prevent old writers, verify a consistent backup and recover into a safe target before changing the live pointer.

Adoption is a bounded compatibility change from the existing source checkpoint. Preserve completed work, all findings and the seven-stage schedule. The framework and product retain separate canonical homes, connected by exact release and state identities.

The verification tools behind the V5 lessons

python logoPython · unittest & subprocess

V5 verification

Focused tests, deterministic child-process timeout fixtures, recovery-state checks and deduplication tooling. The independent Linux Python 3.11 replay and primary Python 3.13 run remain separately attributed; this is not a Windows or production claim.

Python logo — jsonschema validation libraryJSON Schema · Python jsonschema

Evidence validation

Structured JSON evidence validation in the recorded Action 3 environment. Schema validity is a bounded evidence check, not proof of complete product behavior.

linux logoLinux · isolated review and CI

Test environment

Recorded independent replay environment and isolated MySmartRouter CI. Linux execution does not establish Windows execution, installed Hostinger isolation or production readiness.

github actions logoGitHub Actions · PHP / MariaDB CI

Source-controlled verification

The September 25 R69 record binds candidate source to isolated CI: 291 baseline blobs preserved plus 52 additions, with failing-first evidence and corrected pilot tests. Independent exact-head acceptance and installed/runtime verification remain separate.

Preserved earlier reference · historical wording and evidence

History only. The earlier text below retains its original scope and dates. The V6 requirements and October 3 checkpoint above govern this page’s current description. Earlier modes, retry allowances, timer-only refresh and startup paths do not redefine V6.

V5
Reviewed framework improvements → MySmartRouter Build

How V5 strengthens MySmartRouter’s Build framework

V5 turns earlier delivery lessons into more explicit authority, applicability, handoff, review and recovery controls. These improvements inform the product’s next authorized implementation; they do not turn framework tests into a claim that MySmartRouter is already running every control.

A useful result must be tied to the right task, the right source, the right actor and inspectable evidence—with human judgment retained at material decisions.
01

Authority without losing accepted work

V5 improvement. V5 makes inheritance and source identity inspectable. Action 1 mapped 328 spans across a 35-source effective framework context; the explicit A01/M26 owner amendment and the full inherited GL-15 safeguards were retained.

MySmartRouter application. For MySmartRouter, recover the real product state, R59 accepted source/CI, candidate and Recovery Anchor before a handoff. Do not rebuild accepted work or import a newer framework filename as authority.

Evidence boundary. The semantic disposition is ADEQUATE_WITH_STATED_LIMITATIONS at specification level. The 35-source V5 context is not the 38-source R69 product-pilot catalog.

02

Persistence tied to the invocation

V5 improvement. The reviewed design separates a producer heartbeat, an acknowledgement and behavioral proof. CURRENT requires pinned authority, complete equal-priority loading, project/recovery context, applicable controls, operation readiness and a matching durable receipt/readback.

MySmartRouter application. Bind each consequential Build action to its actor, task, source and proof. A timed refresh or signed return may support freshness or integrity, but cannot substitute for the required behavior.

Evidence boundary. Optional cron/watchdogs do not prove memory. Unmocked Guard 2 and installed product persistence were not established by the V5 sidecars.

03

Facts decide which controls apply

V5 improvement. V5 derives the action from observed tool, target and effect facts. Every module receives a disposition after full loading; unknown or contradictory facts stop the affected action. A write cannot become read-only because a model labels it that way.

MySmartRouter application. Require typed action and applicable-control receipts before Git, Drive, hosting, voice-triggered or other consequential operations. Dormant controls remain loaded; candidate modules are not silently activated.

Evidence boundary. The reviewer noted that the mandatory-module table under-encodes some M26 triggers. Inherited triggers remain binding; a product runner must not trust that table alone.

04

Handoffs with verifiable return requirements

V5 improvement. The orchestration contract specifies capability, trigger, input, authorization, output, failure, retry, readback, evidence and notification. Each external operation is qualified by actor × product × operation × target × session.

MySmartRouter application. Claude, Cursor or Lovable handoffs carry authority identity, project/stage, accepted SHA, candidate, Recovery Anchor, allowed tools/paths, forbidden mutations, tests, destination and STOP/return conditions.

Evidence boundary. A copy button is convenience, not evidence of execution. Claude is an independent reviewer only when separately assigned in a suitable context; an author’s own review is not independent acceptance.

05

Human control and three peer build paths

V5 improvement. V5 preserves Manual, Light Build and MySmartRouter as peers. Build path, execution cadence and execution location remain separate decisions. Early owner UAT, material decisions and disputed findings stay visible.

MySmartRouter application. Manual retains owner-paced NEXT → bounded work → GPT REVIEW. Light Build retains direct engineering, early working UAT and full QA. Orchestration is selected only when its coordination value justifies the overhead.

Evidence boundary. A MySmartRouter product task does not automatically select the MySmartRouter build path. Voice, Telegram, a scheduler tick or AUTO-NEXT cannot bypass a required owner decision.

06

BUILD EDIT checks the consequences of a change

V5 improvement. V5 replaces a self-reported edit PASS with an impact map covering direct, derived, check-only and expected-unchanged artifacts; physical-tree, schema/registry, stale-pointer, propagation and readback checks make drift detectable.

MySmartRouter application. Keep product source, framework authority, configuration and evidence separate. Bind an authorized change to exact files and compare the candidate with both the locked baseline and last accepted checkpoint.

Evidence boundary. These are framework edit controls and local verification patterns, not proof that all provider writes are intercepted or isolated in the running product.

07

Recaps and recovery that survive interruptions

V5 improvement. The HTML recap retains project/path identity, prior accepted iteration, candidate, current item, Recovery Anchor, reversion target, evidence and the next permitted action. Side work and remediation remain nested under the master schedule.

MySmartRouter application. Return ITEM | STATUS | NEXT STEP with changed/unchanged scope and a copyable handoff. Persist command attempts, exits, logs and artifact hashes before advancing; resume from verified state, not an assistant’s recollection.

Evidence boundary. A durable local journal is not remote banking. Interrupted or unknown attempts stay unknown until reconciled; a later run does not retroactively prove an earlier one.

08

Test recovery before claiming resilience

V5 improvement. Action 3 introduced 13 focused tests and independently reviewed Linux replay around a test-only subprocess timeout proxy. Saved runs retained failure evidence and restored the expected candidate reports.

MySmartRouter application. Use failing-first checks, interrupted-run cases, state/hash validation, bounded retry and recovery evidence when validating MySmartRouter’s real dependencies. Preserve its accepted signer, SQLite and separate-user design until an authorized decision changes it.

Evidence boundary. This is test-only evidence, not Windows execution, production timeout behavior or live recovery certification. Repeated runs of the same suite are not additional independent tests.

09

Reconcile findings without counting repetition as votes

V5 improvement. Action 4’s exact-payload gate preserved 210 mixed records in 106 content/reference groups, supported by 42 focused tests. Original findings, dispositions, reviewer slots and differing payloads remained traceable.

MySmartRouter application. Give the Build governor a finding-level review record: evidence, disposition, bounded repair and retest. Retain disagreement; a final rejection of an independent finding requires the recorded owner decision.

Evidence boundary. The groups are not 106 independently verified defects. Exact matching does not detect paraphrased duplicates, and the sidecar is not an installed live ingestion pipeline.

10

Draft-only email with durable, separate output legs

V5 improvement. The amended email contract reserves work before generation, persists exact generated bytes and tracks private, nondeploying Git and governed Drive delivery/readback independently. Restart reuses the result; a failed leg does not regenerate it.

MySmartRouter application. After authorized product persistence proof, the proposed flow can read an approved mailbox/query and prepare SOURCE SUMMARY / PROPOSED RESPONSE / NOT SENT outputs. Voice uses normal applicability/authorization; Telegram reports review-ready, milestone or failure events.

Evidence boundary. This remains a product implementation/acceptance requirement. No send, delete, archive, label change or native mailbox draft is implied. Unknown generation outcomes need reconciliation; notification failure does not undo successful canonical writes.

Source basis: V5 Execution Bible R10; Bootstrap R02; Manual/Light preservation matrix; orchestration and amended email contracts; Action 1/3/4 closeout records; corrected Gemini R02. The framework reference details the underlying controls. The embedded assessment evidence preserves their scoring and source boundaries.

V6
V6 · October 3, 2026

Current V6 capability and acceptance map.

These are the V6 product requirements and their remaining proof boundaries, not a claim that every workflow is already deployed.

CapabilityV6 behaviorAcceptance still required
Build shellApproved Dark B layout, shared navigation, one build/version identity, one ad hoc copy prompt, state-driven stage and owner action.Exact-build screenshots, owner UAT and same-state WORK transitions.
Model routingExact Model Direct or explicitly approved Auto Router; truthful provider/model/cost metadata.Catalog reconciliation, failed-route behavior and live provider evidence.
Sessions / contextDistinct OPEN, CONTEXT and DELETE; selected sources with provenance, caps, dedupe and secret scrubbing.No call before Submit; repeated Save does not duplicate records.
Image / videoServer-side idempotency; truthful busy/progress/recovery; type/size boundaries, spoof rejection and private asset lifecycle.Double-click/reload tests, supported providers and recovery proof.
Drive / emailReal OAuth lifecycle and chosen destination readback; draft-only email has separate read authorization.Connect/expiry/reconnect/disconnect; no silent expansion of Drive-only grants.
Scheduled jobsSimple cron/prompt jobs with editable templates, Run Now, timezone/DST preview and occurrence controls.Authentication, overlap, timeout/cost ceilings, logs and retention.
Help / reports / cacheHelp matches visible workflows; Cume and exports match totals; new builds appear without clearing user data.Responsive/accessibility matrix, report reconciliation and cache upgrade tests.
Security / migrationAuth/CSRF/OAuth/secret/asset boundaries; separate data migration gate.Backup/apply/postcheck/rollback and environment recovery.
V4 Mobile Build-Control Transport

Twilio integration · historical read validation, production status separate

The historical VPL Build Framework V2 design defined Twilio as the primary two-way mobile transport for governed build alerts and operator replies. The historical record reported read-only validation from the Windows VPL environment for account authentication, active account status, phone-number discovery, SMS capability and Messaging resource access. The record described a restricted VPL API key and withheld production outbound SMS pending A2P approval. This website revision does not reverify the account, registration or production messaging state. This transport extends the supervisory control plane without changing MySmartRouter's core routing or credential isolation. V4 is designed for multiple alert methods rather than a single transport: Twilio can provide governed two-way SMS, while Pushover and Telegram provide additional mobile notification paths so build status, review gates, failures and approval requests can reach the operator through the most appropriate configured channel.

Preserved earlier reference · historical wording and evidence

History only. The earlier text below retains its original scope and dates. The V6 requirements and October 3 checkpoint above govern this page’s current description. Earlier modes, retry allowances, timer-only refresh and startup paths do not redefine V6.

V4
Preserved product implementation history

V4 capabilities and the inherited product foundation

The V4 record built on the V2 governed control surface and V3 stable baseline: scope safety, supervised Build work, desktop voice, session/history handling, contextual sources and staged routing/media modes. The cards and table below retain that earlier feature account. Their implementation labels describe the historical record, not a fresh verification of V6 or production deployment.

V3.0 protected stable baseline W0–W7 banked historical authority Historical R1 post-W7 correction record Historical W8 gate · not today’s next step

V4 architecture snapshot · historical foundation

V4 preserves the working BUILD, AUTO ROUTER and FREE MODEL foundation while governing additive change through source gates, independent review and banked evidence. The locked V4 architecture expands toward five top-level modes — BUILD, CREATE — AUTO ROUTER, CREATE — AUTO ROUTER MULTI, CREATE — FREE MODEL and IMAGE / VIDEO CREATOR — without allowing new modes to silently inherit BUILD credentials or database scope.

Five-Mode Scope Safety

V4 introduces a shared mode/scope registry so existing modes remain isolated and unknown scopes fail explicitly instead of silently resolving to BUILD.

Desktop Voice Reliability

The preferred Windows path uses getUserMedia + MediaRecorder + server-side transcription, while Stop ends capture without submitting and dictated text remains in the compose field for manual review.

Session History + Activity Consolidation

Useful per-request activity detail moves into Session History so history becomes the primary drill-down surface rather than maintaining a separate Activity path.

Multi-Select Library Context

V4 extends Library Context toward multiple selected sources with preserved provenance, bounded context ceilings and backward-compatible one-item behavior.

Continuity + Hash Gates

Each bounded implementation wave can verify the exact source produced by the previous banked wave before edits begin, preventing silent drift across agents or sessions.

Diagnostics + Collector Architecture

The V4 design includes a Windows troubleshooting-log collector pattern that can pull scrubbed diagnostic evidence into the local Google Drive-synced project evidence plane without embedding Drive credentials in the app.

Build — GPT as Governor

Build is not a blank prompt box. GPT is calibrated as the Build Director / Governor, receives the MySmartRouter operating context, and is expected to guide the next action rather than make the user manage the process.

DRIFT RISK

The earlier UI used a time-based freshness indicator and refresh control. Under the reviewed V5 design, color, age and reinjection are reminders—not proof of CURRENT; invocation-bound authority, applicability and behavioral evidence are required.

Governed Handoffs

Handoff controls identify the recommended next specialist/tool. The recommended handoff is visually ON so the user can see what should happen next instead of interpreting a row of equal choices.

Ralph Mode

Ralph is a bounded execution loop, not another AI model. GPT determines whether Ralph is appropriate and prescribes task scope, acceptance criteria, loop class, iteration ceiling, time/cost ceiling and tests.

Return / Handoff Inbox

Returned work from another tool or agent can be brought back into the active Build session, reviewed, imported, saved and used to drive the next governed step.

Live Relay + Run QA

The earlier design routed a frozen task to a configured reviewer through the relay. V5 strengthens packet identity, reviewer independence, evidence admission and owner adjudication; a relay response alone cannot establish acceptance.

Create — Auto Router

The user enters the work and MySmartRouter uses the configured OpenRouter automatic-routing path so the user does not have to manually select a model for every request.

Create — Free Model

A separate creation mode uses an available zero-token-price OpenRouter route when available, giving the user a practical place for drafts, exploration, brainstorming and other lightweight work without consuming paid model credits.

Voice / Tap to Speak

Users can dictate long prompts, see live transcription, stop and submit, and save the result as JSON. Voice makes complex direction faster when typing would slow the work down.

Persistent Sessions

Build, Auto Router and Free Model each maintain their own Session History. V2.0 keeps the last 25 sessions per section and supports Open and Delete without mixing history across modes.

Session Cost Visibility

Build and Auto Router expose current-session cost and per-session cost in history. Each mode also shows a rolling Total Cost · Past 30 Days based on the current date rather than a calendar-month reset.

Separate Private Configuration

Build, Auto Router and Free Model keep independent server-side OpenRouter and MySQL configuration so keys, database access and section history are not forced into one shared configuration.

Help Center

V2.0 adds plain-language help for Build, Ralph, handoffs, Drift Risk, relay/QA, Auto Router, Free Model, voice, sessions, OpenRouter setup, MySQL setup, hosting setup, security and troubleshooting.

Last Build Update

The Build header keeps a visible summary of the current session, working owner/model and latest activity so the user can return after time away and quickly understand where the build stands.

Mobile + Desktop

The control surface is designed to remain usable in Windows Chrome and on narrow mobile screens without turning the interface into an unreadable desktop-only layout.

Foundation / V4 CapabilityWhat It DoesUser BenefitHistorical implementation status
Build Governor ContextCalibrates GPT to MySmartRouter's Build rules, available controls, current session state and operator-minimization standard.Less drift, less explaining, fewer process decisions pushed back to the user.Historically reported implemented
OpenRouter Intelligence Broker (W7)Adds an AUTO-isolated intelligence substrate for model, task, benchmark, endpoint and media-capability discovery with provenance controls and a durable 450/day outbound-attempt ceiling.Gives later router/media waves a governed intelligence source without silently altering existing production chat routing.Historical W7 bank and R1 corrective gate; not the present V6 directive
Build Supervisor GovernancePersists leases, control/evidence state and supervisor contracts under the governed BUILD plane.Creates a durable foundation for bounded execution while allowing live executor authority to remain withheld until known residuals are corrected.W6A/W6B/W6C banked; live supervisor execution intentionally gated
Twilio Mobile Control BridgeAdds a two-way mobile transport path for governed status, approvals and natural-language operator replies under GPT control.Allows the product/build governor to reach the operator away from the desktop without requiring manual relay between agents.Historical read-path validation; current messaging/A2P status not reverified
DRIFT RISKTracks Governor freshness and provides manual/automatic re-anchoring.Reduces long-session context drift and makes context health visible.Historically reported implemented
Handoff TogglesShows which handoff is currently recommended.The user can see the expected next action immediately.Historically reported implemented
Ralph ModeProvides bounded loop controls under GPT governance.Lets repetitive build work proceed with limits instead of open-ended autonomy.Historically reported implemented
Run QARoutes an independent review through the Live Relay.Separates execution from certification and improves confidence in completed work.Historically reported implemented; live smoke check remains
Create — Auto RouterDelegates model selection through OpenRouter's configured automatic-routing path.Removes the need to know which model to choose for routine creation work.Historically reported implemented; live route check remains
Create — Free ModelUses an available free OpenRouter route when available.Provides a low-cost place to draft, explore and experiment.Historically reported implemented
VoiceTurns spoken direction into long-form prompts with live transcription.Faster input for detailed instructions and hands-free ideation.Historically reported implemented; real-device mic smoke check remains
Session History + DeleteStores the last 25 sessions by mode and supports Open/Delete.Work can be resumed without clutter becoming permanent.Historically reported implemented
Session / 30-Day CostShows authoritative cost where provider metadata is available.Makes AI spend visible at the workstream and recent-usage level.Historically reported implemented; provider cost validation remains
Help CenterExplains each area and setup in non-technical language.Makes the product usable by practical builders, not only developers.Historically reported implemented

The September 25 V6 source/CI record is summarized in Build Evolution below. Historical feature implementation, current source evidence and installed-product acceptance remain separate.

V6
V6 · October 3, 2026

The approved V6 workspace.

Dark B is the product UX baseline. This architecture page retains its existing website design.

Shared shell

Use consistent navigation and one visible build/version identity. Preserve the selected project, session and current stage across relevant views.

Deliberate submission

Context selection prepares work; it must not trigger a provider request. Voice or copied text remains reviewable in the compose field before Submit.

Sessions that resume

OPEN resumes the saved session; CONTEXT attaches selected material with provenance; DELETE is a distinct operation. Repeated saves must not multiply records.

Visible progress

Busy, success, blocked and unknown outcomes reflect actual state. Do not show completion when only a launch or transport was prepared.

Context control

Show source selection, deduplication, capacity and secret-scrubbing boundaries. Capture the actual payload used for governed work.

Product verification

Test keyboard/ARIA, supported viewports and browsers, current help labels and exact-build screenshots. Multi-pane comparison remains historical direction unless separately adopted.

Preserved earlier reference · historical wording and evidence

History only. The earlier text below retains its original scope and dates. The V6 requirements and October 3 checkpoint above govern this page’s current description. Earlier modes, retry allowances, timer-only refresh and startup paths do not redefine V6.

02
Preserved Architecture Direction

Multi-Pane AI Operating Surface

V3 roadmap — not banked V2 behavior

This section is intentionally preserved from the earlier MySmartRouter architecture. The preserved V2.0 implementation used distinct Build, Create — Auto Router and Create — Free Model sessions rather than the multi-pane workspace described below. Multi-pane workstreams remain a future expansion candidate.

The preserved multi-pane design starts with a large chat pane and can expand into independent workstreams. Its desktop/iPad side-by-side and narrow-screen swipe behavior is a design target. The later hosted work-mode/session implementation must be distinguished from acceptance of this complete pane model.

Independent Pane State

Each pane owns its own conversation ID, title, messages, model, system instructions, streaming state, abort controller, draft, errors, route metadata, and accumulated cost.

Streaming + Stop + Regenerate

Responses stream independently. Stopping or regenerating one pane affects only that pane and leaves neighboring work untouched.

History + Persistence

IndexedDB belongs to the early browser-local design. Hosted session/history source also uses server-side database and configuration boundaries. Neither storage mechanism alone proves V5 invocation-bound persistence or the full pane roadmap.

Attachments

Supported local text/Markdown files and Drive references can become explicit pane context. The application records which attachments were associated with the request.

Portable Exports

Conversations can be exported as JSON or Markdown, while schema-aware import preserves older V1/V2 records without destructive identifier collisions.

Responsive Identity

The product deliberately avoids becoming a generic sidebar-plus-single-thread clone. Large side-by-side AI workstreams remain a core interaction principle.

V6
V6 · October 3, 2026

Model Direct and Auto Router.

Selection intent and actual provider delivery remain separately observable.

RouteRequired behaviorFailure boundary
Model DirectPreserve the exact canonical model/version selected by the user.Unavailable or mismatched identity fails closed; no hidden substitution.
Auto RouterUse the approved dispatcher policy and record dispatcher, final model and actual provider.Do not imply an exact-model guarantee when routing was delegated.
TelemetryRecord request identity, timestamps, tokens/usage where supplied and supported price information.Unknown cost or health remains unknown, never fabricated zero.
Catalog / credentialsBind current capability, configured credential scope and eligible model to the intended operation.A configured connection is not session readiness or proof of a completed call.

Integrations/routing/catalog is master stage 3 and remains WAITING. Older Free Model, multi-profile and fan-out descriptions below are lineage, not the current routing contract.

Source-evidenced transport and provider-catalog context

curl logoPHP cURL / libcurl

Provider and Google transport

Source-level HTTP transport for provider calls and Google services. A configured route or callable transport is not evidence that every provider or account is authenticated and working.

meta-llama logoMeta / Llama · provider catalog

Configured routing

Provider artwork and catalog references are retained as source-configured routing context. Catalog presence is not proof of a live, authenticated model execution.

qwen logoQwen · provider catalog

Configured routing

Source catalog/provider references identify this model family without claiming a new direct connection, live route or independent assessment.

Preserved earlier reference · historical wording and evidence

History only. The earlier text below retains its original scope and dates. The V6 requirements and October 3 checkpoint above govern this page’s current description. Earlier modes, retry allowances, timer-only refresh and startup paths do not redefine V6.

03
Historical routing design and later expansion boundaries

User Choice vs Smart Model Selection

V2 baseline / V3 design history

The V2.0 baseline exposed Build, Create — Auto Router and Create — Free Model. Auto Router delegates model selection; Build uses the governed Build configuration; Free Model uses a free route when available. The detailed exact-model selector and routing-profile framework below is preserved as a future V3 direction.

The preserved routing-profile concept separates model choice from provider strategy. Later V5/V5.1 source broadens the configured provider/media catalog and SmartRoute direction. The V6 record retains source-level configuration and eligibility boundaries; every live route still requires its own authenticated capability and outcome evidence.

The table is the earlier exact-model/profile design, not a claim that every row is a current, runtime-verified control. Provider labels and catalog entries identify configuration or design scope, not universal model access.

Routing ModeWho Selects?Behavior
Exact ModelUserThe selected OpenRouter model ID is sent directly. Provider routing can still be constrained separately.
Fast / Low CostUserKeeps the selected model but biases provider routing toward lower price.
BalancedUserKeeps the selected model and relies largely on standard OpenRouter provider behavior.
Deep ReasoningUserKeeps the selected model and raises reasoning effort where supported.
Coding / BuildUserKeeps the selected model while applying coding/build-oriented instructions and compatible controls.
ResearchUserKeeps the selected model while emphasizing evidence, inference, uncertainty, and synthesis.
Auto / Smart SelectApplication / OpenRouterThe request uses openrouter/auto, delegating model selection while still exposing the route actually used.

Recommended UX Refinement

The clearest product language is a primary choice of I Choose or Smart Select. When Smart Select is active, the user then chooses the objective—Fast & Low Cost, Balanced, Deep Reasoning, Coding, or Research—while MySmartRouter retains transparency about the final model/provider route.

V6
V6 · October 3, 2026

Connected context with explicit authority.

Git and Drive are equal qualified stores; every artifact still has an explicit authoritative revision.

Provenance

Preserve source ID, revision/hash, selected content, project mapping and the scope of its use. Connected material supplies evidence; it does not grant instructions authority.

OAuth lifecycle

Represent connect, expiry, reconnect and disconnect truthfully. Qualify the actual account, grant and destination; do not infer email permissions from a Drive connection.

Verified save

Save to the chosen destination and read back the actual resulting bytes. A transport receipt, prepared link or filename alone is not completed persistence.

Google identity, private configuration and evidence transport

openssl logoPHP OpenSSL · AES-256-GCM

Private configuration

The inspected Google-authentication and connection-service source uses OpenSSL encryption for private token/configuration material. No tokens are published and no new production key or connection is created by this documentation update.

google drive logoGoogle Drive · OAuth 2.0 / PKCE

Evidence and Google integration

Versioned review packets and authority handoffs use Drive. MySmartRouter source also contains the Google authorization/PKCE boundary. Public website evidence uses same-site resources, never a visitor’s access to private Drive.

Preserved earlier reference · historical wording and evidence

History only. The earlier text below retains its original scope and dates. The V6 requirements and October 3 checkpoint above govern this page’s current description. Earlier modes, retry allowances, timer-only refresh and startup paths do not redefine V6.

04
Connected context and V5 authority requirements

Drive, Projects, Context and Authority

Source implementation and design horizon are different. The R69 packet includes Google authorization and connection-service source; its pilot prepares source-bound authority delivery. Per-pane Drive mapping and the complete connected-workspace experience retain their own feature gates. A prepared artifact does not prove that a model received, loaded or applied it.

Project / Context

Each pane can carry a project and context profile such as VPL, MyRocketStudio, IdeaMax, ResumeRocket, Hostinger, Research, Personal, or None.

→

Authority Discovery

Discover the canonical identity and complete required source set. Framework completeness comes before action applicability; retrieval convenience must not drop inherited controls.

→

Provenance

The pane records which authority was loaded, its file identity, load time, relevant section information, and relationship to the conversation.

Authority entry and full-context loading

The earlier run gdrive vpl/master command is an entry concept, not a selective-loading exemption. V5 requires the full canonical equal-priority framework semantics and required project/recovery context before action applicability. A retrieved summary cannot establish persistence CURRENT.

Drive-Backed Chat Save/Open

The save/open design maps conversations to explicit Drive identities and checks remote version metadata before overwrite. V5 adds exact write/readback receipts and failed-leg retry; the full per-pane experience remains separately acceptance-gated.

Conflict Protection

Resolve a local/Drive mismatch against the exact file and version. Open the remote state, prepare a separate candidate or obtain deliberate overwrite authority; do not substitute a similarly named file or infer success from a connector response.

V6
V6 · October 3, 2026

GPT WORK: prepare, launch, return, review.

The app and direct conversation enter the same governed build with the same state revision.

Adapter stateWhat it means
PREPAREDDirective and one copyable handoff are ready; no receiving execution is claimed.
LAUNCH_REQUESTEDA launch was requested; session acknowledgement is still required.
SESSION_BOUNDThe receiving actor/session acknowledges the project, release, directive and state.
EXECUTINGThe qualified actor performs bounded authorized work.
RETURN_SAVEDThe complete return and evidence were saved and read back.
REVIEW_REQUIREDGPT reconciles the return, refreshes authority and determines the next permitted action.

A prompt copied into another app does not establish dispatch. Routes without technical enforcement are explicitly instructional. App/chat switching must resume the same project and cannot duplicate completed operations.

Preserved earlier reference · historical wording and evidence

History only. The earlier text below retains its original scope and dates. The V6 requirements and October 3 checkpoint above govern this page’s current description. Earlier modes, retry allowances, timer-only refresh and startup paths do not redefine V6.

05
Preserved Multi-Model Direction

Multi-Model Launch + Cross-Chat Work

V3 roadmap — preserved, not claimed complete

Simultaneous model fan-out, independent comparison panes and generalized cross-chat context transfer remain valuable future capabilities. They are retained here as design intent and remain design intent, not evidence of V6 release completion.

The preserved multi-pane concept turns one prompt into several independently traceable workstreams. The assessed product architectures remained synchronous HTTP / sequential dispatch; the V5 framework review did not convert them into concurrent autonomous agents.

Multi-Model Launch

In this preserved multi-pane design, a user would enter one prompt and select several models. Concurrent launch remains a product-design horizon, not a claim about the assessed synchronous HTTP / sequential-dispatch implementation. MySmartRouter creates one normal independent pane per selected model and records a shared launch ID for provenance and combined analytics.

Independent Branches

After the common starting question, each branch becomes fully independent. The user can challenge one model, redirect another, or stop one branch without affecting siblings.

Launch Cost Accounting

Each branch keeps its normal usage and cost ledger while the parent launch record aggregates total request count, tokens, and combined spend across the fan-out.

Copy / Paste Handoff

Copy Full Chat, Copy From Here, and Copy Context Only create clean portable context. Paste Into Chat makes the destination independent while preserving optional source provenance separately.

ONE QUESTION ↓ SELECT: Claude + GPT + Gemini + DeepSeek ↓ DESIGN: INDEPENDENT PANES / CONCURRENCY HORIZON ↓ COMPARE / DEVELOP / COPY CONTEXT / CONTINUE INDEPENDENTLY
V6
V6 · October 3, 2026

Control through the same authenticated state.

Human decisions, bounded execution and independent review remain visible in V6.

One operation attempt

An unexpected external-operation result stops automatic repetition. Save evidence, obtain GPT review and issue a corrected directive before another attempt.

Current-state transitions

App, WORK and authenticated notification commands use the same authorization, revision, idempotency and gate checks. Stale views cannot advance the build.

Protected action boundary

Execution requires valid current context and proof receipts. The app cannot own or replace the signer key, code, journal or trusted reader.

Unknown stays unresolved

A lost acknowledgement does not prove no effect. Hold the durable reservation and reconcile before any further action.

Independent acceptance

Executor tests and DONE statements are evidence. Qualified independent review, GPT adjudication and material owner acceptance remain separate.

Preserve the pause

Website publication does not resume engineering, provision a signer, issue Runtime Attempt 1, merge code or deploy the product.

Notification implementation boundary

nodejs logoTelegram · external Node.js relay boundary

Notifications and integration

The documented relay lies outside the inspected PHP package. Its Node.js runtime is an integration boundary, not a claim that the relay was installed, tested or activated by the V5 review.

Preserved earlier reference · historical wording and evidence

History only. The earlier text below retains its original scope and dates. The V6 requirements and October 3 checkpoint above govern this page’s current description. Earlier modes, retry allowances, timer-only refresh and startup paths do not redefine V6.

06
Governance & Safety Boundary

Control Without Hidden Automation

From visible V2 controls to V5-informed governance. Governor context, Ralph, handoff recommendations, the Return Inbox and Run QA established the earlier interface. V5 adds observed-fact applicability, explicit actor readiness, source-bound review, durable readback and retained owner decisions. These controls inform the authorized V6 work rather than certifying a running autonomous system.

Human architectural control

The owner sets intent, material UX/UAT acceptance, consent and consequential release decisions. Disputed independent findings remain open until their recorded disposition; model vote counts do not resolve them.

Governor, executor and reviewer

GPT coordinates bounded work and evidence reconciliation. An executor returns implementation and tests; a separately assigned reviewer challenges the frozen result. A model reviewing its own work cannot supply the independent gate.

No hidden scope expansion

Tool, target and effect facts determine required controls. Voice, Telegram, Ralph loops or scheduled invocations use the same authorization, pause, retry and STOP boundaries as typed work.

Credential and environment separation

Keep provider credentials, Google authorization and application configuration outside public HTML. The source-defined encryption and transport layers do not prove any particular live account is ready.

Traceable acceptance

Preserve the requested action, authority/source identities, candidate, raw return, tests, independent findings and owner decision. A signed PASS is an integrity input, not proof that the required work was performed.

Notification is not state

Telegram and optional mobile channels report permitted events. They are not canonical authority or the project-state store; an optional notification failure is tracked separately from successful verified output writes.

V6
V6 · October 3, 2026

Persistence requirements locked; runtime proof open.

Durability includes context, state, side effects and recovery—not just a successful database write.

Complete continuity

Load governing rules, operating instructions and cumulative build content at equal priority. Capture the actual delivered request, source revisions and capacity checks; a digest or shortened summary alone is insufficient.

Every return and turn

Perform a full refresh on each actor return and on required hard-refresh events. Ordinary exchanges retain project/release/state binding and response validation. Drift or a changed authority triggers another full refresh.

Protected execution

Bind actions to an immediate challenge/proof receipt and a protected action broker. The application must not control the signer, private key, journal or trusted reader. Instructional-only routes must be labeled.

Durable state

Keep immutable revisions and one authoritative mutable project pointer. Use expected-version updates, durable reservations, idempotency keys and fencing; stale writers cannot advance the current state.

Uncertain outcomes

Timeout, lost acknowledgement or expired lease does not prove an operation failed. Hold the reservation, reconcile actual effect and record the decision before any newly authorized attempt.

Recovery

Restore application, data, configuration and environment under separate checks. Prevent old writers, verify a consistent backup and recover into a safe target before changing the live pointer.

Hosting finding: the recorded shared-hosting checks have not qualified the required protected signer/service boundary for the exact product target. Support for sister websites does not establish MySmartRouter’s exact account configuration. GitHub research can inform a changed custody or execution design; no external library has been adopted as a drop-in fix. “No qualified solution found” is not proof that none exists.

Storage, signer and database verification

sqlite logoSQLite · signer state

Security and persistence

Source-defined private replay/challenge ledger used by the MySmartRouter runtime signer. Its presence in source and CI does not establish an installed signer or persistent CURRENT state.

mariadb logoMariaDB · PHP/PDO integration tests

Database verification

Database service exercised by the isolated exact-head MySmartRouter CI record. Existing MySQL architecture remains relevant; the MariaDB test environment is identified separately from a production database.

libsodium logoPHP sodium / libsodium · Ed25519

Signature verification

PHP sodium functions provide the source-defined signature verification used by the signer/verifier path. This describes the extension and primitive, not a security certification or a newly installed service.

Preserved earlier reference · historical wording and evidence

History only. The earlier text below retains its original scope and dates. The V6 requirements and October 3 checkpoint above govern this page’s current description. Earlier modes, retry allowances, timer-only refresh and startup paths do not redefine V6.

07
Product accounting and governed state

Request records, cost and recoverable state

The historical hosted work modes record session and usage data where provider metadata is available. V6 source adds signer/replay-state and verification boundaries. Reviewed V5 controls connect those records to the exact action, source, receipt and recovery state; a storage write or an estimated cost is not proof of completed work.

Current Session Cost

Build and Auto Router show the accumulated cost of the active session when authoritative provider cost metadata is available.

Cost in Session History

Historical Build and Auto Router sessions carry their saved cost in the session metadata/pill so users can see which workstreams consumed spend.

Rolling 30-Day Cost

Each mode shows Total Cost · Past 30 Days using a true rolling date window. Free Model will ordinarily remain at zero when the provider reports zero-token-price usage.

Broader analytics below remain architecture direction

The detailed Session/Today/7 Days/Month/All Time analytics model and unlimited independent-pane ledger described below comes from the earlier architecture. The preserved V2.0 implementation focused on session cost, per-session history cost and rolling 30-day totals.

5Reporting periods: Session, Today, 7 Days, Month, All Time
8Top-line metrics: cost, requests, input, output, total tokens, avg/request, active chats, top model
1Local usage ledger joining model, provider, project, context, routing profile, authority and attachments
∞Independent panes/workstreams within practical browser and API limits
Per-Response Metrics

Input, output, total tokens, cost, reasoning tokens, cached tokens, model and provider are captured when returned.

Per-Conversation Totals

Each pane accumulates request count, total tokens, and cost so the user can see the operational footprint of a workstream.

Expanded Analytics

V2A can roll usage by model, provider, conversation, project, context profile, routing profile, and time period while monthly budgets provide a spend guardrail.

V5 improvement: preserve the result; retry only the failed delivery

The amended dual-output design generates one canonical result, persists its exact bytes and readback, then tracks private Git and Drive delivery separately. Reuse verified output after interruption; do not incur a second model call simply because one storage leg failed. An unknown generation outcome is reconciled rather than silently regenerated. These remain product implementation and runtime-test requirements, not a claim of exactly-once provider execution.

V6
V6 · October 3, 2026

October 3, 2026 · current V6 build recap

Revision MSR-WEB-V6-20261003-R01. Current pause checkpoint follows the R57 A3 review; earlier milestones remain dated history.

Pause checkpoint · October 3, 2026. V6 architecture is FINAL. Persistence requirements are locked; production persistence is not qualified. The build remains at stage 1 of 7. The signer is unprovisioned and fail-closed; runtime Attempt 1 has not been issued. No merge or deployment is authorized by this website update.

EvidenceRecorded resultLimit
HF5.1 candidatef360929bd7cd2abe2b08b8cde0673586c462a5b9Current source candidate, not an installed release.
Recorded CI24 authority + 66 pilot = 90 distinct cases; seven HF5.1 results are within the pilot total.Source/fixture evidence; not 97 tests and not runtime acceptance.
Independent source reviewClaude R53: PASS_WITH_LIMITATIONS; GPT R54 accepted the source checkpoint.Independent PHP execution was not performed; production installation was not certified.
Findings and regression38 findings retained; full two-baseline application/data/configuration/environment regression is not established.Preserve unresolved findings and prior failures; do not convert retained evidence into PASS.
Hosting qualificationR57 A3 retrieved metadata; required isolation, durable service and recovery checks remain unresolved for the exact target.Other sites’ support answers cannot qualify this product’s account. Shared-hosting libraries cannot establish a missing trust boundary.
Master stageStatusWhat remains
1 · Persistence / runtime proofCURRENT · PAUSEDLocked requirements; protected custody, actual host/runtime, delivered-context proof and WORK continuity remain unqualified.
2 · Draft-only email / dual outputWAITINGApproved read scope, once-generated output, private Git and Drive saves with exact readbacks; no send or mailbox mutation.
3 · Integrations / routing / catalogWAITINGExact model/dispatcher identity, current catalog and actor-specific capability evidence.
4 · Product UATWAITINGReal owner workflows, failure/recovery, responsive/accessibility checks on the exact runnable candidate.
5 · Final regression / evidence closureWAITINGBoth protected baseline and last accepted checkpoint; all required cases, findings and independent evidence reconciled.
6 · Packaging / installation / rollbackWAITINGClean install, cache/version behavior, migration gates and proven environment recovery.
7 · Production releaseWAITINGOwner-approved exact source, qualified deployment route and authenticated live verification.

Next after the pause: complete the unified V6 release package and acceptance sequence, rebind the existing product safely, qualify custody/runtime, then resume the preserved product schedule. Email extraction is downstream of persistence: approved read scope, sanitization, reservation, once-generated output and exact private Git/Drive readbacks are required; sending and mailbox mutation remain outside that stage.

October 3 update logRecorded effect
V6 architecture incorporatedUnified WORK and state model; approved Dark B UX; exact routing, sessions/context/media requirements.
R57 / pause reconciledHosting qualification remains unresolved; architecture final and persistence design locked do not imply production acceptance.
Regression made explicit90 recorded unique source/fixture cases; independent review limits, 38 retained findings and uncompleted full regression preserved.
Publication scopeContent update only. Existing page filename, styling, navigation targets, graphics, founder content and original assessment evidence retained.
08
Build Evolution

V1 → V2 → V3 → V4 → V5.1 → V6

Product lineage · source evidence is not a production release

The inherited V1–V4 architecture remains visible below. V5.1 is the preserved September 12 staging record. V6 adds accepted source/CI work through R59 and the separately review-gated R69 admission candidate. Framework V5 is a governance revision—not a claim that the product moved backward from V6.

September 25 · V6 source/CI evidence

Accepted source/CI baseline: R59 097ade662a3161f4ae51a45e956b923cf074a701. Separate R69 candidate: 7dbbc763f79d63d4c82fe6a111bfb69520b0ca91; 291 baseline blobs preserved + 52 additions = 343 source blobs. The recorded corrected CI run passed 16/16 pilot cases after a failing-first gate, alongside inherited workflow checks including MariaDB and a separate-UID signer.

Prepared source transport: the pilot bound 38 canonical sources, including the full HTML master, to action/challenge/catalog/bundle identities and required the delivery digest in an authenticated return. This did not prove provider receipt or understanding. The recorded terminal boundary remained BLOCKED_INDEPENDENT_REVIEW_PENDING; the prepared transport state was PREPARED_TRANSPORT_PROVIDER_UNVERIFIED.

These are the dated source/CI facts, not a newly performed product review. No exact-head independent acceptance, installed persistence or production release is inferred. The older W7/W8 sequence remains history, not today’s execution instruction.

Architecture HorizonHistorical design horizon / evidence boundary through V6Why It Matters
True Multi-Pane WorkspaceSide-by-side independent AI panes with separate state, streaming and model choice.Lets users compare and develop several AI workstreams without switching apps.
Exact Model / Profile SelectorEarlier exact-model/profile design; any V6 route must retain explicit configuration, eligibility and live-provider proof.Gives advanced users more control while keeping Auto Router simple for everyone else.
Drive / Project AuthorityConnected project authority, file provenance, governed context discovery and conflict-safe save/open behavior.Reduces repeated context rebuilding and keeps AI work attached to the right project source.
Multi-Model Fan-OutConcurrency is a design horizon, not a claim about the assessed synchronous HTTP / sequential dispatch implementation.Makes model comparison and second-opinion workflows much faster.
Cross-Chat Context TransferCopy full chat, copy from here, context-only transfer and structured provenance between workstreams.Moves useful work between specialists without losing the origin of the context.
Git / GitHub IntegrationRepository identity and exact-head CI are evidenced in the V6 R69 record. Installed orchestration and product-level Git control still need their own acceptance.Makes Build status evidence-based instead of relying on manual relay.
Hostinger / Deployment IntegrationGoverned hosting/deployment checks and safe environment status.Extends the control surface from “built” to “actually deployed and working.”
Reusable Workflow TemplatesSaved governed workflows for common build/review/release patterns.Turns successful operating patterns into repeatable one-click starting points.
Model Debate / SynthesisControlled multi-model review, disagreement and synthesis patterns.Improves decision quality without making the operator manually coordinate every reviewer.
Task Queues + Approval GatesPersistent queues, explicit approval points and resumable background work.Supports longer-running projects while preserving human control.
Team / Permission LayerMulti-user access, role permissions and shared project control.Moves MySmartRouter from an individual operator tool toward a team operating system.
V1
Multi-Pane OpenRouter Client

Early standalone prototype/design introduced model catalog, pane-state, streaming, local-persistence, export/import, cost and responsive-workspace concepts. It is preserved as history, not acceptance of the complete hosted V6 pane experience.

V2
Governed Connected Workspace

Added governed BUILD execution, Auto Router and Free Model creation paths, Drive/context concepts, provenance, handoffs, Ralph, independent QA, session history, cost visibility, voice and operator-minimizing controls.

V3
Protected Stable Baseline

Consolidated the working implementation into the authoritative stable source baseline with QA/finalization evidence, protected behavior, per-mode isolation and continuity artifacts that V4 must preserve.

V4
Supervised Five-Mode Architecture

Adds the locked five-mode structure, scope-safety registry, desktop voice repair, Save JSON/session hardening, activity/history consolidation, multi-select Library Context, diagnostic collection, stronger build governance and staged Multi / Image-Video expansion.

V5.1
Preserved multi-provider staging

September 12 product evidence extends configured routing, media, sessions, notifications and Drive handoff. Staging defects and root promotion remain separately qualified.

V6
Source preservation and admission proof

R59 accepted source/CI and the R69 candidate make authority loading, signer state, exact source identity, deficient-PASS rejection and review boundaries explicit. This is not installed/runtime acceptance.

How the V5 lessons inform the next product gate

The planned sequence is fresh product-state recovery and authorized framework adoption → preserved-baseline recalibration → the smallest approved persistence wave and real behavioral proof → draft-only email/dual-output implementation → remaining V6 UAT, integration and release gates. Website editing does not start that sequence. The accepted source, signer/storage decisions and operational checkpoint remain unchanged.

Framework improvements within the product chronology

The VPL framework and MySmartRouter product have separate version histories. The milestones below connect the reviewed framework work to product requirements without treating V5 framework grading as a V6 product release.

Estimated cumulative framework engineering effort: 240–400 hours. This is a low-confidence, unlogged reconstruction of framework architecture and its review/evidence system—not Peter’s measured personal hours, elapsed time, model runtime, savings or billable effort. The workstream ranges are one cumulative estimate, placed alongside illustrative milestones; future product completion and deployment are excluded.

V3 foundation · September 6

The original nine-dimension assessment recorded 97.00 under its historical instrument. Product architecture, problem decomposition and human decisions provided evidence for the later governance work.

40–64 estimated hours · cumulative workstream: Architecture framing, authority and decision boundaries.

V4 FINAL / REV006 foundation

Bootstrap-first authority, Manual/Light/MySmartRouter peer paths, independent review, Recovery Anchors and two-baseline comparison made accepted behavior an explicit reference.

48–80 estimated hours · cumulative workstream: Workflow, persistence, source identity and recovery design.

MySmartRouter V6 · September 25

R59 source was preserved in the R69 candidate. Failing-first and corrected CI checked the source-only admission boundary; prepared delivery still did not prove provider execution.

40–72 estimated hours · cumulative workstream: Verification tooling, fixtures and negative-path tests; not a separate product-completion allowance.

V5 HF03/T01 · independent challenge

The frozen 451-file candidate remained intact while reviews exposed inheritance, timeout, applicability and evidence-handling limits. Finding reconciliation led to bounded repairs rather than an uncontrolled rewrite.

56–88 estimated hours · cumulative workstream: Independent review, triage and bounded remediation.

September 28 · decisions, replay and provenance

Action 1 mapped 328 spans / 35 sources with explicit amendment and retained GL-15. Action 3 used 13 focused tests; Action 4 used 42 and retained 210 mixed records / 106 groups. The stated specification and test-only limits remain.

32–56 estimated hours · cumulative workstream: Evidence packaging, provenance and reproducibility.

September 28 · accepted assessments

Gemini/Magai issued 95.00 and the informed 99.50 successor. Corrected R02 rationale kept both scores unchanged. The numerical changes from the respective frozen/historical baselines were +0.50 and +2.50; the instruments are not interchangeable.

24–40 estimated hours · cumulative workstream: Documentation and assessment preparation.

Continuous improvement: preserve accepted work → develop → challenge independently → reconcile findings → repair narrowly → test/replay → retain evidence and limits → assess → apply the lesson to the next authorized product step.

Reference revision · September 28, 2026 · R04

Reconciled product/source status, V5 Build controls, contextual technology roles and assessment evidence. Preserves V1–V5.1 product history and the separately identified V6 source/CI record.

09
Brand & Positioning

MySmartRouter.com

MySmartRouter.com final locked logo

Smarter AI Routing for Real Work

The product name describes the operating promise directly: work across AI models without manually managing separate disconnected environments. The architecture emphasizes transparent routing, independent workstreams, connected authority, deliberate context transfer, and operator control.

Founder / Operator-Builder

About Peter

Peter DeCaro
Peter DeCaroSenior AI & Business Operations Consultant

Peter DeCaro, currently Senior AI & Business Operations Consultant at Vantage Solutions Group, is an operations and technology-focused product builder with more than 25 years of experience improving, automating and scaling complex business operations. Across his career, he has worked for and with eight publicly traded companies and has operated at the intersection of customer operations, revenue operations, process improvement, technology implementation and organizational scale. His experience includes leadership and transformation work associated with companies including Fluent, LLC, IAC Applications, AOL and KIT Digital, as well as consulting and product-development work through Vantage Solutions Group and Vantage Product Labs.

His career has consistently centered on a practical question that now sits at the heart of MySmartRouter: how can technology remove operational friction, create repeatable decision systems and allow people to produce better outcomes with less manual work? Long before generative AI became a mainstream operating tool, that work included process redesign, workflow automation, KPI governance, CRM and ERP implementation, customer-success operating models, vendor and workforce management, executive reporting and the rapid stabilization and scaling of growing businesses.

Peter has overseen revenue operations in excess of $50 million annually, built programs supporting customer-success and service teams of approximately 50 to 100 people, and led operational improvement initiatives across high-volume, technology-enabled organizations. His broader operating background includes large-scale customer experience environments, offshore and multi-site operations, fulfillment and service transformation, sales and revenue operations, automation, performance management and executive-level operating cadence. He is Six Sigma / Lean Six Sigma trained and has spent much of his career applying continuous-improvement principles to real operating environments rather than treating process design as an academic exercise.

In 2023, Peter was recognized by the Management and Strategy Institute (MSI) for continuous improvement, reflecting a career built around measurable operational change. That discipline has increasingly been applied to software and AI-enabled product development: translating operating problems into modular applications, measurable workflows and repeatable systems.

Most recently, through Vantage Product Labs, Peter has focused on building practical AI-enabled applications and reusable product engines. Those projects include a flight-monitoring application designed to continuously track fare changes across travel providers; ResumeRocketPro, an ATS-oriented resume analysis, scoring and optimization platform; KDP AI Secrets, a structured information-product and publishing asset creation system; and the broader MyRocket Studio / RocketCore architecture in the wider VPL product portfolio.

These products reflect a consistent operator's perspective: software should not merely generate output—it should organize work, preserve evidence, reduce repetitive decisions, create quality controls and make the next operating cycle better than the one before it. MySmartRouter applies that approach to AI work: make model choice, context, handoffs, evidence and cost visible, then use reviewed delivery lessons to improve the next governed iteration. The wider MyRocket Studio / RocketCore portfolio remains separate product context.

Professional Development / AI / Continuous Improvement

Certifications

Peter's certifications reflect the two disciplines informing MySmartRouter and the wider VPL portfolio: formal continuous-improvement methodology and hands-on development of AI-enabled operating systems. The combination supports an operator-builder approach in which automation, process control, prompt engineering, AI agents and production application design are treated as connected capabilities rather than isolated technologies.

Six Sigma / Lean Process Excellence
Six Sigma Black BeltContinuous Improvement / Process Excellence
Six Sigma Green BeltContinuous Improvement / Process Excellence
Six Sigma Yellow BeltContinuous Improvement / Process Excellence
Lean Six SigmaLean + Six Sigma Process Improvement
AI, Prompt Engineering, Agents & Application Development
Prompt Engineering CertificationQuantum Leap Academy
No-Code AI Prompting: Websites and ApplicationsUdemy
OpenAI Codex Full Course 2026: AI Coding, Automation, AgentsUdemy
OpenAI Codex Masterclass: Build Your AI Operating SystemUdemy
Advanced Master AI Prompt EngineeringUdemy
ChatGPT for Customer SupportGreat Learning
Building AI Voice Agents for ProductionDeepLearning.AI
ChatGPT Prompt Engineering for DevelopersDeepLearning.AI
Academy Accreditation - AI Agent FundamentalsDatabricks Academy
Generative AI FundamentalsDatabricks Academy
+
MySmartRouter.com-Specific Browser / Routing Layer

Additional Technologies for This Project

This retained project inventory identifies browser, hosted PHP, routing, authentication and delivery technologies in the product’s design/source history. Browser-local prototypes, hosted work modes and external notification services are distinct layers—not interchangeable proof of a live V6 service. The newer signer, encrypted configuration, database/CI and framework-verification roles are explained where they apply in the sections above.

MySmartRouter Routing, Browser Runtime & Identity
OpenRouterUnified AI model gateway used for model discovery, chat execution, provider routing, fallbacks, usage accounting and Auto / Smart Select behavior.
TwilioTwo-way mobile transport layer for V4 build-governance alerts and operator replies. The historical record contains account, number, SMS-capability and Messaging read checks. Current credentials, A2P registration and production SMS were not reverified in this update.
PushoverOptional app-based notification channel in the product design. Account configuration and real delivery require their own product/channel acceptance.
TelegramGoverned notification/control-assistance channel. The external relay boundary and normal authorization rules are described under Governance; no connection or runtime activation is implied.
Google Chrome / ChromiumPrimary browser runtime target for the standalone application, including streaming Fetch/SSE behavior, browser storage, clipboard workflows and mobile/desktop web execution.
Google Identity Services / OAuthGoogle authorization in the connected-workspace design. The later hosted source includes server-side OAuth/PKCE and encrypted token handling; credentials are not embedded in this public HTML.
OAuth 2.0 + PKCEProof Key for Code Exchange appears in the inspected hosted Google authorization source. The earlier browser/OpenRouter authorization concept is separate; source presence is not proof of a currently authenticated account.
IndexedDBBrowser-local conversation and usage persistence in the early standalone/multi-pane design. The hosted database/session implementation and the V5 invocation-proof contract have separate responsibilities.
Fetch API + Server-Sent EventsBrowser-native request/streaming primitives in the early pane design. The assessed synchronous HTTP / sequential-dispatch architecture is not proof of concurrent streaming or autonomous model collaboration.
PHP 8 Server RuntimeHosted API, authentication, relay, diagnostics, session/reporting and Build-related source carried in the inspected product package. Source availability is distinguished from installed-version and live-operation proof.
MySQL / MariaDBServer-side relational persistence for the Build library, sessions, activity, usage, configuration, handoff records and governed operational history.
Hostinger Production HostingThe designated hosting target for PHP, private configuration and database integration. Reads, writes, deployment and rollback require separate actor/operation/target/session evidence; cron cannot certify persistence CURRENT.
OpenAI Whisper / Audio TranscriptionThe V4 source includes a transcription API path for converting captured audio into text for routed workspace use.
Web App Manifest / PWA MetadataManifest, favicon and touch-icon assets in the hosted interface source support browser/mobile presentation. Metadata alone does not certify installation or offline application behavior.
HTTPS + cURL Relay LayerServer-side outbound HTTP transport supports OpenRouter and governed relay execution while keeping sensitive provider credentials off the browser client.
Lovable Governed HandoffControlled artifact/clipboard handoff and return-import design, strengthened by V5 task/source/permission/STOP contracts. It is not a direct Lovable API integration or stored product credential.

Brand marks in this added project-specific block are embedded directly in the standalone HTML. No external image path or sandbox dependency is required to render the OpenRouter, Twilio, Chrome, Google, PHP, MySQL, Hostinger, OpenAI/Whisper or Lovable marks.

🚀
Historical governed product baseline · September 12, 2026

MySmartRouter V5.1 — preserved staging record

The September 12 V5.1 record froze feature definition ahead of defect remediation. It expanded the multi-provider routing, media, session, notification and Google Drive design beyond the earlier single-gateway workspace. The staged implementation and packaging history below are retained as product lineage; they are not the current V6 next-action directive or proof of a root production release.

V5.1 feature-definition snapshot · historical
SmartRouteTask-aware model + provider optimization using quality/task fit, authoritative price, latency/health and resilience evidence.
OpenRouterPrimary multi-model PAYG route; no longer hard-coded as the product identity.
API MartGoverned multi-model route target retained from V5 architecture; configuration/eligibility must be explicit and non-orphaned.
TelnyxMulti-model inference route candidate with OpenAI-compatible PAYG model access, subject to per-model capability mapping.
RunwareMulti-model/multimodal PAYG route spanning text and media workflows.
ReplicateMedia-specific PAYG model execution candidate for Image/Video Creator.
RunwayMedia-generation API candidate for governed image/video workflows.
Stability AIImage-generation API candidate for media-specific provider settings.
TelegramGoverned external relay for notifications/delivery; separate Node runtime remains outside the PHP package.
PushoverOptional iPhone/mobile push notification transport alongside browser and Telegram.
Google DriveContextual asset save target from the surface where work is created; Gmail send is removed from V5.1.
LovableDownstream SaaS/UI design execution plane; never canonical source authority.
GitHubCanonical source identity, exact commit/tree packaging evidence and independent review lineage.
HostingerInherited hosting/private-configuration boundary and optional reminder design; not proof of current deployment or runtime freshness.
V5.1 interaction model: General Settings was designated for shared provider credentials, notification channels, Google authorization, database/configuration and product preferences; work modes retained section-specific settings. Session History OPEN was intended to provide reusable context and a prepared follow-on prompt, replacing legacy “Library Context” terminology. The staging findings below distinguish intended behavior from accepted functionality.
Historical staging findings: the September 12 record reported media database-collation failure, inactive Session History OPEN behavior, incomplete provider configuration, optimizer evidence gaps, Free Model history persistence failure and responsive/interaction defects. Those findings belonged to the V5.1 remediation stage. Their present closure is not established by this historical list; the later V6 source/CI and review records must govern any authorized continuation.
🚀
Development / AI / Data / Delivery Stack

Supporting VPL Development Technologies

The VPL engineering ecosystem below is retained as broader development and research history, not a declaration that every tool is a dependency of MySmartRouter. AI assistants, development environments, workflow services and research providers have different roles across VPL products. MySmartRouter-specific runtime, routing, security and verification technologies are identified in their relevant sections above.

LLM / AI Models & AI Development
GPT / OpenAIAI reasoning, generation, analysis and multimodal workflows
Claude / AnthropicAI-assisted architecture, coding, review and long-context development
Gemini / GoogleMultimodal AI reasoning and Google-connected development workflows
Grok / xAIAI research, reasoning and comparative model workflows
DeepSeekAI model experimentation, reasoning and technical workflows
MoonlitAI / development experimentation and supporting workflow tooling
CursorAI-assisted software development and codebase implementation
BoltRapid AI-enabled application prototyping
LovableRapid product/UI prototyping and application experimentation
Automation & Orchestration
MakeVisual workflow automation and systems integration
n8nWorkflow orchestration, API automation and agentic process integration
ZapierSaaS workflow automation and event-driven integrations
Research, Data & Provider Layer
Official APIsStructured source access where supported
ApifyModular scraping and web-data acquisition
RapidAPIExternal API marketplace and provider integration
Bright DataCommercial web-data infrastructure and acquisition
OxylabsCommercial proxy and web-intelligence infrastructure
MySQLRelational application and analytics data storage
Application Engineering & Delivery
PythonCore application logic, automation and data processing
StreamlitInteractive Python application interfaces
PHPServer-side web application and hosting workflows
HTML5Standalone interfaces, reports and product experiences
CSSResponsive interface styling and visual systems
JavaScriptBrowser-side behavior and interactive experiences
GitHubSource control, repositories, versioning and deployment workflows
GitLocal and remote source-version management
HostingerWeb hosting, databases and production deployment
Workspace, Campaign & Operating Tools
Google WorkspaceDocs, Sheets, Drive and collaborative operating files
Google DriveShared artifacts, build packages and project continuity
GetResponseEmail marketing and campaign-delivery workflows
TrelloWorkflow/board orchestration and build-task management

Product and company marks are shown for technology-identification purposes. Availability and use vary by product module and build stage.

V5.1 Routing / Media / Delivery Additions
API MartMulti-model inference route target with explicit Settings configuration and model eligibility.
TelnyxPAYG multi-model inference routing candidate.
RunwarePAYG text + media inference provider candidate.
ReplicatePAYG media-model execution candidate.
RunwayImage/video generation API candidate.
Stability AICredit/PAYG image API candidate.
PushoverOptional mobile push notification transport.
TelegramGoverned notification/delivery relay boundary.
GitHub ActionsExact-commit checks, packaging evidence and CI regression.
HostingerPHP hosting target and inherited reminder design. Production execution needs target/session evidence; cron cannot establish CURRENT.
V6
V6 · October 3, 2026

Continuity on every return and ordinary turn.

A timer or a recent recap is insufficient evidence that governing content reached the actor and constrained the action.

Full refresh

Load governing, operating and cumulative build content on each return and required hard event; verify actual payload completeness and capacity.

Bound every turn

Retain release/project/state binding and response validation during ordinary chat. Detect drift and force full refresh before further material work.

Enforce actions

Use immediate proof receipts and protected brokered grants. Keep event/reservation evidence through interruption, retries and recovery; optional watchdogs supplement these controls.

These are locked V6 requirements. Their implementation and actual runtime acceptance remain part of the paused persistence stage.

Preserved earlier reference · historical wording and evidence

History only. The earlier text below retains its original scope and dates. The V6 requirements and October 3 checkpoint above govern this page’s current description. Earlier modes, retry allowances, timer-only refresh and startup paths do not redefine V6.

AD
V5-informed persistence and recovery

Anti-Drift Supervisor: from timers to invocation proof

The earlier V4 design used time, activity and event triggers to refresh control context. The reviewed V5 A01/M26 design retains anti-drift safeguards while making proof specific to the invocation, action, actor and authoritative source—not the presence of a timer or a successful recap.

Reloading information is not the same as applying it correctly.

01 · Freshness triggers

The inherited baseline calls for refresh at 30 real minutes, four completed directive/result exchanges and hard events. These triggers signal when to re-establish alignment; they do not establish CURRENT on their own.

02 · Behavioral boundary

For consequential work, resolve the canonical source set, required project/recovery context, typed action, all module dispositions, readiness and the required balanced challenge. Correct verbal recall followed by wrong behavior is a failure.

03 · Durable evidence

Bind the receipt to the actual actor/session, source, action and observed result; verify the durable write/readback. Missing, stale or contradictory required proof blocks the affected operation.

What the product must prove

At the separately authorized persistence wave, preserve the accepted signer, SQLite and separate-user design and verify its real runtime feasibility. A producer heartbeat, optional cron/watchdog, consumer acknowledgement or signed result cannot replace complete loading and behavioral conformance. The R69 source-only pilot and V5 test harnesses do not establish installed CURRENT or live production recovery.

QA
Assessment methods and source evidence

Inspect the framework evidence behind the scores

The rubric, selected assessed code and corrected report are contained in this HTML. The six source artifacts belong to the V5 framework assessment—not the MySmartRouter PHP application, the R69 product-pilot package or a complete deployable framework. Their exact bytes and hashes are preserved for inspection.

View Scoring Rubric · both September 28 assessment instruments

Scoring Rubrics & Method Boundaries

The two scores answer related questions under different instruments. They must not be blended, averaged together or represented as a percentile.

Track 1 · ten-dimension HF03/T01 method

Each dimension is scored from 0 to 100. The final result is the arithmetic mean of all ten dimension scores. The September 28 comparison uses the frozen HF03/T01 identities below; the historical September 23 page retains its original labels and values.

DimensionScale / weight
1. AI / System Architecture0–100; equal 1/10 weight
2. Problem Decomposition0–100; equal 1/10 weight
3. Multi-Model Orchestration0–100; equal 1/10 weight
4. Product / System Integration0–100; equal 1/10 weight
5. API / Data / Tool Integration0–100; equal 1/10 weight
6. Workflow & State Architecture0–100; equal 1/10 weight
7. Governance & Change Control0–100; equal 1/10 weight
8. QA / Debugging / Recovery0–100; equal 1/10 weight
9. Operational Problem Translation0–100; equal 1/10 weight
10. Individual AI Leverage0–100; equal 1/10 weight

This is a documented comparison method, not a claim that an unavailable earlier detailed scoring manual was recovered. View the separately preserved September 23 assessment history.

Track 2 · V3 applied-AI architecture rubric

The nine dimension ceilings sum to 100. Awarded points are summed directly; they are not averaged again. Production deployment absence has zero direct scoring weight. Framework maturity is a separate result.

DimensionMaximum points
A. Problem Decomposition & Operational Translation15
B. AI / System Architecture15
C. Human Architectural Judgment & Control15
D. AI Agent Orchestration & Leverage12
E. Product / System Integration10
F. Workflow, State & Recovery Architecture10
G. QA / Validation / Debugging Architecture10
H. Governance & Change Control8
I. Scope Expansion via AI5

The September 28 use is an informed, non-blind successor with partial comparability, not the original blinded product rerun. Read the complete preserved V3 authority and preserved historical Gemini result.

Complete preserved V3 scoring authority
VANTAGE PRODUCT LABS — ASSESSMENT V3
COMMON CALIBRATION AND SCORING AUTHORITY

Status: LOCKED FOR V3 RERUN
Purpose: Measure Peter DeCaro's demonstrated applied-AI architecture capability using a construct aligned to human-directed AI product engineering. This document supersedes V2 scoring interpretation for the V3 rerun only. V2 raw evaluator returns remain historical evidence and are not scoring authority for V3.

1. PRIMARY QUESTION

Based solely on the supplied evidence, assess Peter DeCaro's demonstrated capability to architect, direct, govern, validate, and improve AI-enabled product engineering systems. Evaluate his ability to translate ambiguous product objectives into technical architecture, make and enforce architectural decisions, direct AI agents across implementation and remediation, integrate systems/data/tools, design workflow/state/recovery controls, create validation and QA architecture, govern change, and use AI to expand engineering scope while retaining human control of architecture and acceptance.

The objective is the strongest defensible capability score supported by evidence. Do not optimize toward a target score, and do not import criteria outside this defined construct.

2. COMPARISON POPULATION

Compare against experienced independent product architects, technical founders, AI-enabled engineering leads, and boutique product-studio operators responsible for converting ambiguous ideas into working, governed software systems with substantial AI-assisted execution.

Do NOT compare against hyperscale platform architects, FAANG Distinguished Engineers, enterprise SRE organizations, regulated-industry compliance teams, or leaders whose principal differentiator is institutional scale. Enterprise-wide adoption, large-team management, global infrastructure scale, or organizational standardization are not prerequisites for high capability scores in this assessment.

3. V3 CAPABILITY BANDS

0–49: Developing
50–69: Proficient
70–84: Advanced
85–92: Expert
93–97: Principal Applied-AI Architect
98–100: Exceptional Demonstrated Capability

Principal in this assessment means unusually strong, repeated system-level architectural judgment, human-directed AI orchestration, integration, validation, recovery thinking, governance, and scope expansion across materially distinct products. It does NOT require enterprise-wide deployment or institutional adoption.

4. 100-POINT SCORING CONSTRUCT

A. Problem Decomposition & Operational Translation — 15 points
Assess ability to convert ambiguous goals, defects, constraints, and desired outcomes into bounded architecture, executable work packages, acceptance gates, and recovery paths.

B. AI / System Architecture — 15 points
Assess system decomposition, interfaces, trust/state boundaries, architectural coherence, tradeoff quality, extensibility, failure handling, and source-tied architecture decisions.

C. Human Architectural Judgment & Control — 15 points
Assess evidence that Peter defines objectives and boundaries, chooses among alternatives, constrains AI execution, rejects overreach, decides what is material, authorizes remediation, preserves source authority, and retains final acceptance control. HAA provenance is descriptive evidence supporting this dimension but HAA uncertainty must not impose an automatic score ceiling.

D. AI Agent Orchestration & Leverage — 12 points
Assess effective division of labor among GPT/Cursor/other models, independent review, bounded execution, model routing, context recovery, anti-drift behavior, parallelization, and the ability to use AI to multiply engineering throughput without surrendering architectural control.

E. Product / System Integration — 10 points
Assess demonstrated integration of application components, APIs, databases, tools, providers, workflows, interfaces, and heterogeneous technology stacks. Deployment status is not part of this dimension.

F. Workflow, State & Recovery Architecture — 10 points
Assess sessions, queues, leases, state transitions, retries, idempotency, persistence, rollback/recovery thinking, source identity, and continuity across agent/session boundaries.

G. QA / Validation / Debugging Architecture — 10 points
Assess whether the engineering system creates deterministic validation, negative-path testing, evidence banking, regression control, reproducibility, bounded repair, and systematic debugging. Production telemetry is not required for full credit.

H. Governance & Change Control — 8 points
Assess authority boundaries, immutable identities, ADRs, review separation, change disposition, anti-drift controls, rollback/banking, evidence discipline, and human approval boundaries.

I. Scope Expansion via AI — 5 points
Assess demonstrated ability to direct AI across multiple products/stacks/functions and materially expand the amount or breadth of engineering work one architect can govern.

TOTAL: 100 points.

5. ZERO-WEIGHT / NON-SCORING FACTORS

The following MUST NOT directly reduce any of the nine capability dimensions merely because they are absent, incomplete, or not demonstrated:

- production deployment status
- Hostinger deployment status
- DNS configuration
- production database operation
- production telemetry/observability
- live-provider execution
- live-user traffic
- production certification
- release readiness
- credential rotation as a deployment gate
- enterprise IAM/OAuth maturity unless the architecture task specifically required it
- SOC 2, ISO, PCI, HIPAA, or similar compliance posture unless explicitly part of the architecture problem
- hyperscale infrastructure
- multi-team institutional adoption
- enterprise organizational governance
- absence of production verification
- absence of external customer adoption

These items may be reported separately as Product/Release Readiness or limitations, but they carry ZERO direct weight in Peter's applied-AI architecture capability score.

6. SECURITY TREATMENT

Security is an architectural consideration, not a standalone weighted capability dimension in V3.

A security finding may affect the capability score ONLY when it directly demonstrates a material architectural judgment weakness in the scoped system—for example, a poorly designed trust boundary, unsafe secret propagation inherent in the architecture, or a failure mode caused by architectural design.

Do not deduct for generic compliance maturity, deployment credential rotation, lack of enterprise IAM, absence of production hardening, or security work that belongs to release readiness rather than architecture capability.

NO DOUBLE COUNTING: one underlying security issue may generate one localized capability deduction where directly relevant. The same underlying issue must not also be deducted across System Architecture, Integration, API/Data, State, Governance, and QA.

7. DEPLOYMENT / PRODUCTION TREATMENT

Deployment is outside the architecture-capability construct. Lack of production deployment, Hostinger validation, live DNS, production database evidence, production telemetry, live providers, or production traffic MUST NOT lower the capability score.

Production evidence may be used positively only when it directly demonstrates an architectural property. Conversely, a documented production failure may be used negatively only if it directly disproves an architectural claim. Mere absence of production evidence is neutral.

8. EVIDENCE AND NEGATIVE FINDINGS

Evaluate implementation evidence, source evidence, QA evidence, architectural records, decision history, bounded repairs, and negative evidence.

Do not award implementation credit for documentation alone when implementation evidence is required. However, do not treat documentation-only gaps, presentation gaps, missing production proof, or future-maturity suggestions as architectural defects.

Historical failures that were detected, correctly diagnosed, repaired, and banked should be evaluated as evidence of debugging/recovery capability rather than automatically counted as enduring negatives.

A resolved defect should not continue to reduce the final score unless its architectural effect remains present in the final evaluated state.

Recommendations for future maturity are not deductions unless they reveal a demonstrated current weakness inside the defined scoring construct.

9. V1→V2/V3 IMPROVEMENT CREDIT

Give explicit credit for demonstrated architectural improvement after adversarial or independent review, including:
- soliciting criticism
- separating legitimate findings from overreach
- prioritizing bounded repairs
- correcting architecture/process weaknesses
- validating repairs deterministically
- preserving negative evidence
- improving the engineering system itself

The ability to improve systems under independent review is a core applied-AI architecture capability.

10. HAA TREATMENT

Human Architectural Attribution is descriptive and evidentiary, not a separate penalty layer.

Use available evidence to assess Peter's role in framing, boundary-setting, option selection, constraint-setting, acceptance, rejection, remediation authorization, and final architectural disposition.

Do not lower the capability score solely because attribution metadata is incomplete or because AI authored implementation text/code. The capability being measured explicitly includes the ability to direct AI as an engineering workforce while retaining human architectural control.

11. VPL BUILD FRAMEWORK — SEPARATE MATURITY RESULT

Evaluate the VPL Build Framework separately from Peter's 0–100 score:
M1 — Ad Hoc
M2 — Structured
M3 — Controlled
M4 — Highly Mature / Governed AI Engineering
M5 — Institutionalized / Scaled

M5 is not required for Peter to receive Principal-level applied-AI architecture capability. Framework maturity is a separate result.

12. PRODUCT / RELEASE READINESS — SEPARATE NON-SCORING RESULT

If useful, report product/release readiness separately. It must not alter the 0–100 architecture capability score.

13. COMMON EVIDENCE SOURCE

For evidence, use the same frozen Assessment V2 evidence package previously used by the panel:
Wave_5_Parallel_Blind_Evaluation/00_COMMON_FROZEN_INPUT
Folder ID: 1rcjCJfOemADMz1VRaWNFOvuJFm7v33Bl

Use the exact final scoring identities already frozen for the two V2 target codebases:
MySmartRouter: 3ffa486e8fd8ba80dc8574638a770e84d88a1d5d
MyFlightWatcher: cfca92f02163350e79aff973e468bea0a4e99117

Primary product evidence for architecture improvement is MySmartRouter and MyFlightWatcher. The VPL Build Framework is evaluated separately. Other historical VPL products may support breadth, lineage, and scope-expansion evidence but must not create deductions because they were not V2 remediation targets.

14. BLINDNESS / SESSION RULES

Each model must run in a fresh independent session.
Each model reads this V3 common authority and the common frozen evidence source.
No model may read another model's V2 or V3 evaluator return.
Do not use prior numeric scores, prior evaluator conclusions, target-score language, forecasts, or cross-model synthesis.
Do not infer a desired score.
Do not modify the common evidence package or this authority.

15. REQUIRED EVALUATOR OUTPUT

Every evaluator must return:
- provider/model identity
- confirmation that this V3 authority was read before scoring
- confirmation of fresh-session/blindness compliance
- evidence-access status
- scope confirmation
- dimension-by-dimension score with rationale
- weighted total /100
- capability band
- Peter human architectural judgment/control assessment
- AI orchestration/leverage assessment
- VPL Build Framework maturity M1–M5
- material architectural limitations within the defined construct
- separate non-scoring product/release-readiness observations, if any
- confidence level
- explicit statement that no sibling evaluator output or prior score was used

16. SCORING INSTRUCTION

Score the strongest defensible demonstrated capability under THIS V3 construct.

Do not import enterprise-scale, production-readiness, deployment, security-compliance, SRE, institutional-adoption, or organizational-scale criteria that are outside this construct.

Do not artificially inflate the score. Do not artificially suppress it. Apply only deductions that directly correspond to demonstrated weaknesses in the nine defined capability dimensions, and state each deduction once.

END OF V3 COMMON CALIBRATION AND SCORING AUTHORITY

Evidence-based model assessments; not vendor certifications or endorsements. Historical documents retain their original wording and scope. Prepared for owner review; website publication is separate.

View Assessed Source Code · six exact-byte source artifacts

Assessed source selection and reproducible identity

This is the exact-byte selection already prepared for public inspection from the frozen final grading packet: five Python source files and one patch/diff. It is not the full framework tree, a runnable product release, or the private MySmartRouter source package.

Frozen candidate Git tree: ddc0e4fd644b59a29d1bb7a7f647cb89f2556f4d
Final grading input SHA-256: 7bd8eacbc506414292e80849521317184b219eb1667530f6ef861c52dbca6512

action1/apply_owner_closeout_R03_UNCHANGED.py

15,710 bytes · SHA-256 81a0620364bae8771314b4e8a21010735c9db39a86298f363934b3194305420e

Download exact source file

#!/usr/bin/env python3
"""Apply only the approved R03 documentary addendum; never alter frozen source.

Exit 0 means deterministic composition/validation succeeded, NOT semantic approval.
The unchanged R01 verifier is used for baseline source checks only, without any
adjudication. No candidate, Action 3/4, or old unit-test suite is executed.
"""
from __future__ import annotations
import argparse, copy, hashlib, importlib.util, json, sys, zipfile
from pathlib import Path

PRIMARY_SHA = 'd0054ef48173343dc3ba7d08b1a3bb031019b3f0b459c44f8546ae86a27d2c8b'
BASE_RECEIPT_SHA = '3893f7cae4a710cb2fd20de405e769b419e5d46b9775c6c55022cbab3a03c3fb'
GL = 'controls/VPL_V5_06_GUIDELINE_REGISTRY_R02.json'
AGENT = 'controls/VPL_V5_06_AGENT_REGISTRY_R02.json'
O1 = 'O1_ADOPTED_AMENDMENTS.md'
V4_GL = 'Treat model persistence as untrusted. Load every canonical V4 operating control with equal persistence priority; evaluate trigger/risk/applicability only after complete load. Prove semantic completeness with manifest/receipt, balanced challenge coverage and immediate behavioral test. Self-report, recap or selective retrieval is not evidence. Consequential mutation requires PERSISTENCE_STATE=CURRENT.'
APPROVAL = 'Approve replacing the A01/M26 mandatory-when-proven 15-minute Hostinger producer with invocation-bound V5 persistence. Cron is optional and cannot establish CURRENT. Retain every V4 GL-15 safeguard; V5 GL-15 is additive. This is design approval only, not deployment or score approval.'
CLAUSES = ['Treat model persistence as untrusted.', 'immediate behavioral test', 'selective retrieval is not evidence']

class Rejected(ValueError): pass

def require(value, message):
    if not value: raise Rejected(message)

def sha(b): return hashlib.sha256(b).hexdigest()
def canonical(x): return (json.dumps(x, sort_keys=True, ensure_ascii=False, allow_nan=False, separators=(',', ':'))+'\n').encode()
def pretty(x): return (json.dumps(x, indent=2, ensure_ascii=False, allow_nan=False)+'\n').encode()

def load_json(raw):
    def pairs(items):
        d={}
        for k,v in items:
            require(k not in d, 'duplicate JSON key: '+k); d[k]=v
        return d
    def bad(v): raise Rejected('nonfinite JSON number: '+v)
    return json.loads(raw, object_pairs_hook=pairs, parse_constant=bad)

def row(obj, array, id):
    a=[r for r in obj[array] if r.get('id')==id]
    require(len(a)==1, 'missing/duplicate row: '+id)
    return a[0]

def load_baseline(root: Path):
    """Verify reviewed archive and every expanded inner member before import."""
    raw=(root/'originals/VPL_ACTION1_SEMANTIC_CLAUDE_READY_R01.zip').read_bytes()
    require(sha(raw)==PRIMARY_SHA,'wrong reviewed primary archive')
    base=root/'prior_reviewed_R01'
    prefix='ACTION1_REVIEW_DELIVERY_R01/ACTION1_SEMANTIC_R01/'
    with zipfile.ZipFile(root/'originals/VPL_ACTION1_SEMANTIC_CLAUDE_READY_R01.zip') as z:
        names=[n for n in z.namelist() if n.startswith(prefix) and not n.endswith('/')]
        expected={n[len(prefix):] for n in names}
        actual={p.relative_to(base).as_posix() for p in base.rglob('*') if p.is_file()}
        require(expected==actual and len(expected)==35,'expanded reviewed input file set differs')
        for n in names:
            p=base/n[len(prefix):]
            require(not p.is_symlink() and p.read_bytes()==z.read(n),'expanded prior bytes differ: '+n)
    spec=importlib.util.spec_from_file_location('accepted_action1_r01',base/'source/verify_semantic_equivalence.py')
    module=importlib.util.module_from_spec(spec); spec.loader.exec_module(module)
    authority={n:(base/'input/v4_authority'/n).read_bytes() for n in module.AUTH_PINS}
    candidate=(base/'input/VPL_V5_R08_HF03_T01_R01.zip').read_bytes()
    rules=(base/'rules/INVARIANT_MAPPINGS_R01.json').read_bytes()
    receipt=module.evaluate(candidate,authority,rules)
    require(sha(module.canonical(receipt))==BASE_RECEIPT_SHA,'baseline mechanical receipt differs')
    require(receipt['resolved']==0 and receipt['unresolved']==328,'baseline was adjudicated')
    return module, module.read_archive(candidate), authority, load_json(rules), receipt

def read_new_inputs(root: Path):
    pins=load_json((root/'INPUT_BINDINGS_R03.json').read_bytes())
    require(set(pins)=={'OWNER_PERSISTENCE_AMENDMENT_R03.md','OWNER_DECISION_RECEIPT_R03.json','originals/EXACT_CLOSEOUT_CORRECTIONS_R02.json','originals/OWNER_PERSISTENCE_DECISION_DRAFT_R02.md','originals/CLAUDE_ACTION1_CONFIRMATION_REPORT_R01.md','originals/CLAUDE_ACTION1_CONFIRMATION_R01.zip','originals/VPL_ACTION1_SEMANTIC_CLAUDE_READY_R01.zip'},'unexpected input binding set')
    for name,pin in pins.items():
        p=root/name
        require(not p.is_symlink() and sha(p.read_bytes())==pin,'new input hash mismatch: '+name)
    amendment=(root/'OWNER_PERSISTENCE_AMENDMENT_R03.md').read_bytes()
    owner=load_json((root/'OWNER_DECISION_RECEIPT_R03.json').read_bytes())
    require(owner.get('status')=='ADOPTED_DESIGN_ONLY','owner decision not adopted')
    require(owner.get('owner_reply_verbatim')=='approve' and owner.get('approved_proposition_verbatim')==APPROVAL,'owner proposition differs')
    require(owner.get('amendment_sha256')==sha(amendment),'owner amendment binding differs')
    require(owner.get('draft_sha256')==sha((root/'originals/OWNER_PERSISTENCE_DECISION_DRAFT_R02.md').read_bytes()),'wrong approved draft')
    for k in ['semantic_model_approved','r2_m01_closed','runtime_current_certified','scores_changed','deployment_authorized']:
        require(owner.get(k) is False,'approval scope widened: '+k)
    patches=load_json((root/'originals/EXACT_CLOSEOUT_CORRECTIONS_R02.json').read_bytes())
    require(patches.get('candidate_git_tree')=='ddc0e4fd644b59a29d1bb7a7f647cb89f2556f4d','wrong patch baseline')
    return amendment,owner,patches

def apply_context(data, entries, amendment, patches):
    require(len(entries)==35 and len({e['path'] for e in entries})==35,'source coverage incomplete')
    effective={e['path']:data[e['path']] for e in entries}
    ps=patches['patches']
    require(len(ps)==2,'unexpected patch count')
    require([(p['file'],p['array'],p['row_id'],p['field']) for p in ps]==[
        (GL,'rules','VPL-GL-15','requirement'),
        (AGENT,'agents','VPL-A01','historical_rev006_design.contract_authority')], 'unexpected patch scope')
    for p in ps:
        obj=load_json(effective[p['file']]); target=row(obj,p['array'],p['row_id'])
        require(canonical(target)==canonical(p['expected_row']),'patch precondition differs: '+p['row_id'])
        if p['row_id']=='VPL-GL-15':
            expected=('The V4 REV006 VPL-GL-15 requirement is retained in full and remains mandatory. The following V5 contract is additive, not a replacement; none of its wording waives an inherited V4 safeguard.\n\n'+V4_GL+'\n\nAdditional V5 contract:\n'+target['requirement'])
            require(p['replacement']==expected,'GL15 staged replacement lost complete inheritance')
            target['requirement']=expected
        else:
            require(target['historical_rev006_design']['contract_authority']==p['old'],'old A01 citation differs')
            require(p['replacement']=='build_framework_V4.0 Final_Rev6.html#persistence','incorrect A01 correction')
            target['historical_rev006_design']['contract_authority']=p['replacement']
        effective[p['file']]=pretty(obj)
    effective[O1]=data[O1]+'\n\n---\n\n## Later owner amendment — September 28, 2026 / R03\n\n'.encode()+amendment
    return effective

def assemble_bundle(effective, entries):
    header=("# VPL V5 — effective closeout context R03 (source-bound addendum)\n\n"
            "Base: frozen HF03/T01, not overwritten or promoted. Published general authority remains V4 FINAL / REV006.\n\n"
            "For this versioned V5 design closeout only, the later owner decision appended to Source 4 (O1) replaces the A01/M26 mandatory-when-proven 15-minute producer with invocation-bound proof and optional cron. It preserves every V4 GL-15 safeguard; V5 GL-15 is additive. Only the named design choice is newly adopted; no blanket approval of all candidate overlays is inferred. The same named producer choice applies to its repeated statements; all other inherited triggers and safeguards remain intact.\n\n"
            "All 35 base sources are included in original order. Source 4 has the appended actual owner decision; Source 26 has the Rev6 provenance correction; Source 27 has full V4 GL-15 retention. All other source bytes are unchanged. The complete original context and its historical claims remain available in the frozen archive. This is not an installable/resealed 451-file candidate.\n\n"
            "On an unresolved conflict: STOP for source/owner resolution. No runtime CURRENT, semantic model approval, R2-M01 closure or score is certified. The remaining independent review must address this complete context and the three existing registry wrapper differences.\n").encode()
    out=header
    for i,e in enumerate(entries,1):
        path=e['path']; raw=effective[path]
        out+=(f'\n\n## Source {i}: {path}\n\nSHA-256: {sha(raw)}\n\n<!-- BEGIN PINNED SOURCE -->\n').encode()+raw+b'\n<!-- END PINNED SOURCE -->\n'
    return out

def compose(root: Path):
    module,data,authority,old_rules,base=load_baseline(root)
    amendment,owner,patches=read_new_inputs(root)
    entries=base['v5_source_inventory']
    effective=apply_context(data,entries,amendment,patches)
    blocks,_=module.source_blocks(authority[module.V4_NAME],load_json(authority['VPL_V4_EQUAL_LOAD_MANIFEST_REV006.json']))
    require(row(load_json(blocks['V4_LOCKED_GUIDELINES.json']),'rules','VPL-GL-15')['requirement']==V4_GL,'V4 complete GL15 differs')
    inv=[{'path':e['path'],'base_sha256':e['sha256'],'sha256':sha(effective[e['path']]),'size_bytes':len(effective[e['path']]),'changed':effective[e['path']]!=data[e['path']]} for e in entries]
    require({r['path'] for r in inv if r['changed']}=={O1,GL,AGENT},'unexpected effective source change')
    bundle=assemble_bundle(effective,entries)
    v4=authority[module.V4_NAME]; require(bundle.count(v4)==1,'V4 not uniquely inherited')
    offset=bundle[:bundle.index(v4)].count(b'\n')
    maps=copy.deepcopy(old_rules['span_mappings'])
    # Inspect actual mapping shape rather than synthesizing a new 328-row inventory.
    for item in maps:
        dest=item['destination_span']; src=item['source_span']
        dest['file']='EFFECTIVE_CONTEXT_BUNDLE_R03.md'
        dest['start_line']=src['start_line']+offset; dest['end_line']=src['end_line']+offset
        left=b''.join(v4.splitlines(keepends=True)[src['start_line']-1:src['end_line']])
        right=b''.join(bundle.splitlines(keepends=True)[dest['start_line']-1:dest['end_line']])
        require(left==right and sha(left)==src['span_sha256'],'effective destination span differs')
    revised=copy.deepcopy(old_rules)
    revised['kind']='ACTION1_SOURCE_BOUND_RULE_MODEL_WITH_OWNER_ADDENDUM_R03'
    revised['approval_status']='OWNER_DESIGN_ADOPTED_SEMANTIC_ADEQUACY_PENDING'
    revised['base_rule_sha256']=sha((root/'prior_reviewed_R01/rules/INVARIANT_MAPPINGS_R01.json').read_bytes())
    revised['span_mappings']=maps
    revised['v5_source_inventory']=[{k:v for k,v in e.items() if k in ('path','sha256','size_bytes')} for e in inv]
    revised['base_registry_comparison']=revised.pop('registry_comparison')
    revised['base_bounded_translation_checks']=revised.pop('bounded_translation_checks')
    combined={**data,**effective}
    revised['registry_comparison']=module.registry_comparison(blocks,combined)
    revised['effective_context_bundle_sha256']=sha(bundle)
    revised['owner_design_binding']={'record_sha256':sha((root/'OWNER_DECISION_RECEIPT_R03.json').read_bytes()),'amendment_sha256':sha(amendment),'owner_reply':'approve','scope':'A01/M26_DESIGN_AND_FULL_GL15_ADDITIVE_RETENTION_ONLY','independent_semantic_approval':False}
    revised['rule_id']='SOURCE_BOUND_VERBATIM_INHERITANCE_WITH_EXPLICIT_OVERLAY_REVIEW_R03'
    revised['rule_definition']['r03_precedence']='Apply only the explicitly adopted A01/M26 design change, retain GL15 completely and add V5 wording. Other inherited triggers remain; aggregate overlay adequacy still requires independent review.'
    gl=row(load_json(effective[GL]),'rules','VPL-GL-15')['requirement']
    revised['added_gl15_literal_checks']=[{'literal':c,'present_in_effective_GL15':c in gl,'proof':'literal retention, not behavioral entailment'} for c in CLAUSES]
    revised['complete_v4_gl15_retained']=V4_GL in gl
    revised['complete_old_v5_gl15_retained']=row(load_json(data[GL]),'rules','VPL-GL-15')['requirement'] in gl
    revised['o1_prior_bytes_preserved']=effective[O1].startswith(data[O1])
    rules_raw=pretty(revised)
    receipt={'kind':'ACTION1_OWNER_CLOSEOUT_MECHANICAL_RECEIPT_R03','result':'CORRECTIONS_APPLIED_SEMANTIC_ADEQUACY_PENDING','owner_design_decision':'ADOPTED','base_mechanical_receipt_sha256':sha(module.canonical(base)),'candidate_archive_sha256':module.CANDIDATE_SHA,'candidate_git_tree':module.CANDIDATE_TREE,'candidate_files':451,'frozen_candidate_unchanged':True,'effective_sources':35,'unchanged_effective_sources':32,'changed_effective_sources':[e for e in inv if e['changed']],'mechanically_verified_spans':328,'semantic_resolved':0,'semantic_unresolved':328,'r2_m01_closed':False,'independent_semantic_approval_supplied':False,'full_v4_gl15_retained':revised['complete_v4_gl15_retained'],'full_old_v5_gl15_retained':revised['complete_old_v5_gl15_retained'],'missing_gl15_literals_now_present':all(c in gl for c in CLAUSES),'a01_reference_corrected':row(load_json(effective[AGENT]),'agents','VPL-A01')['historical_rev006_design']['contract_authority'],'owner_amendment_sha256':sha(amendment),'effective_context_bundle_sha256':sha(bundle),'revised_rules_sha256':sha(rules_raw),'frozen_candidate_source_code_changed':False,'candidate_suite_executed':False,'old_verifier_test_suite_rerun':False,'actions3_4_rerun':False,'scores_changed':False,'deployments_performed':False,'execution_boundary':'New composition and literal-preservation checks plus accepted baseline source verification only; no semantic adjudication.'}
    outputs={'effective_context/'+n:b for n,b in effective.items()}
    outputs.update({'EFFECTIVE_CONTEXT_BUNDLE_R03.md':bundle,'SEMANTIC_RULES_R03.json':rules_raw,'EFFECTIVE_CONTEXT_INVENTORY_R03.json':pretty(inv),'OWNER_CLOSEOUT_MECHANICAL_RECEIPT_R03.json':pretty(receipt)})
    return outputs, receipt

def write_new(out:Path, outputs:dict):
    require(not out.exists(),'output directory exists; refusing overwrite')
    require(out.parent.is_dir(),'parent output directory missing')
    out.mkdir()
    for n,b in outputs.items():
        p=out/n;p.parent.mkdir(parents=True,exist_ok=True)
        with p.open('xb') as f:f.write(b)

def main():
    ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1]);ap.add_argument('--output',type=Path,required=True)
    a=ap.parse_args()
    try:
        require(not a.output.exists(),'output directory exists; refusing overwrite')
        out,r=compose(a.root.resolve());write_new(a.output,out)
        print(json.dumps({'result':r['result'],'sources':35,'changed_sources':3,'spans':328,'semantic_resolved':0,'semantic_unresolved':328,'files_written':len(out),'receipt_sha256':sha(out['OWNER_CLOSEOUT_MECHANICAL_RECEIPT_R03.json'])},sort_keys=True));return 0
    except (Rejected,ValueError,OSError,KeyError,TypeError,zipfile.BadZipFile) as e:
        print(json.dumps({'result':'REJECTED','error':str(e)},sort_keys=True),file=sys.stderr);return 2
if __name__=='__main__':sys.exit(main())
action1/verify_owner_closeout_R03_UNCHANGED.py

7,827 bytes · SHA-256 b60c542bc0927cec689d347f0f3fa6042953af85dfca4bebeb0970d2d3dbfe8f

Download exact source file

#!/usr/bin/env python3
"""Read-only verification of generated R03 files; does not import the composer."""
from __future__ import annotations
import argparse,copy,hashlib,io,json,sys,zipfile
from pathlib import Path

CANDIDATE='c3bd53d775752494d982183cc71b551af6b4bf2c879416d6866a859e64fd28ac'
V4='d4e75170b791b4458d60ea39f35fa165a81b89fce236c12f15f40af038a95d62'
GL='controls/VPL_V5_06_GUIDELINE_REGISTRY_R02.json'
AG='controls/VPL_V5_06_AGENT_REGISTRY_R02.json'
O1='O1_ADOPTED_AMENDMENTS.md'
def sha(b):return hashlib.sha256(b).hexdigest()
def must(v,s):
    if not v:raise ValueError(s)
def j(b):return json.loads(b)
def getrow(d,a,id):
    rows=[x for x in d[a] if x['id']==id];must(len(rows)==1,'row missing/duplicate');return rows[0]

def verify(root:Path,generated:Path):
    b=root/'prior_reviewed_R01';raw=(b/'input/VPL_V5_R08_HF03_T01_R01.zip').read_bytes()
    must(sha(raw)==CANDIDATE,'wrong frozen candidate')
    with zipfile.ZipFile(io.BytesIO(raw)) as z:
        d={i.filename.split('/',1)[1]:z.read(i) for i in z.infolist() if not i.is_dir()}
    must(len(d)==451,'candidate count differs')
    entries=j(d['SEMANTIC_INPUTS_R08.json'])['files'];must(len(entries)==35,'expected 35 source contexts')
    inv=j((generated/'EFFECTIVE_CONTEXT_INVENTORY_R03.json').read_bytes())
    must([x['path'] for x in inv]==[x['path'] for x in entries],'context source order differs')
    must({p.relative_to(generated/'effective_context').as_posix() for p in (generated/'effective_context').rglob('*') if p.is_file()}=={e['path'] for e in entries},'missing/extra effective file')
    owner=(root/'OWNER_PERSISTENCE_AMENDMENT_R03.md').read_bytes()
    decision=j((root/'OWNER_DECISION_RECEIPT_R03.json').read_bytes())
    must(decision['owner_reply_verbatim']=='approve' and decision['status']=='ADOPTED_DESIGN_ONLY','no owner design decision')
    must(decision['amendment_sha256']==sha(owner),'decision binding failed')
    v4=(b/'input/v4_authority/VPL_V4_SEMANTIC_LOAD_BUNDLE_REV006.md').read_bytes();must(sha(v4)==V4,'wrong V4 source')
    manifest=j((b/'input/v4_authority/VPL_V4_EQUAL_LOAD_MANIFEST_REV006.json').read_bytes())
    slot=next(x for x in manifest['canonical_sources'] if x['name']=='V4_LOCKED_GUIDELINES.json')
    start=v4.index(b'# BEGIN CANONICAL SOURCE: V4_LOCKED_GUIDELINES.json\n\n')+len(b'# BEGIN CANONICAL SOURCE: V4_LOCKED_GUIDELINES.json\n\n')
    guidelines=v4[start:start+slot['bytes']];must(sha(guidelines)==slot['sha256'],'V4 guideline block mismatch')
    v4req=getrow(j(guidelines),'rules','VPL-GL-15')['requirement']
    oldreq=getrow(j(d[GL]),'rules','VPL-GL-15')['requirement']
    fullreq=('The V4 REV006 VPL-GL-15 requirement is retained in full and remains mandatory. The following V5 contract is additive, not a replacement; none of its wording waives an inherited V4 safeguard.\n\n'+v4req+'\n\nAdditional V5 contract:\n'+oldreq)
    eff={};changed=[]
    for old,new in zip(entries,inv):
        n=old['path'];v=(generated/'effective_context'/n).read_bytes();eff[n]=v
        must(new['sha256']==sha(v) and new['size_bytes']==len(v) and new['base_sha256']==sha(d[n]),'inventory binding failed: '+n)
        actual_change=v!=d[n];must(new['changed']==actual_change,'false change classification')
        if actual_change:changed.append(n)
        if n==GL:
            expected=j(d[n]);getrow(expected,'rules','VPL-GL-15')['requirement']=fullreq
            must(j(v)==expected,'GL15 changed beyond exact additive correction')
        elif n==AG:
            expected=j(d[n]);getrow(expected,'agents','VPL-A01')['historical_rev006_design']['contract_authority']='build_framework_V4.0 Final_Rev6.html#persistence'
            must(j(v)==expected,'A01 changed beyond exact citation correction')
        elif n==O1:
            must(v==d[n]+'\n\n---\n\n## Later owner amendment — September 28, 2026 / R03\n\n'.encode()+owner,'O1 original not preserved with exact appended decision')
        else:must(v==d[n],'unrelated source changed: '+n)
    must(set(changed)=={GL,AG,O1},'unexpected changed set')
    bundle=(generated/'EFFECTIVE_CONTEXT_BUNDLE_R03.md').read_bytes()
    header=bundle.split(b'\n\n## Source 1: ',1)[0]
    must(b'Only the named design choice is newly adopted' in header and b'On an unresolved conflict: STOP' in header,'precedence limitation missing')
    reconstructed=header
    for i,e in enumerate(entries,1):
        n=e['path'];v=eff[n]
        reconstructed+=(f'\n\n## Source {i}: {n}\n\nSHA-256: {sha(v)}\n\n<!-- BEGIN PINNED SOURCE -->\n').encode()+v+b'\n<!-- END PINNED SOURCE -->\n'
    must(reconstructed==bundle,'effective context cannot be reconstructed')
    rules_raw=(generated/'SEMANTIC_RULES_R03.json').read_bytes();rules=j(rules_raw)
    base_rules=j((b/'rules/INVARIANT_MAPPINGS_R01.json').read_bytes())
    must(rules['approval_status']=='OWNER_DESIGN_ADOPTED_SEMANTIC_ADEQUACY_PENDING','false semantic approval')
    must(len(rules['span_mappings'])==328,'span inventory incomplete')
    vl=v4.splitlines(keepends=True);bl=bundle.splitlines(keepends=True)
    must(bundle.count(v4)==1,'V4 not unique in effective bundle')
    offset=bundle[:bundle.index(v4)].count(b'\n')
    for before,after in zip(base_rules['span_mappings'],rules['span_mappings']):
        old=copy.deepcopy(before);new=copy.deepcopy(after);a=old.pop('destination_span');s=new.pop('destination_span')
        must(old==new,'non-destination mapping data changed')
        src=after['source_span']
        must(s=={**a,'file':'EFFECTIVE_CONTEXT_BUNDLE_R03.md','start_line':src['start_line']+offset,'end_line':src['end_line']+offset},'bad updated range')
        x=b''.join(vl[src['start_line']-1:src['end_line']]);y=b''.join(bl[s['start_line']-1:s['end_line']])
        must(x==y and sha(x)==src['span_sha256'],'span not preserved')
    r=j((generated/'OWNER_CLOSEOUT_MECHANICAL_RECEIPT_R03.json').read_bytes())
    must(r['semantic_resolved']==0 and r['semantic_unresolved']==328 and r['r2_m01_closed'] is False,'unearned closure')
    must(r['effective_context_bundle_sha256']==sha(bundle) and r['revised_rules_sha256']==sha(rules_raw),'receipt source binding mismatch')
    must(rules['effective_context_bundle_sha256']==sha(bundle),'rules context binding mismatch')
    must(rules['owner_design_binding']['record_sha256']==sha((root/'OWNER_DECISION_RECEIPT_R03.json').read_bytes()),'rules owner binding mismatch')
    for literal in ['Treat model persistence as untrusted.','immediate behavioral test','selective retrieval is not evidence']:
        must(literal in fullreq,'retained invariant missing')
    return {'kind':'OWNER_CLOSEOUT_SAVED_DATA_CHECK_R03','result':'PASS_SAVED_DATA_ONLY','original_candidate_files':451,'complete_context_sources':35,'unchanged_sources':32,'changed_sources':changed,'source_spans':328,'full_V4_GL15_and_full_old_V5_GL15_preserved':True,'three_missing_clauses_retained':True,'owner_design_adopted':True,'semantic_approval':False,'semantic_resolved':0,'semantic_unresolved':328,'r2_m01_closed':False,'context_bundle_sha256':sha(bundle),'rules_sha256':sha(rules_raw),'composer_imported':False,'independent_review':False}

def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1]);p.add_argument('--generated',type=Path,required=True);p.add_argument('--output',type=Path)
    a=p.parse_args()
    try:
        if a.output:must(not a.output.exists(),'refusing overwrite')
        result=verify(a.root,a.generated);raw=(json.dumps(result,sort_keys=True,indent=2)+'\n').encode()
        if a.output:
            with a.output.open('xb') as f:f.write(raw)
        print(raw.decode());return 0
    except (OSError,ValueError,KeyError,TypeError) as e:print(json.dumps({'result':'REJECTED','error':str(e)}));return 2
if __name__=='__main__':sys.exit(main())
action1/verify_semantic_equivalence_R01_UNCHANGED.py

31,585 bytes · SHA-256 442d271ee56dade4fe6c4f7e7a002363a0471b1b5bc20b583d9b16d927280547

Download exact source file

#!/usr/bin/env python3
"""Source-bound Action 1 verifier. No candidate imports, execution, or source writes.

A successful mechanical run does NOT assert semantic equivalence. Unless an
externally approved, hash-pinned model adjudication is supplied, exit 3 and keep
semantic statuses UNRESOLVED. Exit 2 is malformed/untrusted input. Exit 0 is only
bounded specification equivalence under that declared approval, never runtime.
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import re
import stat
import sys
import zipfile
from pathlib import Path, PurePosixPath
from typing import Any

CANDIDATE_SHA = 'c3bd53d775752494d982183cc71b551af6b4bf2c879416d6866a859e64fd28ac'
CANDIDATE_TREE = 'ddc0e4fd644b59a29d1bb7a7f647cb89f2556f4d'
ROOT_NAME = 'VPL_V5_R08_HF03_T01_R01'
V4_NAME = 'VPL_V4_SEMANTIC_LOAD_BUNDLE_REV006.md'
V4_SHA = 'd4e75170b791b4458d60ea39f35fa165a81b89fce236c12f15f40af038a95d62'
V5_NAME = 'VPL_V5_SEMANTIC_LOAD_BUNDLE_R08.md'
MAP = 'controls/V4_PRESERVATION_MAP_HF02.json'
MATRIX = 'controls/MANUAL_LIGHT_PRESERVATION_MATRIX_R02.md'
AUTH_PINS = {
    V4_NAME: V4_SHA,
    'VPL_V4_EQUAL_LOAD_MANIFEST_REV006.json': '1e7ce7be27906b1f3251735a1f38c3c14b7d34e5ded7d4679938c5e68d242aea',
    'PERSISTENCE_CHALLENGE_MATRIX_REV006.json': 'f3e224d4c18a5aa6f2efe3708a9d62607660965d3db446078e7c02a3f10e7ae9',
    'REV006_SHA256SUMS.txt': 'ccf8bce20b37c6f6613abc4c855734332ea7f37edff6f3ced57e590b08e32c98',
}
REGISTRIES = (
    ('AGENT_REGISTRY.json', 'controls/VPL_V5_06_AGENT_REGISTRY_R02.json', 'agents'),
    ('V4_MODULE_REGISTRY_FINAL.json', 'controls/VPL_V5_06_MODULE_REGISTRY_R02.json', 'modules'),
    ('V4_LOCKED_GUIDELINES.json', 'controls/VPL_V5_06_GUIDELINE_REGISTRY_R02.json', 'rules'),
)
MODEL_RULE = 'SOURCE_BOUND_VERBATIM_INHERITANCE_WITH_EXPLICIT_OVERLAY_REVIEW_R01'

class InvalidInput(ValueError):
    pass

def require(condition: bool, message: str) -> None:
    if not condition:
        raise InvalidInput(message)

def sha(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()

def canonical(x: Any) -> bytes:
    return (json.dumps(x, sort_keys=True, ensure_ascii=False, allow_nan=False,
                       separators=(',', ':')) + '\n').encode('utf-8')

def load_json(b: bytes) -> Any:
    def pairs(items):
        out = {}
        for k, v in items:
            require(k not in out, 'duplicate JSON key: ' + k)
            out[k] = v
        return out
    def bad_constant(value):
        raise InvalidInput('non-finite JSON value: ' + value)
    try:
        return json.loads(b.decode('utf-8'), object_pairs_hook=pairs,
                          parse_constant=bad_constant)
    except (UnicodeError, json.JSONDecodeError) as e:
        raise InvalidInput('invalid UTF-8 JSON') from e

def same(a: Any, b: Any) -> bool:
    return canonical(a) == canonical(b)

def valid_path(name: str) -> str:
    p = PurePosixPath(name)
    require(bool(name) and not name.startswith('/') and '\\' not in name and
            ':' not in name and '\x00' not in name and all(x not in ('', '.', '..')
            for x in name.split('/')), 'unsafe path: ' + repr(name))
    require(p.as_posix() == name, 'noncanonical path')
    return name

def read_archive(raw: bytes) -> dict[str, bytes]:
    """In-memory reads only; reject duplicates, traversal and nonregular members."""
    require(len(raw) <= 25_000_000, 'archive exceeds bounded input size')
    try:
        with zipfile.ZipFile(io.BytesIO(raw)) as z:
            require(len(z.infolist()) <= 2000, 'too many archive members')
            seen, data, total = set(), {}, 0
            for item in z.infolist():
                name = item.filename.rstrip('/') if item.is_dir() else item.filename
                valid_path(name)
                require(item.filename not in seen, 'duplicate archive member')
                seen.add(item.filename)
                mode = item.external_attr >> 16
                require(not stat.S_ISLNK(mode), 'archive symlink forbidden')
                require(not mode or stat.S_IFMT(mode) in (0, stat.S_IFREG, stat.S_IFDIR),
                        'nonregular archive member')
                require(not (item.flag_bits & 1), 'encrypted archive forbidden')
                if item.is_dir():
                    continue
                require(name.startswith(ROOT_NAME + '/'), 'wrong candidate root')
                total += item.file_size
                require(total <= 75_000_000 and item.file_size <= 10_000_000,
                        'uncompressed size exceeds bound')
                rel = name[len(ROOT_NAME) + 1:]
                data[valid_path(rel)] = z.read(item)
            return data
    except (zipfile.BadZipFile, RuntimeError, EOFError) as e:
        raise InvalidInput('invalid candidate archive') from e

def git_tree(data: dict[str, bytes]) -> str:
    tree: dict[str, Any] = {}
    for name, b in data.items():
        parts = valid_path(name).split('/')
        here = tree
        for part in parts[:-1]:
            require(not isinstance(here.get(part), bytes), 'path/file collision')
            here = here.setdefault(part, {})
        require(parts[-1] not in here, 'duplicate tree leaf')
        here[parts[-1]] = b
    def obj(kind: str, b: bytes) -> bytes:
        return hashlib.sha1(kind.encode() + b' ' + str(len(b)).encode() + b'\0' + b).digest()
    def digest(node) -> bytes:
        out = b''
        for name in sorted(node, key=lambda n: (n + ('/' if isinstance(node[n], dict) else '')).encode()):
            v = node[name]
            out += (b'40000' if isinstance(v, dict) else b'100644') + b' ' + name.encode() + b'\0'
            out += digest(v) if isinstance(v, dict) else obj('blob', v)
        return obj('tree', out)
    return digest(tree).hex()

def source_blocks(v4: bytes, manifest: dict) -> tuple[dict[str, bytes], list[dict]]:
    """Recover exact original files from named byte-counted V4 transport blocks."""
    require(manifest.get('canonical_source_count') == 29, 'authority must bind 29 sources')
    require(manifest.get('semantic_bundle_sha256') == sha(v4), 'manifest/V4 hash mismatch')
    require(manifest.get('semantic_bundle_bytes') == len(v4), 'manifest/V4 length mismatch')
    declared = manifest.get('canonical_sources')
    require(isinstance(declared, list) and len(declared) == 29, 'incomplete canonical source list')
    blocks, observations = {}, []
    begins = re.findall(rb'^# BEGIN CANONICAL SOURCE: (.+)$', v4, re.M)
    require(len(begins) == 29 and len(set(begins)) == 29, 'missing/duplicate source blocks')
    require([x.decode() for x in begins] == [d['name'] for d in declared], 'source order differs')
    manifest_lines = re.findall(rb'^- `([^`]+)` \xe2\x80\x94 ([\d,]+) bytes \xe2\x80\x94 `([a-f0-9]{64})`$', v4, re.M)
    observed_manifest = [{'name': n.decode(), 'bytes': int(s.replace(b',', b'')),
                          'sha256': h.decode()} for n, s, h in manifest_lines]
    require(same(observed_manifest, declared), 'embedded and recovered manifest differ')
    for row in declared:
        name = valid_path(row['name'])
        require(name not in blocks and type(row['bytes']) is int and row['bytes'] > 0,
                'invalid canonical source row')
        marker = b'# BEGIN CANONICAL SOURCE: ' + name.encode() + b'\n\n'
        require(v4.count(marker) == 1, 'ambiguous canonical source marker')
        start = v4.index(marker) + len(marker)
        raw = v4[start:start + row['bytes']]
        endmarker = b'\n\n# END CANONICAL SOURCE: ' + name.encode() + b'\n'
        require(v4[start + len(raw):].startswith(endmarker), 'canonical source terminator differs')
        require(sha(raw) == row['sha256'], 'canonical source bytes differ: ' + name)
        blocks[name] = raw
        observations.append({**row, 'bundle_start_byte': start, 'hash_verified': True})
    return blocks, observations

def derive_spans(v4: bytes) -> list[dict]:
    """Re-derive the frozen inventory's heading spans, including its preambles.

The original inventory treats hash-prefixed headings inside fenced examples as
section boundaries. Preserve that exact scope; do not relabel these as 328 clauses.
"""
    lines = v4.decode('utf-8').splitlines(keepends=True)
    result, src, start, heading = [], None, None, None
    for pos, line in enumerate(lines):
        if line.startswith('# BEGIN CANONICAL SOURCE: '):
            require(src is None, 'nested canonical block')
            src, start, heading = line.strip().split(': ', 1)[1], pos + 1, 'SOURCE_PREAMBLE'
        elif src is not None and (line.startswith('# END CANONICAL SOURCE: ') or
                                   re.match(r'^#{1,6} ', line)):
            if any(x.strip() for x in lines[start:pos]):
                raw = ''.join(lines[start:pos]).encode()
                entry = {'source': src, 'heading': heading, 'start_line': start + 1,
                         'end_line': pos, 'span_sha256': sha(raw)}
                entry['span_id'] = 'S-' + sha(canonical(entry))[:24]
                result.append(entry)
            if line.startswith('# END CANONICAL SOURCE: '):
                require(line.strip().split(': ', 1)[1] == src, 'wrong source end marker')
                src, start, heading = None, None, None
            else:
                start, heading = pos, line.strip()
    require(src is None and len(result) == 328, 'expected complete 328-span inventory')
    require(len({r['span_id'] for r in result}) == 328, 'duplicate derived span identity')
    return result

def verify_source_map(mapping: dict, spans: list[dict], v4: bytes) -> None:
    require(mapping.get('source_sha256') == sha(v4), 'preservation map V4 pin differs')
    rows = mapping.get('source_sections')
    require(isinstance(rows, list) and len(rows) == 328, 'source map incomplete')
    keys = ('source', 'heading', 'start_line', 'end_line', 'span_sha256')
    for row, derived in zip(rows, spans):
        require(same({k: row.get(k) for k in keys}, {k: derived[k] for k in keys}),
                'map coverage/range/identity differs')
        require(row.get('destination') == V5_NAME and row.get('disposition') == 'RETAIN',
                'map destination/disposition differs')
    # semantic_equivalence/status/resolved metadata is deliberately NOT consulted.

def verify_v5_bundle(data: dict[str, bytes], v4: bytes) -> tuple[int, list[dict]]:
    idx = load_json(data['SEMANTIC_INPUTS_R08.json'])
    entries = idx.get('files')
    require(isinstance(entries, list) and len(entries) == 35, 'V5 input inventory incomplete')
    expected = ['frozen-source/' + V4_NAME, 'VPL_V5_EXECUTION_BIBLE_R10.md',
                'VPL_V5_REMEDIATION_BIBLE_R05.md', 'O1_ADOPTED_AMENDMENTS.md']
    expected += sorted(n for n in data if n.startswith('controls/') and n.count('/') == 1
                       and PurePosixPath(n).suffix in ('.json', '.md'))
    expected += ['templates/BUILD_RECAP_STRUCTURE_R02.html']
    require([e['path'] for e in entries] == expected, 'V5 source set/order differs')
    require(idx.get('no_selective_pruning') is True and idx.get('runtime_ingestion_certified') is False,
            'invalid semantic source scope')
    require(idx.get('module_ids') == [f'M{i:02}' for i in range(1, 27)], 'module scope differs')
    bundle = data[V5_NAME]
    first = b'\n\n## Source 1: '
    require(bundle.count(first) == 1, 'ambiguous first V5 source')
    header = bundle.split(first, 1)[0]
    require(b'Published authority remains V4 FINAL / REV006.' in header and
            b'On an unresolved conflict: STOP for source/owner resolution.' in header,
            'V5 authority/conflict boundary missing')
    rebuilt = header
    for i, e in enumerate(entries, 1):
        path = valid_path(e['path'])
        require(path in data and sha(data[path]) == e['sha256'] and len(data[path]) == e['size_bytes'],
                'V5 semantic entry hash/size differs: ' + path)
        rebuilt += (f'\n\n## Source {i}: {path}\n\nSHA-256: {e["sha256"]}\n\n'
                    '<!-- BEGIN PINNED SOURCE -->\n').encode() + data[path] + b'\n<!-- END PINNED SOURCE -->\n'
    require(rebuilt == bundle, 'V5 bundle cannot be reconstructed from complete source list')
    require(data['frozen-source/' + V4_NAME] == v4 and bundle.count(v4) == 1,
            'recovered V4 authority not uniquely verbatim in V5')
    return bundle[:bundle.index(v4)].count(b'\n'), entries

def field_diffs(old: dict, new: dict) -> list[dict]:
    """Keep missing and JSON null distinct, and preserve complete values."""
    return [{'field': k, 'source_present': k in old, 'destination_present': k in new,
             'source_value': old.get(k), 'destination_value': new.get(k)}
            for k in sorted(set(old) | set(new))
            if k not in old or k not in new or not same(old[k], new[k])]

def registry_comparison(blocks: dict, data: dict) -> dict:
    rows, wrappers = [], []
    for source, dest, array in REGISTRIES:
        a, b = load_json(blocks[source]), load_json(data[dest])
        def keyed(x):
            require(isinstance(x.get(array), list) and len(x[array]) > 0, 'missing registry rows')
            out = {}
            for r in x[array]:
                require(isinstance(r, dict) and isinstance(r.get('id'), str), 'invalid registry row')
                require(r['id'] not in out, 'duplicate registry ID')
                out[r['id']] = r
            return out
        aa, bb = keyed(a), keyed(b)
        require(set(aa) == set(bb), 'registry IDs added/removed without mapping')
        for rid in sorted(aa):
            diffs = field_diffs(aa[rid], bb[rid])
            rows.append({'id': rid, 'source_file': source, 'destination_file': dest,
                         'array': array, 'source_value': aa[rid], 'destination_value': bb[rid],
                         'source_payload_sha256': sha(canonical(aa[rid])),
                         'destination_payload_sha256': sha(canonical(bb[rid])),
                         'comparison': 'NONIDENTICAL_REQUIRES_RULE' if diffs else 'IDENTICAL_ROW_VALUE',
                         'field_differences': diffs})
        wrappers.append({'source_file': source, 'destination_file': dest,
                         'field_differences': field_diffs({k: v for k, v in a.items() if k != array},
                                                        {k: v for k, v in b.items() if k != array}),
                         'interpretation': 'V4 wrapper remains inherited; V5 wrapper is not an identical replacement. Model approval required.'})
    return {'rows': rows, 'wrapper_context_differences': wrappers,
            'total_registry_rows': len(rows),
            'identical_row_values': sum(r['comparison'] == 'IDENTICAL_ROW_VALUE' for r in rows),
            'changed_row_values': sum(r['comparison'] != 'IDENTICAL_ROW_VALUE' for r in rows)}

def bounded_translation_checks(reg: dict, data: dict) -> dict:
    """Execute explicit PROPOSED source-to-destination predicate mappings.

    These predicates are not approved semantic rules merely because they pass.
    M01/M25 are exact transformations, not similarity tests. Persistence pairs
    make the human interpretation assumption visible with exact source anchors.
    Scheduler replacement is reported as a change, never an identity proof.
    """
    by_id = {r['id']: r for r in reg['rows']}
    checks = []
    m01 = by_id['M01']
    old, new = m01['source_value']['contract'], m01['destination_value']['contract']
    a = 'REV 006 retains'
    b = 'V4 FINAL / REV006 authority also requires'
    suffix = ' Candidate mutable position is read only from VPL_V5_CURRENT_STATE.json.'
    checks.append({'id': 'TR-M01', 'operator': 'EXACT_NAMED_SUBSTITUTION_AND_APPEND',
                   'source_id': 'M01', 'source_phrase': a, 'destination_phrase': b,
                   'append': suffix, 'predicate_pass': old.count(a) == 1 and new == old.replace(a,b) + suffix,
                   'semantic_adjudication': 'REQUIRED_NOT_INFERRED'})
    m25 = by_id['M25']
    suffix = ' A trigger while this module remains proposed must return UNCERTAIN_ESCALATE and STOP; owner activation is separate.'
    checks.append({'id': 'TR-M25', 'operator': 'EXACT_APPEND_WITH_ORIGINAL_CONTRACT_UNCHANGED',
                   'source_id': 'M25', 'append': suffix,
                   'predicate_pass': m25['destination_value']['contract'] == m25['source_value']['contract'] + suffix,
                   'semantic_adjudication': 'REQUIRED_NOT_INFERRED'})
    current = data['controls/PERSISTENCE_STATE_R02.md'].decode('utf-8')
    pairs = [
        ('M26', 'contract', 'Load all canonical V4 module semantics equally', 'loaded the full equal-priority semantic set', 'equal-priority full load'),
        ('M26', 'contract', 'balanced anti-parroting challenge plus behavioral proof', 'required balanced behavioral challenge', 'balanced challenge'),
        ('M26', 'contract', 'save complete receipt', 'banked a matching durable receipt with readback', 'durable source-bound receipt'),
        ('VPL-GL-15', 'requirement', 'Load every canonical V4 operating control with equal persistence priority', 'loaded the full equal-priority semantic set', 'equal-priority full load'),
        ('VPL-GL-15', 'requirement', 'balanced challenge coverage and immediate behavioral test', 'required balanced behavioral challenge', 'balanced challenge plus action-bound contract'),
        ('VPL-GL-15', 'requirement', 'Self-report, recap or selective retrieval is not evidence', 'a verbal recap, or a contract-test PASS alone cannot establish CURRENT', 'recap/test PASS insufficient'),
    ]
    for i, (rid, field, left, right, concept) in enumerate(pairs, 1):
        checks.append({'id': f'PR-{i:02}', 'operator': 'PROPOSED_LITERAL_ANCHORED_PROPOSITION_PAIR',
                       'concept': concept, 'source_id': rid, 'source_field': field,
                       'source_anchor': left, 'destination_file': 'controls/PERSISTENCE_STATE_R02.md',
                       'destination_anchor': right,
                       'predicate_pass': left in by_id[rid]['source_value'][field] and right in current,
                       'semantic_adjudication': 'PAIR_MEANING_REQUIRES_APPROVAL; matching anchors is not a general entailment proof'})
    a01, m26 = by_id['VPL-A01'], by_id['M26']
    scheduler_change = (a01['source_value'].get('schedule') != a01['destination_value'].get('schedule'))
    module_change = ('Hostinger 15-minute full-bundle producer' in m26['source_value']['contract'] and
                     'optional freshness/watchdog producer' in m26['destination_value']['contract'])
    return {'checks': checks, 'predicates_passed': sum(x['predicate_pass'] for x in checks),
            'predicates_total': len(checks),
            'cron_policy_difference_detected': scheduler_change and module_change,
            'cron_policy_classification': 'NONIDENTICAL_DESIGN_REQUIRES_EXPLICIT_OWNER_DISPOSITION',
            'rule_status': 'PROPOSED_FOR_SEMANTIC_ADJUDICATION_NOT_SELF_APPROVED'}


def verify_rules(rules: dict, spans: list[dict], offset: int, reg: dict,
                 matrix: bytes, entries: list[dict]) -> list[dict]:
    require(isinstance(rules, dict), 'rule model must be an object')
    require(rules.get('kind') == 'ACTION1_SOURCE_BOUND_RULE_MODEL_R01' and
            rules.get('rule_id') == MODEL_RULE, 'unknown rule model')
    require(rules.get('proof_scope') == 'BOUNDED_SPECIFICATION_MODEL_NOT_RUNTIME', 'scope overclaim')
    require(rules.get('v4_sha256') == V4_SHA and rules.get('candidate_sha256') == CANDIDATE_SHA,
            'rule source binding differs')
    require(rules.get('matrix_sha256') == sha(matrix), 'rule matrix binding differs')
    require(same(rules.get('v5_source_inventory'), entries), 'rule overlay inventory differs')
    require(same(rules.get('registry_comparison'), reg), 'rule registry values/context differ')
    maps = rules.get('span_mappings')
    require(isinstance(maps, list) and len(maps) == len(spans), 'rule mappings incomplete')
    out = []
    for expected, row in zip(spans, maps):
        require(isinstance(row, dict), 'span mapping must be an object')
        require(same(row.get('source_span'), expected), 'mapping source span altered or reordered')
        require(row.get('operator') == 'EXACT_SPAN_IN_COMPLETE_SOURCE_CONTEXT', 'unknown span operator')
        destination = {'file': V5_NAME, 'start_line': expected['start_line'] + offset,
                       'end_line': expected['end_line'] + offset, 'span_sha256': expected['span_sha256']}
        require(same(row.get('destination_span'), destination), 'mapping destination wrong')
        require(row.get('manual') == 'LOAD_ALL_PRESERVE_SOURCE_DEFINED_TRIGGERS' and
                row.get('light') == 'LOAD_ALL_PRESERVE_SOURCE_DEFINED_TRIGGERS', 'route/activation assumption changed')
        require(row.get('approval_requirement') == 'EXTERNAL_MODEL_ADJUDICATION', 'missing approval boundary')
        out.append({'span_id': expected['span_id'], 'source': expected,
                    'destination': destination, 'operator': row['operator'],
                    'manual': row['manual'], 'light': row['light'],
                    'mechanical_result': 'PASS_VERBATIM_SPECIFICATION_MAPPING',
                    'semantic_status': 'UNRESOLVED',
                    'reason': 'Exact-span/context predicate passes; this does not approve the inheritance/overlay semantic model.'})
    return out

def check_adjudication(raw: bytes | None, trusted_sha: str | None, rules_sha: str,
                       reg: dict) -> tuple[bool, dict]:
    """External trust input, not a signature, reviewer identity, or self-approval.

A future operator must supply BOTH an approval record and its independently
trusted SHA. This wave supplies no such record. Synthetic fixtures are tests only.
"""
    if raw is None:
        require(trusted_sha is None, 'approval hash without record')
        return False, {'state': 'NOT_SUPPLIED', 'identity_attested': False}
    require(trusted_sha is not None and bool(re.fullmatch('[0-9a-f]{64}', trusted_sha)) and
            sha(raw) == trusted_sha, 'untrusted approval record')
    a = load_json(raw)
    require(isinstance(a, dict), 'approval must be an object')
    require(a.get('kind') == 'ACTION1_EXTERNAL_SPECIFICATION_MODEL_ADJUDICATION_R01', 'wrong approval kind')
    require(a.get('rules_sha256') == rules_sha and a.get('candidate_sha256') == CANDIDATE_SHA and
            a.get('v4_sha256') == V4_SHA, 'approval binds different source/model')
    require(a.get('decision') == 'APPROVE_BOUNDED_SPECIFICATION_MODEL' and
            a.get('rule_id') == MODEL_RULE, 'no explicit semantic model approval')
    require(a.get('all_328_span_mappings_reviewed') is True and
            a.get('all_35_source_overlay_effects_reviewed') is True and
            a.get('wrapper_context_differences_reviewed') is True, 'incomplete interpretation review')
    for key in ('owner_decision_reference', 'independent_review_reference'):
        require(isinstance(a.get(key), str) and bool(a[key].strip()), 'missing approval provenance')
    ids = sorted(r['id'] for r in reg['rows'] if r['field_differences'])
    require(a.get('approved_changed_registry_ids') == ids, 'changed registry decisions incomplete')
    return True, {'state': 'SUPPLIED_HASH_PINNED_DECLARATION', 'sha256': sha(raw),
                  'owner_decision_reference': a['owner_decision_reference'],
                  'independent_review_reference': a['independent_review_reference'],
                  'identity_attested': False,
                  'trust_boundary': 'Supplied trusted hash and documentary declarations; authenticity/semantic judgment are external, not proved by this program.'}

def evaluate(candidate: bytes, authority: dict[str, bytes], rules_raw: bytes,
             adjudication: bytes | None = None, adjudication_sha: str | None = None) -> dict:
    require(sha(candidate) == CANDIDATE_SHA, 'candidate archive pin mismatch')
    data = read_archive(candidate)
    require(len(data) == 451 and git_tree(data) == CANDIDATE_TREE, 'candidate count/tree differs')
    for name, pin in AUTH_PINS.items():
        require(name in authority and sha(authority[name]) == pin, 'recovered authority pin mismatch: ' + name)
    v4 = authority[V4_NAME]
    manifest = load_json(authority['VPL_V4_EQUAL_LOAD_MANIFEST_REV006.json'])
    challenge = load_json(authority['PERSISTENCE_CHALLENGE_MATRIX_REV006.json'])
    sums = {line.split('  ', 1)[1]: line.split('  ', 1)[0]
            for line in authority['REV006_SHA256SUMS.txt'].decode().splitlines()}
    for name in (V4_NAME, 'VPL_V4_EQUAL_LOAD_MANIFEST_REV006.json', 'PERSISTENCE_CHALLENGE_MATRIX_REV006.json'):
        require(sums.get(name) == sha(authority[name]), 'recovered file fails original checksum record')
    blocks, block_proofs = source_blocks(v4, manifest)
    spans = derive_spans(v4)
    mapping = load_json(data[MAP])
    verify_source_map(mapping, spans, v4)
    offset, entries = verify_v5_bundle(data, v4)
    matrix = data[MATRIX]
    require(mapping.get('matrix_sha256') == sha(matrix), 'matrix/map hash mismatch')
    base_ids = re.findall(rb'^\| ((?:P|M|L|C)\d{2}) \|', matrix, re.M)
    h_ids = re.findall(rb'^\| (H\d{2}) \|', matrix, re.M)
    require(len(base_ids) == len(set(base_ids)) == 41 and h_ids == [f'H{i:02}'.encode() for i in range(1,8)], 'matrix rows missing/duplicated')
    reg = registry_comparison(blocks, data)
    rules = load_json(rules_raw)
    results = verify_rules(rules, spans, offset, reg, matrix, entries)
    translation = bounded_translation_checks(reg, data)
    require(same(rules.get('bounded_translation_checks'), translation), 'translation predicate mapping differs')
    require(translation['predicates_passed'] == translation['predicates_total'], 'bounded translation predicate failed')
    v4_lines = v4.splitlines(keepends=True)
    v5_lines = data[V5_NAME].splitlines(keepends=True)
    for result in results:
        a, b = result['source'], result['destination']
        aa = b''.join(v4_lines[a['start_line']-1:a['end_line']])
        bb = b''.join(v5_lines[b['start_line']-1:b['end_line']])
        require(aa == bb and sha(aa) == a['span_sha256'], 'actual mapped span differs')
    # Evaluate authoritative machine-readable persistence predicates, without
    # pretending a schema/challenge definition is an executed behavioral proof.
    require(manifest.get('no_priority_weighting') is True, 'equal-priority invariant missing')
    require(challenge.get('mutation_requirement') == 'PERSISTENCE_STATE=CURRENT', 'mutation invariant missing')
    require(challenge.get('proofs') == ['semantic_completeness', 'cross_reference_understanding',
                                      'false_premise_rejection', 'behavioral_follow_through'], 'proof requirement differs')
    approved, approval = check_adjudication(adjudication, adjudication_sha, sha(rules_raw), reg)
    if approved:
        for result in results:
            result['semantic_status'] = 'EQUIVALENT_UNDER_EXTERNALLY_APPROVED_BOUNDED_MODEL'
            result['reason'] = 'Derived exact-span/context predicate passed under the hash-pinned external model adjudication; no runtime claim.'
    missing = [name for name in ('VPL_V4_EQUAL_LOAD_MANIFEST_REV006.json', 'PERSISTENCE_CHALLENGE_MATRIX_REV006.json')
               if not any(PurePosixPath(p).name == name for p in data)]
    return {'kind': 'SEMANTIC_EQUIVALENCE_RECEIPT_R08_ACTION1_R01',
            'result': 'PASS_UNDER_EXTERNALLY_APPROVED_BOUNDED_MODEL' if approved else 'MECHANICAL_PASS_SEMANTIC_APPROVAL_PENDING',
            'exit_code': 0 if approved else 3,
            'total_spans': len(results), 'mechanically_verified_spans': len(results),
            'resolved': len(results) if approved else 0,
            'unresolved': 0 if approved else len(results),
            'r2_m01_closed': False, 'closure_note': 'Independent coordinator/owner closure is external; this tool never promotes the finding.',
            'proof_scope': 'BOUNDED_SPECIFICATION_MODEL_NOT_RUNTIME',
            'verifier_sha256': sha(Path(__file__).read_bytes()),
            'source_binding': {'candidate_archive_sha256': sha(candidate), 'candidate_git_tree': git_tree(data),
                               'candidate_files': len(data), 'v4_bundle_sha256': sha(v4),
                               'v5_bundle_sha256': sha(data[V5_NAME]), 'matrix_sha256': sha(matrix),
                               'rule_model_sha256': sha(rules_raw)},
            'source_blocks': block_proofs, 'v5_source_inventory': entries,
            'matrix_base_rows_verified': 41, 'matrix_h_rows_verified': 7,
            'registry_comparison': reg, 'bounded_translation_checks': translation, 'external_model_adjudication': approval,
            'recovered_authority_files': [{'file': n, 'sha256': sha(authority[n]),
                                          'original_checksum_matches': True} for n in AUTH_PINS if n != 'REV006_SHA256SUMS.txt'],
            'supplemented_original_candidate_omissions': missing,
            'supplement_note': 'Recovered V4 authority accompanies the sidecar; missing originals were NOT inserted into or backdated into frozen candidate.',
            'persistence_definition_checks': {'equal_priority': True, 'complete_29_sources': True,
                                            'balanced_four_proofs_required': True, 'runtime_proofs_executed': False},
            'results': results,
            'zero_manual_decisions_during_execution': True,
            'rule_authorship_and_semantic_adjudication_are_not_automated': True,
            'arbitrary_natural_language_conflicts_exhaustively_detected': False,
            'runtime_or_model_persistence_certified': False, 'candidate_code_executed': False,
            'source_written': False, 'score_change_established': False}

def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--candidate', type=Path, required=True)
    parser.add_argument('--v4-authority', type=Path, required=True)
    parser.add_argument('--rules', type=Path, required=True)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--adjudication', type=Path)
    parser.add_argument('--adjudication-sha256')
    args = parser.parse_args(argv)
    try:
        require(not args.output.exists(), 'refusing to overwrite existing output')
        require(args.output.parent.is_dir(), 'output directory must already exist')
        authority = {n: (args.v4_authority/n).read_bytes() for n in AUTH_PINS}
        receipt = evaluate(args.candidate.read_bytes(), authority, args.rules.read_bytes(),
                           args.adjudication.read_bytes() if args.adjudication else None,
                           args.adjudication_sha256)
        with args.output.open('xb') as f:
            f.write(canonical(receipt))
        print(json.dumps({'result': receipt['result'], 'total_spans': receipt['total_spans'],
                          'mechanically_verified_spans': receipt['mechanically_verified_spans'],
                          'resolved': receipt['resolved'], 'unresolved': receipt['unresolved'],
                          'receipt_sha256': sha(args.output.read_bytes())}, sort_keys=True))
        return receipt['exit_code']
    except (InvalidInput, OSError, KeyError, TypeError, IndexError) as e:
        print(json.dumps({'result': 'INPUT_REJECTED', 'error': str(e)}, sort_keys=True), file=sys.stderr)
        return 2

if __name__ == '__main__':
    sys.exit(main())
action3/check_t01_resume.py

14,677 bytes · SHA-256 92d436e1ebb17411186d764d81d6883daa35e455264b6096553641c39d45b861

Download exact source file

#!/usr/bin/env python3
"""Bounded T01 confirmation harness; only disposable output directories are written.
Uses real source preflight and runner execution, never journal-supplied executable code.
ACTION3 R01 integrates a test-only source-frame stall for --timeout-only. The fault
uses a real subprocess timeout; normal execution and final resume are uninjected.
No production/runtime certification or semantic-equivalence proof is implied.
"""
from __future__ import annotations
import argparse,copy,hashlib,importlib.util,json,math,os,runpy,shutil,subprocess,sys,time,types
sys.dont_write_bytecode = True
from pathlib import Path
from datetime import datetime,timezone

def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def write(p,d):Path(p).write_text(json.dumps(d,indent=2)+'\n')

# ACTION3 R01: test-only fault injection, never a candidate-source patch.
# The real selected source frame is held before its first statement. The parent
# waits for that handshake before starting a real subprocess timeout. Startup
# speed and the runtime of unrelated commands therefore cannot select the fault.

def positive_seconds(value):
 value=float(value)
 if not math.isfinite(value) or value <= 0:
  raise argparse.ArgumentTypeError('timing must be finite and positive')
 return value

def nonnegative_seconds(value):
 value=float(value)
 if not math.isfinite(value) or value < 0:
  raise argparse.ArgumentTypeError('delay must be finite and nonnegative')
 return value

def wait_for_source_frame(proc,ready,target,limit):
 deadline=time.monotonic()+limit
 while not ready.exists():
  code=proc.poll()
  if code is not None:
   raise RuntimeError('fault child exited before source-frame handshake: '+str(code))
  if time.monotonic() >= deadline:
   raise RuntimeError('source-frame handshake deadline exceeded; NOT a verified timeout')
  time.sleep(0.01)
 event=json.loads(ready.read_text())
 if (event.get('kind')!='ACTION3_SOURCE_FRAME_STALL' or
     event.get('pid')!=proc.pid or event.get('target')!=str(target) or
     event.get('target_sha256')!=sha(target)):
  raise RuntimeError('invalid source-frame handshake')
 return event

def run_with_source_stall(command,ready,timeout_seconds,ready_seconds,startup_delay,**kwargs):
 """Run actual source through a test-only entry-frame gate; raise real timeout."""
 if not isinstance(command,list) or len(command)<3 or command[1]!='-B':
  raise ValueError('unexpected source command shape')
 target=Path(command[2]).resolve()
 if ready.exists():
  raise ValueError('refusing existing fault evidence')
 gated=[sys.executable,'-B',str(Path(__file__).resolve()),'--action3-gated-child',
        str(ready),str(startup_delay),str(target),*command[3:]]
 kwargs.pop('timeout',None)  # Start fault budget ONLY after the handshake.
 proc=subprocess.Popen(gated,**kwargs)
 try:
  wait_for_source_frame(proc,ready,target,ready_seconds)
  # This is the real subprocess wait, not a fabricated exception or exit code.
  code=proc.wait(timeout=timeout_seconds)
  return subprocess.CompletedProcess(command,code)
 finally:
  if proc.poll() is None:
   proc.kill()
  proc.wait()

def gated_child(argv):
 ready=Path(argv[0]);delay=nonnegative_seconds(argv[1]);target=Path(argv[2]).resolve()
 if ready.exists():
  raise ValueError('ready path already exists')
 time.sleep(delay)  # Optional explicit slow-start regression fixture.
 sys.argv=[str(target),*argv[3:]];sys.path.insert(0,str(target.parent))
 def at_source(frame,event,arg):
  if event=='call' and frame.f_code.co_filename==str(target):
   body={'kind':'ACTION3_SOURCE_FRAME_STALL','pid':os.getpid(),
         'target':str(target),'target_sha256':sha(target),
         'phase':'before_first_statement','test_only':True}
   temp=ready.with_suffix('.pending');write(temp,body);temp.replace(ready)
   print('ACTION3 TEST-ONLY STALL: '+str(target),flush=True)
   while True:time.sleep(3600)  # Parent kills this process on its bounded timeout.
  return at_source
 sys.settrace(at_source)
 try:runpy.run_path(str(target),run_name='__main__')
 finally:sys.settrace(None)
 raise RuntimeError('target frame was never intercepted')

def subprocess_proxy(run):
 return types.SimpleNamespace(**dict(vars(subprocess),run=run))

def fault_runner(argv):
 script=Path(argv[0]).resolve();index=int(argv[1]);ready=Path(argv[2]).resolve()
 budget=positive_seconds(argv[3]);startup=positive_seconds(argv[4]);delay=nonnegative_seconds(argv[5])
 sys.path.insert(0,str(script.parent))
 spec=importlib.util.spec_from_file_location('action3_frozen_runner',script)
 module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
 plan=module.command_plan()
 if not 1<=index<=len(plan):raise ValueError('fault index outside actual plan')
 target_name=plan[index-1][0]
 if sum(name==target_name for name,_ in plan)!=1:raise ValueError('ambiguous fault target')
 injected=[]
 def controlled_run(command,**kwargs):
  if len(command)>=3 and Path(command[2]).name==target_name:
   if injected:raise RuntimeError('duplicate injection attempt')
   injected.append(target_name)
   return run_with_source_stall(command,ready,budget,startup,delay,**kwargs)
  return subprocess.run(command,**kwargs)
 # Change only this imported runner's subprocess binding for this fault run.
 # Do not patch the global subprocess module, source files, plan, hashes or receipts.
 module.subprocess=subprocess_proxy(controlled_run)
 sys.argv=[str(script),*argv[6:]]
 code=module.main()
 if not injected:raise RuntimeError('requested fault was not reached')
 return code

def validate_timeout_checkpoint(seed,journal,failure,index):
 """Derived state checks: no completed work may be credited to a failed attempt."""
 checks=[
  (failure.get('result')=='FAIL','missing failed reproduction receipt'),
  (journal.get('commands')==seed.get('commands'),'verified checkpoint advanced or changed'),
  (len(journal.get('attempts',[]))==len(seed.get('attempts',[]))+1,'unexpected attempt count'),
  (journal.get('state')=='FAILED_OR_INCOMPLETE','journal not marked failed/incomplete'),
 ]
 for passed,reason in checks:
  if not passed:raise AssertionError(reason)
 attempt=journal['attempts'][-1]
 if (attempt.get('index')!=index or attempt.get('exit_code')!=124 or
     attempt.get('state')!='FAILED_OR_INCOMPLETE'):
  raise AssertionError('requested command did not record a genuine incomplete timeout')
 return attempt

def main():
 if sys.flags.optimize:raise RuntimeError('Run without -O / PYTHONOPTIMIZE; assertions must be enabled')
 p=argparse.ArgumentParser(description=__doc__);p.add_argument('--candidate',type=Path,required=True);p.add_argument('--archive',type=Path,required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--actor',required=True);p.add_argument('--session',required=True);p.add_argument('--timeout-only',action='store_true');p.add_argument('--fault-at',type=int,default=3);p.add_argument('--fault-timeout',type=positive_seconds,default=0.2);p.add_argument('--fault-ready-timeout',type=positive_seconds,default=30.0);p.add_argument('--fault-startup-delay',type=nonnegative_seconds,default=0.0);p.add_argument('--runner-timeout',type=positive_seconds,default=600.0);a=p.parse_args()
 if not 2<=a.fault_at<=12:p.error('--fault-at must be between 2 and 12')
 C=a.candidate.resolve();A=a.archive.resolve();O=a.out.resolve()
 if O.exists():raise ValueError('Output must be new; preserve previous evidence')
 if O==C or O.is_relative_to(C) or C.is_relative_to(O):raise ValueError('Source/output must be disjoint')
 O.mkdir(parents=True);results=[];run=O/'legitimate'
 initial={q.relative_to(C).as_posix():sha(q) for q in C.rglob('*') if q.is_file()}
 script=C/'runner/verify_review_packet.py'
 def invoke(label,out,extra=(),actor=None,archive=None,expected=0,fault=False):
  log=O/(label+'.log');cmd=[sys.executable,'-B',str(script),'--actor',actor or a.actor,'--session',a.session,'--out',str(out),'--predecessor-archive',str(archive or A),*extra]
  if fault:
   cmd=[sys.executable,'-B',str(Path(__file__).resolve()),'--action3-fault-runner',str(script),str(a.fault_at),str(O/'FAULT_READY.json'),str(a.fault_timeout),str(a.fault_ready_timeout),str(a.fault_startup_delay),*cmd[3:]]
  start=time.monotonic()
  with log.open('wb') as f:r=subprocess.run(cmd,stdout=f,stderr=subprocess.STDOUT,timeout=a.runner_timeout)
  record={'id':label,'exit_code':r.returncode,'expected_exit_code':expected,'pass':r.returncode==expected,'log':log.name,'log_sha256':sha(log),'seconds':round(time.monotonic()-start,3)}
  results.append(record);write(O/'CHECKS.json',results);print(json.dumps(record),flush=True)
  if not record['pass']:raise AssertionError(label+' returned unexpected exit code')
  return log
 if a.timeout_only:
  checkpoint=a.fault_at-1
  invoke('pause_after_'+str(checkpoint),run,['--stop-after',str(checkpoint)],expected=75)
  seed=json.loads((run/'COMMAND_PROGRESS.json').read_text())
  assert len(seed['commands'])==checkpoint
  invoke('forced_timeout',run,['--resume'],expected=1,fault=True)
  failure_path=run/'REVIEWER_REPRODUCTION_RECEIPT.json'
  failure=json.loads(failure_path.read_text())
  journal=json.loads((run/'COMMAND_PROGRESS.json').read_text())
  # A failed attempt must not advance the verified checkpoint or invent a PASS.
  failed_attempt=validate_timeout_checkpoint(seed,journal,failure,a.fault_at)
  ready=json.loads((O/'FAULT_READY.json').read_text())
  target=Path(ready['target']);assert target.name==seed['plan'][a.fault_at-1][0]
  assert ready['target_sha256']==sha(C/'runner'/target.name)
  failure_bytes=failure_path.read_bytes();failure_hash=sha(failure_path)
  invoke('resume_after_timeout',run,['--resume'],expected=0)
  receipt=json.loads(failure_path.read_text())
  assert (run/'receipt_history'/f'{failure_hash}.json').read_bytes()==failure_bytes
  journal=json.loads((run/'COMMAND_PROGRESS.json').read_text())
  assert journal['commands'][:checkpoint]==seed['commands']
  assert failed_attempt in journal['attempts']
  assert len(journal['attempts'])==len(seed['plan'])+1
  assert [row['index'] for row in journal['commands']]==list(range(1,len(seed['plan'])+1))
  assert receipt['resumptions'][-1]['completed_commands_restored']==checkpoint
  results.append({'id':'failed_attempt_and_receipt_preserved','pass':True,
                  'failed_receipt_sha256':failure_hash,'fault_at_command':a.fault_at,
                  'completed_commands_restored':checkpoint,
                  'fault_mode':'test-only source-frame stall; real subprocess timeout',
                  'fault_timeout_seconds':a.fault_timeout,
                  'startup_handshake_timeout_seconds':a.fault_ready_timeout,
                  'configured_startup_delay_seconds':a.fault_startup_delay,
                  'fault_ready_sha256':sha(O/'FAULT_READY.json'),
                  'resume_mode':'unmodified real runner; no injection'})
 else:
  invoke('pause_after_9',run,['--stop-after','9'],expected=75)
  seed=json.loads((run/'COMMAND_PROGRESS.json').read_text());assert len(seed['commands'])==9
  # These are not copies of a real user edit. They intentionally forge journals in disposable fixtures.
  for kind in ('replace','add','delete'):
   dest=O/('tampered_'+kind);shutil.copytree(run,dest)
   journal=copy.deepcopy(seed);target='runner/t01_added_fixture.py' if kind=='add' else 'runner/test_hf03.py'
   if kind=='delete':delta={'path':target,'deleted':True}
   else:
    artifact=dest/'forged_fixture.py';artifact.write_text("raise RuntimeError('T01 FORGED FIXTURE MUST NOT EXECUTE')\n")
    delta={'path':target,'artifact':artifact.name,'sha256':sha(artifact)}
   journal['commands'][-1]['delta'].append(delta);write(dest/'COMMAND_PROGRESS.json',journal)
   before=len(journal['attempts']);log=invoke('reject_'+kind,dest,['--resume'],expected=2)
   assert 'delta outside writable evidence scope: '+target in log.read_text()
   after=json.loads((dest/'COMMAND_PROGRESS.json').read_text());assert len(after['attempts'])==before
   results.append({'id':kind+'_rejected_before_next_execution','pass':True,'target':target})
  wrong=O/'wrong_actor';shutil.copytree(run,wrong);invoke('wrong_actor',wrong,['--resume'],actor=a.actor+'-OTHER',expected=2)
  wrong=O/'wrong_archive';shutil.copytree(run,wrong);bad=O/'incorrect_archive.zip';bad.write_bytes(b'wrong-archive-fixture');invoke('wrong_archive',wrong,['--resume'],archive=bad,expected=2)
  # Valid restart must discard an unrecorded mutation, then execute only remaining commands.
  (run/'isolated-candidate/runner/unrecorded_interruption.py').write_text('# abandoned scratch mutation\n')
  invoke('legitimate_resume',run,['--resume'],expected=0)
  assert not (run/'isolated-candidate/runner/unrecorded_interruption.py').exists()
  receipt=json.loads((run/'REVIEWER_REPRODUCTION_RECEIPT.json').read_text());journal=json.loads((run/'COMMAND_PROGRESS.json').read_text())
  assert [x['index'] for x in journal['commands']]==list(range(1,13)) and len(journal['attempts'])==12
  assert receipt['resumptions'][-1]['completed_commands_restored']==9
  results.append({'id':'exactly_remaining_commands_executed','pass':True,'restored':9,'executed_after_resume':[10,11,12]})
 assert receipt['result']=='PASS' and receipt['recounted_tests']['failed']==receipt['recounted_tests']['not_run']==0
 exact=[]
 for row in receipt['result_comparisons']:
  output=run/'reports'/Path(row['path']).name
  equal=output.read_bytes()==(C/row['path']).read_bytes();assert equal
  exact.append({'path':row['path'],'sha256':sha(output),'byte_identical':equal,'recounted':row['recounted']})
 final={q.relative_to(C).as_posix():sha(q) for q in C.rglob('*') if q.is_file()};assert initial==final
 write(O/'CHECKS.json',results)
 report={'kind':'T01_FORCED_INTERRUPTION_CONFIRMATION' if a.timeout_only else 'T01_REAL_RUNNER_RESUME_CONFIRMATION','result':'PASS','actor':a.actor,'session':a.session,'at_utc':datetime.now(timezone.utc).isoformat(),'source_files':len(initial),'source_unchanged':True,'state_sha256':sha(C/'VPL_V5_CURRENT_STATE.json'),'reproduction_receipt_sha256':sha(run/'REVIEWER_REPRODUCTION_RECEIPT.json'),'commands':len(receipt['commands']),'recounted':receipt['recounted_tests'],'reports':exact,'checks':results,'boundary':'Executing actor evidence only. Not independent reviewer acceptance, authenticated identity, provider or production certification.'}
 write(O/'SUMMARY.json',report);print(json.dumps({'result':report['result'],'recounted':report['recounted'],'reports':len(exact)}),flush=True)
if __name__=='__main__':
 if len(sys.argv)>1 and sys.argv[1]=='--action3-gated-child':gated_child(sys.argv[2:])
 elif len(sys.argv)>1 and sys.argv[1]=='--action3-fault-runner':sys.exit(fault_runner(sys.argv[2:]))
 else:main()
action3/check_t01_resume.py.diff

14,311 bytes · SHA-256 effd3dc40d78da47455f65daee188d4c0c45d752f7f8cbc2a08a79db7e33c304

Download exact source file

--- frozen-handoff/check_t01_resume.py
+++ ACTION3_TIMEOUT_R01/source/check_t01_resume.py
@@ -1,40 +1,190 @@
 #!/usr/bin/env python3
 """Bounded T01 confirmation harness; only disposable output directories are written.
 Uses real source preflight and runner execution, never journal-supplied executable code.
+ACTION3 R01 integrates a test-only source-frame stall for --timeout-only. The fault
+uses a real subprocess timeout; normal execution and final resume are uninjected.
+No production/runtime certification or semantic-equivalence proof is implied.
 """
 from __future__ import annotations
-import argparse,copy,hashlib,json,os,shutil,subprocess,sys,time
+import argparse,copy,hashlib,importlib.util,json,math,os,runpy,shutil,subprocess,sys,time,types
+sys.dont_write_bytecode = True
 from pathlib import Path
 from datetime import datetime,timezone
 
 def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
 def write(p,d):Path(p).write_text(json.dumps(d,indent=2)+'\n')
+
+# ACTION3 R01: test-only fault injection, never a candidate-source patch.
+# The real selected source frame is held before its first statement. The parent
+# waits for that handshake before starting a real subprocess timeout. Startup
+# speed and the runtime of unrelated commands therefore cannot select the fault.
+
+def positive_seconds(value):
+ value=float(value)
+ if not math.isfinite(value) or value <= 0:
+  raise argparse.ArgumentTypeError('timing must be finite and positive')
+ return value
+
+def nonnegative_seconds(value):
+ value=float(value)
+ if not math.isfinite(value) or value < 0:
+  raise argparse.ArgumentTypeError('delay must be finite and nonnegative')
+ return value
+
+def wait_for_source_frame(proc,ready,target,limit):
+ deadline=time.monotonic()+limit
+ while not ready.exists():
+  code=proc.poll()
+  if code is not None:
+   raise RuntimeError('fault child exited before source-frame handshake: '+str(code))
+  if time.monotonic() >= deadline:
+   raise RuntimeError('source-frame handshake deadline exceeded; NOT a verified timeout')
+  time.sleep(0.01)
+ event=json.loads(ready.read_text())
+ if (event.get('kind')!='ACTION3_SOURCE_FRAME_STALL' or
+     event.get('pid')!=proc.pid or event.get('target')!=str(target) or
+     event.get('target_sha256')!=sha(target)):
+  raise RuntimeError('invalid source-frame handshake')
+ return event
+
+def run_with_source_stall(command,ready,timeout_seconds,ready_seconds,startup_delay,**kwargs):
+ """Run actual source through a test-only entry-frame gate; raise real timeout."""
+ if not isinstance(command,list) or len(command)<3 or command[1]!='-B':
+  raise ValueError('unexpected source command shape')
+ target=Path(command[2]).resolve()
+ if ready.exists():
+  raise ValueError('refusing existing fault evidence')
+ gated=[sys.executable,'-B',str(Path(__file__).resolve()),'--action3-gated-child',
+        str(ready),str(startup_delay),str(target),*command[3:]]
+ kwargs.pop('timeout',None)  # Start fault budget ONLY after the handshake.
+ proc=subprocess.Popen(gated,**kwargs)
+ try:
+  wait_for_source_frame(proc,ready,target,ready_seconds)
+  # This is the real subprocess wait, not a fabricated exception or exit code.
+  code=proc.wait(timeout=timeout_seconds)
+  return subprocess.CompletedProcess(command,code)
+ finally:
+  if proc.poll() is None:
+   proc.kill()
+  proc.wait()
+
+def gated_child(argv):
+ ready=Path(argv[0]);delay=nonnegative_seconds(argv[1]);target=Path(argv[2]).resolve()
+ if ready.exists():
+  raise ValueError('ready path already exists')
+ time.sleep(delay)  # Optional explicit slow-start regression fixture.
+ sys.argv=[str(target),*argv[3:]];sys.path.insert(0,str(target.parent))
+ def at_source(frame,event,arg):
+  if event=='call' and frame.f_code.co_filename==str(target):
+   body={'kind':'ACTION3_SOURCE_FRAME_STALL','pid':os.getpid(),
+         'target':str(target),'target_sha256':sha(target),
+         'phase':'before_first_statement','test_only':True}
+   temp=ready.with_suffix('.pending');write(temp,body);temp.replace(ready)
+   print('ACTION3 TEST-ONLY STALL: '+str(target),flush=True)
+   while True:time.sleep(3600)  # Parent kills this process on its bounded timeout.
+  return at_source
+ sys.settrace(at_source)
+ try:runpy.run_path(str(target),run_name='__main__')
+ finally:sys.settrace(None)
+ raise RuntimeError('target frame was never intercepted')
+
+def subprocess_proxy(run):
+ return types.SimpleNamespace(**dict(vars(subprocess),run=run))
+
+def fault_runner(argv):
+ script=Path(argv[0]).resolve();index=int(argv[1]);ready=Path(argv[2]).resolve()
+ budget=positive_seconds(argv[3]);startup=positive_seconds(argv[4]);delay=nonnegative_seconds(argv[5])
+ sys.path.insert(0,str(script.parent))
+ spec=importlib.util.spec_from_file_location('action3_frozen_runner',script)
+ module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
+ plan=module.command_plan()
+ if not 1<=index<=len(plan):raise ValueError('fault index outside actual plan')
+ target_name=plan[index-1][0]
+ if sum(name==target_name for name,_ in plan)!=1:raise ValueError('ambiguous fault target')
+ injected=[]
+ def controlled_run(command,**kwargs):
+  if len(command)>=3 and Path(command[2]).name==target_name:
+   if injected:raise RuntimeError('duplicate injection attempt')
+   injected.append(target_name)
+   return run_with_source_stall(command,ready,budget,startup,delay,**kwargs)
+  return subprocess.run(command,**kwargs)
+ # Change only this imported runner's subprocess binding for this fault run.
+ # Do not patch the global subprocess module, source files, plan, hashes or receipts.
+ module.subprocess=subprocess_proxy(controlled_run)
+ sys.argv=[str(script),*argv[6:]]
+ code=module.main()
+ if not injected:raise RuntimeError('requested fault was not reached')
+ return code
+
+def validate_timeout_checkpoint(seed,journal,failure,index):
+ """Derived state checks: no completed work may be credited to a failed attempt."""
+ checks=[
+  (failure.get('result')=='FAIL','missing failed reproduction receipt'),
+  (journal.get('commands')==seed.get('commands'),'verified checkpoint advanced or changed'),
+  (len(journal.get('attempts',[]))==len(seed.get('attempts',[]))+1,'unexpected attempt count'),
+  (journal.get('state')=='FAILED_OR_INCOMPLETE','journal not marked failed/incomplete'),
+ ]
+ for passed,reason in checks:
+  if not passed:raise AssertionError(reason)
+ attempt=journal['attempts'][-1]
+ if (attempt.get('index')!=index or attempt.get('exit_code')!=124 or
+     attempt.get('state')!='FAILED_OR_INCOMPLETE'):
+  raise AssertionError('requested command did not record a genuine incomplete timeout')
+ return attempt
+
 def main():
- p=argparse.ArgumentParser(description=__doc__);p.add_argument('--candidate',type=Path,required=True);p.add_argument('--archive',type=Path,required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--actor',required=True);p.add_argument('--session',required=True);p.add_argument('--timeout-only',action='store_true');a=p.parse_args()
+ if sys.flags.optimize:raise RuntimeError('Run without -O / PYTHONOPTIMIZE; assertions must be enabled')
+ p=argparse.ArgumentParser(description=__doc__);p.add_argument('--candidate',type=Path,required=True);p.add_argument('--archive',type=Path,required=True);p.add_argument('--out',type=Path,required=True);p.add_argument('--actor',required=True);p.add_argument('--session',required=True);p.add_argument('--timeout-only',action='store_true');p.add_argument('--fault-at',type=int,default=3);p.add_argument('--fault-timeout',type=positive_seconds,default=0.2);p.add_argument('--fault-ready-timeout',type=positive_seconds,default=30.0);p.add_argument('--fault-startup-delay',type=nonnegative_seconds,default=0.0);p.add_argument('--runner-timeout',type=positive_seconds,default=600.0);a=p.parse_args()
+ if not 2<=a.fault_at<=12:p.error('--fault-at must be between 2 and 12')
  C=a.candidate.resolve();A=a.archive.resolve();O=a.out.resolve()
  if O.exists():raise ValueError('Output must be new; preserve previous evidence')
  if O==C or O.is_relative_to(C) or C.is_relative_to(O):raise ValueError('Source/output must be disjoint')
  O.mkdir(parents=True);results=[];run=O/'legitimate'
  initial={q.relative_to(C).as_posix():sha(q) for q in C.rglob('*') if q.is_file()}
  script=C/'runner/verify_review_packet.py'
- def invoke(label,out,extra=(),actor=None,archive=None,expected=0):
-  log=O/(label+'.log');cmd=[sys.executable,'-B',str(script),'--actor',actor or a.actor,'--session',a.session,'--out',str(out),'--predecessor-archive',str(archive or A),*extra];start=time.time()
-  with log.open('wb') as f:r=subprocess.run(cmd,stdout=f,stderr=subprocess.STDOUT,timeout=600)
-  record={'id':label,'exit_code':r.returncode,'expected_exit_code':expected,'pass':r.returncode==expected,'log':log.name,'log_sha256':sha(log),'seconds':round(time.time()-start,3)}
+ def invoke(label,out,extra=(),actor=None,archive=None,expected=0,fault=False):
+  log=O/(label+'.log');cmd=[sys.executable,'-B',str(script),'--actor',actor or a.actor,'--session',a.session,'--out',str(out),'--predecessor-archive',str(archive or A),*extra]
+  if fault:
+   cmd=[sys.executable,'-B',str(Path(__file__).resolve()),'--action3-fault-runner',str(script),str(a.fault_at),str(O/'FAULT_READY.json'),str(a.fault_timeout),str(a.fault_ready_timeout),str(a.fault_startup_delay),*cmd[3:]]
+  start=time.monotonic()
+  with log.open('wb') as f:r=subprocess.run(cmd,stdout=f,stderr=subprocess.STDOUT,timeout=a.runner_timeout)
+  record={'id':label,'exit_code':r.returncode,'expected_exit_code':expected,'pass':r.returncode==expected,'log':log.name,'log_sha256':sha(log),'seconds':round(time.monotonic()-start,3)}
   results.append(record);write(O/'CHECKS.json',results);print(json.dumps(record),flush=True)
   if not record['pass']:raise AssertionError(label+' returned unexpected exit code')
   return log
  if a.timeout_only:
-  invoke('pause_after_2',run,['--stop-after','2'],expected=75)
-  invoke('forced_timeout',run,['--resume','--command-timeout','1'],expected=1)
-  failure=json.loads((run/'REVIEWER_REPRODUCTION_RECEIPT.json').read_text());assert failure['result']=='FAIL'
-  journal=json.loads((run/'COMMAND_PROGRESS.json').read_text());assert len(journal['commands'])==2 and journal['attempts'][-1]['exit_code']==124
-  failure_hash=sha(run/'REVIEWER_REPRODUCTION_RECEIPT.json')
+  checkpoint=a.fault_at-1
+  invoke('pause_after_'+str(checkpoint),run,['--stop-after',str(checkpoint)],expected=75)
+  seed=json.loads((run/'COMMAND_PROGRESS.json').read_text())
+  assert len(seed['commands'])==checkpoint
+  invoke('forced_timeout',run,['--resume'],expected=1,fault=True)
+  failure_path=run/'REVIEWER_REPRODUCTION_RECEIPT.json'
+  failure=json.loads(failure_path.read_text())
+  journal=json.loads((run/'COMMAND_PROGRESS.json').read_text())
+  # A failed attempt must not advance the verified checkpoint or invent a PASS.
+  failed_attempt=validate_timeout_checkpoint(seed,journal,failure,a.fault_at)
+  ready=json.loads((O/'FAULT_READY.json').read_text())
+  target=Path(ready['target']);assert target.name==seed['plan'][a.fault_at-1][0]
+  assert ready['target_sha256']==sha(C/'runner'/target.name)
+  failure_bytes=failure_path.read_bytes();failure_hash=sha(failure_path)
   invoke('resume_after_timeout',run,['--resume'],expected=0)
-  receipt=json.loads((run/'REVIEWER_REPRODUCTION_RECEIPT.json').read_text())
-  assert (run/'receipt_history'/f'{failure_hash}.json').is_file()
-  journal=json.loads((run/'COMMAND_PROGRESS.json').read_text());assert any(x.get('exit_code')==124 for x in journal['attempts'])
-  results.append({'id':'failed_attempt_and_receipt_preserved','pass':True,'failed_receipt_sha256':failure_hash,'completed_commands_restored':receipt['resumptions'][-1]['completed_commands_restored']})
+  receipt=json.loads(failure_path.read_text())
+  assert (run/'receipt_history'/f'{failure_hash}.json').read_bytes()==failure_bytes
+  journal=json.loads((run/'COMMAND_PROGRESS.json').read_text())
+  assert journal['commands'][:checkpoint]==seed['commands']
+  assert failed_attempt in journal['attempts']
+  assert len(journal['attempts'])==len(seed['plan'])+1
+  assert [row['index'] for row in journal['commands']]==list(range(1,len(seed['plan'])+1))
+  assert receipt['resumptions'][-1]['completed_commands_restored']==checkpoint
+  results.append({'id':'failed_attempt_and_receipt_preserved','pass':True,
+                  'failed_receipt_sha256':failure_hash,'fault_at_command':a.fault_at,
+                  'completed_commands_restored':checkpoint,
+                  'fault_mode':'test-only source-frame stall; real subprocess timeout',
+                  'fault_timeout_seconds':a.fault_timeout,
+                  'startup_handshake_timeout_seconds':a.fault_ready_timeout,
+                  'configured_startup_delay_seconds':a.fault_startup_delay,
+                  'fault_ready_sha256':sha(O/'FAULT_READY.json'),
+                  'resume_mode':'unmodified real runner; no injection'})
  else:
   invoke('pause_after_9',run,['--stop-after','9'],expected=75)
   seed=json.loads((run/'COMMAND_PROGRESS.json').read_text());assert len(seed['commands'])==9
@@ -71,4 +221,7 @@
  write(O/'CHECKS.json',results)
  report={'kind':'T01_FORCED_INTERRUPTION_CONFIRMATION' if a.timeout_only else 'T01_REAL_RUNNER_RESUME_CONFIRMATION','result':'PASS','actor':a.actor,'session':a.session,'at_utc':datetime.now(timezone.utc).isoformat(),'source_files':len(initial),'source_unchanged':True,'state_sha256':sha(C/'VPL_V5_CURRENT_STATE.json'),'reproduction_receipt_sha256':sha(run/'REVIEWER_REPRODUCTION_RECEIPT.json'),'commands':len(receipt['commands']),'recounted':receipt['recounted_tests'],'reports':exact,'checks':results,'boundary':'Executing actor evidence only. Not independent reviewer acceptance, authenticated identity, provider or production certification.'}
  write(O/'SUMMARY.json',report);print(json.dumps({'result':report['result'],'recounted':report['recounted'],'reports':len(exact)}),flush=True)
-if __name__=='__main__':main()
+if __name__=='__main__':
+ if len(sys.argv)>1 and sys.argv[1]=='--action3-gated-child':gated_child(sys.argv[2:])
+ elif len(sys.argv)>1 and sys.argv[1]=='--action3-fault-runner':sys.exit(fault_runner(sys.argv[2:]))
+ else:main()
action4/dedup_ledger.py

16,536 bytes · SHA-256 8fd6fbe4d62dae365051ecabbabcfafc03508a93ec584d47bf790bb7d5fcec3f

Download exact source file

#!/usr/bin/env python3
"""Deterministic, preservation-first pre-ingestion gate for the VPL R05 intake.

Standard-library only. No model, network, scoring, semantic matching or source edits.
Exact payload equality is NOT proof of shared authorship or independent execution.
Original IDs/rows/provenance remain in every emitted ledger. Nothing is deleted.
"""
from __future__ import annotations
import argparse
import copy
import hashlib
import json
import re
import sys
from collections import defaultdict
from pathlib import Path
from typing import Any

POLICY_ID = 'ACTION4_EXACT_PAYLOAD_PREINGEST_R01'
SLOTS = frozenset({'CLAUDE', 'GEMINI', 'GROK', 'DEEPSEEK', 'GLM', 'KIMI'})
COLLECTIONS = {
    'new_findings': 'NEW_FINDING',
    'prior_finding_dispositions': 'PRIOR_DISPOSITION',
    'prior_dispositions': 'PRIOR_DISPOSITION',
    'prior_n_rows': 'PRIOR_DISPOSITION',
    'independently_confirmed_peer_limitations': 'PEER_CONFIRMATION',
}
CATEGORIES = ('NEW_FINDING', 'PRIOR_DISPOSITION', 'PEER_CONFIRMATION')
# For NEW findings only, the identifier is excluded from grouping. Prior/peer
# reference identities remain part of the group key. In particular: retain
# severity, disposition, evidence, location, stage, all prose and list ordering.
ID_FIELDS = frozenset({'id', 'finding_id'})

class AdmissionError(ValueError):
    """Malformed/ambiguous input must not create a publishable derived ledger."""


def require(condition: bool, message: str) -> None:
    if not condition:
        raise AdmissionError(message)


def canonical(value: Any) -> bytes:
    """This project's JSON serialization, not a claim of universal JSON canonicalization."""
    try:
        return json.dumps(value, sort_keys=True, ensure_ascii=False,
                          separators=(',', ':'), allow_nan=False).encode('utf-8')
    except (TypeError, ValueError, UnicodeError) as exc:
        raise AdmissionError(f'NON_CANONICAL_JSON: {exc}') from exc


def sha(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def strict_json(data: bytes) -> Any:
    def pairs(items):
        result = {}
        for key, val in items:
            require(key not in result, f'DUPLICATE_JSON_KEY: {key}')
            result[key] = val
        return result
    def bad_constant(value):
        raise AdmissionError(f'NON_FINITE_JSON: {value}')
    try:
        return json.loads(data.decode('utf-8'), object_pairs_hook=pairs,
                          parse_constant=bad_constant)
    except (UnicodeError, json.JSONDecodeError) as exc:
        raise AdmissionError(f'INVALID_JSON: {exc}') from exc


def nonblank(value: Any, field: str) -> str:
    require(isinstance(value, str) and bool(value.strip()), f'INVALID_{field}')
    return value


def row_id(row: dict) -> str:
    present = [row[k] for k in ID_FIELDS if k in row]
    require(bool(present), 'MISSING_FINDING_ID')
    for value in present:
        nonblank(value, 'FINDING_ID')
    require(len(set(present)) == 1, 'CONFLICTING_ID_ALIASES')
    return present[0]


def source_context(intake: dict) -> dict:
    source = intake.get('source')
    require(isinstance(source, dict), 'MISSING_SOURCE_CONTEXT')
    repo = nonblank(source.get('repository'), 'REPOSITORY')
    commit = source.get('commit')
    require(isinstance(commit, str) and re.fullmatch('[0-9a-f]{40}', commit) is not None,
            'INVALID_SOURCE_COMMIT')
    return {'repository': repo, 'commit': commit}


def collect_rows(intake: dict) -> tuple[list[dict], list[dict], dict]:
    require(isinstance(intake, dict), 'INTAKE_NOT_OBJECT')
    require(intake.get('kind') == 'V5_FRESH_R03_CONSOLIDATED_INTAKE', 'WRONG_INTAKE_KIND')
    require(isinstance(intake.get('reviewer_records'), dict), 'MISSING_REVIEWER_RECORDS')
    require(set(intake['reviewer_records']) == SLOTS, 'REVIEWER_COVERAGE_MISMATCH')
    context = source_context(intake)
    raw_records, coverage = [], []
    for slot in sorted(SLOTS):
        record = intake['reviewer_records'][slot]
        require(isinstance(record, dict), f'INVALID_REVIEWER_RECORD: {slot}')
        require('submitted_ledger' in record, f'MISSING_LEDGER_FIELD: {slot}')
        ledger = record['submitted_ledger']
        if ledger is None:
            reason = nonblank(record.get('ledger_availability'), 'MISSING_LEDGER_REASON')
            coverage.append({'slot': slot, 'ledger_state': 'NOT_AVAILABLE',
                             'reason': reason, 'rows': None, 'not_a_clean_review': True})
            continue
        require(isinstance(ledger, dict), f'INVALID_LEDGER: {slot}')
        require(ledger.get('reviewer_slot') == slot, f'REVIEWER_NAMESPACE_MISMATCH: {slot}')
        require('new_findings' in ledger, f'MISSING_NEW_FINDINGS: {slot}')
        target = ledger.get('target')
        if target is not None:
            require(isinstance(target, dict), f'INVALID_TARGET: {slot}')
            if 'source_commit' in target:
                require(target['source_commit'] == context['commit'], f'MIXED_SOURCE_COMMIT: {slot}')
            if 'repository' in target:
                require(target['repository'] == context['repository'], f'MIXED_REPOSITORY: {slot}')
        # Reject unrecognized finding/disposition row arrays, rather than ignore them.
        for name, value in ledger.items():
            if isinstance(value, list) and any(t in name.lower() for t in ('finding', 'disposition')):
                require(name in COLLECTIONS, f'UNSUPPORTED_ROW_COLLECTION: {slot}/{name}')
        counts, seen_identity = defaultdict(int), {}
        for collection, category in COLLECTIONS.items():
            if collection not in ledger:
                continue
            array = ledger[collection]
            require(isinstance(array, list), f'INVALID_ARRAY: {slot}/{collection}')
            for index, row in enumerate(array):
                require(isinstance(row, dict), f'INVALID_ROW: {slot}/{collection}/{index}')
                identifier = row_id(row)
                payload = {k: v for k, v in row.items() if k not in ID_FIELDS}
                require(bool(payload), f'EMPTY_FINDING_PAYLOAD: {slot}/{identifier}')
                if category == 'NEW_FINDING':
                    require(any(isinstance(row.get(k), str) and row[k].strip() for k in ('title', 'finding', 'description')),
                            f'MISSING_FINDING_CLAIM: {slot}/{identifier}')
                payload_bytes = canonical(payload)
                identity = (category, identifier)
                if identity in seen_identity:
                    require(seen_identity[identity] == payload_bytes,
                            f'CONFLICTING_ID_WITHIN_REVIEWER: {slot}/{identifier}')
                seen_identity[identity] = payload_bytes
                pointer = f'/reviewer_records/{slot}/submitted_ledger/{collection}/{index}'
                raw_records.append({
                    'occurrence_ref': pointer, 'slot': slot, 'category': category,
                    'collection': collection, 'original_id': identifier,
                    'original_row': copy.deepcopy(row),
                    'original_row_canonical_sha256': sha(canonical(row)),
                    'payload_sha256': sha(payload_bytes),
                    'source_context': context.copy(),
                    'provenance': {
                        'round': record.get('round'),
                        'source_review_commit': record.get('source_review_commit'),
                        'stage1_commit': record.get('stage1_commit'),
                        'declared_session': ledger.get('session', ledger.get('audit_run_id')),
                        'remote_ledger_sha256_as_recorded': record.get('ledger_sha256', record.get('ledger_git_sha256')),
                        'embedded_ledger_canonical_sha256': sha(canonical(ledger)),
                        'assurance': 'BOUND_TO_INPUT_SNAPSHOT_NOT_NEW_PROVIDER_ATTESTATION',
                    },
                })
                counts[category] += 1
        coverage.append({'slot': slot, 'ledger_state': 'PRESENT',
                         'rows': sum(counts.values()), 'by_category': dict(sorted(counts.items())),
                         'intake_status_as_recorded': record.get('intake_status')})
    require(bool(raw_records), 'NO_ROWS_TO_INGEST')
    return raw_records, coverage, context


def deduplicate_before_ingestion(raw_records: list[dict]) -> tuple[list[dict], list[dict]]:
    """Group before counting. Compare actual bytes as well as their digest.

    Never merge by title/topic, reviewer name, source ID alone, supplied duplicate
    flags, or inferred meaning. A different evidence reference changes the payload.
    """
    buckets = defaultdict(list)
    for item in raw_records:
        payload = {k: v for k, v in item['original_row'].items() if k not in ID_FIELDS}
        # A generic 'OPEN' disposition on N01 is not the disposition on N02.
        # Ignore ID only for substantive NEW_FINDING payload copies, never for
        # references/dispositions about an identified pre-existing finding.
        key = canonical({'category': item['category'], 'source': item['source_context'],
                         'referenced_id': None if item['category'] == 'NEW_FINDING' else item['original_id'],
                         'payload': payload})
        buckets[key].append(item)
    groups, crosswalk = [], []
    for key in sorted(buckets):
        members = sorted(buckets[key], key=lambda x: x['occurrence_ref'])
        group_id = 'A4-' + sha(key)
        # Representative is a storage choice, explicitly not a human authorship claim.
        rep = members[0]
        ids = sorted({x['original_id'] for x in members})
        group = {
            'group_id': group_id, 'category': rep['category'],
            'payload_sha256': rep['payload_sha256'],
            'payload': {k: v for k, v in rep['original_row'].items() if k not in ID_FIELDS},
            'representative_ref': rep['occurrence_ref'],
            'representative_is_not_authorship_claim': True,
            'occurrences': [x['occurrence_ref'] for x in members],
            'source_ids': ids, 'reviewer_slots': sorted({x['slot'] for x in members}),
            'duplicate_occurrences_excluded_from_new_content_count': len(members) - 1,
            'additional_independent_votes_from_repetition': 0,
            'independent_reproduction_status': 'NOT_ESTABLISHED_BY_DEDUPLICATION',
            'content_admission_only': True,
        }
        groups.append(group)
        for i, row in enumerate(members):
            crosswalk.append({
                'occurrence_ref': row['occurrence_ref'], 'slot': row['slot'],
                'original_id': row['original_id'], 'category': row['category'],
                'group_id': group_id,
                'content_count_contribution': 1 if i == 0 else 0,
                'classification': 'REPRESENTATIVE_CONTENT' if i == 0 else 'EXACT_PAYLOAD_REPEAT',
                'duplicate_additional_independent_vote_credit': 0,
                'raw_record_retained': True,
            })
    return sorted(groups, key=lambda x: x['group_id']), sorted(crosswalk, key=lambda x: x['occurrence_ref'])


def build_ledger(intake: dict, input_sha256: str) -> dict:
    require(isinstance(input_sha256, str) and re.fullmatch('[0-9a-f]{64}', input_sha256) is not None,
            'INVALID_INPUT_HASH')
    # Validate the entire preserved JSON tree, including otherwise uncounted metadata.
    canonical(intake)
    raw, coverage, context = collect_rows(intake)
    groups, crosswalk = deduplicate_before_ingestion(raw)
    # No tally is accepted before the gate: counts come ONLY from admitted groups.
    counts = {}
    for category in CATEGORIES:
        rows_n = sum(r['category'] == category for r in raw)
        groups_n = sum(g['category'] == category for g in groups)
        counts[category] = {'submitted_rows': rows_n, 'distinct_payload_groups': groups_n,
                            'repeat_occurrences_not_added_to_content_count': rows_n - groups_n}
    require(len(crosswalk) == len(raw), 'CROSSWALK_COVERAGE_ERROR')
    require(sum(x['content_count_contribution'] for x in crosswalk) == len(groups), 'COUNT_ERROR')
    # Same IDs with different conclusions across reviewers are retained as variants.
    variants = defaultdict(list)
    for item in raw:
        variants[(item['category'], item['original_id'])].append(item)
    id_variants = []
    for (category, identifier), members in sorted(variants.items()):
        if len({x['payload_sha256'] for x in members}) > 1:
            id_variants.append({'category': category, 'source_id': identifier,
                                'status': 'DISTINCT_PAYLOADS_PRESERVED_NOT_ADJUDICATED',
                                'occurrences': sorted(x['occurrence_ref'] for x in members)})
    return {
        'kind': 'VPL_ACTION4_PREINGESTED_LEDGER', 'policy_id': POLICY_ID,
        'input_sha256': input_sha256, 'input_revision': intake.get('revision'),
        'source_context': context,
        'scope': 'Reprocess historical FRESH_R03 inputs that fed HF03; no findings re-reviewed or closed.',
        'gate': 'EXACT_PAYLOAD_DEDUPLICATION_BEFORE_DERIVED_LEDGER_COUNTS',
        'rules': {
            'new_finding_id_fields_excluded_from_payload_comparison': sorted(ID_FIELDS),
            'prior_and_peer_reference_ids_included_in_group_key': True,
            'canonicalization': 'JSON sorted object keys, UTF-8, compact separators; no prose/list normalization',
            'all_other_payload_fields_compared': True,
            'supplied_duplicate_flags_used_as_proof': False,
            'similarity_or_id_only_merge': False,
            'source_truth_or_authorship_verified': False,
            'automatic_independent_corroboration_award': False,
        },
        'counts': counts, 'reviewer_coverage': coverage,
        'raw_records': raw, 'admitted_groups': groups, 'duplicate_crosswalk': crosswalk,
        'same_id_distinct_payload_variants': id_variants,
        'original_intake': copy.deepcopy(intake),
        'status': 'DERIVED_CONTENT_LEDGER_NOT_REVIEW_VERDICT_OR_SCORE',
        'limitations': [
            'Exact payload comparison does not detect paraphrase/semantic duplicates.',
            'Distinct payloads are not necessarily distinct underlying defects.',
            'Distinct evidence references remain separate; their truth/independence requires evidence review.',
            'Repeated identical payloads supply zero additional independent votes automatically.',
            'The bound consolidated intake is the input; no fresh Git/remote reviewer revalidation is implied.',
            'Missing ledger is recorded as unavailable, never as a clean review.',
            'No frozen candidate, historical disposition, assessment, or live pipeline is overwritten.',
        ],
    }


def serialize(value: Any) -> bytes:
    return (json.dumps(value, sort_keys=True, ensure_ascii=False, indent=2, allow_nan=False) + '\n').encode('utf-8')


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--input', type=Path, required=True)
    parser.add_argument('--expected-input-sha256', required=True)
    parser.add_argument('--output', type=Path, required=True,
                        help='New output file only; existing files are never overwritten.')
    args = parser.parse_args(argv)
    try:
        require(not args.input.is_symlink(), 'INPUT_SYMLINK_NOT_ALLOWED')
        data = args.input.read_bytes()
        require(len(data) <= 20_000_000, 'INPUT_TOO_LARGE')
        require(sha(data) == args.expected_input_sha256, 'INPUT_HASH_MISMATCH')
        document = build_ledger(strict_json(data), sha(data))
        require(args.output.resolve() != args.input.resolve(), 'OUTPUT_IS_INPUT')
        require(args.output.parent.is_dir(), 'OUTPUT_PARENT_MISSING')
        encoded = serialize(document)  # finish serialization before creating any output
        # Exclusive create prevents accidental replacement of prior evidence.
        with args.output.open('xb') as stream:
            stream.write(encoded)
        print(json.dumps({'status': 'DERIVED_LEDGER_WRITTEN', 'counts': document['counts'],
                          'output_sha256': sha(args.output.read_bytes()), 'policy': POLICY_ID}, sort_keys=True))
        return 0
    except (AdmissionError, OSError, RecursionError) as exc:
        print(f'ADMISSION_STOP: {exc}', file=sys.stderr)
        return 2

if __name__ == '__main__':
    raise SystemExit(main())

Download original source manifest

These source artifacts support bounded specification review, test-only timeout/recovery checks and exact-payload grouping. Their presence does not establish production safety, unmocked Guard 2, autonomous state transport or an installed CURRENT state.

Read Final Assessment · Gemini report correction R02

The evaluator-issued report below retains the accepted 95.00 / 99.50 scores and corrects their reasoning and comparability statements. It is preserved as an assessment record, not a new test run or an operating instruction.

Download original assessment report

# GEMINI_REPORT_CORRECTION_ONLY_R02

**Delivery and arithmetic:** VERIFIED.  
**Evaluator-issued successor scores:** 95.00 / 99.50 (Retained unchanged).

## 1. Rubric, Evidence, and Traceability Corrections

This report amends the justifications, classifications, and traceability of the R01 final grading to strictly align with the `GRADING_READSET_R01.md` evidence boundaries. No scoring formulas or totals have been altered.

### A. Track 2, Dimension E (Product/System Integration) Correction
*   **Original R01 Flaw:** Incorrectly labeled Dimension E as "production execution" and justified the score retention (9.5/10) based purely on the lack of MySmartRouter production evidence.
*   **Corrected Judgment:** The V3 authority defines Dimension E as "Product / System Integration," expressly excluding deployment status from direct scoring weight. The 9.5/10 score stands *not* because of a deployment gap, but because the new HF03/T01 evidence (Actions 1, 3, 4) is entirely framework-focused. It introduces test-only fault harnesses and ledger scripts but does not provide new architectural evidence regarding product integration design for MySmartRouter or MyFlightWatcher. The score is carried forward accurately; the rationale is corrected to reflect the V3 rubric's scope.

### B. Track 1, Dimension 8 (QA/Debugging/Recovery) Correction
*   **Original R01 Flaw:** Assumed 97/100 was a mathematical ceiling and that the +0.50 score cap was forced by "strict points limits."
*   **Corrected Judgment:** A score of 97/100 is not a hard cap. The retention of 97 is an evidence-based judgment. Action 3 introduced 13 focused test methods utilizing a test-only deterministic timeout harness. While this proves advanced diagnostic isolation (a local subprocess proxy for fault injection), it does *not* prove unmocked Guard 2 execution or live production recovery. A score of 97 already reflects elite QA/Debugging capability. Retaining it acknowledges that Action 3 was a diagnostic sidecar repair that restored local state exactly, but it did not fundamentally expand the architecture's QA scope beyond what the 97 already captured.

### C. Track 2, Dimensions B & D Correction
*   **Original R01 Flaw:** Awarded the remaining +0.5 headroom without addressing the original historical deductions (synchronous HTTP vs. event streaming; sequential dispatch vs. autonomous collaboration).
*   **Corrected Judgment:** The original product architectures (HTTP, sequential dispatch) were not altered by HF03/T01. However, the +0.5 gains are still warranted under the V3 rubric because V3 scores *applied-AI architect capability*, not just specific product feature implementation. Action 1 (mechanically mapped semantics and owner amendments) demonstrates mastery over deterministic state enforcement (System Architecture, Dim B), mitigating risks inherent in synchronous patterns. Action 4 (exact-payload duplicate pruning before ingestion) demonstrates elite control over multi-model outputs (Agent Orchestration, Dim D), proving advanced boundary management despite the lack of fully autonomous collaboration. The score gains are affirmed based on framework maturation demonstrating high-level architectural judgment.

### D. Action 1 & Action 4 Evidence Boundaries Corrected
*   **Action 1:** The R01 report overstated Action 1's effect. Action 1 yields `ADEQUATE_WITH_STATED_LIMITATIONS`. It mechanically mapped spans and applied explicit A01/M26 owner amendments, but it does *not* constitute unqualified R2-M01 closure or establish a runtime CURRENT state. It proves bounded specification acceptance, leaving owner judgment as an active necessity.
*   **Action 4:** The R01 report falsely claimed the baseline suffered from "finding-count inflation." The evidence shows Action 4 processed 210 *mixed* records (including dispositions and peer confirmations), intentionally grouping content without awarding independent votes to duplicates. The score gain reflects the sophisticated mechanical handling of these payloads, not the correction of an inflated previous score.
*   **Live Connectors:** The assertion "No live API, Git, or Drive connectors" is corrected. The bounded sidecar tests (Actions 1, 3, 4) did not require or verify *new* connector operations. A coordinator Drive transfer occurred, but this does not prove automated state transport or grant new integration score credit.

---

## 2. Track 1: HF03/T01 10-Dimension Assessment (Corrected)

| Dimension | Baseline | Successor | Delta | New Supporting Evidence | Limiting Evidence |
| :--- | :---: | :---: | :---: | :--- | :--- |
| **1. AI/System Architecture** | 95 | 96 | +1 | Action 1: Mechanical verification of 328 spans and A01/M26 explicit owner amendment. | Action 1 yields ADEQUATE_WITH_STATED_LIMITATIONS; Q1 M26 encoding limits remain. |
| **2. Problem Decomposition** | 95 | 96 | +1 | Action 4: Exact-payload pre-ingestion sidecar handles 210 mixed rows into 106 groups. | Duplicate identification previously existed manually; this is mechanical grouping. |
| **3. Multi-Model Orchestration** | 94 | 95 | +1 | Action 4: Retains exact provenance while grouping multi-model output without independent vote inflation. | Continued manual courier overhead limits orchestration fluidity. |
| **4. Product/System Integration** | 92 | 92 | 0 | (Carry Forward) | No new MySmartRouter product integration evidence provided. |
| **5. API/Data/Tool Integration** | 92 | 92 | 0 | (Carry Forward) | No new live Drive/Git connector operation verified in these sidecars. |
| **6. Workflow & State Architecture** | 95 | 96 | +1 | Action 3: Deterministic timeout harness decouples state checks from machine speed. | State transport still requires human courier execution. |
| **7. Governance & Change Control** | 93 | 94 | +1 | Action 1: R04 adjudication replaces manual trust with mechanically verified specification models. | Guard 2 unmocked execution remains unverified; cooperative identity binding. |
| **8. QA/Debugging/Recovery** | 97 | 97 | 0 | Action 3: 13 focused tests successfully restored exact states via local subprocess proxy. | Test-only fault injection; does not constitute live production recovery. |
| **9. Operational Problem Translation** | 95 | 95 | 0 | (Carry Forward) | No new evidence specific to operational business translation. |
| **10. Individual AI Leverage** | 97 | 97 | 0 | (Carry Forward) | Leverage bounded by lack of live agent autonomous execution. |

**Track 1 Total:** 950 / 10 = **95.00**

---

## 3. Track 2: V3 9-Dimension Weighted Assessment (Corrected)

| Dimension | Baseline | Successor | Delta | Reason for Change |
| :--- | :---: | :---: | :---: | :--- |
| **A. Problem Decomposition & Op Translation** | 14.5 | 15.0 | +0.5 | Action 4: Mechanical handling of 210 mixed records into grouped architectures demonstrates elite decomposition capability. |
| **B. AI / System Architecture** | 14.5 | 15.0 | +0.5 | Action 1: Mechanical verification of semantic spans proves deterministic control, mitigating risks of original synchronous HTTP deductions. |
| **C. Human Architectural Judgment & Control** | 14.5 | 15.0 | +0.5 | Action 1: R04 adjudication and explicit owner amendments demonstrate precise human governance over AI models. |
| **D. AI Agent Orchestration & Leverage** | 11.5 | 12.0 | +0.5 | Action 4: Grouping cross-model outputs without vote inflation proves advanced boundary management, offsetting original sequential dispatch deductions. |
| **E. Product / System Integration** | 9.5 | 9.5 | 0 | Unchanged: No new evidence provided for product-level (MySmartRouter) system integration. |
| **F. Workflow, State & Recovery Architecture** | 9.5 | 10.0 | +0.5 | Action 3: Deterministic timeout harness proves resilient local state resumption independent of environmental variance. |
| **G. QA / Validation / Debugging Architecture** | 10.0 | 10.0 | 0 | Unchanged (Max). |
| **H. Governance & Change Control** | 8.0 | 8.0 | 0 | Unchanged (Max). |
| **I. Scope Expansion via AI** | 5.0 | 5.0 | 0 | Unchanged (Max). |

**Track 2 Total:** **99.50 / 100**

---

## 4. Traceability & Comparability Verdict

*   **Track 1 Comparability:** VALID. Evaluated against the exact 10 dimensions/scale of the HF03/T01 frozen state.
*   **Track 2 Comparability:** PARTIAL / ADMISSIBLE WITH CONDITIONS. Evaluated against the V3 rubric. Framework engineering was deemed admissible as applied-AI capability evidence for dimensions A-D and F, supplementing rather than replacing original product audits.
*   **Evaluator Identity/Date:** GEMINI/MAGAI, September 28, 2026.
*   **Input Binding:** `VPL_DUAL_SCORE_FINAL_EVIDENCE_R01.zip` (SHA-256: 7bd8eacbc506414292e80849521317184b219eb1667530f6ef861c52dbca6512).
*   **Current Action:** Report Correction Only (R02). No tests rerun, no public HTML touched, no scores altered from R01.