agent-bios 0.19.3 → 0.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DEPENDENCIES.md +62 -20
- package/INSTALL.md +1 -1
- package/README.md +16 -21
- package/claude/agents/frontier.md +1 -1
- package/claude/agents/sweep.md +2 -1
- package/claude/agents/workhorse.md +2 -2
- package/claude/guides/claude-prompting.md +494 -167
- package/claude/guides/cli-multi-model-workflow.md +8 -7
- package/claude/guides/gpt-prompting.md +241 -111
- package/claude/guides/session-distill-workflow.md +93 -43
- package/claude/guides/tooling-gotchas.md +3 -1
- package/codex/agents/reviewer.toml +2 -2
- package/codex/agents/sweep.toml +1 -1
- package/codex/agents/workhorse.toml +2 -2
- package/codex/guides/claude-prompting.md +494 -167
- package/codex/guides/cli-multi-model-workflow.md +8 -7
- package/codex/guides/gpt-prompting.md +241 -111
- package/codex/guides/session-distill-workflow.md +93 -43
- package/codex/guides/tooling-gotchas.md +3 -1
- package/compose/assemble.py +4 -1
- package/compose/canary.sh +8 -6
- package/compose/host_platform.py +158 -15
- package/compose/instructions-state.py +183 -41
- package/compose/instructions_app.py +2 -2
- package/compose/instructions_install.py +222 -27
- package/compose/instructions_session.py +250 -75
- package/compose/instructions_setup.py +6 -6
- package/compose/instructions_setup_cli.py +2 -36
- package/compose/instructions_setup_i18n.py +3 -3
- package/compose/instructions_store.py +160 -3
- package/compose/instructions_transaction.py +29 -5
- package/compose/instructions_ui_runtime.py +2 -2
- package/compose/setup/START.md +1 -1
- package/docs/advanced-launch.md +4 -0
- package/docs/releases/0.19.4.md +99 -0
- package/docs/releases/0.20.0.md +102 -0
- package/docs/setup.md +4 -4
- package/install.sh +54 -20
- package/launch/agent-launch.py +171 -22
- package/launch/agent-launch.toml +64 -29
- package/launch/agent-launch.zsh +104 -13
- package/launch/claude_subcommands.py +179 -0
- package/launch/provision-venv.sh +1 -1
- package/launch/shell_integration.py +7 -1
- package/learn/collect-learning.py +60 -9
- package/learn/migrate-learnings.py +70 -4
- package/learn/redact.py +2 -1
- package/package.json +37 -4
- package/provenance.json +1 -1
- package/session-cost.py +141 -18
- package/session-distill/coverage.json +6 -0
- package/session-distill/distill.py +2575 -0
- package/session-distill/grammar/__init__.py +0 -0
- package/session-distill/grammar/owner_lines.py +874 -0
- package/session-distill/originators.json +9 -0
- package/session-distill/packets/cross_review.md +31 -0
- package/session-distill/packets/form.md +86 -0
- package/session-distill/packets/judge.md +81 -0
- package/session-distill/packets/placement_contract.md +90 -0
- package/session-distill/packets/propose.md +124 -0
- package/session-distill/packets/read.md +57 -0
- package/session-distill/packets/reconsider.md +53 -0
- package/session-distill/packets/s7b.md +65 -0
- package/session-distill/packets/s9b.md +39 -0
- package/session-distill/packets/stitch.md +35 -0
- package/session-distill/packets/sweep.md +33 -0
- package/session-distill/runlib/__init__.py +0 -0
- package/session-distill/runlib/bound.py +1102 -0
- package/session-distill/runlib/breaker.py +467 -0
- package/session-distill/runlib/census.py +2347 -0
- package/session-distill/runlib/claims.py +420 -0
- package/session-distill/runlib/controls.py +902 -0
- package/session-distill/runlib/coverage.py +881 -0
- package/session-distill/runlib/declare.py +888 -0
- package/session-distill/runlib/delivery_evidence.py +1145 -0
- package/session-distill/runlib/derive.py +812 -0
- package/session-distill/runlib/destinations.py +3072 -0
- package/session-distill/runlib/dispatch.py +7939 -0
- package/session-distill/runlib/drift.py +1077 -0
- package/session-distill/runlib/entry.py +401 -0
- package/session-distill/runlib/evidence.py +890 -0
- package/session-distill/runlib/exposure.py +1162 -0
- package/session-distill/runlib/gate.py +2727 -0
- package/session-distill/runlib/gitread.py +79 -0
- package/session-distill/runlib/inventory.py +19624 -0
- package/session-distill/runlib/journal.py +1919 -0
- package/session-distill/runlib/ledger.py +3210 -0
- package/session-distill/runlib/ledger_compat.py +101 -0
- package/session-distill/runlib/ledger_migration.py +190 -0
- package/session-distill/runlib/lifecycle_intake.py +693 -0
- package/session-distill/runlib/lineage.py +454 -0
- package/session-distill/runlib/measures.py +249 -0
- package/session-distill/runlib/monitor.py +1180 -0
- package/session-distill/runlib/operations.py +522 -0
- package/session-distill/runlib/packet.py +838 -0
- package/session-distill/runlib/placement.py +1769 -0
- package/session-distill/runlib/projection.py +4090 -0
- package/session-distill/runlib/ranking.py +740 -0
- package/session-distill/runlib/receipts.py +200 -0
- package/session-distill/runlib/records.py +1965 -0
- package/session-distill/runlib/search.py +249 -0
- package/session-distill/runlib/sequencing.py +829 -0
- package/session-distill/runlib/sources.py +641 -0
- package/session-distill/runlib/stage_adjudicate.py +845 -0
- package/session-distill/runlib/stage_apply.py +1378 -0
- package/session-distill/runlib/stage_approvals.py +758 -0
- package/session-distill/runlib/stage_close.py +1220 -0
- package/session-distill/runlib/stage_confirm.py +929 -0
- package/session-distill/runlib/stage_delivery.py +3080 -0
- package/session-distill/runlib/stage_form.py +2576 -0
- package/session-distill/runlib/stage_judge.py +4248 -0
- package/session-distill/runlib/stage_propose.py +3307 -0
- package/session-distill/runlib/stage_read.py +5179 -0
- package/session-distill/runlib/stage_render.py +2739 -0
- package/session-distill/runlib/stage_retrieve.py +924 -0
- package/session-distill/runlib/stage_review_korean.py +1002 -0
- package/session-distill/runlib/stage_review_proposals.py +1292 -0
- package/session-distill/runlib/stagelock.py +412 -0
- package/session-distill/runlib/stop.py +1061 -0
- package/session-distill/runlib/targets.py +809 -0
- package/session-distill/runlib/usage.py +280 -0
- package/session-distill/runlib/validate.py +319 -0
- package/session-distill/runlib/views.py +4327 -0
- package/session-distill/schemas/adjudication.schema.json +35 -0
- package/session-distill/schemas/approval.schema.json +35 -0
- package/session-distill/schemas/census.schema.json +128 -0
- package/session-distill/schemas/checks.schema.json +207 -0
- package/session-distill/schemas/claim.schema.json +16 -0
- package/session-distill/schemas/confirmation.schema.json +24 -0
- package/session-distill/schemas/coverage.schema.json +66 -0
- package/session-distill/schemas/cross_review.schema.json +24 -0
- package/session-distill/schemas/event.schema.json +20 -0
- package/session-distill/schemas/evidence.schema.json +20 -0
- package/session-distill/schemas/expected_observation.schema.json +18 -0
- package/session-distill/schemas/form.schema.json +103 -0
- package/session-distill/schemas/intake.schema.json +71 -0
- package/session-distill/schemas/inventory.schema.json +872 -0
- package/session-distill/schemas/judge.schema.json +77 -0
- package/session-distill/schemas/ledger.schema.json +313 -0
- package/session-distill/schemas/observation.schema.json +16 -0
- package/session-distill/schemas/propose.schema.json +555 -0
- package/session-distill/schemas/read.schema.json +76 -0
- package/session-distill/schemas/reconsider.schema.json +122 -0
- package/session-distill/schemas/run.schema.json +150 -0
- package/session-distill/schemas/s7b.schema.json +200 -0
- package/session-distill/schemas/s9b.schema.json +28 -0
- package/session-distill/schemas/stitch.schema.json +25 -0
- package/session-distill/schemas/sweep.schema.json +25 -0
- package/session-distill/seats.json +149 -0
- package/session-distill/tables/allowed_pairs.json +257 -0
- package/session-distill/tables/controls.json +30 -0
- package/session-distill/tables/delivery_evidence.json +36 -0
- package/session-distill/tables/delivery_evidence_fixtures.json +731 -0
- package/session-distill/tables/destinations.json +684 -0
- package/session-distill/tables/drift_layers.json +68 -0
- package/session-distill/tables/exposure_rules.json +192 -0
- package/session-distill/tables/placement_rules.json +148 -0
- package/session-distill/tables/propose_fixtures.json +154 -0
- package/session-distill/tables/ranking.json +194 -0
- package/session-distill/tables/redundancy.json +10 -0
- package/session-distill/tables/structural_rules.json +44 -0
- package/session-distill/tables/transition_fixtures.json +398 -0
- package/session-distill/tables/transitions.json +69 -0
- package/session-distill/tables/unit_outcome.json +67 -0
- package/session-distill/tables/unit_outcome_fixtures.json +2364 -0
- package/wrappers/claude-run.sh +481 -33
- package/wrappers/claude_hermetic_evidence.py +1423 -0
- package/wrappers/codex-helm.sh +44 -13
- package/wrappers/codex-run.sh +183 -20
- package/wrappers/codex_frame_filter.py +1199 -0
- package/wrappers/codex_protocol.py +737 -0
- package/wrappers/jsonl_lines.py +65 -0
|
@@ -0,0 +1,1423 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Effective-context evidence for one `claude-run` call, read from the host's own records.
|
|
3
|
+
|
|
4
|
+
`claude-run --profile hermetic` runs `claude -p` in a cell — a fresh HOME, a fresh
|
|
5
|
+
CLAUDE_CONFIG_DIR and a working directory — and this helper turns what the host recorded
|
|
6
|
+
there into the capture a gate judges. It judges nothing itself: every value below is a field
|
|
7
|
+
of the host's transcript, its stream, or a listing taken before the call, and the gate
|
|
8
|
+
(session-distill's, or any reader) compares them with what the caller declared.
|
|
9
|
+
|
|
10
|
+
prepare before the call: refuse a cell or working directory under the caller's HOME (its
|
|
11
|
+
ancestors hold the owner's instruction files, which Claude loads from every
|
|
12
|
+
ancestor of its working directory), record the instruction surfaces that do sit
|
|
13
|
+
in the working directory's ancestry, list the working directory, and mint the
|
|
14
|
+
session id the call is persisted under
|
|
15
|
+
render after the call: `host.json` (profile, flag-set hash, working directory as the host
|
|
16
|
+
recorded it, the pre-call listing, session id, the sent requests, the responses,
|
|
17
|
+
the StructuredOutput calls, and the effective context — instruction files by path,
|
|
18
|
+
kind and normalised sha256, appended system prompts by sha256, skills, agents,
|
|
19
|
+
hooks), `actions.jsonl` (every tool request and its result, content reduced to a
|
|
20
|
+
length and a sha256), the receipt evidence, and the final result object on stdout
|
|
21
|
+
server-policy run `claude doctor` once in the call's environment and print, as one JSON line, the
|
|
22
|
+
status of its "Managed settings (remote):" line and the verdict on it; nothing else of
|
|
23
|
+
its output is kept
|
|
24
|
+
|
|
25
|
+
The session is persisted on purpose: the transcript is the only record of which instruction
|
|
26
|
+
files the host loaded (the stream's init event lists tools and skills, never instructions).
|
|
27
|
+
An appended system prompt is observed in the sent request's system blocks: each text the
|
|
28
|
+
caller appended — declared with its sha256, or passed after `--` — is recorded, in order,
|
|
29
|
+
when the host-recorded system text carries it, by the sha256 of the bytes that were appended.
|
|
30
|
+
|
|
31
|
+
Ported from the claude-runner probe prototype (ctxrec.py: transcript summary and the
|
|
32
|
+
normalised instruction hash; witness.py: the sent-request reconstruction), reduced to what
|
|
33
|
+
the capture carries. Requires Python 3.9 and the standard library only, because it ships
|
|
34
|
+
beside the adapter.
|
|
35
|
+
|
|
36
|
+
claude_hermetic_evidence.py --self-test
|
|
37
|
+
"""
|
|
38
|
+
import argparse
|
|
39
|
+
import hashlib
|
|
40
|
+
import json
|
|
41
|
+
import os
|
|
42
|
+
import pathlib
|
|
43
|
+
import re
|
|
44
|
+
import sys
|
|
45
|
+
import uuid
|
|
46
|
+
|
|
47
|
+
# What a host loads from a directory and every ancestor of its working directory (instruction
|
|
48
|
+
# files; skills, agents, commands and settings below .claude/ and .codex/), the MCP declaration,
|
|
49
|
+
# and a bare settings file: none may sit in a hermetic cell's ancestry (plan P5).
|
|
50
|
+
SURFACES = ("CLAUDE.md", "CLAUDE.local.md", "AGENTS.md", ".mcp.json", ".claude", ".codex", "settings.json",
|
|
51
|
+
"settings.local.json")
|
|
52
|
+
MANIFEST_PLACEHOLDER = "<manifest>"
|
|
53
|
+
REMINDER_INSTRUCTIONS = "<system-reminder>\nCodebase and user instructions are shown below"
|
|
54
|
+
HOST_NUDGES = ("Output token limit hit", "[structured-output-enforce]")
|
|
55
|
+
INSTRUCTION_HEADER = re.compile(r"^Contents of (.+?) \((.*?)\):\s*$", re.M)
|
|
56
|
+
# The transcript's record kinds and attachment types, per Claude version, as measured from that
|
|
57
|
+
# version's hermetic calls (D-20261102-29ca35). The vendor calls the format internal and changing
|
|
58
|
+
# between versions, and a renamed kind read as an absent one: no requests, no instructions, and no
|
|
59
|
+
# problem. So a transcript holding a kind or an attachment type outside every measured set is
|
|
60
|
+
# refused naming it, the version that wrote it and the versions measured; a version whose records
|
|
61
|
+
# stay inside the known kinds passes unpinned. The sets hold what the helper reads (READ_TYPES,
|
|
62
|
+
# READ_ATTACHMENTS) and what is known and left unread; `hook*` attachments are read by prefix. 2.1.304:
|
|
63
|
+
# the 404 transcripts of the 2026-10-20 probe captures. A version is added by the author-side re-pin
|
|
64
|
+
# procedure, which measures it with one hermetic call, and reaches users with the release carrying it.
|
|
65
|
+
# A version's set holds the kinds its sample showed, not every kind that version writes: a read kind
|
|
66
|
+
# the sample did not show (one empty hermetic call loads no instruction file) is known from the union.
|
|
67
|
+
RECORD_KINDS = {
|
|
68
|
+
"2.1.304": {
|
|
69
|
+
"types": ("agent-name", "ai-title", "api-request", "api-request-blob", "api-request-shape", "assistant",
|
|
70
|
+
"atis-latch", "attachment", "cost-state", "custom-title", "file-history-snapshot", "fork-context-ref",
|
|
71
|
+
"last-prompt", "mode", "permission-mode", "queue-operation", "shim-session-start", "system", "user"),
|
|
72
|
+
"attachments": ("agent_listing_delta", "budget_usd", "date", "deferred_tools_delta", "deferred_tools_record",
|
|
73
|
+
"environment", "file", "hook_additional_context", "hook_non_blocking_error", "hook_success",
|
|
74
|
+
"instructions", "max_turns_reached", "model", "prompt_snapshot", "read_truncation_notice",
|
|
75
|
+
"remote_session_change", "sandbox_instructions", "session_context", "skill_listing",
|
|
76
|
+
"structured_output", "total_tokens_reminder"),
|
|
77
|
+
},
|
|
78
|
+
# 2.1.317: the A-1 re-pin's six calls (2026-11-04), one standalone hermetic call and five structured-output
|
|
79
|
+
# judge calls through dispatch. `tools-used` is new: it names the tools a session used (here StructuredOutput,
|
|
80
|
+
# which the helper reads from the assistant's tool_use blocks), carries no context, and is known and left unread.
|
|
81
|
+
"2.1.317": {
|
|
82
|
+
"types": ("api-request", "api-request-blob", "api-request-shape", "assistant", "atis-latch", "attachment",
|
|
83
|
+
"cost-state", "last-prompt", "queue-operation", "tools-used", "user"),
|
|
84
|
+
"attachments": ("date", "environment", "model", "prompt_snapshot", "session_context", "structured_output"),
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
READ_TYPES = ("api-request", "api-request-blob", "api-request-shape", "assistant", "attachment", "user")
|
|
88
|
+
READ_ATTACHMENTS = ("agent_listing_delta", "deferred_tools_delta", "environment", "instructions", "skill_listing")
|
|
89
|
+
# Claude Code's managed settings load under every flag (--safe-mode, --setting-sources "",
|
|
90
|
+
# --restricted alike), so a hermetic call on a managed machine is not fully hermetic. Before the call
|
|
91
|
+
# these documented locations (code.claude.com/docs/en/managed-settings, read 2026-11-02) are checked
|
|
92
|
+
# for existence only, never read; when any exists the call still runs and its capture says which and
|
|
93
|
+
# that it is not fully hermetic (D-20261102-6b6676). A location whose check fails (a parent the user
|
|
94
|
+
# may not search, a registry read refused) is neither: it is recorded as unverified, and an unverified
|
|
95
|
+
# location is no more fully hermetic than a present one. `{user}` is the login name. On Windows the
|
|
96
|
+
# `Settings` value under each Policies key counts too. The server-delivered organisation policy is
|
|
97
|
+
# SERVER_POLICY_LINE's.
|
|
98
|
+
MANAGED_SOURCES = {
|
|
99
|
+
"darwin": ("/Library/Application Support/ClaudeCode/managed-settings.json",
|
|
100
|
+
"/Library/Application Support/ClaudeCode/managed-settings.d",
|
|
101
|
+
"/Library/Application Support/ClaudeCode/managed-mcp.json",
|
|
102
|
+
"/Library/Managed Preferences/com.anthropic.claudecode.plist",
|
|
103
|
+
"/Library/Managed Preferences/{user}/com.anthropic.claudecode.plist"),
|
|
104
|
+
"linux": ("/etc/claude-code/managed-settings.json", "/etc/claude-code/managed-settings.d",
|
|
105
|
+
"/etc/claude-code/managed-mcp.json"),
|
|
106
|
+
"win32": ("C:\\Program Files\\ClaudeCode\\managed-settings.json", "C:\\Program Files\\ClaudeCode\\managed-settings.d",
|
|
107
|
+
"C:\\Program Files\\ClaudeCode\\managed-mcp.json"),
|
|
108
|
+
}
|
|
109
|
+
WINDOWS_POLICY_KEYS = (("HKEY_LOCAL_MACHINE", 0x80000002), ("HKEY_CURRENT_USER", 0x80000001))
|
|
110
|
+
# The server-delivered half (D-20261102-252c92): a Team or Enterprise credential fetches its
|
|
111
|
+
# organisation's policy at startup, which no file check sees. `claude doctor` (v2.1.248+) reports the
|
|
112
|
+
# fetch's outcome without a model call on one documented line; that line alone is read, in the call's
|
|
113
|
+
# own environment, and only its status is kept (at most 200 characters). Clean means exactly
|
|
114
|
+
# SERVER_POLICY_CLEAN; any other status is "not confirmed"; no line, an exit other than 0 or no answer
|
|
115
|
+
# within SERVER_POLICY_TIMEOUT_S is "unknown", never clean. Nothing skips the fetch: exporting a
|
|
116
|
+
# provider or base-URL variable to avoid it would evade an organisation's policy.
|
|
117
|
+
SERVER_POLICY_LINE = "Managed settings (remote):"
|
|
118
|
+
SERVER_POLICY_CLEAN = "none configured for this organization"
|
|
119
|
+
SERVER_POLICY_TIMEOUT_S = 60
|
|
120
|
+
SERVER_POLICY_VERDICTS = ("clean", "not confirmed", "unknown")
|
|
121
|
+
ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07]*\x07")
|
|
122
|
+
# Why a receipt's hermeticity is not assessed: the inherit profile loads the cell's settings on purpose,
|
|
123
|
+
# and a capture written before the assessment existed (or by another host) carries none.
|
|
124
|
+
NOT_ASSESSED_INHERIT = "the inherit profile loads the cell's own settings by design; hermeticity is assessed for hermetic calls"
|
|
125
|
+
NOT_ASSESSED_MISSING = "the capture carries no hermeticity assessment"
|
|
126
|
+
# What a capture records as unverified when its call's pre-call check left no managed-settings record.
|
|
127
|
+
MANAGED_NOT_CHECKED = "no pre-call managed-settings check was recorded for this call"
|
|
128
|
+
# Why the call keeps `--setting-sources ""`, whose empty value the CLI reference does not describe.
|
|
129
|
+
SETTING_SOURCES_MOOT = ("--setting-sources \"\" is undocumented for an empty value and moot here: the call runs with "
|
|
130
|
+
"a fresh HOME and configuration directory, in an empty cell working directory, and the "
|
|
131
|
+
"evidence check reads every source the host recorded as loaded")
|
|
132
|
+
# Passed after `--`, each of these puts text into the system prompt the call is sent.
|
|
133
|
+
APPENDING_FLAGS = ("--append-system-prompt", "--append-system-prompt-file", "--system-prompt",
|
|
134
|
+
"--system-prompt-file")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def sha256(data):
|
|
138
|
+
return hashlib.sha256(data if isinstance(data, bytes) else data.encode("utf-8")).hexdigest()
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def canonical(obj):
|
|
142
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def canonical_sha256(obj):
|
|
146
|
+
return sha256(canonical(obj))
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def norm_text(text):
|
|
150
|
+
"""The host renders instruction files before use (trailing newline trimmed, HTML comments
|
|
151
|
+
removed); a declared file is compared with what loaded on this form."""
|
|
152
|
+
if isinstance(text, bytes):
|
|
153
|
+
text = text.decode("utf-8", "replace")
|
|
154
|
+
return re.sub(r"\s+", " ", re.sub(r"<!--.*?-->", "", text, flags=re.S)).strip()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def norm_sha256(text):
|
|
158
|
+
return sha256(norm_text(text))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def flags_sha256(flags, manifest=None):
|
|
162
|
+
"""The flag-set hash a capture carries: the profile's flags and whatever the caller passed
|
|
163
|
+
after `--`, with the producing profile's manifest path replaced by its placeholder, so one
|
|
164
|
+
pin covers every manifest directory."""
|
|
165
|
+
rule = f"//{manifest.strip('/')}/" if manifest else None
|
|
166
|
+
held = [f.replace(rule, f"//{MANIFEST_PLACEHOLDER}/") if rule else f for f in flags]
|
|
167
|
+
return canonical_sha256(held)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# --- before the call ----------------------------------------------------------------------------
|
|
171
|
+
|
|
172
|
+
def under(path, root):
|
|
173
|
+
path, root = pathlib.Path(path).resolve(), pathlib.Path(root).resolve()
|
|
174
|
+
return path == root or root in path.parents
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def ancestor_exposure(cwd):
|
|
178
|
+
"""Instruction surfaces in the ancestry of `cwd` (the working directory itself excluded: its
|
|
179
|
+
files are the call's manifest). Files carry their sha256; a .claude directory its file count."""
|
|
180
|
+
found = []
|
|
181
|
+
for directory in pathlib.Path(cwd).resolve().parents:
|
|
182
|
+
for name in SURFACES:
|
|
183
|
+
path = directory / name
|
|
184
|
+
if path.is_file():
|
|
185
|
+
found.append({"path": str(path), "sha256": sha256(path.read_bytes())})
|
|
186
|
+
elif path.is_dir():
|
|
187
|
+
found.append({"path": str(path), "files": sum(len(files) for _, _, files in os.walk(path))})
|
|
188
|
+
return found
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def listing(cwd):
|
|
192
|
+
"""The working directory before the call: every file by relative path and sha256 (a symlink
|
|
193
|
+
by path, sha256 null), directories implied."""
|
|
194
|
+
root = pathlib.Path(cwd)
|
|
195
|
+
out = []
|
|
196
|
+
for path in sorted(root.rglob("*")):
|
|
197
|
+
if path.is_symlink():
|
|
198
|
+
out.append({"path": str(path.relative_to(root)), "sha256": None})
|
|
199
|
+
elif path.is_file():
|
|
200
|
+
out.append({"path": str(path.relative_to(root)), "sha256": sha256(path.read_bytes())})
|
|
201
|
+
return out
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def operator_homes(home=None):
|
|
205
|
+
"""The operator's home from the account database, and HOME when it names another place: a
|
|
206
|
+
caller can point HOME anywhere, so HOME alone never decides what is outside the home."""
|
|
207
|
+
import pwd
|
|
208
|
+
homes = [pwd.getpwuid(os.getuid()).pw_dir]
|
|
209
|
+
if home and pathlib.Path(home).resolve() != pathlib.Path(homes[0]).resolve():
|
|
210
|
+
homes.append(home)
|
|
211
|
+
return homes
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def existing(path):
|
|
215
|
+
"""`path` resolved through its nearest existing ancestor, so a root not yet made is judged
|
|
216
|
+
where it will be made."""
|
|
217
|
+
path = pathlib.Path(path).absolute()
|
|
218
|
+
tail = []
|
|
219
|
+
while not path.exists() and path != path.parent:
|
|
220
|
+
tail.insert(0, path.name)
|
|
221
|
+
path = path.parent
|
|
222
|
+
return path.resolve().joinpath(*tail)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def surface_problems(directory):
|
|
226
|
+
return [f"CELL_ANCESTOR_SURFACE {directory / name}: an instruction surface in the cell's ancestry"
|
|
227
|
+
for name in SURFACES if (directory / name).exists()]
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def root_problems(root, homes):
|
|
231
|
+
"""Plan P5, before anything is made: the cell root lies outside the operator's home, and if it
|
|
232
|
+
exists it is the operator's own and mode 700; neither it nor any ancestor holds a surface."""
|
|
233
|
+
root = existing(root)
|
|
234
|
+
problems = [f"CELL_UNDER_HOME the cell root {root} lies under {home}, whose ancestry holds the owner's "
|
|
235
|
+
f"instruction files" for home in homes if under(root, home)]
|
|
236
|
+
if root.is_dir():
|
|
237
|
+
info = root.stat()
|
|
238
|
+
if info.st_uid != os.getuid():
|
|
239
|
+
problems.append(f"CELL_ROOT_OWNER the cell root {root} belongs to uid {info.st_uid}, not the operator")
|
|
240
|
+
if info.st_mode & 0o777 != 0o700:
|
|
241
|
+
problems.append(f"CELL_ROOT_MODE the cell root {root} is mode {info.st_mode & 0o777:o}, not 700")
|
|
242
|
+
for directory in [root, *root.parents]:
|
|
243
|
+
problems.extend(surface_problems(directory))
|
|
244
|
+
return problems
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def prepare_problems(cell, cwd, homes, strict):
|
|
248
|
+
"""Why a cell or working directory may not be used, by name; empty when it may. `strict`
|
|
249
|
+
(the hermetic profile) refuses an instruction surface anywhere in the working directory's
|
|
250
|
+
ancestry; otherwise it is recorded as exposure."""
|
|
251
|
+
problems = []
|
|
252
|
+
for label, path in (("cell", cell), ("working directory", cwd)):
|
|
253
|
+
problems.extend(f"CELL_UNDER_HOME the {label} {path} lies under {home}, whose ancestry holds the owner's "
|
|
254
|
+
f"instruction files" for home in homes if path and under(path, home))
|
|
255
|
+
if not pathlib.Path(cwd).is_dir():
|
|
256
|
+
problems.append(f"CELL_CWD_MISSING the working directory {cwd} is not a directory")
|
|
257
|
+
elif strict:
|
|
258
|
+
for directory in pathlib.Path(cwd).resolve().parents:
|
|
259
|
+
problems.extend(surface_problems(directory))
|
|
260
|
+
return problems
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def bind_problems(root, cell, cwd, manifest=None):
|
|
264
|
+
"""The cell actually used is the validated root's: the cell, its home, configuration home and
|
|
265
|
+
working directory — and the call's working directory — resolve strictly beneath the root, and
|
|
266
|
+
the producing profile's read root is that working directory (the one the manifest declares)."""
|
|
267
|
+
base = pathlib.Path(root).resolve()
|
|
268
|
+
problems = []
|
|
269
|
+
for label, path in (("cell", cell), ("cell home", f"{cell}/home"), ("cell configuration home", f"{cell}/config"),
|
|
270
|
+
("cell working directory", f"{cell}/cwd"), ("working directory", cwd)):
|
|
271
|
+
resolved = pathlib.Path(path).resolve()
|
|
272
|
+
if base not in resolved.parents:
|
|
273
|
+
problems.append(f"CELL_OUTSIDE_ROOT the {label} {path} resolves to {resolved}, outside the validated "
|
|
274
|
+
f"cell root {base}")
|
|
275
|
+
if manifest is not None and pathlib.Path(manifest).resolve() != pathlib.Path(cwd).resolve():
|
|
276
|
+
problems.append(f"READ_ROOT_MISMATCH the producing read root {pathlib.Path(manifest).resolve()} is not the "
|
|
277
|
+
f"working directory the manifest declares, {pathlib.Path(cwd).resolve()}")
|
|
278
|
+
return problems
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def bind(root, cell, cwd, manifest):
|
|
282
|
+
problems = bind_problems(root, cell, cwd, manifest)
|
|
283
|
+
for line in problems:
|
|
284
|
+
print(f"claude-run: {line}", file=sys.stderr)
|
|
285
|
+
return 3 if problems else 0
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def check_root(root, home):
|
|
289
|
+
problems = root_problems(root, operator_homes(home))
|
|
290
|
+
for line in problems:
|
|
291
|
+
print(f"claude-run: {line}", file=sys.stderr)
|
|
292
|
+
return 3 if problems else 0
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def managed_sources(root="", system=None, user=None):
|
|
296
|
+
"""The documented managed-settings locations on this machine, by existence alone: (those that
|
|
297
|
+
exist, those whose check failed, each with the failure's class). Only a location that cannot
|
|
298
|
+
exist (no such file, a parent that is not a directory) counts as absent. `root` prefixes every
|
|
299
|
+
file path, so a control can plant one."""
|
|
300
|
+
system = system or ("linux" if sys.platform.startswith("linux") else sys.platform)
|
|
301
|
+
user = user or os.environ.get("USER") or os.environ.get("USERNAME") or ""
|
|
302
|
+
found, unverified = [], []
|
|
303
|
+
for path in MANAGED_SOURCES.get(system, ()):
|
|
304
|
+
path = path.format(user=user)
|
|
305
|
+
try:
|
|
306
|
+
os.lstat(root + path)
|
|
307
|
+
except (FileNotFoundError, NotADirectoryError):
|
|
308
|
+
continue
|
|
309
|
+
except OSError as exc:
|
|
310
|
+
unverified.append(f"{path} ({exc.__class__.__name__})")
|
|
311
|
+
continue
|
|
312
|
+
found.append(path)
|
|
313
|
+
if system == "win32" and not root:
|
|
314
|
+
present, failed = windows_policy_values()
|
|
315
|
+
found += present
|
|
316
|
+
unverified += failed
|
|
317
|
+
return found, unverified
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def windows_policy_values():
|
|
321
|
+
"""`HKLM|HKCU\\SOFTWARE\\Policies\\ClaudeCode` `Settings` values that exist, asked for their size only
|
|
322
|
+
(RegGetValueW with no data buffer), so a policy's content is never read: (present, unverified).
|
|
323
|
+
Only ERROR_FILE_NOT_FOUND is absence; any other failure leaves the value unverified."""
|
|
324
|
+
import ctypes
|
|
325
|
+
from ctypes import wintypes
|
|
326
|
+
advapi = ctypes.WinDLL("advapi32")
|
|
327
|
+
advapi.RegGetValueW.argtypes = [wintypes.HANDLE, wintypes.LPCWSTR, wintypes.LPCWSTR, wintypes.DWORD,
|
|
328
|
+
ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(wintypes.DWORD)]
|
|
329
|
+
found, unverified = [], []
|
|
330
|
+
for name, hive in WINDOWS_POLICY_KEYS:
|
|
331
|
+
size = wintypes.DWORD(0)
|
|
332
|
+
code = advapi.RegGetValueW(wintypes.HANDLE(hive), "SOFTWARE\\Policies\\ClaudeCode", "Settings", 0x0000FFFF,
|
|
333
|
+
None, None, ctypes.byref(size))
|
|
334
|
+
value = f"{name}\\SOFTWARE\\Policies\\ClaudeCode\\Settings"
|
|
335
|
+
if code == 0:
|
|
336
|
+
found.append(value)
|
|
337
|
+
elif code != 2:
|
|
338
|
+
unverified.append(f"{value} (error {code})")
|
|
339
|
+
return found, unverified
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def server_policy_verdict(output, returncode):
|
|
343
|
+
"""The server-policy record for one `claude doctor` run: its documented line's status and the verdict
|
|
344
|
+
on it. Nothing else of the output is kept, since the rest names the account."""
|
|
345
|
+
if returncode != 0:
|
|
346
|
+
return {"status": None, "verdict": "unknown", "reason": f"claude doctor exited {returncode}"}
|
|
347
|
+
lines = [ANSI.sub("", line).strip() for line in output.splitlines()]
|
|
348
|
+
found = [line[len(SERVER_POLICY_LINE):].strip() for line in lines if line.startswith(SERVER_POLICY_LINE)]
|
|
349
|
+
if len(found) != 1:
|
|
350
|
+
return {"status": None, "verdict": "unknown",
|
|
351
|
+
"reason": f"claude doctor printed {len(found)} '{SERVER_POLICY_LINE}' lines, not one"}
|
|
352
|
+
status = found[0][:200]
|
|
353
|
+
if status == SERVER_POLICY_CLEAN:
|
|
354
|
+
return {"status": status, "verdict": "clean", "reason": None}
|
|
355
|
+
return {"status": status, "verdict": "not confirmed",
|
|
356
|
+
"reason": "the organisation's server-delivered policy is not confirmed absent, so the call is not "
|
|
357
|
+
"confirmed hermetic"}
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def server_policy(claude_bin, timeout=None):
|
|
361
|
+
"""Run `claude doctor` once in this process's environment (claude-run gives it the call's) with stdin
|
|
362
|
+
closed, and return its server-policy record."""
|
|
363
|
+
import subprocess
|
|
364
|
+
try:
|
|
365
|
+
done = subprocess.run([claude_bin, "doctor"], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
|
366
|
+
stderr=subprocess.STDOUT, timeout=timeout or SERVER_POLICY_TIMEOUT_S)
|
|
367
|
+
except subprocess.TimeoutExpired:
|
|
368
|
+
return {"status": None, "verdict": "unknown",
|
|
369
|
+
"reason": f"claude doctor did not finish within {timeout or SERVER_POLICY_TIMEOUT_S} s"}
|
|
370
|
+
except OSError as exc:
|
|
371
|
+
return {"status": None, "verdict": "unknown", "reason": f"claude doctor did not start: {exc.__class__.__name__}"}
|
|
372
|
+
return server_policy_verdict(done.stdout.decode("utf-8", "replace"), done.returncode)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def read_server_policy(path):
|
|
376
|
+
"""The server-policy record a dispatcher handed over, or an unknown one saying why there is none."""
|
|
377
|
+
if not path:
|
|
378
|
+
return {"status": None, "verdict": "unknown",
|
|
379
|
+
"reason": "no server-policy check was run for this call (a distill run checks once, before its first "
|
|
380
|
+
"hermetic Claude call)"}
|
|
381
|
+
try:
|
|
382
|
+
held = json.loads(pathlib.Path(path).read_text(encoding="utf-8"))
|
|
383
|
+
except (OSError, ValueError) as exc:
|
|
384
|
+
return {"status": None, "verdict": "unknown",
|
|
385
|
+
"reason": f"the server-policy record is unreadable: {exc.__class__.__name__}"}
|
|
386
|
+
return server_policy_record(held)
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def server_policy_record(held):
|
|
390
|
+
"""`held` as a server-policy record, or an unknown one when it is not one: a clean verdict stands only
|
|
391
|
+
on the clean status itself."""
|
|
392
|
+
record = {"status": held.get("status"), "verdict": held.get("verdict"), "reason": held.get("reason")} \
|
|
393
|
+
if isinstance(held, dict) else {}
|
|
394
|
+
if (record.get("verdict") not in SERVER_POLICY_VERDICTS
|
|
395
|
+
or not (record["status"] is None or isinstance(record["status"], str) and len(record["status"]) <= 200)
|
|
396
|
+
or not (record["reason"] is None or isinstance(record["reason"], str))
|
|
397
|
+
or record["verdict"] == "clean" and record["status"] != SERVER_POLICY_CLEAN):
|
|
398
|
+
return {"status": None, "verdict": "unknown", "reason": "the server-policy record is not one"}
|
|
399
|
+
return record
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def fully_hermetic(managed, unverified, policy):
|
|
403
|
+
"""Fully hermetic only when every managed-settings location was checked and found absent and the
|
|
404
|
+
server-delivered policy is confirmed clean, as server_policy_record reads it (a clean verdict
|
|
405
|
+
stands only on the clean status); anything not established is not."""
|
|
406
|
+
return (managed == [] and unverified == [] and isinstance(policy, dict)
|
|
407
|
+
and server_policy_record(policy)["verdict"] == "clean")
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def hermeticity(profile, pre, policy):
|
|
411
|
+
"""The call's hermeticity as its capture and receipt state it, from the pre-call record `pre` (a
|
|
412
|
+
record without the managed-settings check is one whose locations are all unverified)."""
|
|
413
|
+
if profile != "hermetic":
|
|
414
|
+
return {"assessed": False, "reason": NOT_ASSESSED_INHERIT}
|
|
415
|
+
managed, unverified = pre.get("managed_settings"), pre.get("managed_unverified")
|
|
416
|
+
if not isinstance(managed, list) or not isinstance(unverified, list):
|
|
417
|
+
managed, unverified = managed if isinstance(managed, list) else [], [MANAGED_NOT_CHECKED]
|
|
418
|
+
return {"assessed": True, "managed_sources": list(managed), "managed_unverified": list(unverified),
|
|
419
|
+
"server_policy": policy, "fully_hermetic": fully_hermetic(managed, unverified, policy),
|
|
420
|
+
"setting_sources_note": SETTING_SOURCES_MOOT}
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def receipt_hermeticity(host):
|
|
424
|
+
"""The receipt's `hermeticity` evidence for a capture's host.json: the assessment it carries, as
|
|
425
|
+
canonical JSON, or one saying it carries none. `fully_hermetic` is derived again from the parts
|
|
426
|
+
the assessment states, so a capture cannot carry a clean verdict its parts do not establish."""
|
|
427
|
+
held = host.get("hermeticity") if isinstance(host, dict) else None
|
|
428
|
+
if isinstance(held, dict) and held.get("assessed") is True:
|
|
429
|
+
return canonical({**held, "fully_hermetic": fully_hermetic(
|
|
430
|
+
held.get("managed_sources"), held.get("managed_unverified"), held.get("server_policy"))})
|
|
431
|
+
if isinstance(held, dict) and held.get("assessed") is False and isinstance(held.get("reason"), str) and held["reason"]:
|
|
432
|
+
return canonical(held)
|
|
433
|
+
return canonical({"assessed": False, "reason": NOT_ASSESSED_MISSING})
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def server_policy_command(args):
|
|
437
|
+
sys.stdout.write(json.dumps(server_policy(args.claude_bin), sort_keys=True) + "\n")
|
|
438
|
+
return 0
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
def prepare(cell, cwd, home, out, strict=False, homes=None, managed_root=""):
|
|
442
|
+
problems = prepare_problems(cell, cwd, homes if homes is not None else operator_homes(home), strict)
|
|
443
|
+
if problems:
|
|
444
|
+
for line in problems:
|
|
445
|
+
print(f"claude-run: {line}", file=sys.stderr)
|
|
446
|
+
return 3
|
|
447
|
+
managed, unverified = managed_sources(managed_root)
|
|
448
|
+
if managed:
|
|
449
|
+
print(f"claude-run: managed settings exist at {', '.join(managed)}; they load under every flag, so this "
|
|
450
|
+
f"call is not fully hermetic, and its capture says so", file=sys.stderr)
|
|
451
|
+
if unverified:
|
|
452
|
+
print(f"claude-run: managed-settings locations could not be checked: {', '.join(unverified)}; this call is "
|
|
453
|
+
f"not confirmed fully hermetic, and its capture says so", file=sys.stderr)
|
|
454
|
+
pathlib.Path(out).write_text(json.dumps({"cwd": str(cwd), "workdir_files": listing(cwd),
|
|
455
|
+
"ancestor_exposure": ancestor_exposure(cwd),
|
|
456
|
+
"managed_settings": managed, "managed_unverified": unverified},
|
|
457
|
+
sort_keys=True),
|
|
458
|
+
encoding="utf-8")
|
|
459
|
+
print(uuid.uuid4())
|
|
460
|
+
return 0
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
# --- the host's records -------------------------------------------------------------------------
|
|
464
|
+
|
|
465
|
+
def read_records(path):
|
|
466
|
+
records = []
|
|
467
|
+
with open(path, encoding="utf-8") as handle:
|
|
468
|
+
for line in handle:
|
|
469
|
+
line = line.strip()
|
|
470
|
+
if line:
|
|
471
|
+
records.append(json.loads(line))
|
|
472
|
+
return records
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
def message_blocks(message):
|
|
476
|
+
content = message.get("content")
|
|
477
|
+
return [{"type": "text", "text": content}] if isinstance(content, str) else list(content or [])
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def classify_user_blocks(blocks):
|
|
481
|
+
"""(instruction files listed in the request, the packet text). The packet is the last text
|
|
482
|
+
block that is neither a system reminder nor a host nudge: the host appends nudges to the
|
|
483
|
+
first user message when it retries, so position alone does not identify it."""
|
|
484
|
+
files, candidates = [], []
|
|
485
|
+
for block in blocks:
|
|
486
|
+
if block.get("type") != "text":
|
|
487
|
+
continue
|
|
488
|
+
text = block.get("text", "")
|
|
489
|
+
if text.startswith(REMINDER_INSTRUCTIONS):
|
|
490
|
+
heads = list(INSTRUCTION_HEADER.finditer(text))
|
|
491
|
+
files.extend({"path": m.group(1), "kind_text": m.group(2)} for m in heads)
|
|
492
|
+
elif text.startswith("<system-reminder>") or any(text.startswith(h) for h in HOST_NUDGES):
|
|
493
|
+
continue
|
|
494
|
+
else:
|
|
495
|
+
candidates.append(text)
|
|
496
|
+
return files, (candidates[-1] if candidates else None)
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def requests_of(records, role):
|
|
500
|
+
"""The requests the host recorded as sent, reconstructed: an `api-request` names its system
|
|
501
|
+
blocks and tools by shape hash and its messages by blob hash (a message equal to a transcript
|
|
502
|
+
record is not stored again, and its hash is recomputed here)."""
|
|
503
|
+
shapes, blobs, sent = {}, {}, []
|
|
504
|
+
for r in records:
|
|
505
|
+
kind = r.get("type")
|
|
506
|
+
message = r.get("message") or {}
|
|
507
|
+
if kind in ("user", "assistant") and message.get("content") is not None:
|
|
508
|
+
m = {"role": message.get("role"), "content": message_blocks(message)}
|
|
509
|
+
blobs.setdefault(sha256(canonical(m)), m)
|
|
510
|
+
if kind == "api-request-shape":
|
|
511
|
+
shapes[r.get("shapeHash")] = r.get("shape") or {}
|
|
512
|
+
elif kind == "api-request-blob":
|
|
513
|
+
blobs[r.get("hash")] = r.get("message")
|
|
514
|
+
elif kind == "api-request":
|
|
515
|
+
sent.append(r)
|
|
516
|
+
by_id = {r.get("id"): r for r in sent}
|
|
517
|
+
|
|
518
|
+
def messages(request, depth=0):
|
|
519
|
+
if depth > 50:
|
|
520
|
+
raise ValueError("request chain too deep")
|
|
521
|
+
base = []
|
|
522
|
+
if request.get("base"):
|
|
523
|
+
if request["base"] not in by_id:
|
|
524
|
+
raise ValueError(f"request {request.get('id')} names a missing base {request['base']}")
|
|
525
|
+
base = messages(by_id[request["base"]], depth + 1)[:request.get("keep", 0)]
|
|
526
|
+
return base + [blobs.get(h) or {"role": "unresolved", "content": []} for h in request.get("tail", [])]
|
|
527
|
+
|
|
528
|
+
out = []
|
|
529
|
+
for r in sent:
|
|
530
|
+
params = r.get("params") or {}
|
|
531
|
+
shape = shapes.get(r.get("shapeHash")) or {}
|
|
532
|
+
tools = shape.get("tools") or []
|
|
533
|
+
structured = [t for t in tools if t.get("name") == "StructuredOutput"]
|
|
534
|
+
q = {"id": r.get("id"), "role": role, "query_source": r.get("querySource"), "model": params.get("model"),
|
|
535
|
+
"effort": (params.get("output_config") or {}).get("effort"), "max_tokens": params.get("max_tokens"),
|
|
536
|
+
"tools": [t.get("name") for t in tools],
|
|
537
|
+
"structured_output_schema": structured[0].get("input_schema") if structured else None,
|
|
538
|
+
"system_blocks": [{"sha256": sha256(b.get("text", "")), "chars": len(b.get("text", ""))}
|
|
539
|
+
for b in shape.get("system") or []],
|
|
540
|
+
"system_text": "\n".join(b.get("text", "") for b in shape.get("system") or []),
|
|
541
|
+
"packet_text": None, "listed_instructions": []}
|
|
542
|
+
try:
|
|
543
|
+
first = next((m for m in messages(r) if m.get("role") == "user"), None)
|
|
544
|
+
except ValueError as exc:
|
|
545
|
+
q["error"] = str(exc)
|
|
546
|
+
first = None
|
|
547
|
+
if first is not None:
|
|
548
|
+
q["listed_instructions"], q["packet_text"] = classify_user_blocks(message_blocks(first))
|
|
549
|
+
out.append(q)
|
|
550
|
+
return out
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def kind_problems(records):
|
|
554
|
+
"""The record kinds and attachment types in `records` outside every measured set, each named
|
|
555
|
+
with the Claude version that wrote the transcript and the versions the sets were measured on.
|
|
556
|
+
Any version passes whose records stay inside the known kinds: the check is for drift, not a pin.
|
|
557
|
+
A transcript in which no record names a version is refused, since the drift could not be named."""
|
|
558
|
+
versions = sorted({r["version"] for r in records if isinstance(r, dict) and isinstance(r.get("version"), str)})
|
|
559
|
+
if not versions:
|
|
560
|
+
return [f"RECORD_VERSION_UNKNOWN {len(records)} record(s), none naming the Claude version that wrote them"]
|
|
561
|
+
known_types = {k for kinds in RECORD_KINDS.values() for k in kinds["types"]}
|
|
562
|
+
known_attachments = {k for kinds in RECORD_KINDS.values() for k in kinds["attachments"]}
|
|
563
|
+
where = f"(Claude {'/'.join(versions)}; the known kinds were measured on {', '.join(sorted(RECORD_KINDS))})"
|
|
564
|
+
problems = sorted({f"RECORD_KIND_UNKNOWN {r.get('type')!r} {where}" for r in records
|
|
565
|
+
if isinstance(r, dict) and r.get("type") not in known_types})
|
|
566
|
+
problems += sorted({f"ATTACHMENT_TYPE_UNKNOWN {(r.get('attachment') or {}).get('type')!r} {where}"
|
|
567
|
+
for r in records if isinstance(r, dict) and r.get("type") == "attachment"
|
|
568
|
+
and (r.get("attachment") or {}).get("type") not in known_attachments
|
|
569
|
+
and not str((r.get("attachment") or {}).get("type") or "").startswith("hook")})
|
|
570
|
+
return problems
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def summarise(path, role):
|
|
574
|
+
"""One transcript's requests, responses, StructuredOutput calls, tool actions and context."""
|
|
575
|
+
records = read_records(path)
|
|
576
|
+
s = {"kind_problems": kind_problems(records), "requests": requests_of(records, role), "assistant": [], "structured_calls": [], "actions": [],
|
|
577
|
+
"instructions": [], "skills": [], "agents": [], "hooks": [], "mcp_servers": [], "cwd": None, "session_id": None}
|
|
578
|
+
seen, results = set(), {}
|
|
579
|
+
for r in records:
|
|
580
|
+
kind = r.get("type")
|
|
581
|
+
message = r.get("message") or {}
|
|
582
|
+
if kind == "attachment":
|
|
583
|
+
a = r.get("attachment") or {}
|
|
584
|
+
at = a.get("type") or ""
|
|
585
|
+
if at == "instructions":
|
|
586
|
+
s["instructions"].extend({"path": f.get("path"), "kind": f.get("type"),
|
|
587
|
+
"sha256": norm_sha256(f.get("content") or "")} for f in a.get("files") or [])
|
|
588
|
+
elif at == "skill_listing" and isinstance(a.get("names"), list):
|
|
589
|
+
s["skills"].extend(a["names"])
|
|
590
|
+
elif at == "deferred_tools_delta":
|
|
591
|
+
# the MCP servers the host connected, or tried to: pending, failed or awaiting auth
|
|
592
|
+
for key in ("pendingMcpServers", "failedMcpServers", "needsAuthMcpServers", "connectedMcpServers"):
|
|
593
|
+
s["mcp_servers"].extend(n if isinstance(n, str) else (n or {}).get("name")
|
|
594
|
+
for n in a.get(key) or [])
|
|
595
|
+
elif at == "agent_listing_delta":
|
|
596
|
+
s["agents"].extend(a.get("addedTypes") or [])
|
|
597
|
+
elif at.startswith("hook"):
|
|
598
|
+
# the hook's event as the host recorded it (design §8.1: hooks by event name),
|
|
599
|
+
# never the attachment's category, which two different hooks share
|
|
600
|
+
s["hooks"].append(a.get("hookEvent") or a.get("hookName") or f"{at}:unnamed")
|
|
601
|
+
elif at == "environment" and isinstance(a.get("snapshot"), dict):
|
|
602
|
+
s["cwd"] = a["snapshot"].get("workingDirectory")
|
|
603
|
+
elif kind == "user":
|
|
604
|
+
if s["session_id"] is None:
|
|
605
|
+
s["session_id"] = r.get("sessionId")
|
|
606
|
+
s["user_cwd"] = r.get("cwd")
|
|
607
|
+
for block in message_blocks(message):
|
|
608
|
+
if isinstance(block, dict) and block.get("type") == "tool_result":
|
|
609
|
+
content = block.get("content")
|
|
610
|
+
text = content if isinstance(content, str) else "".join(
|
|
611
|
+
c.get("text", "") for c in content or [] if isinstance(c, dict))
|
|
612
|
+
results[block.get("tool_use_id")] = {"is_error": bool(block.get("is_error")),
|
|
613
|
+
"chars": len(text), "sha256": sha256(text)}
|
|
614
|
+
elif kind == "assistant":
|
|
615
|
+
for block in message_blocks(message):
|
|
616
|
+
if isinstance(block, dict) and block.get("type") == "tool_use":
|
|
617
|
+
if block.get("name") == "StructuredOutput":
|
|
618
|
+
s["structured_calls"].append(block.get("input"))
|
|
619
|
+
else:
|
|
620
|
+
s["actions"].append({"tool_use_id": block.get("id"), "name": block.get("name"),
|
|
621
|
+
"input": block.get("input"), "role": role})
|
|
622
|
+
msg_id = message.get("id")
|
|
623
|
+
if msg_id in seen: # a split message repeats its record; one per message id
|
|
624
|
+
continue
|
|
625
|
+
seen.add(msg_id)
|
|
626
|
+
s["assistant"].append({"request_id": r.get("requestRef"), "role": role, "model": message.get("model"),
|
|
627
|
+
"stop_reason": message.get("stop_reason"),
|
|
628
|
+
"synthetic": message.get("model") == "<synthetic>" or bool(r.get("isApiErrorMessage"))})
|
|
629
|
+
for action in s["actions"]:
|
|
630
|
+
action["result"] = results.get(action["tool_use_id"])
|
|
631
|
+
return s
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def transcripts(config, session_id):
|
|
635
|
+
"""(main transcripts, subagent transcripts) under the cell's configuration home. With a
|
|
636
|
+
session id the main transcript is that session's file; without one (the inherit profile),
|
|
637
|
+
every top-level session file in the cell."""
|
|
638
|
+
projects = pathlib.Path(config) / "projects"
|
|
639
|
+
if not projects.is_dir():
|
|
640
|
+
return [], []
|
|
641
|
+
mains = sorted(p for p in projects.glob("*/*.jsonl") if session_id is None or p.stem == session_id)
|
|
642
|
+
subs = sorted(p for m in mains for p in (m.parent / m.stem).glob("subagents/*.jsonl"))
|
|
643
|
+
return mains, subs
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def appended_prompts(requests, appended, passthrough):
|
|
647
|
+
"""Every text the caller put into the system prompt, recorded in argv order when the host's
|
|
648
|
+
recorded system text carries it: declared files first, then whatever came after `--`."""
|
|
649
|
+
system = "\n".join(q["system_text"] for q in requests if q["role"] == "main")
|
|
650
|
+
candidates = [dict(item, source="declared") for item in appended]
|
|
651
|
+
i = 0
|
|
652
|
+
while i < len(passthrough):
|
|
653
|
+
flag, value = passthrough[i], None
|
|
654
|
+
name = flag.split("=", 1)[0]
|
|
655
|
+
if name in APPENDING_FLAGS:
|
|
656
|
+
if "=" in flag:
|
|
657
|
+
value = flag.split("=", 1)[1]
|
|
658
|
+
elif i + 1 < len(passthrough):
|
|
659
|
+
value, i = passthrough[i + 1], i + 1
|
|
660
|
+
if value is not None:
|
|
661
|
+
if name.endswith("-file"):
|
|
662
|
+
try:
|
|
663
|
+
data = pathlib.Path(value).read_bytes()
|
|
664
|
+
except OSError:
|
|
665
|
+
data = None
|
|
666
|
+
else:
|
|
667
|
+
data = value.encode("utf-8")
|
|
668
|
+
if data is not None:
|
|
669
|
+
candidates.append({"name": f"{name} {pathlib.Path(value).name if name.endswith('-file') else ''}".strip(),
|
|
670
|
+
"bytes": data, "source": "passthrough"})
|
|
671
|
+
i += 1
|
|
672
|
+
out = []
|
|
673
|
+
for c in candidates:
|
|
674
|
+
text = c["bytes"].decode("utf-8", "replace").strip()
|
|
675
|
+
if text and text in system:
|
|
676
|
+
entry = {"name": c["name"], "sha256": sha256(c["bytes"]), "source": c["source"]}
|
|
677
|
+
if c.get("declared_sha256"):
|
|
678
|
+
entry["declared_sha256"] = c["declared_sha256"]
|
|
679
|
+
out.append(entry)
|
|
680
|
+
return out
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
# The one JSONL splitter, beside this file and nowhere else, as this file is beside its adapter
|
|
684
|
+
JSONL_LINES = pathlib.Path(__file__).resolve().parent / "jsonl_lines.py"
|
|
685
|
+
_jsonl_lines = None
|
|
686
|
+
|
|
687
|
+
|
|
688
|
+
def jsonl_split(text):
|
|
689
|
+
"""`text` cut at "\n" only: a stream row may hold U+2028 or U+2029 raw inside a string, and a
|
|
690
|
+
bare CR is whitespace; neither ends it. A reader passes text decoded from the file's bytes,
|
|
691
|
+
since text-mode reading turns a bare CR into a line break first."""
|
|
692
|
+
global _jsonl_lines
|
|
693
|
+
if _jsonl_lines is None:
|
|
694
|
+
if not JSONL_LINES.is_file():
|
|
695
|
+
raise FileNotFoundError(f"the JSONL splitter is not beside this helper: {JSONL_LINES}")
|
|
696
|
+
import importlib.util
|
|
697
|
+
spec = importlib.util.spec_from_file_location("agent_bios_jsonl_lines", JSONL_LINES)
|
|
698
|
+
module = importlib.util.module_from_spec(spec)
|
|
699
|
+
spec.loader.exec_module(module)
|
|
700
|
+
_jsonl_lines = module
|
|
701
|
+
return _jsonl_lines.split(text)
|
|
702
|
+
|
|
703
|
+
|
|
704
|
+
def stream_mcp_servers(stream):
|
|
705
|
+
"""The MCP servers the host's stream `system/init` event names."""
|
|
706
|
+
names = []
|
|
707
|
+
try:
|
|
708
|
+
text = pathlib.Path(stream).read_bytes().decode("utf-8", "replace")
|
|
709
|
+
except OSError:
|
|
710
|
+
return names
|
|
711
|
+
for line in jsonl_split(text):
|
|
712
|
+
try:
|
|
713
|
+
obj = json.loads(line)
|
|
714
|
+
except ValueError:
|
|
715
|
+
continue
|
|
716
|
+
if isinstance(obj, dict) and obj.get("type") == "system" and obj.get("subtype") == "init":
|
|
717
|
+
names.extend(m.get("name") if isinstance(m, dict) else m for m in obj.get("mcp_servers") or [])
|
|
718
|
+
return names
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
def result_object(stream):
|
|
722
|
+
"""The host's closing result object: the last `result` line of the stream, or the whole
|
|
723
|
+
output when it is one JSON object (the json output format); None when there is none."""
|
|
724
|
+
try:
|
|
725
|
+
text = pathlib.Path(stream).read_bytes().decode("utf-8", "replace")
|
|
726
|
+
except OSError:
|
|
727
|
+
return None
|
|
728
|
+
try:
|
|
729
|
+
whole = json.loads(text)
|
|
730
|
+
except ValueError:
|
|
731
|
+
whole = None
|
|
732
|
+
if isinstance(whole, dict) and whole.get("type") == "result":
|
|
733
|
+
return whole
|
|
734
|
+
found = None
|
|
735
|
+
for line in jsonl_split(text):
|
|
736
|
+
try:
|
|
737
|
+
obj = json.loads(line)
|
|
738
|
+
except ValueError:
|
|
739
|
+
continue
|
|
740
|
+
if isinstance(obj, dict) and obj.get("type") == "result":
|
|
741
|
+
found = obj
|
|
742
|
+
return found
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def render(args):
|
|
746
|
+
"""host.json for the call, from the cell's records; returns (host, actions, result)."""
|
|
747
|
+
pre = json.loads(pathlib.Path(args.listing).read_text(encoding="utf-8")) if args.listing else {}
|
|
748
|
+
mains, subs = transcripts(args.config, args.session_id)
|
|
749
|
+
summaries, problems = [], []
|
|
750
|
+
for path, role in [(p, "main") for p in mains] + [(p, "subagent") for p in subs]:
|
|
751
|
+
try:
|
|
752
|
+
summaries.append(summarise(path, role))
|
|
753
|
+
except (OSError, ValueError) as exc:
|
|
754
|
+
problems.append(f"TRANSCRIPT_UNREADABLE {path.name}: {exc.__class__.__name__}")
|
|
755
|
+
continue
|
|
756
|
+
problems.extend(f"{problem} in {path.name}" for problem in summaries[-1]["kind_problems"])
|
|
757
|
+
main = next((s for s in summaries if s["requests"] or s["assistant"]), summaries[0] if summaries else None)
|
|
758
|
+
requests = [q for s in summaries for q in s["requests"]]
|
|
759
|
+
appended = [{"name": n, "bytes": pathlib.Path(f).read_bytes(), "declared_sha256": d}
|
|
760
|
+
for n, f, d in zip(args.appended_name, args.appended_file, args.appended_declared)]
|
|
761
|
+
result = result_object(args.stream) if args.stream else None
|
|
762
|
+
host = {
|
|
763
|
+
# the producing profile's flag set is pinned under its own name (seats.json)
|
|
764
|
+
"host": "claude", "call_id": args.call_id, "use": args.use,
|
|
765
|
+
"profile": f"{args.profile}-producing" if args.use == "producing" else args.profile,
|
|
766
|
+
"profile_flags": args.flag, "passthrough": args.extra,
|
|
767
|
+
"profile_flags_sha256": flags_sha256(args.flag + args.extra, args.manifest),
|
|
768
|
+
"cwd": (main or {}).get("cwd") or (main or {}).get("user_cwd"),
|
|
769
|
+
"session_id": (main or {}).get("session_id") or (result or {}).get("session_id") or args.session_id,
|
|
770
|
+
"workdir_files": pre.get("workdir_files", []), "ancestor_exposure": pre.get("ancestor_exposure", []),
|
|
771
|
+
"binary": args.binary, "env_names": sorted(args.env_name),
|
|
772
|
+
"hermeticity": hermeticity(args.profile, pre, read_server_policy(args.server_policy)),
|
|
773
|
+
"transcripts": [str(p.relative_to(pathlib.Path(args.config))) for p in mains + subs],
|
|
774
|
+
"requests": [{k: v for k, v in q.items() if k != "system_text"} for q in requests],
|
|
775
|
+
"assistant": [a for s in summaries for a in s["assistant"]],
|
|
776
|
+
"structured_calls": [c for s in summaries for c in s["structured_calls"]],
|
|
777
|
+
}
|
|
778
|
+
# Evidence with a transcript missing is not evidence of the call: the sources, requests and
|
|
779
|
+
# responses that transcript held would be absent from every check. No context is rendered,
|
|
780
|
+
# which the gate refuses, and the problems are named.
|
|
781
|
+
if summaries and not problems:
|
|
782
|
+
host["context"] = {
|
|
783
|
+
"instructions": sorted({i["path"]: i for s in summaries for i in s["instructions"]}.values(),
|
|
784
|
+
key=lambda i: i["path"]),
|
|
785
|
+
"appended_prompts": appended_prompts(requests, appended, args.extra),
|
|
786
|
+
"skills": sorted({n for s in summaries for n in s["skills"]}),
|
|
787
|
+
"agents": sorted({n for s in summaries for n in s["agents"]}),
|
|
788
|
+
"hooks": sorted({n for s in summaries for n in s["hooks"]}),
|
|
789
|
+
"mcp_servers": sorted({n for n in [*(n for s in summaries for n in s["mcp_servers"]),
|
|
790
|
+
*(stream_mcp_servers(args.stream) if args.stream else [])] if n}),
|
|
791
|
+
}
|
|
792
|
+
if problems:
|
|
793
|
+
host["problems"] = problems
|
|
794
|
+
actions = [a for s in summaries for a in s["actions"]]
|
|
795
|
+
return host, actions, result
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def capture_sha256(root):
|
|
799
|
+
"""One digest over every file under the capture: its relative path and its bytes' sha256."""
|
|
800
|
+
root = pathlib.Path(root)
|
|
801
|
+
return canonical_sha256(sorted([str(p.relative_to(root)), sha256(p.read_bytes())]
|
|
802
|
+
for p in root.rglob("*") if p.is_file()))
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
def receipt_evidence(host, result, capture, schema):
|
|
806
|
+
"""The evidence keys this adapter can derive for its own receipt (design §3.2's list); the
|
|
807
|
+
manifest and payload hashes belong to the caller that declared them."""
|
|
808
|
+
seen = {}
|
|
809
|
+
for a in host["assistant"]:
|
|
810
|
+
if not a["synthetic"] and a["model"]:
|
|
811
|
+
seen.setdefault(a["role"], set()).add(a["model"])
|
|
812
|
+
# No usage keys: result.usage is the last main segment, not the call (design §13.3), and the
|
|
813
|
+
# closing aggregate is complete only once the caller reconciles every request against it.
|
|
814
|
+
return {"call_id": host["call_id"] or "", "profile": host["profile"],
|
|
815
|
+
"profile_flags_sha256": host["profile_flags_sha256"], "cwd": host["cwd"] or "",
|
|
816
|
+
"session_id": host["session_id"] or "",
|
|
817
|
+
"schema_sha256": sha256(pathlib.Path(schema).read_bytes()) if schema else "none",
|
|
818
|
+
"seat_observed": canonical({role: sorted(models) for role, models in sorted(seen.items())}),
|
|
819
|
+
"context_observed_sha256": canonical_sha256(host.get("context")),
|
|
820
|
+
"capture_sha256": capture_sha256(capture), "hermeticity": receipt_hermeticity(host)}
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
def render_command(args):
|
|
824
|
+
host, actions, result = render(args)
|
|
825
|
+
capture = pathlib.Path(args.capture)
|
|
826
|
+
capture.mkdir(parents=True, exist_ok=True)
|
|
827
|
+
(capture / "host.json").write_text(json.dumps(host, indent=1, sort_keys=True, ensure_ascii=False) + "\n",
|
|
828
|
+
encoding="utf-8")
|
|
829
|
+
(capture / "actions.jsonl").write_text("".join(json.dumps(a, sort_keys=True, ensure_ascii=False) + "\n"
|
|
830
|
+
for a in actions), encoding="utf-8")
|
|
831
|
+
if args.evidence_out:
|
|
832
|
+
evidence = receipt_evidence(host, result, capture, args.schema)
|
|
833
|
+
pathlib.Path(args.evidence_out).write_text("".join(f"{k}={v}\n" for k, v in evidence.items()),
|
|
834
|
+
encoding="utf-8")
|
|
835
|
+
if host.get("problems"):
|
|
836
|
+
for line in host["problems"]:
|
|
837
|
+
print(f"claude-run: {line}", file=sys.stderr)
|
|
838
|
+
return 4
|
|
839
|
+
if args.print_result and result is not None:
|
|
840
|
+
sys.stdout.write(json.dumps(result, ensure_ascii=False) + "\n")
|
|
841
|
+
return 0
|
|
842
|
+
|
|
843
|
+
|
|
844
|
+
# --- self-test ----------------------------------------------------------------------------------
|
|
845
|
+
|
|
846
|
+
def self_test():
|
|
847
|
+
import contextlib
|
|
848
|
+
import io
|
|
849
|
+
import shutil
|
|
850
|
+
import tempfile
|
|
851
|
+
failures, ran = [], []
|
|
852
|
+
|
|
853
|
+
def control(name, ok, detail=""):
|
|
854
|
+
ran.append(name)
|
|
855
|
+
if not ok:
|
|
856
|
+
failures.append(f"{name}: {detail}")
|
|
857
|
+
|
|
858
|
+
scratch = pathlib.Path(tempfile.mkdtemp(prefix="claude-hermetic-evidence-"))
|
|
859
|
+
try:
|
|
860
|
+
cwd, config = scratch / "cell" / "cwd", scratch / "cell" / "config"
|
|
861
|
+
cwd.mkdir(parents=True)
|
|
862
|
+
config.mkdir()
|
|
863
|
+
schema = {"type": "object", "properties": {"answer": {"type": "string"}}, "required": ["answer"]}
|
|
864
|
+
packet = "CALL-ID: c1\nReturn the answer.\n"
|
|
865
|
+
base_system = ["You are Claude Code.", "Environment block.", "Tool guidance."]
|
|
866
|
+
|
|
867
|
+
def transcript(name="s1", plants=(), system_extra=(), tools=(), role_model="claude-sonnet-5-5",
|
|
868
|
+
version="2.1.304", extra=()):
|
|
869
|
+
"""A synthetic session in the record shapes the host writes (probe 4), each record but a blob
|
|
870
|
+
naming the writing `version` as the host's do; `extra` records are appended as given."""
|
|
871
|
+
records, user_blocks = [], []
|
|
872
|
+
files = [p for p in plants if p[0] == "instruction"]
|
|
873
|
+
if files:
|
|
874
|
+
text = REMINDER_INSTRUCTIONS + ":\n\n" + "\n\n".join(f"Contents of {p} ({k}):\n\n{c}" for _, p, k, c in files)
|
|
875
|
+
user_blocks.append({"type": "text", "text": text})
|
|
876
|
+
records.append({"type": "attachment", "attachment": {"type": "instructions",
|
|
877
|
+
"files": [{"path": p, "type": k, "content": c} for _, p, k, c in files]}})
|
|
878
|
+
for plant in plants:
|
|
879
|
+
if plant[0] == "skill":
|
|
880
|
+
records.append({"type": "attachment", "attachment": {"type": "skill_listing", "names": [plant[1]]}})
|
|
881
|
+
elif plant[0] == "agent":
|
|
882
|
+
records.append({"type": "attachment", "attachment": {"type": "agent_listing_delta", "addedTypes": [plant[1]]}})
|
|
883
|
+
elif plant[0] == "mcp":
|
|
884
|
+
records.append({"type": "attachment", "attachment": {"type": "deferred_tools_delta",
|
|
885
|
+
"pendingMcpServers": [plant[1]]}})
|
|
886
|
+
elif plant[0] == "hook":
|
|
887
|
+
records.append({"type": "attachment", "attachment": {"type": "hook_success", "hookName": plant[1],
|
|
888
|
+
"hookEvent": plant[1]}})
|
|
889
|
+
user_blocks.append({"type": "text", "text": packet})
|
|
890
|
+
records.append({"type": "attachment", "attachment": {"type": "environment",
|
|
891
|
+
"snapshot": {"workingDirectory": str(cwd)}}})
|
|
892
|
+
records.append({"type": "user", "sessionId": name, "cwd": str(cwd),
|
|
893
|
+
"message": {"role": "user", "content": user_blocks}})
|
|
894
|
+
tool_defs = [{"name": "StructuredOutput", "input_schema": schema}] + [{"name": t} for t in tools]
|
|
895
|
+
records.append({"type": "api-request-shape", "shapeHash": "h1",
|
|
896
|
+
"shape": {"system": [{"text": t} for t in base_system + list(system_extra)], "tools": tool_defs}})
|
|
897
|
+
first = {"role": "user", "content": user_blocks}
|
|
898
|
+
records.append({"type": "api-request", "id": "req-1", "shapeHash": "h1", "tail": [sha256(canonical(first))],
|
|
899
|
+
"params": {"model": role_model, "max_tokens": 32000, "output_config": {"effort": "medium"}}})
|
|
900
|
+
content = []
|
|
901
|
+
for n, (tool, arg, error, body) in enumerate(p[1:] for p in plants if p[0] == "tool"):
|
|
902
|
+
content.append({"type": "tool_use", "id": f"tu{n}", "name": tool, "input": {"file_path": arg}})
|
|
903
|
+
records.append({"type": "user", "message": {"role": "user", "content": [
|
|
904
|
+
{"type": "tool_result", "tool_use_id": f"tu{n}", "is_error": error, "content": body}]}})
|
|
905
|
+
content.append({"type": "tool_use", "id": "so", "name": "StructuredOutput", "input": {"answer": "OK"}})
|
|
906
|
+
records.append({"type": "assistant", "requestRef": "req-1",
|
|
907
|
+
"message": {"id": "msg-1", "role": "assistant", "model": role_model, "stop_reason": "tool_use",
|
|
908
|
+
"content": content}})
|
|
909
|
+
records.extend(extra)
|
|
910
|
+
for r in records:
|
|
911
|
+
if version is not None and r.get("type") != "api-request-blob":
|
|
912
|
+
r.setdefault("version", version)
|
|
913
|
+
folder = config / "projects" / "-cell-cwd"
|
|
914
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
915
|
+
for old in folder.glob("*.jsonl"):
|
|
916
|
+
old.unlink()
|
|
917
|
+
(folder / f"{name}.jsonl").write_text("".join(json.dumps(r) + "\n" for r in records), encoding="utf-8")
|
|
918
|
+
|
|
919
|
+
stream = scratch / "stream.jsonl"
|
|
920
|
+
stream.write_text(json.dumps({"type": "system", "subtype": "init"}) + "\n"
|
|
921
|
+
+ json.dumps({"type": "result", "is_error": False, "structured_output": {"answer": "OK"},
|
|
922
|
+
"usage": {"input_tokens": 3, "output_tokens": 5}}) + "\n", encoding="utf-8")
|
|
923
|
+
listing_file = scratch / "pre.json"
|
|
924
|
+
|
|
925
|
+
def run(flags=("--safe-mode",), extra=(), appended=(), manifest=None, use="judge", policy=None,
|
|
926
|
+
profile="hermetic"):
|
|
927
|
+
ns = argparse.Namespace(listing=str(listing_file), config=str(config), session_id="s1", stream=str(stream),
|
|
928
|
+
call_id="c1", profile=profile, use=use, flag=list(flags), extra=list(extra),
|
|
929
|
+
manifest=manifest, binary="/x/claude", env_name=["HOME"],
|
|
930
|
+
appended_name=[a[0] for a in appended], appended_file=[a[1] for a in appended],
|
|
931
|
+
appended_declared=[a[2] for a in appended], server_policy=policy)
|
|
932
|
+
return render(ns)
|
|
933
|
+
|
|
934
|
+
# positive control first: a clean call records the request as sent and no context at all
|
|
935
|
+
with contextlib.redirect_stdout(io.StringIO()) as minted:
|
|
936
|
+
rc = prepare(str(scratch / "cell"), str(cwd), "", str(listing_file), strict=True,
|
|
937
|
+
homes=[str(scratch / "elsewhere")])
|
|
938
|
+
control("prepare-mints-a-session-id", bool(re.fullmatch(r"[0-9a-f-]{36}\n", minted.getvalue())), minted.getvalue())
|
|
939
|
+
control("prepare-a-clean-cell", rc == 0 and json.loads(listing_file.read_text())["workdir_files"] == [])
|
|
940
|
+
transcript()
|
|
941
|
+
host, actions, result = run()
|
|
942
|
+
context = host.get("context") or {}
|
|
943
|
+
control("clean-call-records-no-context", context == {"instructions": [], "appended_prompts": [], "skills": [],
|
|
944
|
+
"agents": [], "hooks": [], "mcp_servers": []}, str(context))
|
|
945
|
+
q = (host["requests"] or [{}])[0]
|
|
946
|
+
control("request-recorded-as-sent", q.get("packet_text") == packet and q.get("structured_output_schema") == schema
|
|
947
|
+
and q.get("model") == "claude-sonnet-5-5" and q.get("role") == "main", str(q))
|
|
948
|
+
control("host-recorded-cwd-and-session", host["cwd"] == str(cwd) and host["session_id"] == "s1", str(host["cwd"]))
|
|
949
|
+
control("structured-call-and-response", host["structured_calls"] == [{"answer": "OK"}]
|
|
950
|
+
and host["assistant"] == [{"request_id": "req-1", "role": "main", "model": "claude-sonnet-5-5",
|
|
951
|
+
"stop_reason": "tool_use", "synthetic": False}], str(host["assistant"]))
|
|
952
|
+
control("result-object-is-the-last-result-line", result == {"type": "result", "is_error": False,
|
|
953
|
+
"structured_output": {"answer": "OK"},
|
|
954
|
+
"usage": {"input_tokens": 3, "output_tokens": 5}})
|
|
955
|
+
|
|
956
|
+
# D-20261102-29ca35: the record kinds are checked against the union of the measured sets. Every kind
|
|
957
|
+
# the helper reads is in that union, or a transcript holding one would be refused; a version's own set
|
|
958
|
+
# need not hold them all, since it records what its sample showed.
|
|
959
|
+
def read_kinds_measured():
|
|
960
|
+
return (bool(RECORD_KINDS) and set(READ_TYPES) <= {k for v in RECORD_KINDS.values() for k in v["types"]}
|
|
961
|
+
and set(READ_ATTACHMENTS) <= {k for v in RECORD_KINDS.values() for k in v["attachments"]})
|
|
962
|
+
|
|
963
|
+
control("kinds-the-read-ones-are-in-the-measured-union", read_kinds_measured())
|
|
964
|
+
RECORD_KINDS["9.9.9-sparse"] = {"types": ("assistant", "attachment", "user"), "attachments": ("environment",)}
|
|
965
|
+
try:
|
|
966
|
+
transcript(version="9.9.9-sparse")
|
|
967
|
+
host = run()[0]
|
|
968
|
+
control("kinds-a-sparse-sample-is-recorded-as-a-set-not-as-a-removal",
|
|
969
|
+
read_kinds_measured() and "problems" not in host and "context" in host, str(host.get("problems")))
|
|
970
|
+
finally:
|
|
971
|
+
del RECORD_KINDS["9.9.9-sparse"]
|
|
972
|
+
transcript(extra=[{"type": "queue-operation"}, {"type": "attachment", "attachment": {"type": "prompt_snapshot"}}])
|
|
973
|
+
host = run()[0]
|
|
974
|
+
control("kinds-a-known-unread-kind-passes", "problems" not in host and "context" in host, str(host.get("problems")))
|
|
975
|
+
transcript(version="2.1.316")
|
|
976
|
+
host = run()[0]
|
|
977
|
+
control("kinds-another-version-inside-the-known-kinds-passes", "problems" not in host and "context" in host,
|
|
978
|
+
str(host.get("problems")))
|
|
979
|
+
measured = ", ".join(sorted(RECORD_KINDS)) # a re-pin adds a version; the needles follow it
|
|
980
|
+
for label, kwargs, needle in (
|
|
981
|
+
("kinds-a-renamed-record-kind-is-refused-by-name", {"extra": [{"type": "api-request-v2"}]},
|
|
982
|
+
f"RECORD_KIND_UNKNOWN 'api-request-v2' (Claude 2.1.304; the known kinds were measured on {measured}) "
|
|
983
|
+
"in s1.jsonl"),
|
|
984
|
+
("kinds-an-unknown-attachment-type-is-refused-by-name",
|
|
985
|
+
{"extra": [{"type": "attachment", "attachment": {"type": "instructions_v2"}}]},
|
|
986
|
+
"ATTACHMENT_TYPE_UNKNOWN 'instructions_v2' (Claude 2.1.304; the known kinds were measured on "
|
|
987
|
+
f"{measured}) in s1.jsonl"),
|
|
988
|
+
("kinds-a-new-kind-on-another-version-names-both-versions",
|
|
989
|
+
{"version": "2.1.316", "extra": [{"type": "api-request-v2"}]},
|
|
990
|
+
f"RECORD_KIND_UNKNOWN 'api-request-v2' (Claude 2.1.316; the known kinds were measured on {measured})"),
|
|
991
|
+
("kinds-a-transcript-naming-no-version-is-refused", {"version": None},
|
|
992
|
+
"RECORD_VERSION_UNKNOWN")):
|
|
993
|
+
transcript(**kwargs)
|
|
994
|
+
host = run()[0]
|
|
995
|
+
control(label, any(needle in p for p in host.get("problems", [])) and "context" not in host,
|
|
996
|
+
str(host.get("problems")))
|
|
997
|
+
|
|
998
|
+
# D-20261102-6b6676: managed settings are checked before the call, for existence only; present,
|
|
999
|
+
# the call still runs, and its capture names them and says it is not fully hermetic
|
|
1000
|
+
system = "linux" if sys.platform.startswith("linux") else sys.platform
|
|
1001
|
+
managed_root = scratch / "managed-root"
|
|
1002
|
+
control("managed-none-at-a-clean-root", managed_sources(str(managed_root), "darwin", "u") == ([], [])
|
|
1003
|
+
and managed_sources(str(managed_root), "linux", "u") == ([], []))
|
|
1004
|
+
(managed_root / "Library/Application Support/ClaudeCode/managed-settings.d").mkdir(parents=True)
|
|
1005
|
+
(managed_root / "Library/Managed Preferences/u").mkdir(parents=True)
|
|
1006
|
+
(managed_root / "Library/Managed Preferences/u/com.anthropic.claudecode.plist").write_text("")
|
|
1007
|
+
(managed_root / "etc/claude-code").mkdir(parents=True)
|
|
1008
|
+
(managed_root / "etc/claude-code/managed-mcp.json").write_text("")
|
|
1009
|
+
control("managed-each-planted-source-is-named",
|
|
1010
|
+
managed_sources(str(managed_root), "darwin", "u") == ([
|
|
1011
|
+
"/Library/Application Support/ClaudeCode/managed-settings.d",
|
|
1012
|
+
"/Library/Managed Preferences/u/com.anthropic.claudecode.plist"], [])
|
|
1013
|
+
and managed_sources(str(managed_root), "linux", "u") == (["/etc/claude-code/managed-mcp.json"], []))
|
|
1014
|
+
planted = managed_sources(str(managed_root), system, os.environ.get("USER") or os.environ.get("USERNAME") or "")[0]
|
|
1015
|
+
said = io.StringIO()
|
|
1016
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(said):
|
|
1017
|
+
rc = prepare(str(scratch / "cell"), str(cwd), "", str(listing_file), strict=True,
|
|
1018
|
+
homes=[str(scratch / "elsewhere")], managed_root=str(managed_root))
|
|
1019
|
+
transcript()
|
|
1020
|
+
clean_policy = scratch / "server-policy-clean.json"
|
|
1021
|
+
clean_policy.write_text(json.dumps({"status": SERVER_POLICY_CLEAN, "verdict": "clean", "reason": None}),
|
|
1022
|
+
encoding="utf-8")
|
|
1023
|
+
held = run(policy=str(clean_policy))[0].get("hermeticity") or {}
|
|
1024
|
+
control("managed-present-the-call-runs-and-its-capture-says-not-fully-hermetic",
|
|
1025
|
+
rc == 0 and bool(planted) and held.get("managed_sources") == planted and held.get("assessed") is True
|
|
1026
|
+
and held.get("fully_hermetic") is False and "not fully hermetic" in said.getvalue()
|
|
1027
|
+
and held.get("setting_sources_note") == SETTING_SOURCES_MOOT, f"{rc} {held}")
|
|
1028
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
1029
|
+
prepare(str(scratch / "cell"), str(cwd), "", str(listing_file), strict=True,
|
|
1030
|
+
homes=[str(scratch / "elsewhere")], managed_root=str(scratch / "managed-none"))
|
|
1031
|
+
held = run(policy=str(clean_policy))[0].get("hermeticity") or {}
|
|
1032
|
+
control("managed-absent-and-server-clean-the-capture-says-fully-hermetic",
|
|
1033
|
+
held.get("managed_sources") == [] and held.get("managed_unverified") == []
|
|
1034
|
+
and held.get("fully_hermetic") is True and held.get("server_policy", {}).get("verdict") == "clean",
|
|
1035
|
+
str(held))
|
|
1036
|
+
# A location whose check fails is unverified, never absent: a parent the user may not search
|
|
1037
|
+
# (PermissionError; root searches anything, so it is planted only for another user) and a
|
|
1038
|
+
# parent that is a symlink loop (ELOOP, for every user). Unverified, the call still runs, its
|
|
1039
|
+
# capture names each location with the failure's class, and neither it nor the receipt is clean.
|
|
1040
|
+
locked = scratch / "managed-locked"
|
|
1041
|
+
(locked / "Library/Application Support/ClaudeCode").mkdir(parents=True)
|
|
1042
|
+
(locked / "Library/Managed Preferences").symlink_to("Managed Preferences")
|
|
1043
|
+
(locked / "etc").symlink_to("etc")
|
|
1044
|
+
searchable = os.geteuid() != 0
|
|
1045
|
+
(locked / "Library/Application Support/ClaudeCode").chmod(0o000)
|
|
1046
|
+
try:
|
|
1047
|
+
darwin, linux = managed_sources(str(locked), "darwin", "u"), managed_sources(str(locked), "linux", "u")
|
|
1048
|
+
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said:
|
|
1049
|
+
rc = prepare(str(scratch / "cell"), str(cwd), "", str(listing_file), strict=True,
|
|
1050
|
+
homes=[str(scratch / "elsewhere")], managed_root=str(locked))
|
|
1051
|
+
finally:
|
|
1052
|
+
(locked / "Library/Application Support/ClaudeCode").chmod(0o700)
|
|
1053
|
+
want_darwin = [*([f"{p} (PermissionError)" for p in MANAGED_SOURCES["darwin"][:3]] if searchable else []),
|
|
1054
|
+
*(f"{p.format(user='u')} (OSError)" for p in MANAGED_SOURCES["darwin"][3:])]
|
|
1055
|
+
control("managed-a-location-whose-check-fails-is-unverified-not-absent",
|
|
1056
|
+
darwin == ([], want_darwin)
|
|
1057
|
+
and linux == ([], [f"{p} (OSError)" for p in MANAGED_SOURCES["linux"]]), f"{darwin} {linux}")
|
|
1058
|
+
unverified = json.loads(listing_file.read_text()).get("managed_unverified")
|
|
1059
|
+
captured = run(policy=str(clean_policy))[0]
|
|
1060
|
+
held = captured.get("hermeticity") or {}
|
|
1061
|
+
receipt = json.loads(receipt_hermeticity(captured))
|
|
1062
|
+
control("managed-unverified-the-call-runs-and-neither-capture-nor-receipt-is-clean",
|
|
1063
|
+
rc == 0 and bool(unverified) and held.get("managed_unverified") == unverified
|
|
1064
|
+
and held.get("managed_sources") == [] and held.get("fully_hermetic") is False
|
|
1065
|
+
and receipt.get("fully_hermetic") is False and receipt.get("managed_unverified") == unverified
|
|
1066
|
+
and "could not be checked" in said.getvalue(), f"{rc} {unverified} {held} {receipt}")
|
|
1067
|
+
# A pre-call record without the check (an older listing, a run that never checked) is unverified.
|
|
1068
|
+
listing_file.write_text(json.dumps({"cwd": str(cwd), "workdir_files": [], "ancestor_exposure": []}),
|
|
1069
|
+
encoding="utf-8")
|
|
1070
|
+
held = run(policy=str(clean_policy))[0].get("hermeticity") or {}
|
|
1071
|
+
control("managed-a-listing-without-the-check-is-unverified",
|
|
1072
|
+
held.get("managed_unverified") == [MANAGED_NOT_CHECKED] and held.get("fully_hermetic") is False,
|
|
1073
|
+
str(held))
|
|
1074
|
+
with contextlib.redirect_stdout(io.StringIO()):
|
|
1075
|
+
prepare(str(scratch / "cell"), str(cwd), "", str(listing_file), strict=True,
|
|
1076
|
+
homes=[str(scratch / "elsewhere")], managed_root=str(scratch / "managed-none"))
|
|
1077
|
+
# The receipt derives fully_hermetic from the parts again: a capture stating it clean over an
|
|
1078
|
+
# unverified location, or without the unverified list, does not reach the receipt as clean.
|
|
1079
|
+
stated = {"assessed": True, "managed_sources": [], "managed_unverified": [], "fully_hermetic": True,
|
|
1080
|
+
"server_policy": {"status": SERVER_POLICY_CLEAN, "verdict": "clean", "reason": None}}
|
|
1081
|
+
control("receipt-fully-hermetic-is-derived-from-the-parts",
|
|
1082
|
+
json.loads(receipt_hermeticity({"hermeticity": stated}))["fully_hermetic"] is True
|
|
1083
|
+
and json.loads(receipt_hermeticity({"hermeticity": {**stated, "managed_unverified": ["x (OSError)"]}}))[
|
|
1084
|
+
"fully_hermetic"] is False
|
|
1085
|
+
and json.loads(receipt_hermeticity({"hermeticity": {
|
|
1086
|
+
k: v for k, v in stated.items() if k != "managed_unverified"}}))["fully_hermetic"] is False
|
|
1087
|
+
and json.loads(receipt_hermeticity({"hermeticity": {**stated, "server_policy": {
|
|
1088
|
+
"status": None, "verdict": "clean", "reason": "failed"}}}))["fully_hermetic"] is False)
|
|
1089
|
+
|
|
1090
|
+
# D-20261102-252c92: the server-delivered half. Only the documented line's status is kept; clean is
|
|
1091
|
+
# that exact status; anything else is not confirmed; no line, a failure or no answer is unknown.
|
|
1092
|
+
account = "Logged in as someone@example.invalid (Example Org)"
|
|
1093
|
+
for name, (output, code), want in (
|
|
1094
|
+
("server-a-clean-status-is-clean", (f"{account}\n \x1b[1mManaged settings (remote):\x1b[0m "
|
|
1095
|
+
f"{SERVER_POLICY_CLEAN}\n", 0), ("clean", SERVER_POLICY_CLEAN)),
|
|
1096
|
+
("server-another-status-is-not-confirmed",
|
|
1097
|
+
(f"{account}\nManaged settings (remote): 3 settings applied\n", 0), ("not confirmed", "3 settings applied")),
|
|
1098
|
+
("server-a-long-status-is-cut-to-200", ("Managed settings (remote): " + "x" * 300 + "\n", 0),
|
|
1099
|
+
("not confirmed", "x" * 200)),
|
|
1100
|
+
("server-no-line-is-unknown", (f"{account}\nManaged settings: none\n", 0), ("unknown", None)),
|
|
1101
|
+
("server-two-lines-are-unknown", ("Managed settings (remote): a\nManaged settings (remote): b\n", 0),
|
|
1102
|
+
("unknown", None)),
|
|
1103
|
+
("server-a-failed-doctor-is-unknown", (f"Managed settings (remote): {SERVER_POLICY_CLEAN}\n", 1),
|
|
1104
|
+
("unknown", None))):
|
|
1105
|
+
record = server_policy_verdict(output, code)
|
|
1106
|
+
control(name, (record["verdict"], record["status"]) == want and "example.invalid" not in json.dumps(record),
|
|
1107
|
+
f"verdict={record['verdict']!r} status_present={record['status'] is not None}")
|
|
1108
|
+
doctor = scratch / "fake-doctor"
|
|
1109
|
+
# it answers clean only when its stdin is the null device, so a doctor handed a pipe is caught
|
|
1110
|
+
doctor.write_text(f"#!{sys.executable}\nimport os, sys, time\nif sys.argv[1:] != ['doctor']:\n sys.exit(9)\n"
|
|
1111
|
+
"time.sleep(float(os.environ.get('FAKE_DOCTOR_SLEEP') or 0))\n"
|
|
1112
|
+
"null, fd0 = os.stat(os.devnull), os.fstat(0)\n"
|
|
1113
|
+
"closed = (fd0.st_rdev, fd0.st_ino) == (null.st_rdev, null.st_ino)\n"
|
|
1114
|
+
"print('Account: someone@example.invalid')\n"
|
|
1115
|
+
f"print('Managed settings (remote): ' + ({SERVER_POLICY_CLEAN!r} if closed else 'stdin was open'))\n",
|
|
1116
|
+
encoding="utf-8")
|
|
1117
|
+
doctor.chmod(0o755)
|
|
1118
|
+
# through the subcommand claude-run runs, itself handed a pipe on stdin, so a doctor that inherited
|
|
1119
|
+
# it would say so whatever this suite's own stdin is
|
|
1120
|
+
import subprocess
|
|
1121
|
+
asked = subprocess.run([sys.executable, str(pathlib.Path(__file__).resolve()), "server-policy",
|
|
1122
|
+
"--claude-bin", str(doctor)], input=b"", stdout=subprocess.PIPE, timeout=60)
|
|
1123
|
+
try:
|
|
1124
|
+
record = json.loads(asked.stdout)
|
|
1125
|
+
except ValueError:
|
|
1126
|
+
record = {}
|
|
1127
|
+
control("server-doctor-runs-with-stdin-closed-and-keeps-one-line",
|
|
1128
|
+
asked.returncode == 0 and record == {"status": SERVER_POLICY_CLEAN, "verdict": "clean", "reason": None},
|
|
1129
|
+
f"exit={asked.returncode} verdict={record.get('verdict')!r}")
|
|
1130
|
+
os.environ["FAKE_DOCTOR_SLEEP"] = "5"
|
|
1131
|
+
try:
|
|
1132
|
+
record = server_policy(str(doctor), timeout=0.5)
|
|
1133
|
+
finally:
|
|
1134
|
+
os.environ.pop("FAKE_DOCTOR_SLEEP", None)
|
|
1135
|
+
control("server-a-doctor-past-its-bound-is-unknown",
|
|
1136
|
+
record["verdict"] == "unknown" and "did not finish within 0.5 s" in (record["reason"] or ""), str(record))
|
|
1137
|
+
unknown = run(policy=None)[0].get("hermeticity") or {}
|
|
1138
|
+
control("server-unchecked-is-unknown-and-never-fully-hermetic",
|
|
1139
|
+
unknown.get("server_policy", {}).get("verdict") == "unknown" and unknown.get("fully_hermetic") is False,
|
|
1140
|
+
str(unknown))
|
|
1141
|
+
forged = scratch / "server-policy-forged.json"
|
|
1142
|
+
forged.write_text(json.dumps({"status": "2 settings applied", "verdict": "clean", "reason": None}), encoding="utf-8")
|
|
1143
|
+
held = run(policy=str(forged))[0].get("hermeticity") or {}
|
|
1144
|
+
control("server-a-clean-verdict-on-another-status-is-not-one",
|
|
1145
|
+
held.get("server_policy", {}).get("verdict") == "unknown" and held.get("fully_hermetic") is False, str(held))
|
|
1146
|
+
refused = scratch / "server-policy-refused.json"
|
|
1147
|
+
refused.write_text(json.dumps(server_policy_verdict("Managed settings (remote): 3 settings applied\n", 0)),
|
|
1148
|
+
encoding="utf-8")
|
|
1149
|
+
held = run(policy=str(refused))[0].get("hermeticity") or {}
|
|
1150
|
+
control("server-not-confirmed-is-recorded-and-not-fully-hermetic",
|
|
1151
|
+
held.get("server_policy", {}).get("status") == "3 settings applied" and held.get("fully_hermetic") is False,
|
|
1152
|
+
str(held))
|
|
1153
|
+
# doctor and the call's own startup fetch write these into the configuration home; they are not a signal
|
|
1154
|
+
for name in ("remote-settings.json", ".synced-at", "policy-limits.json", "policy-limits.signature.json",
|
|
1155
|
+
"policy-limits.stamp.json"):
|
|
1156
|
+
(config / name).write_text("{}", encoding="utf-8")
|
|
1157
|
+
fetched = run(policy=str(clean_policy))[0]
|
|
1158
|
+
control("server-fetched-policy-files-in-the-cell-are-not-problems", "problems" not in fetched
|
|
1159
|
+
and "context" in fetched and (fetched.get("hermeticity") or {}).get("fully_hermetic") is True,
|
|
1160
|
+
str(fetched.get("problems")))
|
|
1161
|
+
for name in ("remote-settings.json", ".synced-at", "policy-limits.json", "policy-limits.signature.json",
|
|
1162
|
+
"policy-limits.stamp.json"):
|
|
1163
|
+
(config / name).unlink()
|
|
1164
|
+
# the receipt's hermeticity: the assessment the capture carries, or one saying it carries none
|
|
1165
|
+
inherit = run(policy=str(clean_policy), profile="inherit")[0]
|
|
1166
|
+
control("receipt-hermeticity-is-the-captures-assessment",
|
|
1167
|
+
receipt_hermeticity(fetched) == canonical(fetched["hermeticity"])
|
|
1168
|
+
and json.loads(receipt_hermeticity(inherit)) == {"assessed": False, "reason": NOT_ASSESSED_INHERIT}
|
|
1169
|
+
and json.loads(receipt_hermeticity({"host": "claude"})) == {"assessed": False, "reason": NOT_ASSESSED_MISSING}
|
|
1170
|
+
and json.loads(receipt_hermeticity({"hermeticity": {"assessed": False}}))["reason"] == NOT_ASSESSED_MISSING,
|
|
1171
|
+
receipt_hermeticity(inherit))
|
|
1172
|
+
|
|
1173
|
+
# the five §3.2 sources, each as the host records it when it loads one: each must be recorded
|
|
1174
|
+
for label, plant, needle in (
|
|
1175
|
+
("working-directory-instruction", ("instruction", f"{cwd}/CLAUDE.md", "Project", "w"), ("instructions", "Project")),
|
|
1176
|
+
("ancestor-instruction", ("instruction", f"{scratch}/CLAUDE.md", "Project", "a"), ("instructions", "Project")),
|
|
1177
|
+
("configuration-home-instruction", ("instruction", f"{config}/CLAUDE.md", "User", "c"), ("instructions", "User")),
|
|
1178
|
+
("memory-file", ("instruction", f"{config}/projects/-cell-cwd/memory/MEMORY.md", "AutoMem", "m"), ("instructions", "AutoMem")),
|
|
1179
|
+
("skill", ("skill", "planted-skill"), ("skills", "planted-skill"))):
|
|
1180
|
+
transcript(plants=[plant])
|
|
1181
|
+
got = run()[0].get("context") or {}
|
|
1182
|
+
if needle[0] == "instructions":
|
|
1183
|
+
hit = [i for i in got.get("instructions", []) if i["path"] == plant[1] and i["kind"] == needle[1]
|
|
1184
|
+
and i["sha256"] == norm_sha256(plant[3])]
|
|
1185
|
+
else:
|
|
1186
|
+
hit = [s for s in got.get("skills", []) if s == needle[1]]
|
|
1187
|
+
control(f"loaded-{label}-is-recorded", len(hit) == 1, str(got))
|
|
1188
|
+
transcript(plants=[("agent", "reviewer")])
|
|
1189
|
+
control("loaded-agent-is-recorded", (run()[0].get("context") or {}).get("agents") == ["reviewer"])
|
|
1190
|
+
# two hooks share the hook_success category: each is recorded by the event the host named
|
|
1191
|
+
transcript(plants=[("hook", "UserPromptSubmit"), ("hook", "SessionStart")])
|
|
1192
|
+
got = (run()[0].get("context") or {}).get("hooks")
|
|
1193
|
+
control("hooks-are-recorded-by-event-name", got == ["SessionStart", "UserPromptSubmit"], str(got))
|
|
1194
|
+
# MCP servers by name (design §8.1), from the transcript and from the stream's init event
|
|
1195
|
+
transcript(plants=[("mcp", "plant-mcp")])
|
|
1196
|
+
got = (run()[0].get("context") or {}).get("mcp_servers")
|
|
1197
|
+
control("transcript-mcp-server-is-recorded", got == ["plant-mcp"], str(got))
|
|
1198
|
+
transcript()
|
|
1199
|
+
saved = stream.read_text(encoding="utf-8")
|
|
1200
|
+
stream.write_text(json.dumps({"type": "system", "subtype": "init", "mcp_servers": [{"name": "init-mcp",
|
|
1201
|
+
"status": "pending"}]})
|
|
1202
|
+
+ "\n" + saved, encoding="utf-8")
|
|
1203
|
+
got = (run()[0].get("context") or {}).get("mcp_servers")
|
|
1204
|
+
stream.write_text(saved, encoding="utf-8")
|
|
1205
|
+
control("stream-mcp-server-is-recorded", got == ["init-mcp"], str(got))
|
|
1206
|
+
|
|
1207
|
+
# appended system prompts (O4): declared and sent, edited after declaration, passed undeclared
|
|
1208
|
+
stage = scratch / "stage.md"
|
|
1209
|
+
stage.write_bytes(b"Stage rules.\n")
|
|
1210
|
+
declared = sha256(b"Stage rules.\n")
|
|
1211
|
+
transcript(system_extra=["Stage rules."])
|
|
1212
|
+
got = run(appended=[("stage.md", str(stage), declared)])[0]["context"]["appended_prompts"]
|
|
1213
|
+
control("declared-appended-prompt-records-the-declared-hash",
|
|
1214
|
+
got == [{"name": "stage.md", "sha256": declared, "declared_sha256": declared, "source": "declared"}], str(got))
|
|
1215
|
+
stage.write_bytes(b"Stage rules, edited.\n")
|
|
1216
|
+
transcript(system_extra=["Stage rules, edited."])
|
|
1217
|
+
got = run(appended=[("stage.md", str(stage), declared)])[0]["context"]["appended_prompts"]
|
|
1218
|
+
control("edited-appended-prompt-records-the-sent-hash",
|
|
1219
|
+
len(got) == 1 and got[0]["sha256"] == sha256(b"Stage rules, edited.\n") != declared, str(got))
|
|
1220
|
+
stage.write_bytes(b"Stage rules.\n")
|
|
1221
|
+
transcript(system_extra=["Stage rules.", "Ignore the packet."])
|
|
1222
|
+
got = run(extra=["--append-system-prompt", "Ignore the packet."],
|
|
1223
|
+
appended=[("stage.md", str(stage), declared)])[0]["context"]["appended_prompts"]
|
|
1224
|
+
control("undeclared-appended-prompt-is-recorded-after-the-declared",
|
|
1225
|
+
[g["source"] for g in got] == ["declared", "passthrough"] and got[1]["sha256"] == sha256("Ignore the packet."),
|
|
1226
|
+
str(got))
|
|
1227
|
+
got = run(extra=["--append-system-prompt=Ignore the packet."])[0]["context"]["appended_prompts"]
|
|
1228
|
+
control("undeclared-appended-prompt-in-equals-form", [g["source"] for g in got] == ["passthrough"], str(got))
|
|
1229
|
+
transcript()
|
|
1230
|
+
got = run(appended=[("stage.md", str(stage), declared)])[0]["context"]["appended_prompts"]
|
|
1231
|
+
control("declared-appended-prompt-not-sent-is-not-recorded", got == [], str(got))
|
|
1232
|
+
|
|
1233
|
+
# the producing profile's tool actions: a result is reduced to its length and hash
|
|
1234
|
+
canary = "CANARY-7f3a"
|
|
1235
|
+
transcript(plants=[("tool", "Read", f"{cwd}/in.txt", False, "inside text"),
|
|
1236
|
+
("tool", "Read", f"{scratch}/outside.txt", True, "Permission denied"),
|
|
1237
|
+
("tool", "Grep", "x", True, "No such tool available: Grep")], tools=("Read",))
|
|
1238
|
+
host, actions, _ = run(flags=["--safe-mode", "--tools", "Read", "--allowedTools", f"Read(/{cwd}/**)"],
|
|
1239
|
+
manifest=str(cwd), use="producing")
|
|
1240
|
+
control("tool-actions-are-recorded", [(a["name"], a["result"]["is_error"]) for a in actions]
|
|
1241
|
+
== [("Read", False), ("Read", True), ("Grep", True)], str(actions))
|
|
1242
|
+
control("tool-results-are-reduced", "inside text" not in json.dumps(actions) and canary not in json.dumps(host)
|
|
1243
|
+
and actions[0]["result"]["sha256"] == sha256("inside text"))
|
|
1244
|
+
control("producing-profile-is-named-apart", host["profile"] == "hermetic-producing", host["profile"])
|
|
1245
|
+
control("producing-flag-hash-is-manifest-independent",
|
|
1246
|
+
host["profile_flags_sha256"] == flags_sha256(["--safe-mode", "--tools", "Read", "--allowedTools",
|
|
1247
|
+
f"Read(//{MANIFEST_PLACEHOLDER}/**)"]))
|
|
1248
|
+
control("passthrough-changes-the-flag-hash", flags_sha256(["--safe-mode"]) != flags_sha256(["--safe-mode", "--x"]))
|
|
1249
|
+
|
|
1250
|
+
# refusals by name
|
|
1251
|
+
problems = prepare_problems(str(scratch / "cell"), str(cwd), [str(scratch)], True)
|
|
1252
|
+
control("cell-under-home-is-refused", any(p.startswith("CELL_UNDER_HOME the cell") for p in problems), str(problems))
|
|
1253
|
+
problems = prepare_problems(str(scratch / "cell"), str(scratch / "absent"), [str(scratch / "elsewhere")], True)
|
|
1254
|
+
control("missing-working-directory-is-refused", any(p.startswith("CELL_CWD_MISSING") for p in problems), str(problems))
|
|
1255
|
+
|
|
1256
|
+
# plan P5 on the cell root, before anything is made: the clean root first
|
|
1257
|
+
root = scratch / "root"
|
|
1258
|
+
root.mkdir(mode=0o700)
|
|
1259
|
+
root.chmod(0o700)
|
|
1260
|
+
control("clean-cell-root-is-accepted", root_problems(root, [str(scratch / "elsewhere")]) == [],
|
|
1261
|
+
str(root_problems(root, [str(scratch / "elsewhere")])))
|
|
1262
|
+
root.chmod(0o755)
|
|
1263
|
+
control("cell-root-not-700-is-refused", any(p.startswith("CELL_ROOT_MODE") for p in root_problems(root, [])))
|
|
1264
|
+
system = pathlib.Path("/usr") # owned by root; only read here
|
|
1265
|
+
control("cell-root-of-another-owner-is-refused", os.getuid() == system.stat().st_uid
|
|
1266
|
+
or any(p.startswith("CELL_ROOT_OWNER") for p in root_problems(system, [])))
|
|
1267
|
+
root.chmod(0o700)
|
|
1268
|
+
for name in (".codex", "settings.json"):
|
|
1269
|
+
(scratch / name).mkdir() if name.startswith(".") else (scratch / name).write_text("{}")
|
|
1270
|
+
got = root_problems(root, [])
|
|
1271
|
+
control(f"planted-ancestor-{name}-refused-by-path",
|
|
1272
|
+
f"CELL_ANCESTOR_SURFACE {scratch.resolve() / name}" in " ".join(got), str(got))
|
|
1273
|
+
shutil.rmtree(scratch / name) if name.startswith(".") else (scratch / name).unlink()
|
|
1274
|
+
# the cell used is the root's: clean, a cell elsewhere, a home that leaves by symlink, a read root
|
|
1275
|
+
bound = root / "c1"
|
|
1276
|
+
for part in ("home", "config", "cwd"):
|
|
1277
|
+
(bound / part).mkdir(parents=True)
|
|
1278
|
+
control("cell-under-the-root-is-bound", bind_problems(root, bound, bound / "cwd", bound / "cwd") == [],
|
|
1279
|
+
str(bind_problems(root, bound, bound / "cwd", bound / "cwd")))
|
|
1280
|
+
stray = scratch / "elsewhere-cell"
|
|
1281
|
+
for part in ("home", "config", "cwd"):
|
|
1282
|
+
(stray / part).mkdir(parents=True)
|
|
1283
|
+
got = bind_problems(root, stray, stray / "cwd")
|
|
1284
|
+
control("cell-outside-the-root-is-refused", any(p.startswith("CELL_OUTSIDE_ROOT the cell ") for p in got), str(got))
|
|
1285
|
+
shutil.rmtree(bound / "home")
|
|
1286
|
+
(bound / "home").symlink_to(stray / "home")
|
|
1287
|
+
got = bind_problems(root, bound, bound / "cwd")
|
|
1288
|
+
control("home-leaving-by-symlink-is-refused", any(p.startswith("CELL_OUTSIDE_ROOT the cell home") for p in got), str(got))
|
|
1289
|
+
got = bind_problems(root, bound, bound / "cwd", stray / "cwd")
|
|
1290
|
+
control("read-root-other-than-the-workdir-is-refused", any(p.startswith("READ_ROOT_MISMATCH") for p in got), str(got))
|
|
1291
|
+
shutil.rmtree(bound)
|
|
1292
|
+
real_home = operator_homes()[0]
|
|
1293
|
+
unmade = pathlib.Path(real_home) / ".claude-run-self-test-never-made" / "cells"
|
|
1294
|
+
got = root_problems(unmade, operator_homes(str(scratch / "elsewhere")))
|
|
1295
|
+
control("home-pointed-elsewhere-does-not-bypass-the-home-rule",
|
|
1296
|
+
any(p.startswith("CELL_UNDER_HOME") for p in got) and not unmade.parent.exists(), str(got))
|
|
1297
|
+
(scratch / "CLAUDE.md").write_text("ancestor\n", encoding="utf-8")
|
|
1298
|
+
exposure = ancestor_exposure(cwd)
|
|
1299
|
+
control("ancestor-surface-is-recorded", any(e["path"] == str((scratch / "CLAUDE.md").resolve()) for e in exposure),
|
|
1300
|
+
str(exposure))
|
|
1301
|
+
got = prepare_problems(str(scratch / "cell"), str(cwd), [str(scratch / "elsewhere")], True)
|
|
1302
|
+
control("strict-prepare-refuses-the-ancestor-by-path",
|
|
1303
|
+
f"CELL_ANCESTOR_SURFACE {(scratch / 'CLAUDE.md').resolve()}" in " ".join(got), str(got))
|
|
1304
|
+
control("lenient-prepare-only-records-it",
|
|
1305
|
+
prepare_problems(str(scratch / "cell"), str(cwd), [str(scratch / "elsewhere")], False) == [])
|
|
1306
|
+
(cwd / "note.txt").write_text("n", encoding="utf-8")
|
|
1307
|
+
control("listing-names-the-working-directory-files", listing(cwd) == [{"path": "note.txt", "sha256": sha256("n")}])
|
|
1308
|
+
stream.write_text("not json\n", encoding="utf-8")
|
|
1309
|
+
control("no-result-line-is-none", result_object(stream) is None)
|
|
1310
|
+
# a stream row ends at "\n" only: the host writes U+2028 and U+2029 raw inside a string, and
|
|
1311
|
+
# a bare CR between tokens is JSON whitespace; neither ends the row
|
|
1312
|
+
sep = "before\u2028between\u2029after"
|
|
1313
|
+
init = {"type": "system", "subtype": "init", "cwd": sep, "mcp_servers": [{"name": "fixture-server"}]}
|
|
1314
|
+
closing = {"type": "result", "subtype": "success", "result": sep}
|
|
1315
|
+
stream.write_bytes((json.dumps(init, ensure_ascii=False) + "\n" + json.dumps(closing, ensure_ascii=False) + "\n")
|
|
1316
|
+
.encode("utf-8"))
|
|
1317
|
+
control("jsonl-line-separators-inside-a-string-read-whole (stream_mcp_servers)",
|
|
1318
|
+
stream_mcp_servers(stream) == ["fixture-server"], str(stream_mcp_servers(stream)))
|
|
1319
|
+
control("jsonl-line-separators-inside-a-string-read-whole (result_object)", result_object(stream) == closing,
|
|
1320
|
+
str(result_object(stream)))
|
|
1321
|
+
stream.write_bytes(("{\r" + json.dumps(init)[1:] + "\r\n" + "{\r" + json.dumps(closing)[1:] + "\n").encode("utf-8"))
|
|
1322
|
+
control("jsonl-bare-cr-whitespace-and-crlf-read-whole (stream_mcp_servers)",
|
|
1323
|
+
stream_mcp_servers(stream) == ["fixture-server"], str(stream_mcp_servers(stream)))
|
|
1324
|
+
control("jsonl-bare-cr-whitespace-and-crlf-read-whole (result_object)", result_object(stream) == closing,
|
|
1325
|
+
str(result_object(stream)))
|
|
1326
|
+
|
|
1327
|
+
# a request chain the transcript cannot resolve, and a transcript that is not JSON lines:
|
|
1328
|
+
# each is recorded by name and leaves no context to be read as clean
|
|
1329
|
+
transcript()
|
|
1330
|
+
session = next((config / "projects").glob("*/s1.jsonl"))
|
|
1331
|
+
lines = session.read_text(encoding="utf-8").splitlines()
|
|
1332
|
+
with_base = [json.dumps(dict(json.loads(l), base="req-missing")) if json.loads(l).get("type") == "api-request" else l
|
|
1333
|
+
for l in lines]
|
|
1334
|
+
session.write_text("\n".join(with_base) + "\n", encoding="utf-8")
|
|
1335
|
+
q = run()[0]["requests"][0]
|
|
1336
|
+
control("missing-base-request-is-named", "names a missing base" in q.get("error", "") and q["packet_text"] is None, str(q))
|
|
1337
|
+
looped = [json.dumps(dict(json.loads(l), base="req-1", keep=1)) if json.loads(l).get("type") == "api-request" else l
|
|
1338
|
+
for l in lines]
|
|
1339
|
+
session.write_text("\n".join(looped) + "\n", encoding="utf-8")
|
|
1340
|
+
q = run()[0]["requests"][0]
|
|
1341
|
+
control("looping-request-chain-is-named", "too deep" in q.get("error", ""), str(q))
|
|
1342
|
+
session.write_text("{not json\n", encoding="utf-8")
|
|
1343
|
+
host = run()[0]
|
|
1344
|
+
control("unreadable-transcript-is-named", any(p.startswith("TRANSCRIPT_UNREADABLE s1.jsonl") for p in host.get("problems", []))
|
|
1345
|
+
and "context" not in host, str(host.get("problems")))
|
|
1346
|
+
# a readable main beside an unreadable subagent transcript is not clean evidence either
|
|
1347
|
+
transcript()
|
|
1348
|
+
child = config / "projects" / "-cell-cwd" / "s1" / "subagents"
|
|
1349
|
+
child.mkdir(parents=True)
|
|
1350
|
+
(child / "agent-1.jsonl").write_text("{not json\n", encoding="utf-8")
|
|
1351
|
+
host = run()[0]
|
|
1352
|
+
control("partial-transcript-set-renders-no-context", "context" not in host and host["requests"]
|
|
1353
|
+
and any("agent-1.jsonl" in p for p in host.get("problems", [])), str(host.get("problems")))
|
|
1354
|
+
shutil.rmtree(child.parent)
|
|
1355
|
+
evidence = receipt_evidence(run()[0], {"usage": {"input_tokens": 3}}, scratch, None)
|
|
1356
|
+
control("receipt-claims-no-call-usage", not {"usage_state", "usage_totals"} & set(evidence), str(sorted(evidence)))
|
|
1357
|
+
finally:
|
|
1358
|
+
shutil.rmtree(scratch, ignore_errors=True)
|
|
1359
|
+
|
|
1360
|
+
for failure in failures:
|
|
1361
|
+
print(f"claude_hermetic_evidence --self-test [FAIL] {failure}")
|
|
1362
|
+
if failures:
|
|
1363
|
+
return 1
|
|
1364
|
+
print(f"claude_hermetic_evidence --self-test: OK ({len(ran)} controls: " + ", ".join(ran) + ")")
|
|
1365
|
+
return 0
|
|
1366
|
+
|
|
1367
|
+
|
|
1368
|
+
def main(argv):
|
|
1369
|
+
if argv[1:] == ["--self-test"]:
|
|
1370
|
+
return self_test()
|
|
1371
|
+
parser = argparse.ArgumentParser(prog="claude_hermetic_evidence.py")
|
|
1372
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
1373
|
+
p = sub.add_parser("prepare")
|
|
1374
|
+
p.add_argument("--cell", required=True)
|
|
1375
|
+
p.add_argument("--cwd", required=True)
|
|
1376
|
+
p.add_argument("--home", default="")
|
|
1377
|
+
p.add_argument("--out", required=True)
|
|
1378
|
+
p.add_argument("--strict", action="store_true")
|
|
1379
|
+
b = sub.add_parser("bind")
|
|
1380
|
+
b.add_argument("--root", required=True)
|
|
1381
|
+
b.add_argument("--cell", required=True)
|
|
1382
|
+
b.add_argument("--cwd", required=True)
|
|
1383
|
+
b.add_argument("--manifest")
|
|
1384
|
+
c = sub.add_parser("check-root")
|
|
1385
|
+
c.add_argument("--root", required=True)
|
|
1386
|
+
c.add_argument("--home", default="")
|
|
1387
|
+
r = sub.add_parser("render")
|
|
1388
|
+
r.add_argument("--capture", required=True)
|
|
1389
|
+
r.add_argument("--config", required=True)
|
|
1390
|
+
r.add_argument("--listing")
|
|
1391
|
+
r.add_argument("--session-id")
|
|
1392
|
+
r.add_argument("--stream")
|
|
1393
|
+
r.add_argument("--call-id")
|
|
1394
|
+
r.add_argument("--profile", required=True)
|
|
1395
|
+
r.add_argument("--use")
|
|
1396
|
+
r.add_argument("--flag", action="append", default=[])
|
|
1397
|
+
r.add_argument("--extra", action="append", default=[])
|
|
1398
|
+
r.add_argument("--manifest")
|
|
1399
|
+
r.add_argument("--binary")
|
|
1400
|
+
r.add_argument("--env-name", action="append", default=[])
|
|
1401
|
+
r.add_argument("--appended-name", action="append", default=[])
|
|
1402
|
+
r.add_argument("--appended-file", action="append", default=[])
|
|
1403
|
+
r.add_argument("--appended-declared", action="append", default=[])
|
|
1404
|
+
r.add_argument("--schema")
|
|
1405
|
+
r.add_argument("--evidence-out")
|
|
1406
|
+
r.add_argument("--print-result", action="store_true")
|
|
1407
|
+
r.add_argument("--server-policy")
|
|
1408
|
+
s = sub.add_parser("server-policy")
|
|
1409
|
+
s.add_argument("--claude-bin", required=True)
|
|
1410
|
+
args = parser.parse_args(argv[1:])
|
|
1411
|
+
if args.command == "prepare":
|
|
1412
|
+
return prepare(args.cell, args.cwd, args.home, args.out, strict=args.strict)
|
|
1413
|
+
if args.command == "bind":
|
|
1414
|
+
return bind(args.root, args.cell, args.cwd, args.manifest)
|
|
1415
|
+
if args.command == "check-root":
|
|
1416
|
+
return check_root(args.root, args.home)
|
|
1417
|
+
if args.command == "server-policy":
|
|
1418
|
+
return server_policy_command(args)
|
|
1419
|
+
return render_command(args)
|
|
1420
|
+
|
|
1421
|
+
|
|
1422
|
+
if __name__ == "__main__":
|
|
1423
|
+
sys.exit(main(sys.argv))
|