anthromesh 0.2.0__py3-none-any.whl

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.
Files changed (73) hide show
  1. anthromesh/__init__.py +3 -0
  2. anthromesh/adapters/__init__.py +18 -0
  3. anthromesh/adapters/base.py +218 -0
  4. anthromesh/adapters/cloud.py +151 -0
  5. anthromesh/adapters/factory.py +31 -0
  6. anthromesh/adapters/heuristic.py +113 -0
  7. anthromesh/adapters/local.py +91 -0
  8. anthromesh/benchmarks/__init__.py +3 -0
  9. anthromesh/benchmarks/datasets.py +207 -0
  10. anthromesh/benchmarks/empirical.py +176 -0
  11. anthromesh/benchmarks/panel_cohort.py +67 -0
  12. anthromesh/benchmarks/public_twin.py +414 -0
  13. anthromesh/benchmarks/public_validation.py +435 -0
  14. anthromesh/benchmarks/replay.py +174 -0
  15. anthromesh/benchmarks/runner.py +140 -0
  16. anthromesh/benchmarks/study.py +245 -0
  17. anthromesh/benchmarks/study_report.py +170 -0
  18. anthromesh/capture/__init__.py +1 -0
  19. anthromesh/capture/github_webhook.py +51 -0
  20. anthromesh/capture/graph.py +221 -0
  21. anthromesh/capture/workflows.py +70 -0
  22. anthromesh/cli.py +807 -0
  23. anthromesh/client.py +96 -0
  24. anthromesh/cohort/__init__.py +3 -0
  25. anthromesh/cohort/categorical_anchor.py +240 -0
  26. anthromesh/cohort/clustering.py +93 -0
  27. anthromesh/cohort/human_anchor.py +92 -0
  28. anthromesh/cohort/ingest.py +104 -0
  29. anthromesh/cohort/oracle.py +153 -0
  30. anthromesh/cohort/twin_priors.py +118 -0
  31. anthromesh/config.py +48 -0
  32. anthromesh/gate/__init__.py +15 -0
  33. anthromesh/gate/calibration.py +95 -0
  34. anthromesh/gate/conformal.py +73 -0
  35. anthromesh/gate/engine.py +293 -0
  36. anthromesh/gate/fast.py +62 -0
  37. anthromesh/gate/fit.py +56 -0
  38. anthromesh/judgment/__init__.py +1 -0
  39. anthromesh/judgment/elicitation.py +206 -0
  40. anthromesh/judgment/monitor.py +128 -0
  41. anthromesh/judgment/panel.py +389 -0
  42. anthromesh/judgment/settings.py +41 -0
  43. anthromesh/models/__init__.py +39 -0
  44. anthromesh/models/cohort.py +76 -0
  45. anthromesh/models/decision.py +81 -0
  46. anthromesh/models/escalation.py +70 -0
  47. anthromesh/models/policy.py +41 -0
  48. anthromesh/models/validity.py +17 -0
  49. anthromesh/protocols/__init__.py +4 -0
  50. anthromesh/protocols/a2a_server.py +414 -0
  51. anthromesh/protocols/capabilities.py +52 -0
  52. anthromesh/protocols/delegation.py +373 -0
  53. anthromesh/protocols/mcp_server.py +500 -0
  54. anthromesh/protocols/oauth.py +177 -0
  55. anthromesh/ros_gate.py +141 -0
  56. anthromesh/twin/__init__.py +3 -0
  57. anthromesh/twin/engine.py +116 -0
  58. anthromesh/twin/inbox.py +221 -0
  59. anthromesh/vault/__init__.py +5 -0
  60. anthromesh/vault/dense.py +171 -0
  61. anthromesh/vault/encryption.py +50 -0
  62. anthromesh/vault/policy_engine.py +123 -0
  63. anthromesh/vault/postgres.py +92 -0
  64. anthromesh/vault/privacy.py +264 -0
  65. anthromesh/vault/retrieval.py +135 -0
  66. anthromesh/vault/storage.py +937 -0
  67. anthromesh-0.2.0.dist-info/METADATA +493 -0
  68. anthromesh-0.2.0.dist-info/RECORD +73 -0
  69. anthromesh-0.2.0.dist-info/WHEEL +5 -0
  70. anthromesh-0.2.0.dist-info/entry_points.txt +2 -0
  71. anthromesh-0.2.0.dist-info/licenses/LICENSE +201 -0
  72. anthromesh-0.2.0.dist-info/licenses/NOTICE +2 -0
  73. anthromesh-0.2.0.dist-info/top_level.txt +1 -0
anthromesh/cli.py ADDED
@@ -0,0 +1,807 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import time
7
+ from dataclasses import replace
8
+ from pathlib import Path
9
+
10
+ from anthromesh.adapters.base import post_json
11
+ from anthromesh.adapters.factory import create_adapter
12
+ from anthromesh.benchmarks.empirical import score_study
13
+ from anthromesh.benchmarks.public_twin import download_public_twin, evaluate_public_twin
14
+ from anthromesh.benchmarks.public_validation import audit_original_public_run, run_public_validation
15
+ from anthromesh.benchmarks.runner import BenchmarkRunner
16
+ from anthromesh.benchmarks.replay import forecast_study, load_dataset
17
+ from anthromesh.benchmarks.study import load_registration, prepare_study, register_study
18
+ from anthromesh.benchmarks.study_report import evaluate_study
19
+ from anthromesh.capture.graph import GraphCapture
20
+ from anthromesh.capture.github_webhook import create_github_capture_app
21
+ from anthromesh.capture.workflows import calendar_responses, github_reviews
22
+ from anthromesh.cohort.clustering import build_clustered_profile
23
+ from anthromesh.cohort.twin_priors import TwinCohortConsent, grant_cohort_consent, revoke_cohort_consent
24
+ from anthromesh.cohort.ingest import build_empirical_profile, read_survey
25
+ from anthromesh.cohort.categorical_anchor import CategoricalAnchorStudy, analyze_categories, draw_anchor_units
26
+ from anthromesh.cohort.human_anchor import AnchorStudy, analyze_anchors
27
+ from anthromesh.cohort.oracle import ResearchCohortOracle
28
+ from anthromesh.config import AnthroMeshConfig
29
+ from anthromesh.gate.conformal import ConformalCalibration, VaultConformalCalibration
30
+ from anthromesh.gate.fit import fit_profiles
31
+ from anthromesh.judgment.elicitation import Elicitation, ElicitationCase
32
+ from anthromesh.judgment.monitor import PredictionMonitor
33
+ from anthromesh.judgment.panel import HumanPanel, PanelAnswer, PanelProfile, PanelQuestion
34
+ from anthromesh.judgment.settings import JudgmentSettings, save_judgment_settings
35
+ from anthromesh.models import CohortProfile, DecisionLog, EscalationStatus, RiskTier
36
+ from anthromesh.protocols.a2a_server import A2AService
37
+ from anthromesh.protocols.capabilities import CapabilityTokens
38
+ from anthromesh.protocols.mcp_server import MCPServer
39
+ from anthromesh.protocols import delegation
40
+ from anthromesh.protocols.oauth import OAuthResource
41
+ from anthromesh.twin.engine import PersonalDecisionTwin
42
+ from anthromesh.twin.inbox import create_inbox_app
43
+ from anthromesh.vault.encryption import export_encrypted_vault
44
+ from anthromesh.vault.policy_engine import PolicyEngine
45
+ from anthromesh.vault.privacy import SubjectData
46
+ from anthromesh.vault.retrieval import HybridDecisionRetriever
47
+ from anthromesh.vault.storage import BehavioralVault
48
+
49
+
50
+ def _remote_model(cfg: AnthroMeshConfig, adapter_name: str) -> bool:
51
+ from urllib.parse import urlsplit
52
+
53
+ if adapter_name == "heuristic":
54
+ return False
55
+ if adapter_name not in {"ollama", "vllm"}:
56
+ return True
57
+ endpoint = cfg.ollama_base_url if adapter_name == "ollama" else cfg.vllm_base_url
58
+ return urlsplit(endpoint).hostname not in {"localhost", "127.0.0.1", "::1"}
59
+
60
+
61
+ def _open_vault(cfg: AnthroMeshConfig) -> BehavioralVault:
62
+ if cfg.postgres_dsn:
63
+ from anthromesh.vault.postgres import PostgresBehavioralVault
64
+
65
+ if cfg.encryption_key is not None:
66
+ raise ValueError("ANTHROMESH_VAULT_KEY applies to SQLCipher; configure PostgreSQL separately.")
67
+ return PostgresBehavioralVault(cfg.postgres_dsn, schema=cfg.postgres_schema)
68
+ return BehavioralVault(db_path=cfg.db_path, encryption_key=cfg.encryption_key)
69
+
70
+
71
+ def _build_runtime(cfg: AnthroMeshConfig) -> tuple[BehavioralVault, PersonalDecisionTwin, ResearchCohortOracle]:
72
+ vault = _open_vault(cfg)
73
+ organization = (
74
+ PolicyEngine.from_file(cfg.organization_policy_path) if cfg.organization_policy_path else None
75
+ )
76
+ policy_engine = (
77
+ PolicyEngine.from_file(cfg.policy_path, organization=organization)
78
+ if cfg.policy_path
79
+ else PolicyEngine(organization=organization)
80
+ )
81
+ adapter = create_adapter(cfg)
82
+ retriever = None
83
+ if cfg.embedding_model:
84
+ def embed_batch(texts: list[str]) -> list[list[float]]:
85
+ response = post_json(
86
+ f"{cfg.ollama_base_url.rstrip('/')}/api/embed",
87
+ {"model": cfg.embedding_model, "input": texts},
88
+ )
89
+ return response["embeddings"]
90
+
91
+ if cfg.vector_index:
92
+ from anthromesh.vault.dense import DenseDecisionIndex
93
+
94
+ index = DenseDecisionIndex(
95
+ vault, f"ollama:{cfg.ollama_base_url}:{cfg.embedding_model}", embed_batch,
96
+ )
97
+ retriever = HybridDecisionRetriever(dense_index=index)
98
+ else:
99
+ retriever = HybridDecisionRetriever(embed_batch=embed_batch)
100
+ elif cfg.vector_index:
101
+ raise ValueError("Configure ANTHROMESH_EMBEDDING_MODEL to use indexed retrieval.")
102
+
103
+ conformal = None
104
+ if cfg.calibration_path and cfg.managed_calibration:
105
+ raise ValueError("Choose vault-managed or file calibration.")
106
+ if cfg.managed_calibration:
107
+ conformal = VaultConformalCalibration(vault)
108
+ elif cfg.calibration_path:
109
+ conformal = ConformalCalibration.from_file(Path(cfg.calibration_path))
110
+
111
+ twin = PersonalDecisionTwin(
112
+ vault=vault,
113
+ policy_engine=policy_engine,
114
+ adapter=adapter,
115
+ confidence_threshold=cfg.confidence_threshold,
116
+ min_evidence_count=cfg.min_evidence_count,
117
+ retriever=retriever,
118
+ conformal=conformal,
119
+ fast_enabled=cfg.fast_enabled,
120
+ memory_only=cfg.memory_only,
121
+ deliberation_seconds=cfg.deliberation_seconds,
122
+ monitor_enabled=cfg.monitor_enabled,
123
+ )
124
+ oracle = ResearchCohortOracle(vault=vault, adapter=adapter)
125
+ return vault, twin, oracle
126
+
127
+
128
+ def main(argv: list[str] | None = None) -> int:
129
+ parser = argparse.ArgumentParser(
130
+ prog="anthromesh",
131
+ description="AnthroMesh preference memory, owner escalation, and delegation (MCP + A2A).",
132
+ )
133
+ sub = parser.add_subparsers(dest="command", required=True)
134
+
135
+ sub.add_parser("init", help="Initialize the local SQLite Behavioral Vault.")
136
+
137
+ export = sub.add_parser("export-encrypted", help="Copy a plaintext vault to an encrypted file.")
138
+ export.add_argument("source", type=Path)
139
+ export.add_argument("destination", type=Path)
140
+
141
+ seed_p = sub.add_parser("seed", help="Seed decisions and/or cohort profiles from JSON files.")
142
+ seed_p.add_argument("--decisions", type=str, help="Path to JSON list of DecisionLog objects.")
143
+ seed_p.add_argument("--cohort", type=str, help="Path to JSON CohortProfile object.")
144
+
145
+ capture = sub.add_parser("import-decisions", help="Import local workflow exports.")
146
+ capture.add_argument("source", choices=["github-review", "google-calendar"])
147
+ capture.add_argument("path", type=Path)
148
+ capture.add_argument("--subject", required=True)
149
+ capture.add_argument("--account", help="GitHub login to import from a review export.")
150
+
151
+ graph = sub.add_parser("sync-graph", help="Capture consented Microsoft Graph decisions.")
152
+ graph.add_argument("stream", choices=["calendar", "email"])
153
+ graph.add_argument("--subject", required=True)
154
+ graph.add_argument("--account", required=True)
155
+ graph.add_argument("--start", help="Start of the calendar window as an ISO timestamp.")
156
+ graph.add_argument("--end", help="End of the calendar window as an ISO timestamp.")
157
+ graph.add_argument("--drafts", type=Path, help="Draft ID to plain text JSON manifest.")
158
+ graph.add_argument("--track-reschedules", action="store_true")
159
+ graph.add_argument("--poll-seconds", type=int)
160
+ graph.add_argument("--token-file", type=Path, help="Optional file containing a delegated access token.")
161
+ graph.add_argument("--reset", action="store_true")
162
+
163
+ webhook = sub.add_parser("serve-github-capture", help="Accept signed GitHub review deliveries.")
164
+ webhook.add_argument("--subject", required=True)
165
+ webhook.add_argument("--account", required=True)
166
+ webhook.add_argument("--repository", required=True, action="append")
167
+ webhook.add_argument("--port", type=int, default=8083)
168
+
169
+ survey = sub.add_parser("import-survey", help="Build a cohort from CSV or Parquet microdata.")
170
+ survey.add_argument("path", type=Path)
171
+ survey.add_argument("--id", required=True)
172
+ survey.add_argument("--domain", required=True)
173
+ survey.add_argument("--trait", action="append", default=[])
174
+ survey.add_argument("--cluster-feature", action="append", default=[])
175
+ survey.add_argument("--cluster-count", type=int)
176
+ survey.add_argument("--twin-prior-weight", type=float, default=0.0)
177
+ survey.add_argument("--response", required=True)
178
+ survey.add_argument("--weight")
179
+ survey.add_argument("--margins", type=Path, help="JSON object of trait-to-category proportions.")
180
+
181
+ calibrate = sub.add_parser("fit-calibration", help="Score held-out human decisions for calibration.")
182
+ calibrate.add_argument("path", type=Path, help="JSON array of held-out DecisionLog entries.")
183
+ calibrate.add_argument("--alpha", type=float, default=0.1)
184
+ calibrate.add_argument("--store", action="store_true", help="Store the fitted profiles in the vault.")
185
+
186
+ registration = sub.add_parser("register-study", help="Freeze a study plan before collecting outcomes.")
187
+ registration.add_argument("plan", type=Path)
188
+ registration.add_argument("destination", type=Path)
189
+ study_check = sub.add_parser("check-study", help="Validate study consent and split eligibility.")
190
+ study_check.add_argument("registration", type=Path)
191
+ study_check.add_argument("dataset", type=Path)
192
+ forecast = sub.add_parser("forecast-study", help="Run one registered model and matched baselines.")
193
+ forecast.add_argument("registration", type=Path)
194
+ forecast.add_argument("dataset", type=Path)
195
+ forecast.add_argument("destination", type=Path)
196
+ forecast.add_argument("--allow-remote-model", action="store_true")
197
+ evaluate = sub.add_parser("evaluate-study", help="Score the complete preregistered evaluation.")
198
+ evaluate.add_argument("registration", type=Path)
199
+ evaluate.add_argument("dataset", type=Path)
200
+ evaluate.add_argument("forecasts", type=Path, nargs="+")
201
+
202
+ download_twin = sub.add_parser("download-public-twin", help="Download the pinned public Twin-2K-500 release.")
203
+ download_twin.add_argument("folder", type=Path)
204
+ sample = sub.add_parser("draw-cohort-anchors", help="Draw anchor IDs from a frozen unlabeled sampling frame.")
205
+ sample.add_argument("frame", type=Path, help="JSON array of unique unit ID strings.")
206
+ sample.add_argument("--count", type=int, required=True)
207
+ sample.add_argument("--seed", type=int, required=True)
208
+
209
+ anchors = sub.add_parser("calibrate-cohort", help="Estimate a binary proportion using independent human anchors.")
210
+ anchors.add_argument("study", type=Path)
211
+ public_twin = sub.add_parser("evaluate-public-twin", help="Evaluate the public Twin-2K-500 wave split.")
212
+ public_twin.add_argument("folder", type=Path, help="Directory containing the catalog and numeric response CSVs.")
213
+ public_twin.add_argument("--participants", type=int, default=60)
214
+ public_twin.add_argument("--seed", default="anthromesh-public-v1")
215
+ public_twin.add_argument("--output", type=Path, help="Save the aggregate JSON report to a new file.")
216
+ audit_public_twin = sub.add_parser("audit-public-twin", help="Audit the original published case set.")
217
+ audit_public_twin.add_argument("folder", type=Path)
218
+ audit_public_twin.add_argument("original_report", type=Path)
219
+ validate_public_twin = sub.add_parser("validate-public-twin", help="Develop or score the frozen population-adjusted Twin.")
220
+ validate_public_twin.add_argument("phase", choices=["development", "sealed"])
221
+ validate_public_twin.add_argument("folder", type=Path)
222
+ validate_public_twin.add_argument("original_report", type=Path)
223
+ validate_public_twin.add_argument("frozen", type=Path)
224
+
225
+ study = sub.add_parser("score-study", help="Score held-out personal or survey study observations.")
226
+ study.add_argument("mode", choices=["personal", "survey"])
227
+ study.add_argument("path", type=Path)
228
+ study.add_argument("--baseline", help="Compare against a named system with paired observations.")
229
+ sub.add_parser("benchmark", help="Run calibration and long-tail variance benchmarks.")
230
+ sub.add_parser("escalations", help="List pending human-in-the-loop escalation tickets.")
231
+ verify = sub.add_parser("verify-audit", help="Verify the vault audit hash chain.")
232
+ verify.add_argument("--expected-head", help="Audit head retained externally.")
233
+
234
+ judgment = sub.add_parser("configure-judgment", help="Record opt-in judgment and audit settings.")
235
+ judgment.add_argument("settings", type=Path)
236
+ assign = sub.add_parser("assign-elicitation", help="Assign a structured scenario to an opted-in subject.")
237
+ assign.add_argument("case", type=Path)
238
+ pending = sub.add_parser("list-elicitation", help="List blinded scenarios and prediction checks.")
239
+ pending.add_argument("subject")
240
+ respond = sub.add_parser("respond-elicitation", help="Record an owner's independent response.")
241
+ respond.add_argument("subject")
242
+ respond.add_argument("case_id")
243
+ respond.add_argument("--action", required=True)
244
+ respond.add_argument("--rationale", default="")
245
+ respond.add_argument("--switch-condition", default="")
246
+ trust = sub.add_parser("trust-map", help="Report aggregate randomized prediction audit results.")
247
+ trust.add_argument("--domain")
248
+
249
+ make_key = sub.add_parser("delegation-key", help="Create an Ed25519 issuer or holder key.")
250
+ make_key.add_argument("path", type=Path)
251
+ issue_grant = sub.add_parser("issue-delegation", help="Issue a signed grant of authority.")
252
+ issue_grant.add_argument("request", type=Path)
253
+ issue_grant.add_argument("destination", type=Path)
254
+ revoke_grant = sub.add_parser("revoke-delegation", help="Revoke a signed delegation.")
255
+ revoke_grant.add_argument("grant_id")
256
+ status_server = sub.add_parser("serve-delegation", help="Publish signing keys and fresh revocation status.")
257
+ status_server.add_argument("--port", type=int, default=8085)
258
+ for command in (issue_grant, revoke_grant, status_server):
259
+ command.add_argument("--issuer", required=True)
260
+ command.add_argument("--issuer-key", required=True, type=Path)
261
+ challenge = sub.add_parser("delegation-challenge", help="Create a one-time verifier challenge.")
262
+ challenge.add_argument("--audience", required=True)
263
+ prove = sub.add_parser("prove-delegated-action", help="Sign the exact challenged action with a holder key.")
264
+ prove.add_argument("grant", type=Path)
265
+ prove.add_argument("destination", type=Path)
266
+ prove.add_argument("--issuer-public-key", required=True)
267
+ prove.add_argument("--holder-key", required=True, type=Path)
268
+ prove.add_argument("--challenge", required=True)
269
+ verify_action = sub.add_parser("verify-delegated-action", help="Verify authority and consume its challenge.")
270
+ verify_action.add_argument("grant", type=Path)
271
+ verify_action.add_argument("status", type=Path, help="JSON returned by the trusted issuer status endpoint.")
272
+ verify_action.add_argument("proof", type=Path)
273
+ verify_action.add_argument("--issuer", required=True)
274
+ verify_action.add_argument("--issuer-public-key", required=True)
275
+ verify_action.add_argument("--audience", required=True)
276
+ for command in (challenge, prove, verify_action):
277
+ command.add_argument("--intent", required=True, type=Path)
278
+ command.add_argument("--artifact", required=True, type=Path)
279
+
280
+ enrol = sub.add_parser("panel-enroll", help="Enroll a consented participant with an external verification credential.")
281
+ enrol.add_argument("profile", type=Path)
282
+ enrol.add_argument("attestation", type=Path)
283
+ enrol.add_argument("--identity-issuer", required=True)
284
+ enrol.add_argument("--identity-audience", required=True)
285
+ enrol.add_argument("--identity-public-key", required=True)
286
+ withdraw = sub.add_parser("panel-withdraw", help="Stop routing tasks to a participant.")
287
+ withdraw.add_argument("subject")
288
+ panel_create = sub.add_parser("panel-question", help="Add a panel question with a compensation ceiling.")
289
+ panel_create.add_argument("question", type=Path)
290
+ panel_claim = sub.add_parser("panel-claim", help="Claim a question for a verified participant.")
291
+ panel_claim.add_argument("subject")
292
+ panel_claim.add_argument("topic")
293
+ panel_answer = sub.add_parser("panel-answer", help="Submit an independently authored response.")
294
+ panel_answer.add_argument("subject")
295
+ panel_answer.add_argument("assignment_id")
296
+ panel_answer.add_argument("answer", type=Path)
297
+ panel_queue = sub.add_parser("panel-review-queue", help="List responses for independent review.")
298
+ panel_queue.add_argument("topic")
299
+ panel_review = sub.add_parser("panel-review", help="Review one response and record earned compensation.")
300
+ panel_review.add_argument("assignment_id")
301
+ panel_review.add_argument("--reviewer", required=True)
302
+ panel_review.add_argument("--decision", choices=["approve", "reject"], required=True)
303
+ panel_review.add_argument("--reason", required=True)
304
+ panel_reconcile = sub.add_parser("panel-reconcile", help="Record an independently completed payment.")
305
+ panel_reconcile.add_argument("assignment_id")
306
+ panel_reconcile.add_argument("--reference", required=True)
307
+ panel_report = sub.add_parser("panel-result", help="Read a panel's aggregate responses.")
308
+ panel_report.add_argument("question_id")
309
+ panel_quality = sub.add_parser("panel-quality", help="Read a participant's review and retest statistics.")
310
+ panel_quality.add_argument("subject")
311
+
312
+ cohort_grant = sub.add_parser("grant-cohort-consent", help="Permit bounded aggregate twin contributions.")
313
+ cohort_grant.add_argument("consent", type=Path)
314
+ cohort_revoke = sub.add_parser("revoke-cohort-consent", help="Stop using a twin's aggregate contributions.")
315
+ cohort_revoke.add_argument("subject")
316
+ cohort_revoke.add_argument("cohort_id")
317
+ panel_eval = sub.add_parser("evaluate-cohort-panel", help="Compare simulations with reviewed panel responses.")
318
+ panel_eval.add_argument("cohort_id")
319
+ panel_eval.add_argument("question_ids", nargs="+")
320
+ panel_eval.add_argument("--sample-size", type=int, default=500)
321
+ panel_eval.add_argument("--allow-remote-model", action="store_true")
322
+
323
+ subject_export = sub.add_parser("export-subject", help="Export subject records and provenance to JSON.")
324
+ subject_export.add_argument("subject_id")
325
+ erase = sub.add_parser("erase-subject", help="Erase subject data or selected decision IDs.")
326
+ erase.add_argument("subject_id")
327
+ erase.add_argument("--decision-id", action="append")
328
+ erase.add_argument("--confirm-subject", required=True)
329
+
330
+ inbox = sub.add_parser("serve-inbox", help="Start the local owner escalation inbox.")
331
+ inbox.add_argument("--port", type=int, default=8084)
332
+ inbox.add_argument("--subject", help="Bind the owner inbox to one subject.")
333
+ inbox.add_argument("--panel-topic", help="Enable panel questions for this subject and topic.")
334
+
335
+ res_p = sub.add_parser("resolve", help="Resolve a pending escalation ticket.")
336
+ res_p.add_argument("ticket_id", type=str)
337
+ res_p.add_argument("--action", required=True, type=str)
338
+ res_p.add_argument("--rationale", required=True, type=str)
339
+
340
+ issue = sub.add_parser("issue-capability", help="Issue a scoped read capability.")
341
+ issue.add_argument("--subject", required=True)
342
+ issue.add_argument("--client", required=True)
343
+ issue.add_argument("--scope", action="append", required=True)
344
+ issue.add_argument("--ttl", type=int, default=3600)
345
+ issue.add_argument("--rate", type=int, default=60)
346
+ revoke = sub.add_parser("revoke-capability", help="Revoke a capability using its public ID.")
347
+ revoke.add_argument("token_id")
348
+
349
+ mcp_p = sub.add_parser("serve-mcp", help="Start the AnthroMesh MCP server.")
350
+ mcp_p.add_argument("--transport", choices=["stdio", "http"], default="http")
351
+ mcp_p.add_argument("--host", default="127.0.0.1")
352
+ mcp_p.add_argument("--port", type=int, default=8081)
353
+ mcp_p.add_argument("--allow-network-bind", action="store_true")
354
+ mcp_p.add_argument("--allow-capability-tokens", action="store_true")
355
+
356
+ ros = sub.add_parser("serve-ros2", help="Run the ROS 2 fast preference-gate node.")
357
+ ros.add_argument("--subject", required=True)
358
+ ros.add_argument("--domain", action="append", required=True)
359
+ ros.add_argument("--minimum-risk", choices=[tier.value for tier in RiskTier], default="low")
360
+ ros.add_argument("--request-topic", default="/anthromesh/gate/request")
361
+ ros.add_argument("--result-topic", default="/anthromesh/gate/result")
362
+ ros.add_argument("--deadline-ms", type=int, default=50)
363
+
364
+ a2a_p = sub.add_parser("serve-a2a", help="Start the AnthroMesh A2A v1.0 server.")
365
+ a2a_p.add_argument("--host", default="127.0.0.1")
366
+ a2a_p.add_argument("--port", type=int, default=8082)
367
+ a2a_p.add_argument("--allow-network-bind", action="store_true")
368
+
369
+ args = parser.parse_args(argv)
370
+ cfg = AnthroMeshConfig()
371
+
372
+ if args.command == "init":
373
+ vault = _open_vault(cfg)
374
+ print(f"Initialized Behavioral Vault at {vault.db_path}")
375
+ return 0
376
+
377
+ if args.command == "export-encrypted":
378
+ if cfg.encryption_key is None:
379
+ parser.error("Set ANTHROMESH_VAULT_KEY before exporting the encrypted vault.")
380
+ export_encrypted_vault(args.source, args.destination, cfg.encryption_key)
381
+ print(f"Exported encrypted vault to {args.destination}")
382
+ return 0
383
+
384
+ if args.command == "seed":
385
+ vault, twin, oracle = _build_runtime(cfg)
386
+ if args.decisions:
387
+ items = json.loads(Path(args.decisions).read_text(encoding="utf-8"))
388
+ for item in items:
389
+ twin.record_decision(DecisionLog.model_validate(item))
390
+ print(f"Seeded {len(items)} decisions into {vault.db_path}")
391
+ if args.cohort:
392
+ profile = CohortProfile.model_validate_json(Path(args.cohort).read_text(encoding="utf-8"))
393
+ oracle.register_cohort(profile)
394
+ print(f"Registered cohort '{profile.cohort_id}' into {vault.db_path}")
395
+ return 0
396
+
397
+ if args.command == "import-decisions":
398
+ source = json.loads(args.path.read_text(encoding="utf-8"))
399
+ if args.source == "github-review":
400
+ if not args.account:
401
+ parser.error("GitHub review import requires --account.")
402
+ decisions = github_reviews(source if isinstance(source, list) else [source],
403
+ args.subject, args.account)
404
+ else:
405
+ decisions = calendar_responses(source if isinstance(source, list) else source["items"],
406
+ args.subject)
407
+ vault = _open_vault(cfg)
408
+ count = vault.import_captured_decisions(decisions)
409
+ print(f"Imported {count} of {len(decisions)} matching decisions.")
410
+ return 0
411
+
412
+ if args.command == "sync-graph":
413
+ if args.poll_seconds is not None and args.poll_seconds < 10:
414
+ parser.error("Graph polling intervals must be at least ten seconds.")
415
+ vault = _open_vault(cfg)
416
+ reset = args.reset
417
+ try:
418
+ while True:
419
+ token = (args.token_file.read_text(encoding="utf-8").strip() if args.token_file
420
+ else os.getenv("ANTHROMESH_GRAPH_ACCESS_TOKEN"))
421
+ if not token:
422
+ parser.error("Provide a delegated Microsoft Graph access token.")
423
+ drafts = json.loads(args.drafts.read_text(encoding="utf-8")) if args.drafts else None
424
+ with GraphCapture(vault, args.subject, args.account, token) as capture:
425
+ count = capture.sync(
426
+ args.stream, start=args.start, end=args.end, drafts=drafts,
427
+ track_reschedules=args.track_reschedules, reset=reset,
428
+ )
429
+ print(f"Captured {count} new {args.stream} decisions.", flush=True)
430
+ reset = False
431
+ if args.poll_seconds is None:
432
+ break
433
+ time.sleep(args.poll_seconds)
434
+ except KeyboardInterrupt:
435
+ pass
436
+ return 0
437
+
438
+ if args.command == "serve-github-capture":
439
+ import uvicorn
440
+
441
+ secret = os.getenv("ANTHROMESH_GITHUB_WEBHOOK_SECRET")
442
+ if not secret:
443
+ parser.error("Set ANTHROMESH_GITHUB_WEBHOOK_SECRET before starting capture.")
444
+ vault = _open_vault(cfg)
445
+ app = create_github_capture_app(
446
+ vault, secret=secret, subject=args.subject, account=args.account,
447
+ repositories=set(args.repository),
448
+ )
449
+ uvicorn.run(app, host="127.0.0.1", port=args.port)
450
+ return 0
451
+
452
+ if args.command == "import-survey":
453
+ vault = _open_vault(cfg)
454
+ margins = json.loads(args.margins.read_text(encoding="utf-8")) if args.margins else None
455
+ if not 0 <= args.twin_prior_weight <= 0.25:
456
+ parser.error("Twin prior weight must be between 0 and 0.25.")
457
+ inputs = dict(cohort_id=args.id, domain=args.domain, response=args.response,
458
+ weight=args.weight, margins=margins)
459
+ if args.cluster_count is not None:
460
+ profile = build_clustered_profile(
461
+ read_survey(args.path), strata=args.trait, features=args.cluster_feature,
462
+ clusters=args.cluster_count, **inputs,
463
+ )
464
+ else:
465
+ if args.cluster_feature:
466
+ parser.error("Provide --cluster-count with clustering features.")
467
+ profile = build_empirical_profile(read_survey(args.path), traits=args.trait, **inputs)
468
+ profile.twin_prior_weight = args.twin_prior_weight
469
+ vault.save_cohort(profile)
470
+ print(f"Imported {len(profile.archetypes)} survey strata into cohort {profile.cohort_id}.")
471
+ return 0
472
+
473
+ if args.command == "fit-calibration":
474
+ values = json.loads(args.path.read_text(encoding="utf-8"))
475
+ held_out = [DecisionLog.model_validate(item) for item in values]
476
+ vault, twin, _ = _build_runtime(replace(cfg, calibration_path=None, managed_calibration=False))
477
+ profiles = [profile.model_dump() for profile in fit_profiles(twin, held_out, args.alpha)]
478
+ if args.store:
479
+ vault.save_calibration_profiles(profiles)
480
+ print(f"Stored {len(profiles)} calibration profiles.")
481
+ else:
482
+ print(json.dumps(profiles, indent=2))
483
+ return 0
484
+
485
+ if args.command == "register-study":
486
+ record = register_study(args.plan, args.destination)
487
+ print(json.dumps({"study_id": record.plan.study_id, "plan_hash": record.plan_hash}))
488
+ return 0
489
+
490
+ if args.command == "check-study":
491
+ record = load_registration(args.registration)
492
+ dataset, digest = load_dataset(args.dataset)
493
+ prepared = prepare_study(record, dataset)
494
+ print(json.dumps({
495
+ "data_source": dataset.source, "dataset_hash": digest,
496
+ "participants": len(prepared.participants), "train": len(prepared.train),
497
+ "calibration": len(prepared.calibration), "test": len(prepared.test),
498
+ "retests": len(prepared.retests),
499
+ }, indent=2))
500
+ return 0
501
+
502
+ if args.command == "forecast-study":
503
+ adapter = create_adapter(cfg)
504
+ remote = _remote_model(cfg, adapter.adapter_name)
505
+ outcome = forecast_study(
506
+ load_registration(args.registration), args.dataset, adapter, args.destination,
507
+ allow_remote=args.allow_remote_model, remote_backend=remote, vault_key=cfg.encryption_key,
508
+ )
509
+ print(f"Recorded {len(outcome.forecasts)} paired forecasts for {outcome.backend}.")
510
+ return 0
511
+
512
+ if args.command == "evaluate-study":
513
+ print(json.dumps(evaluate_study(
514
+ load_registration(args.registration), args.dataset, args.forecasts,
515
+ ), indent=2))
516
+ return 0
517
+
518
+ if args.command == "download-public-twin":
519
+ download_public_twin(args.folder)
520
+ print(args.folder.resolve())
521
+ return 0
522
+
523
+ if args.command == "evaluate-public-twin":
524
+ adapter = create_adapter(cfg)
525
+ if _remote_model(cfg, adapter.adapter_name):
526
+ raise ValueError("Public Twin-2K-500 participant rows are evaluated with a local adapter.")
527
+ if args.output and args.output.exists():
528
+ raise FileExistsError(args.output)
529
+ result = evaluate_public_twin(args.folder, adapter, seed=args.seed, participants=args.participants)
530
+ print(json.dumps(result, indent=2), flush=True)
531
+ if args.output:
532
+ with args.output.open("x", encoding="utf-8") as report:
533
+ report.write(json.dumps(result, indent=2) + "\n")
534
+ return 0
535
+
536
+ if args.command == "audit-public-twin":
537
+ print(json.dumps(audit_original_public_run(args.folder, args.original_report), indent=2))
538
+ return 0
539
+
540
+ if args.command == "validate-public-twin":
541
+ print(json.dumps(run_public_validation(args.folder, args.original_report, args.frozen, phase=args.phase), indent=2))
542
+ return 0
543
+
544
+ if args.command == "draw-cohort-anchors":
545
+ units = json.loads(args.frame.read_text(encoding="utf-8"))
546
+ if not isinstance(units, list) or not all(isinstance(unit, str) for unit in units):
547
+ raise ValueError("The sampling frame must be an array of string unit IDs.")
548
+ print(json.dumps(draw_anchor_units(units, args.count, args.seed), indent=2))
549
+ return 0
550
+
551
+ if args.command == "calibrate-cohort":
552
+ payload = json.loads(args.study.read_text(encoding="utf-8"))
553
+ if "categories" in payload:
554
+ output = analyze_categories(CategoricalAnchorStudy.model_validate(payload))
555
+ else:
556
+ output = analyze_anchors(AnchorStudy.model_validate(payload))
557
+ print(json.dumps(output, indent=2))
558
+ return 0
559
+
560
+ if args.command == "score-study":
561
+ print(json.dumps(score_study(args.path, args.mode, args.baseline), indent=2))
562
+ return 0
563
+
564
+ if args.command == "benchmark":
565
+ adapter = create_adapter(cfg)
566
+ report = BenchmarkRunner(adapter=adapter).run_all()
567
+ print(json.dumps(report.model_dump(), indent=2))
568
+ return 0
569
+
570
+ if args.command == "escalations":
571
+ vault, _, _ = _build_runtime(cfg)
572
+ pending = vault.list_escalations(status=EscalationStatus.PENDING)
573
+ print(json.dumps([t.model_dump() for t in pending], indent=2))
574
+ return 0
575
+
576
+ if args.command in {"configure-judgment", "assign-elicitation", "list-elicitation",
577
+ "respond-elicitation", "trust-map"}:
578
+ vault = _open_vault(cfg)
579
+ elicitation = Elicitation(vault)
580
+ if args.command == "configure-judgment":
581
+ settings = JudgmentSettings.model_validate_json(args.settings.read_text(encoding="utf-8"))
582
+ save_judgment_settings(vault, settings)
583
+ output = settings.model_dump(mode="json")
584
+ elif args.command == "assign-elicitation":
585
+ case = ElicitationCase.model_validate_json(args.case.read_text(encoding="utf-8"))
586
+ output = elicitation.assign(case).model_dump(mode="json")
587
+ elif args.command == "list-elicitation":
588
+ output = elicitation.pending(args.subject)
589
+ elif args.command == "respond-elicitation":
590
+ output = elicitation.respond(
591
+ args.subject, args.case_id, args.action, args.rationale, args.switch_condition,
592
+ ).model_dump(mode="json")
593
+ else:
594
+ output = PredictionMonitor(vault).trust_map(args.domain)
595
+ print(json.dumps(output, indent=2))
596
+ return 0
597
+
598
+ if args.command == "delegation-key":
599
+ print(json.dumps({"public_key": delegation.create_private_key(args.path)}))
600
+ return 0
601
+
602
+ if args.command in {"issue-delegation", "revoke-delegation", "serve-delegation"}:
603
+ issuer = delegation.DelegationIssuer(
604
+ _open_vault(cfg), args.issuer, delegation.read_private_key(args.issuer_key),
605
+ )
606
+ if args.command == "issue-delegation":
607
+ request = delegation.GrantRequest.model_validate_json(args.request.read_bytes())
608
+ with args.destination.open("x", encoding="utf-8") as output:
609
+ grant, token = issuer.issue(request)
610
+ output.write(token + "\n")
611
+ print(json.dumps({"grant_id": grant.jti, "expires_at": grant.exp}))
612
+ elif args.command == "revoke-delegation":
613
+ issuer.revoke(args.grant_id)
614
+ else:
615
+ import uvicorn
616
+
617
+ uvicorn.run(delegation.create_status_app(issuer), host="127.0.0.1", port=args.port)
618
+ return 0
619
+
620
+ if args.command in {"delegation-challenge", "prove-delegated-action", "verify-delegated-action"}:
621
+ import hashlib
622
+
623
+ intent = delegation.Intent.model_validate_json(args.intent.read_bytes())
624
+ content_digest = hashlib.sha256()
625
+ with args.artifact.open("rb") as artifact:
626
+ for chunk in iter(lambda: artifact.read(1024 * 1024), b""):
627
+ content_digest.update(chunk)
628
+ artifact_hash = content_digest.hexdigest()
629
+ if intent.artifact_sha256 != artifact_hash:
630
+ parser.error("The actual artifact does not match the action intent.")
631
+ if args.command == "delegation-challenge":
632
+ value = delegation.issue_challenge(_open_vault(cfg), args.audience, intent)
633
+ print(json.dumps({"challenge": value}))
634
+ elif args.command == "prove-delegated-action":
635
+ proof = delegation.sign_action(
636
+ args.grant.read_text(encoding="utf-8").strip(), args.issuer_public_key,
637
+ delegation.read_private_key(args.holder_key), args.challenge, intent,
638
+ )
639
+ with args.destination.open("x", encoding="utf-8") as output:
640
+ output.write(proof + "\n")
641
+ else:
642
+ status = json.loads(args.status.read_bytes())["status"]
643
+ outcome = delegation.verify_action(
644
+ _open_vault(cfg), issuer=args.issuer, issuer_public_key=args.issuer_public_key,
645
+ audience=args.audience, grant_token=args.grant.read_text(encoding="utf-8").strip(),
646
+ status_token=status, proof_token=args.proof.read_text(encoding="utf-8").strip(),
647
+ intent=intent,
648
+ )
649
+ print(json.dumps(outcome))
650
+ return 0
651
+
652
+ if args.command.startswith("panel-"):
653
+ panel = HumanPanel(_open_vault(cfg))
654
+ output = None
655
+ if args.command == "panel-enroll":
656
+ panel.enroll(
657
+ PanelProfile.model_validate_json(args.profile.read_bytes()),
658
+ args.attestation.read_text(encoding="utf-8").strip(),
659
+ issuer=args.identity_issuer, audience=args.identity_audience,
660
+ public_key=args.identity_public_key,
661
+ )
662
+ elif args.command == "panel-withdraw":
663
+ panel.withdraw(args.subject)
664
+ elif args.command == "panel-question":
665
+ output = {"question_id": panel.submit_question(
666
+ PanelQuestion.model_validate_json(args.question.read_bytes()),
667
+ )}
668
+ elif args.command == "panel-claim":
669
+ output = panel.claim(args.subject, args.topic)
670
+ elif args.command == "panel-answer":
671
+ panel.answer(args.subject, args.assignment_id,
672
+ PanelAnswer.model_validate_json(args.answer.read_bytes()))
673
+ elif args.command == "panel-review-queue":
674
+ output = panel.pending_reviews(args.topic)
675
+ elif args.command == "panel-review":
676
+ panel.review(args.assignment_id, args.reviewer, args.decision == "approve", args.reason)
677
+ elif args.command == "panel-reconcile":
678
+ panel.reconcile(args.assignment_id, args.reference)
679
+ elif args.command == "panel-result":
680
+ output = panel.report(args.question_id)
681
+ else:
682
+ output = panel.quality(args.subject)
683
+ print(json.dumps(output, indent=2))
684
+ return 0
685
+
686
+ if args.command == "grant-cohort-consent":
687
+ grant_cohort_consent(
688
+ _open_vault(cfg), TwinCohortConsent.model_validate_json(args.consent.read_bytes()),
689
+ )
690
+ return 0
691
+ if args.command == "revoke-cohort-consent":
692
+ revoke_cohort_consent(_open_vault(cfg), args.subject, args.cohort_id)
693
+ return 0
694
+ if args.command == "evaluate-cohort-panel":
695
+ from anthromesh.benchmarks.panel_cohort import evaluate_against_panel
696
+
697
+ adapter = create_adapter(cfg)
698
+ if _remote_model(cfg, adapter.adapter_name) and not args.allow_remote_model:
699
+ parser.error("Enable remote model inference explicitly for this evaluation.")
700
+ oracle = ResearchCohortOracle(_open_vault(cfg), adapter)
701
+ print(json.dumps(evaluate_against_panel(
702
+ oracle, args.cohort_id, args.question_ids, sample_size=args.sample_size,
703
+ ), indent=2))
704
+ return 0
705
+
706
+ if args.command in {"export-subject", "erase-subject"}:
707
+ data = SubjectData(_open_vault(cfg))
708
+ if args.command == "export-subject":
709
+ result = data.export(args.subject_id)
710
+ else:
711
+ if args.confirm_subject != args.subject_id:
712
+ parser.error("The confirmation must match the exact subject ID.")
713
+ result = data.erase(
714
+ args.subject_id, decision_ids=set(args.decision_id) if args.decision_id else None,
715
+ )
716
+ print(json.dumps(result, indent=2))
717
+ return 0
718
+
719
+ if args.command == "verify-audit":
720
+ vault = _open_vault(cfg)
721
+ valid = vault.verify_audit_chain(expected_head=args.expected_head)
722
+ print("Audit chain verified." if valid else "Audit verification failed.")
723
+ return 0 if valid else 1
724
+
725
+ if args.command in {"resolve", "serve-inbox"}:
726
+ vault, twin, oracle = _build_runtime(cfg)
727
+
728
+ def resolve(ticket_id: str, action: str, rationale: str) -> dict:
729
+ task = vault.get_a2a_task_for_ticket(ticket_id)
730
+ if task is None:
731
+ ticket, decision = twin.resolve_escalation(ticket_id, action, rationale)
732
+ return {"ticket": ticket.model_dump(), "recorded_decision": decision.model_dump()}
733
+ complete = A2AService(twin=twin, oracle=oracle).resolve_task(
734
+ task["id"], action, rationale
735
+ )
736
+ return complete["artifacts"][-1]["data"]
737
+
738
+ if args.command == "resolve":
739
+ print(json.dumps(resolve(args.ticket_id, args.action, args.rationale), indent=2))
740
+ else:
741
+ import uvicorn
742
+
743
+ password = os.getenv("ANTHROMESH_INBOX_PASSWORD")
744
+ if not password:
745
+ parser.error("Set ANTHROMESH_INBOX_PASSWORD before starting the inbox.")
746
+ uvicorn.run(create_inbox_app(vault, resolve, password, subject=args.subject, panel_topic=args.panel_topic),
747
+ host="127.0.0.1", port=args.port)
748
+ return 0
749
+
750
+ if args.command in {"issue-capability", "revoke-capability"}:
751
+ vault = _open_vault(cfg)
752
+ if args.command == "revoke-capability":
753
+ return 0 if vault.revoke_capability(args.token_id) else 1
754
+ identifier, token = CapabilityTokens(vault).issue(
755
+ args.subject, args.client, args.scope, args.ttl, args.rate,
756
+ )
757
+ print(json.dumps({"token_id": identifier, "token": token}))
758
+ return 0
759
+
760
+ if args.command == "serve-mcp":
761
+ vault, twin, oracle = _build_runtime(cfg)
762
+ tokens = CapabilityTokens(vault) if args.allow_capability_tokens else None
763
+ server = MCPServer(twin=twin, oracle=oracle, capabilities=tokens)
764
+ if args.transport == "stdio":
765
+ server.serve_stdio()
766
+ else:
767
+ issuer = os.getenv("ANTHROMESH_OAUTH_ISSUER")
768
+ resource = os.getenv("ANTHROMESH_OAUTH_RESOURCE")
769
+ jwks = os.getenv("ANTHROMESH_OAUTH_JWKS")
770
+ discover = os.getenv("ANTHROMESH_OAUTH_DISCOVERY") == "1"
771
+ if issuer or resource or jwks or discover:
772
+ if not issuer or not resource or bool(jwks) == discover:
773
+ parser.error("Set the OAuth issuer, resource URL, and a JWKS file or discovery mode.")
774
+ ca_file = os.getenv("ANTHROMESH_OAUTH_CA_FILE")
775
+ server.oauth = OAuthResource(
776
+ issuer, resource, Path(jwks) if jwks else None,
777
+ discover=discover, profile=os.getenv("ANTHROMESH_OAUTH_TOKEN_PROFILE", "rfc9068"),
778
+ ca_file=Path(ca_file) if ca_file else None,
779
+ clock_skew_seconds=int(os.getenv("ANTHROMESH_OAUTH_CLOCK_SKEW_SECONDS", "0")),
780
+ )
781
+ server.serve_http(host=args.host, port=args.port, allow_network_bind=args.allow_network_bind)
782
+ return 0
783
+
784
+ if args.command == "serve-ros2":
785
+ from anthromesh.ros_gate import RosPreferenceGate, serve_ros
786
+
787
+ _, twin, _ = _build_runtime(replace(cfg, fast_enabled=True))
788
+ gate = RosPreferenceGate(
789
+ twin.gate.evaluate_fast, subject_id=args.subject, domains=set(args.domain),
790
+ minimum_risk=RiskTier(args.minimum_risk),
791
+ )
792
+ serve_ros(gate, request_topic=args.request_topic, result_topic=args.result_topic,
793
+ deadline_ms=args.deadline_ms)
794
+ return 0
795
+
796
+ if args.command == "serve-a2a":
797
+ _, twin, oracle = _build_runtime(cfg)
798
+ public_host = "127.0.0.1" if args.host == "0.0.0.0" else args.host
799
+ service = A2AService(twin=twin, oracle=oracle, base_url=f"http://{public_host}:{args.port}")
800
+ service.serve_http(host=args.host, port=args.port, allow_network_bind=args.allow_network_bind)
801
+ return 0
802
+
803
+ return 1
804
+
805
+
806
+ if __name__ == "__main__":
807
+ raise SystemExit(main())