diff --git a/backend/tests/test_dashboard_testing_lab_reset_storage.py b/backend/tests/test_dashboard_testing_lab_reset_storage.py index 88c8f5696..d88cdb97f 100644 --- a/backend/tests/test_dashboard_testing_lab_reset_storage.py +++ b/backend/tests/test_dashboard_testing_lab_reset_storage.py @@ -82,6 +82,7 @@ def test_changed_selected_bytes_cannot_be_archived_or_deleted(tmp_path): # #region Test.LabReset.Storage.ArchiveReadback [C:2] [TYPE Function] +# @TEST_INVARIANT One private pack retains exact bytes once; repeated member metadata cannot expand the selected scope. def test_archive_readback_refuses_corruption_and_scope_expansion(tmp_path): tmp_path.chmod(0o700) raw = b"selected-content" @@ -91,18 +92,85 @@ def test_archive_readback_refuses_corruption_and_scope_expansion(tmp_path): info = live.stat() metadata = {"mode": info.st_mode & 0o777, "uid": info.st_uid, "gid": info.st_gid, "mtime_ns": info.st_mtime_ns} item = {"path": str(live), "bytes": len(raw), "sha256": hashed} - scope = {"files": {"/app/storage": {"selected": [item]}}} - archived = [{**item, "member": "bytes-" + hashed, "file_metadata": metadata}] - archive.write_bytes(tmp_path, "bytes-" + hashed, raw) + scope = {"files": {str(tmp_path): {"selected": [item]}}} + packed = archive.json_bytes(archive.encode({hashed: raw})) + packed_sha = archive.write_bytes(tmp_path, files.PACK, packed) + archived = [{**item, "member": hashed, "pack_sha256": packed_sha, "file_metadata": metadata}] files.verify_archive_files(scope, tmp_path, archived) with pytest.raises(archive.Stop, match="^LAB_RESET_ARCHIVE_SCOPE_CONFLICT$"): files.verify_archive_files(scope, tmp_path, archived + archived) - (tmp_path / ("bytes-" + hashed)).write_bytes(b"corrupt") + corrupted = archive.json_bytes(archive.encode({hashed: b"corrupt"})) + (tmp_path / files.PACK).write_bytes(corrupted) + archived[0]["pack_sha256"] = sha256(corrupted).hexdigest() with pytest.raises(archive.Stop, match="^LAB_RESET_ARCHIVE_READBACK_FAILED$"): files.verify_archive_files(scope, tmp_path, archived) # #endregion Test.LabReset.Storage.ArchiveReadback +# #region Test.LabReset.Storage.PackDedup [C:2] [TYPE Function] +def test_selected_files_have_one_exclusive_private_deduplicated_pack(tmp_path): + evidence = tmp_path / "evidence" + evidence.mkdir(mode=0o700) + live = tmp_path / "live" + live.mkdir() + selected = [] + for name in ("second", "first"): + path = live / name + path.write_bytes(b"selected-content") + selected.append({"path": str(path), "bytes": 16, "sha256": sha256(b"selected-content").hexdigest()}) + scope = {"files": {str(live): {"selected": selected}}} + archived = files.archive_files(scope, evidence) + assert [path.name for path in evidence.iterdir()] == ["selected-files.json"] + pack = evidence / "selected-files.json" + hashed = sha256(b"selected-content").hexdigest() + assert json.loads(pack.read_bytes()) == ["dict", [[hashed, ["bytes", "c2VsZWN0ZWQtY29udGVudA=="]]]] + assert pack.stat().st_mode & 0o777 == 0o600 + assert {item["member"] for item in archived} == {hashed} + assert {item["pack_sha256"] for item in archived} == {sha256(pack.read_bytes()).hexdigest()} + files.verify_archive_files(scope, evidence, archived) + with pytest.raises(FileExistsError): + files.archive_files(scope, evidence) + assert len(list(evidence.iterdir())) == 1 +# #endregion Test.LabReset.Storage.PackDedup + + +# #region Test.LabReset.Storage.PackRefusals [C:2] [TYPE Function] +@pytest.mark.parametrize("change,code", [("extra", "LAB_RESET_ARCHIVE_SCOPE_CONFLICT"), + ("missing", "LAB_RESET_ARCHIVE_SCOPE_CONFLICT"), ("duplicate", "LAB_RESET_ARCHIVE_INVALID"), + ("altered", "LAB_RESET_ARCHIVE_READBACK_FAILED"), ("forged_member", "LAB_RESET_ARCHIVE_SCOPE_CONFLICT"), + ("pack_digest", "LAB_RESET_ARCHIVE_SCOPE_CONFLICT"), ("current_bytes", "LAB_RESET_FILE_CHANGED")]) +def test_pack_tampering_refuses_before_any_selected_file_is_deleted(tmp_path, change, code): + evidence = tmp_path / "evidence" + evidence.mkdir(mode=0o700) + path = tmp_path / "selected" + path.write_bytes(b"original") + hashed = sha256(b"original").hexdigest() + scope = {"files": {str(tmp_path): {"selected": [{"path": str(path), "bytes": 8, "sha256": hashed}]}}} + archived = files.archive_files(scope, evidence) + encoded = ["dict", [[hashed, ["bytes", "b3JpZ2luYWw="]]]] + if change == "extra": + encoded[1].append(["b" * 64, ["bytes", "eA=="]]) + elif change == "missing": + encoded[1].clear() + elif change == "duplicate": + encoded[1].append(encoded[1][0]) + elif change == "altered": + encoded[1][0][1] = ["bytes", "Y2hhbmdlZA=="] + elif change == "forged_member": + archived[0]["member"] = "foreign" + elif change == "current_bytes": + previous = path.stat() + path.write_bytes(b"modified") + os.utime(path, ns=(previous.st_atime_ns, previous.st_mtime_ns)) + raw = archive.json_bytes(encoded) + (evidence / files.PACK).write_bytes(raw) + archived[0]["pack_sha256"] = "f" * 64 if change == "pack_digest" else sha256(raw).hexdigest() + with pytest.raises(archive.Stop, match="^" + code + "$"): + files.verify_archive_files(scope, evidence, archived) + assert path.exists() +# #endregion Test.LabReset.Storage.PackRefusals + + # #region Test.LabReset.Storage.JournalPrivacy [C:2] [TYPE Function] def test_real_molecular_journal_keeps_original_cause_private(tmp_path, capsys): tmp_path.chmod(0o700) diff --git a/scripts/dashboard_testing_lab_reset_files.py b/scripts/dashboard_testing_lab_reset_files.py index 3c9459656..d2e33bcb7 100644 --- a/scripts/dashboard_testing_lab_reset_files.py +++ b/scripts/dashboard_testing_lab_reset_files.py @@ -9,7 +9,7 @@ from pathlib import Path import stat from dashboard_testing_lab_reset_archive import ( - digest, read_bytes, require, safe_path, sync_directory, write_bytes, + decode, digest, encode, json_bytes, read_bytes, read_json, require, safe_path, sync_directory, write_bytes, ) from dashboard_testing_lab_reset_db import node @@ -17,6 +17,7 @@ ROOTS = ("/app/backend/data/dashboard_testing", "/app/backend/git_repos", "/app/ MARKER = "/app/storage/.native-result-holds/activated" INDEX = "/app/storage/.native-result-holds/index.json" LOCK = "/app/storage/.native-result-mutation.catalog.lock" +PACK = "selected-files.json" # #region Tooling.LabReset.Files.Confined [C:2] [TYPE Function] @@ -194,6 +195,7 @@ def validate_holds(scope, state): # #region Tooling.LabReset.Files.Archive [C:3] [TYPE Function] +# @POST One exclusive private canonical pack deduplicates exact selected bytes; every member binds the pack digest. def archive_files(scope, evidence): result = [] blobs = {} @@ -201,27 +203,36 @@ def archive_files(scope, evidence): for item in manifest["selected"]: raw = member(root, item) hashed = item["sha256"] - name = f"bytes-{hashed}" - if hashed not in blobs: - blobs[hashed] = write_bytes(evidence, name, raw) - require(blobs[hashed] == hashed, "LAB_RESET_ARCHIVE_READBACK_FAILED") - result.append({**item, "member": name, "file_metadata": file_metadata(Path(item["path"]))}) - return result + require(hashed not in blobs or blobs[hashed] == raw, "LAB_RESET_ARCHIVE_READBACK_FAILED") + blobs[hashed] = raw + result.append({**item, "member": hashed, "file_metadata": file_metadata(Path(item["path"]))}) + packed_sha = write_bytes(evidence, PACK, json_bytes(encode(blobs))) + return [{**item, "pack_sha256": packed_sha} for item in result] # #endregion Tooling.LabReset.Files.Archive # #region Tooling.LabReset.Files.VerifyArchive [C:3] [TYPE Function] +# @PRE Pack keys, canonical encoding, digest and each original selected member match exactly before any deletion. def verify_archive_files(scope, evidence, archived): expected = sorted([item for manifest in scope["files"].values() for item in manifest["selected"]], key=lambda item: item["path"]) - require([{key: value for key, value in item.items() if key not in ("member", "file_metadata")} + require([{key: value for key, value in item.items() if key not in ("member", "file_metadata", "pack_sha256")} for item in sorted(archived, key=lambda item: item["path"])] == expected, "LAB_RESET_ARCHIVE_SCOPE_CONFLICT") + pack_path = safe_path(evidence, PACK) + packed_raw = read_bytes(pack_path, private=True) + packed_sha = sha256(packed_raw).hexdigest() + blobs = decode(read_json(pack_path, packed_sha, private=True)) + require(type(blobs) is dict and set(blobs) == {item["sha256"] for item in expected} + and json_bytes(encode(blobs)) == packed_raw, "LAB_RESET_ARCHIVE_SCOPE_CONFLICT") + roots = {item["path"]: root for root, manifest in scope["files"].items() for item in manifest["selected"]} for item in archived: - require(item["member"] == f"bytes-{item['sha256']}", "LAB_RESET_ARCHIVE_SCOPE_CONFLICT") + require(item["member"] == item["sha256"] and item["pack_sha256"] == packed_sha, + "LAB_RESET_ARCHIVE_SCOPE_CONFLICT") require(item["file_metadata"] == file_metadata(Path(item["path"])), "LAB_RESET_ARCHIVE_SCOPE_CONFLICT") - raw = read_bytes(safe_path(evidence, item["member"]), private=True) - require(len(raw) == item["bytes"] and sha256(raw).hexdigest() == item["sha256"], + raw = blobs[item["member"]] + require(type(raw) is bytes and len(raw) == item["bytes"] and sha256(raw).hexdigest() == item["sha256"] + and raw == member(roots[item["path"]], item), "LAB_RESET_ARCHIVE_READBACK_FAILED") # #endregion Tooling.LabReset.Files.VerifyArchive diff --git a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md index 9037042a4..016d4d66f 100644 --- a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md +++ b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization-journal.md @@ -818,4 +818,10 @@ The separately authorized single READ ONLY diagnostic used the same reviewed sta The bounded correction removes only `::text` from the identity SQL, restoring the producer's `inet_server_addr()` carrier. Three independent literal component cases require native identity acceptance, typed refusal of masked-address or different-database identity, and the closed SQL carrier contract with one query. The complete two-file offline tool guards passed82; targeted Ruff/compile/diff checks passed. First harness invocation lacked backend PYTHONPATH and had six import failures; the corrected import-only invocation passed, without DB/Docker/test-suite execution. This fixes tooling representation only; new clean-source manifests and fresh hostcheck/inventory-only dispatch still require root review. Do not rerun the stop driver: both application containers are already stopped. N120/ONE354 and USER approval NONE remain unchanged. +### 2026-10-11 — Selected-file archive budget corrected before inventory retry + +Root held fresh inventory dispatch after source review found that the reviewed original selected files contain506 distinct content hashes across approximately18MB. The prior archive implementation would have emitted one `bytes-*` file per distinct hash, exceeding the user's evidence-file budget; no archive phase had been executed. Root approved one deterministic closed-codec JSON pack using existing encode/decode/json_bytes, exact unique SHA key set and member size/hash checks, without extraction or source copies. The CLI and manifest contract remain unchanged. Both application containers remain preserved stopped; no inventory retry or later phase is implied by this preparation correction. N120/ONE354 and USER approval NONE remain unchanged. + +Curator released only the file-archive helper and its storage guards. One exclusive0600 `selected-files.json` contains the canonical SHA→bytes dictionary; every archived member binds its exact key and the same whole-pack digest. Verification checks closed decode/re-encode, exact key set, member size/hash, retained file metadata and unchanged current selected bytes before deletion. Positive dedup/exclusive and negative extra/missing/duplicate/altered/forged-member/pack-digest/current-byte guards passed within90 offline checks; targeted Ruff/C901, compilation, diff and anchors passed. Main verified both frozen hashes. This is offline tooling proof, not an executed archive/reset or completed inventory. + ## @} Stage2.ChartTypeStabilizationJournal20261010 diff --git a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md index 544661fe8..fe22be5f3 100644 --- a/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md +++ b/specs/050-mcp-interface/plans/2026-10-10-chart-type-stabilization.md @@ -35,7 +35,7 @@ Original275: а=0, б=120, source-restored=155. [Сверка803](2026-10-10-del - Official filter_state observer установил: Clear без Apply сохраняет committed context, Apply меняет его. Chart8 closed context/4×2 и source hashes измерялись; Force refresh прошёл через четыре native owners. Новая политика должна наблюдаться из actual page URL key и official state: иной opaque key допустим при том же effective context. Будущая capture независимо проверяет actual request SHA/context. Standalone DATE normalizer сохраняет авторские endpoints/inclusive; D11 native `[from,to)` discoveryFalse/typedTrue refusal реализован компонентами:180 SQL-free guards PASS/connect0, DATE column и TIME global разделены; browser/custom DATE plugin ещё не измерены, финансовые SELECT dates неизменны. - Последний полный suite24f53f97 завершился exit1:4211collected,3907callPASS,199callFAIL,103setupFAIL,2skipped; все4211teardowns PASS, collection/internal errors отсутствуют.302 private causes сохранены. Их нельзя объявлять целиком прежними или fixture-only. Проверенные bounded восстановления storage/DTO/import/quota/approval/recipe/DATE/logging достигают конкретных assertions; они не заменяют новый полный suite. Подробные результаты и безопасные causal traces находятся в журнале. - Текущие live gaps вне исторической source803 области: зарегистрированные superset_api/sql_evidence приходят в всегда отказывающий QueryExecutor; receipt open/finalize fail-open и repr logs открыты. bounded_transform безусловно unsupported. Publish gate после exact selector требует actual evidence, deployment caller не передаёт selector, scheduled verifier visibly unavailable.037FR012/017 и044FR014 активны; эти свойства не retired wholesale, их source/runtime причины требуют реализации и проверки. -- D17 P0: stable scope, actor, durable review projection и независимый completed actual locator реализованы и проверены компонентами. Fixture PNG и synthetic DB publication receipts не доказывают browser capture, genuine Git publication или human review. D17 P0 следует после committed native/log cuts, до unrelated SDK/transform/gate repairs. Phase0 остановил оба owned backend; первый inventory отказал до locks/snapshot из-за address carrier. READ ONLY diagnostic подтвердил исходную DB identity; исправлен SQL carrier, повтор inventory ждёт root-review. После root-review точных resources/manifest и явного разрешения maintenance: allowlisted module archive/reset→current stand restart/0039→fresh chart8 expected capture/PNG. Старое self-authored ожидание green suite до любой stand action superseded; новый полный green suite остаётся обязательным MERGE gate. Перед visual-review/confirm пользователь должен увидеть именно этот PNG; общее разрешение продолжать не заменяет human disposition. Пока review pending, genuine numeric chart8 chain может идти независимо: PASS→разрешённая +1→named-cell FAIL→finally restore→PASS с тем же pin, затем API multi-metric/query/series/pivot/raw acceptance. Superset/finance metadata и чужое состояние защищены. +- D17 P0: stable scope, actor, durable review projection и независимый completed actual locator реализованы и проверены компонентами. Fixture PNG и synthetic DB publication receipts не доказывают browser capture, genuine Git publication или human review. D17 P0 следует после committed native/log cuts, до unrelated SDK/transform/gate repairs. Phase0 остановил оба owned backend; inventory отказал до locks/snapshot на address carrier. READ ONLY diagnostic подтвердил исходную DB identity; SQL carrier/archive pack исправлены компонентами, повтор inventory ждёт root-review. После root-review точных resources/manifest и явного разрешения maintenance: allowlisted module archive/reset→current stand restart/0039→fresh chart8 expected capture/PNG. Старое self-authored ожидание green suite до любой stand action superseded; новый полный green suite остаётся обязательным MERGE gate. Перед visual-review/confirm пользователь должен увидеть именно этот PNG; общее разрешение продолжать не заменяет human disposition. Пока review pending, genuine numeric chart8 chain может идти независимо: PASS→разрешённая +1→named-cell FAIL→finally restore→PASS с тем же pin, затем API multi-metric/query/series/pivot/raw acceptance. Superset/finance metadata и чужое состояние защищены. Подробная прежняя хроника — [журнал](2026-10-10-chart-type-stabilization-journal.md). Измерения native controls/силы cache refresh — `artifacts/stage0/reseed-20261010/`; промежуточная