@sanctuary-framework/mcp-server 0.10.6 → 1.0.0-rc.1

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/dist/index.cjs CHANGED
@@ -20,6 +20,7 @@ var fs = require('fs');
20
20
  var index_js = require('@modelcontextprotocol/sdk/client/index.js');
21
21
  var stdio_js = require('@modelcontextprotocol/sdk/client/stdio.js');
22
22
  var sse_js = require('@modelcontextprotocol/sdk/client/sse.js');
23
+ var url = require('url');
23
24
 
24
25
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
25
26
  var __defProp = Object.defineProperty;
@@ -816,7 +817,8 @@ var RESERVED_NAMESPACE_PREFIXES = [
816
817
  "_handshake",
817
818
  "_shr",
818
819
  "_sovereignty_profile",
819
- "_context_gate_policies"
820
+ "_context_gate_policies",
821
+ "_fortress_mode"
820
822
  ];
821
823
  var StateStore = class _StateStore {
822
824
  storage;
@@ -1390,7 +1392,8 @@ var RESERVED_NAMESPACE_PREFIXES2 = [
1390
1392
  "_handshake",
1391
1393
  "_shr",
1392
1394
  "_sovereignty_profile",
1393
- "_context_gate_policies"
1395
+ "_context_gate_policies",
1396
+ "_fortress_mode"
1394
1397
  ];
1395
1398
  function getReservedNamespaceViolation(namespace) {
1396
1399
  for (const prefix of RESERVED_NAMESPACE_PREFIXES2) {
@@ -4143,8 +4146,12 @@ var DEFAULT_POLICY = {
4143
4146
  // Clears all runtime governance state — always requires approval
4144
4147
  "sanctuary_bootstrap",
4145
4148
  // Creates new Ed25519 identity + publishes — always requires approval
4146
- "sanctuary_export_identity_bundle"
4149
+ "sanctuary_export_identity_bundle",
4147
4150
  // Exports portable identity — always requires approval
4151
+ // WP-MVP-2 Operator Console: federation-node-join requires explicit
4152
+ // operator confirmation per Key 8. No auto-approve path. The console's
4153
+ // JoinApprover drives this gate via `MeshConsoleClient.makeJoinApprover`.
4154
+ "federation_node_join"
4148
4155
  ],
4149
4156
  tier2_anomaly: DEFAULT_TIER2,
4150
4157
  tier3_always_allow: [
@@ -6403,6 +6410,28 @@ function generateDashboardHTML(options) {
6403
6410
  </div>
6404
6411
  </div>
6405
6412
 
6413
+ <!--
6414
+ Mesh Health panel (WP-MVP-3 Follow-up #3).
6415
+ Subscribes to the existing /events SSE channel \u2014 no new transport.
6416
+ Render shape: per-node row with presence + flags + rollup.
6417
+ On open alert: list inline with operator-decision CTAs (rollback /
6418
+ split-brain / canonical-audit promotion).
6419
+ On post-recovery prompt: render rotation-prompt overlay with
6420
+ broker-credential list + "rotate now" buttons (rotation flow itself
6421
+ is the existing v0.10.x broker rotation surface).
6422
+ -->
6423
+ <div class="mesh-health-panel" id="mesh-health-panel">
6424
+ <div class="panel-header">
6425
+ <div class="panel-title">Mesh Health</div>
6426
+ <span class="card-value" id="mesh-health-updated-at" style="font-size: 11px; color: var(--text-secondary);">\u2014</span>
6427
+ </div>
6428
+ <div id="mesh-health-rows" class="mesh-health-rows">
6429
+ <div class="empty-state">Waiting for mesh health data\u2026</div>
6430
+ </div>
6431
+ <div id="mesh-health-alerts" class="mesh-health-alerts" style="margin-top: 12px;"></div>
6432
+ <div id="mesh-post-recovery-prompt" class="mesh-post-recovery-prompt" style="margin-top: 12px; display: none;"></div>
6433
+ </div>
6434
+
6406
6435
  <!-- Sovereignty Profile Panel -->
6407
6436
  <div class="profile-panel" id="sovereignty-profile-panel">
6408
6437
  <div class="panel-header">
@@ -7112,12 +7141,96 @@ function generateDashboardHTML(options) {
7112
7141
  loadProxyServers();
7113
7142
  });
7114
7143
 
7144
+ // \u2500\u2500 Mesh Health (WP-MVP-3 Follow-up #3) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
7145
+ // The federation FailureModeDetector pushes per-tick snapshots and
7146
+ // per-detection alerts via the existing /events channel. Renders are
7147
+ // best-effort \u2014 if the panel DOM is absent (older HTML cache), we
7148
+ // silently skip rather than crashing.
7149
+ eventSource.addEventListener('mesh-health', (e) => {
7150
+ try {
7151
+ const snap = JSON.parse(e.data);
7152
+ renderMeshHealth(snap);
7153
+ } catch (err) { console.error('mesh-health render failed', err); }
7154
+ });
7155
+ eventSource.addEventListener('mesh-failure-mode-alert', (e) => {
7156
+ try {
7157
+ const alert = JSON.parse(e.data);
7158
+ appendMeshAlert(alert);
7159
+ } catch (err) { console.error('mesh alert render failed', err); }
7160
+ });
7161
+ eventSource.addEventListener('mesh-post-recovery-prompt', (e) => {
7162
+ try {
7163
+ const prompt = JSON.parse(e.data);
7164
+ renderMeshPostRecoveryPrompt(prompt);
7165
+ } catch (err) { console.error('mesh post-recovery render failed', err); }
7166
+ });
7167
+
7115
7168
  eventSource.onerror = () => {
7116
7169
  console.error('SSE error');
7117
7170
  setTimeout(setupSSE, 5000);
7118
7171
  };
7119
7172
  }
7120
7173
 
7174
+ // \u2500\u2500 Mesh Health rendering (WP-MVP-3 Follow-up #3) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
7175
+ function renderMeshHealth(snap) {
7176
+ const updatedAt = document.getElementById('mesh-health-updated-at');
7177
+ const rows = document.getElementById('mesh-health-rows');
7178
+ if (!rows || !snap) return;
7179
+ if (updatedAt) updatedAt.textContent = formatTime(snap.generated_at);
7180
+ const nodes = Array.isArray(snap.nodes) ? snap.nodes : [];
7181
+ if (nodes.length === 0) {
7182
+ rows.innerHTML = '<div class="empty-state">No mesh nodes seen yet.</div>';
7183
+ return;
7184
+ }
7185
+ rows.innerHTML = nodes.map((n) => {
7186
+ const flags = (n.flags || []).map((f) => '<span class="mesh-flag">' + esc(f) + '</span>').join(' ');
7187
+ return '<div class="mesh-row" data-rollup="' + esc(n.rollup) + '">' +
7188
+ '<span class="mesh-node-id">' + esc(n.node_id) + '</span>' +
7189
+ '<span class="mesh-presence">' + esc(n.presence) + '</span>' +
7190
+ '<span class="mesh-rollup">' + esc(n.rollup) + '</span>' +
7191
+ '<span class="mesh-flags">' + flags + '</span>' +
7192
+ '</div>';
7193
+ }).join('');
7194
+ const alertsBox = document.getElementById('mesh-health-alerts');
7195
+ if (alertsBox && Array.isArray(snap.open_alerts)) {
7196
+ alertsBox.innerHTML = snap.open_alerts.map((a) =>
7197
+ '<div class="mesh-alert" data-mode="' + esc(a.mode) + '">' +
7198
+ '<div class="mesh-alert-mode">' + esc(a.mode) + ' \u2014 ' + esc(a.target_node) + '</div>' +
7199
+ '<div class="mesh-alert-message">' + esc(a.message) + '</div>' +
7200
+ '</div>'
7201
+ ).join('');
7202
+ }
7203
+ }
7204
+
7205
+ function appendMeshAlert(alert) {
7206
+ const alertsBox = document.getElementById('mesh-health-alerts');
7207
+ if (!alertsBox || !alert) return;
7208
+ const html = '<div class="mesh-alert" data-mode="' + esc(alert.mode) + '">' +
7209
+ '<div class="mesh-alert-mode">' + esc(alert.mode) + ' \u2014 ' + esc(alert.target_node) + '</div>' +
7210
+ '<div class="mesh-alert-message">' + esc(alert.message) + '</div>' +
7211
+ '</div>';
7212
+ alertsBox.insertAdjacentHTML('afterbegin', html);
7213
+ }
7214
+
7215
+ function renderMeshPostRecoveryPrompt(prompt) {
7216
+ const box = document.getElementById('mesh-post-recovery-prompt');
7217
+ if (!box || !prompt) return;
7218
+ box.style.display = 'block';
7219
+ const creds = Array.isArray(prompt.credentials) ? prompt.credentials : [];
7220
+ box.innerHTML = '<div class="mesh-rotation-banner">' +
7221
+ '<strong>Post-rotation hygiene:</strong> we just rotated your fortress root key. ' +
7222
+ 'Rotate externally-scoped broker credentials that third parties may still associate with ' +
7223
+ 'the pre-rotation key material.' +
7224
+ '</div>' +
7225
+ '<ul class="mesh-rotation-list">' +
7226
+ creds.map((c) => '<li>' +
7227
+ '<span class="mesh-cred-name">' + esc(c.secret_name) + '</span>' +
7228
+ '<button class="mesh-cred-rotate" data-secret="' + esc(c.secret_name) + '">' +
7229
+ 'rotate now</button>' +
7230
+ '</li>').join('') +
7231
+ '</ul>';
7232
+ }
7233
+
7121
7234
  // Activity Feed
7122
7235
  function addActivityItem(item) {
7123
7236
  activityLog.unshift(item);
@@ -9678,6 +9791,27 @@ data: ${JSON.stringify(data)}
9678
9791
  broadcastProtectionStatus(data) {
9679
9792
  this.broadcastSSE("protection-status", data);
9680
9793
  }
9794
+ // ── Mesh-health surface (WP-MVP-3 Follow-up #3) ─────────────────────
9795
+ //
9796
+ // The federation FailureModeDetector pushes per-tick health snapshots and
9797
+ // per-detection alerts here; the existing /events SSE channel transports
9798
+ // them to the browser. No new transport.
9799
+ //
9800
+ // Spec §8 + §9. Spawn-prompt acceptance criterion 7: "Mesh Health dashboard
9801
+ // panel renders via existing SSE /events channel — no new transport. Every
9802
+ // state transition produces an observable SSE event."
9803
+ /** Push a Mesh Health snapshot (full re-render trigger on the client). */
9804
+ broadcastMeshHealth(snapshot) {
9805
+ this.broadcastSSE("mesh-health", snapshot);
9806
+ }
9807
+ /** Push a single failure-mode alert (incremental client update). */
9808
+ broadcastMeshFailureModeAlert(alert) {
9809
+ this.broadcastSSE("mesh-failure-mode-alert", alert);
9810
+ }
9811
+ /** Push a post-recovery prompt update (master rotation hygiene flow). */
9812
+ broadcastMeshPostRecoveryPrompt(prompt) {
9813
+ this.broadcastSSE("mesh-post-recovery-prompt", prompt);
9814
+ }
9681
9815
  /**
9682
9816
  * Open a URL in the system's default browser.
9683
9817
  * Cross-platform: macOS (open), Linux (xdg-open), Windows (start).
@@ -13008,7 +13142,7 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
13008
13142
  const now = (/* @__PURE__ */ new Date()).toISOString();
13009
13143
  const canonicalBytes = canonicalize(outcome);
13010
13144
  const canonicalString = new TextDecoder().decode(canonicalBytes);
13011
- const sha2565 = createCommitment(canonicalString);
13145
+ const sha2567 = createCommitment(canonicalString);
13012
13146
  let pedersenData;
13013
13147
  if (includePedersen && Number.isInteger(outcome.rounds) && outcome.rounds >= 0) {
13014
13148
  const pedersen = createPedersenCommitment(outcome.rounds);
@@ -13020,7 +13154,7 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
13020
13154
  const commitmentPayload = {
13021
13155
  bridge_commitment_id: commitmentId,
13022
13156
  session_id: outcome.session_id,
13023
- sha256_commitment: sha2565.commitment,
13157
+ sha256_commitment: sha2567.commitment,
13024
13158
  terms_hash: outcome.terms_hash,
13025
13159
  committer_did: identity.did,
13026
13160
  committed_at: now,
@@ -13031,8 +13165,8 @@ function createBridgeCommitment(outcome, identity, identityEncryptionKey, includ
13031
13165
  return {
13032
13166
  bridge_commitment_id: commitmentId,
13033
13167
  session_id: outcome.session_id,
13034
- sha256_commitment: sha2565.commitment,
13035
- blinding_factor: sha2565.blinding_factor,
13168
+ sha256_commitment: sha2567.commitment,
13169
+ blinding_factor: sha2567.blinding_factor,
13036
13170
  committer_did: identity.did,
13037
13171
  signature: toBase64url(signature),
13038
13172
  pedersen_commitment: pedersenData,
@@ -21556,8 +21690,15 @@ function l3Card(l3) {
21556
21690
  <div><dt>Proofs today</dt><dd>${escHtml(l3.proofs_today)}</dd></div>`
21557
21691
  );
21558
21692
  }
21693
+ var VERASCORE_CLAIM_URL = "https://www.verascore.ai";
21559
21694
  function l4Card(l4) {
21560
- const score = l4.score != null ? `<div class="score-block"><span class="score-value">${escHtml(l4.score)}</span><span class="score-label">Verascore</span></div>` : `<div class="claim-block">${escHtml(l4.claim_cta ?? "Claim your profile at verascore.ai")}</div>`;
21695
+ let score;
21696
+ if (l4.score != null) {
21697
+ score = `<div class="score-block"><span class="score-value">${escHtml(l4.score)}</span><span class="score-label">Verascore</span></div>`;
21698
+ } else {
21699
+ const claimText = l4.claim_cta ?? "Claim your profile at verascore.ai";
21700
+ score = `<div class="claim-block"><a class="claim-link" href="${VERASCORE_CLAIM_URL}" target="_blank" rel="noopener noreferrer">${escHtml(claimText)}</a></div>`;
21701
+ }
21561
21702
  return layerCard(
21562
21703
  l4,
21563
21704
  `<div class="layer-cta">${score}</div>${l4EvidenceBlock(l4)}`
@@ -22220,6 +22361,961 @@ details.audit-details .audit-filters { display: flex; gap: 6px; padding: 0 18px
22220
22361
  </html>`;
22221
22362
  }
22222
22363
 
22364
+ // src/policy-engine/constants.ts
22365
+ var COMPILED_POLICY_SCHEMA_VERSION = "0.1";
22366
+ var POLICY_UPDATE_EVENT_TYPE = "policy_update";
22367
+ var POLICY_SLOTS = [
22368
+ "memory",
22369
+ "credentials",
22370
+ "plans",
22371
+ "outputs"
22372
+ ];
22373
+ function isPolicySlot(value) {
22374
+ return typeof value === "string" && POLICY_SLOTS.includes(value);
22375
+ }
22376
+ var CHANNEL_TEMPLATE_IDS = [
22377
+ "read-outputs-only",
22378
+ "bidirectional-sync",
22379
+ "credential-share-scoped",
22380
+ "plan-inspect-read-only",
22381
+ "escrow-handoff"
22382
+ ];
22383
+ var BUDGET_UNITS = ["tokens", "usd"];
22384
+
22385
+ // src/templates/registry.ts
22386
+ var TEMPLATE_NAMES = [
22387
+ "research-assistant",
22388
+ "coding-assistant",
22389
+ "ops-runner",
22390
+ "planner",
22391
+ "handoff-coordinator",
22392
+ "x-miner",
22393
+ "github-miner"
22394
+ ];
22395
+ function isTemplateName(value) {
22396
+ return typeof value === "string" && TEMPLATE_NAMES.includes(value);
22397
+ }
22398
+ var TemplateValidationError = class extends Error {
22399
+ constructor(templateName, message) {
22400
+ super(`template "${templateName}": ${message}`);
22401
+ this.name = "TemplateValidationError";
22402
+ }
22403
+ };
22404
+ function validateMetadata(name, data) {
22405
+ if (typeof data !== "object" || data === null) {
22406
+ throw new TemplateValidationError(name, "template.json must be an object");
22407
+ }
22408
+ const d = data;
22409
+ if (typeof d.name !== "string" || d.name !== name) {
22410
+ throw new TemplateValidationError(name, `template.json name must be "${name}"`);
22411
+ }
22412
+ if (typeof d.version !== "string" || !/^\d+\.\d+\.\d+$/.test(d.version)) {
22413
+ throw new TemplateValidationError(name, "template.json version must be semver");
22414
+ }
22415
+ if (typeof d.channel !== "string" || !CHANNEL_TEMPLATE_IDS.includes(d.channel)) {
22416
+ throw new TemplateValidationError(
22417
+ name,
22418
+ `template.json channel must be one of: ${CHANNEL_TEMPLATE_IDS.join(", ")}`
22419
+ );
22420
+ }
22421
+ if (typeof d.tier !== "string" || !["A", "B", "C"].includes(d.tier)) {
22422
+ throw new TemplateValidationError(name, "template.json tier must be A, B, or C");
22423
+ }
22424
+ if (typeof d.target_archetype !== "string" || d.target_archetype.length === 0) {
22425
+ throw new TemplateValidationError(name, "template.json target_archetype must be a non-empty string");
22426
+ }
22427
+ if (typeof d.description !== "string" || d.description.length === 0) {
22428
+ throw new TemplateValidationError(name, "template.json description must be a non-empty string");
22429
+ }
22430
+ }
22431
+ function validateDefaults(name, data) {
22432
+ if (typeof data !== "object" || data === null) {
22433
+ throw new TemplateValidationError(name, "defaults.json must be an object");
22434
+ }
22435
+ const d = data;
22436
+ if (!Array.isArray(d.egress)) {
22437
+ throw new TemplateValidationError(name, "defaults.json egress must be an array");
22438
+ }
22439
+ for (const entry of d.egress) {
22440
+ if (typeof entry !== "object" || entry === null) {
22441
+ throw new TemplateValidationError(name, "defaults.json egress entry must be an object");
22442
+ }
22443
+ const e = entry;
22444
+ if (typeof e.destination !== "string" || e.destination.length === 0) {
22445
+ throw new TemplateValidationError(name, "egress entry destination must be a non-empty string");
22446
+ }
22447
+ if (!Array.isArray(e.methods)) {
22448
+ throw new TemplateValidationError(name, "egress entry methods must be an array");
22449
+ }
22450
+ }
22451
+ if (typeof d.budgets !== "object" || d.budgets === null) {
22452
+ throw new TemplateValidationError(name, "defaults.json budgets must be an object");
22453
+ }
22454
+ if (typeof d.retention !== "object" || d.retention === null) {
22455
+ throw new TemplateValidationError(name, "defaults.json retention must be an object");
22456
+ }
22457
+ const ret = d.retention;
22458
+ if (typeof ret.windows !== "object" || ret.windows === null) {
22459
+ throw new TemplateValidationError(name, "defaults.json retention.windows must be an object");
22460
+ }
22461
+ }
22462
+ function validateCommitments(name, data) {
22463
+ if (typeof data !== "object" || data === null) {
22464
+ throw new TemplateValidationError(name, "commitments.json must be an object");
22465
+ }
22466
+ const d = data;
22467
+ if (!Array.isArray(d.shapes)) {
22468
+ throw new TemplateValidationError(name, "commitments.json shapes must be an array");
22469
+ }
22470
+ for (const shape of d.shapes) {
22471
+ if (typeof shape !== "object" || shape === null) {
22472
+ throw new TemplateValidationError(name, "commitment shape must be an object");
22473
+ }
22474
+ const s = shape;
22475
+ if (typeof s.commitment_class !== "string" || s.commitment_class.length === 0) {
22476
+ throw new TemplateValidationError(name, "commitment shape commitment_class must be a non-empty string");
22477
+ }
22478
+ if (typeof s.example_deliverable !== "string") {
22479
+ throw new TemplateValidationError(name, "commitment shape example_deliverable must be a string");
22480
+ }
22481
+ if (typeof s.example_deadline_or_terminal !== "string") {
22482
+ throw new TemplateValidationError(name, "commitment shape example_deadline_or_terminal must be a string");
22483
+ }
22484
+ }
22485
+ }
22486
+ function lintOnboarding(_name, content) {
22487
+ const violations = [];
22488
+ if (content.includes("\u2014")) {
22489
+ violations.push("onboarding.md contains em-dashes (U+2014). Replace with commas, semicolons, colons, or parentheses.");
22490
+ }
22491
+ if (content.includes("\u2013")) {
22492
+ violations.push("onboarding.md contains en-dashes (U+2013). Replace with hyphens or other punctuation.");
22493
+ }
22494
+ return { clean: violations.length === 0, violations };
22495
+ }
22496
+ function resolveTemplatesDir() {
22497
+ const thisFile = url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
22498
+ const thisDir = path.dirname(thisFile);
22499
+ if (thisDir.includes("/dist/")) {
22500
+ return thisDir.replace("/dist/templates", "/src/templates");
22501
+ }
22502
+ return thisDir;
22503
+ }
22504
+ function loadTemplateBundle(name, templatesDir) {
22505
+ const dir = path.join(templatesDir, name);
22506
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
22507
+ throw new TemplateValidationError(name, `template directory not found: ${dir}`);
22508
+ }
22509
+ const metadataRaw = JSON.parse(fs.readFileSync(path.join(dir, "template.json"), "utf-8"));
22510
+ validateMetadata(name, metadataRaw);
22511
+ const policyEnglish = fs.readFileSync(path.join(dir, "policy.md"), "utf-8").trim();
22512
+ if (policyEnglish.length === 0) {
22513
+ throw new TemplateValidationError(name, "policy.md must not be empty");
22514
+ }
22515
+ const defaultsRaw = JSON.parse(fs.readFileSync(path.join(dir, "defaults.json"), "utf-8"));
22516
+ validateDefaults(name, defaultsRaw);
22517
+ const commitmentsRaw = JSON.parse(fs.readFileSync(path.join(dir, "commitments.json"), "utf-8"));
22518
+ validateCommitments(name, commitmentsRaw);
22519
+ const onboarding = fs.readFileSync(path.join(dir, "onboarding.md"), "utf-8").trim();
22520
+ if (onboarding.length === 0) {
22521
+ throw new TemplateValidationError(name, "onboarding.md must not be empty");
22522
+ }
22523
+ const lint = lintOnboarding(name, onboarding);
22524
+ if (!lint.clean) {
22525
+ throw new TemplateValidationError(name, lint.violations.join("; "));
22526
+ }
22527
+ return {
22528
+ metadata: metadataRaw,
22529
+ policy_english: policyEnglish,
22530
+ defaults: defaultsRaw,
22531
+ commitments: commitmentsRaw,
22532
+ onboarding
22533
+ };
22534
+ }
22535
+ var _cache = null;
22536
+ function ensureLoaded() {
22537
+ if (_cache) return _cache;
22538
+ _cache = /* @__PURE__ */ new Map();
22539
+ const dir = resolveTemplatesDir();
22540
+ for (const name of TEMPLATE_NAMES) {
22541
+ _cache.set(name, loadTemplateBundle(name, dir));
22542
+ }
22543
+ return _cache;
22544
+ }
22545
+ function listTemplates() {
22546
+ const cache = ensureLoaded();
22547
+ return TEMPLATE_NAMES.map((name) => {
22548
+ const bundle = cache.get(name);
22549
+ return {
22550
+ metadata: bundle.metadata,
22551
+ onboarding: bundle.onboarding
22552
+ };
22553
+ });
22554
+ }
22555
+ function getTemplate2(name) {
22556
+ if (!isTemplateName(name)) return null;
22557
+ const cache = ensureLoaded();
22558
+ return cache.get(name) ?? null;
22559
+ }
22560
+ function getTemplateEntry(name) {
22561
+ const bundle = getTemplate2(name);
22562
+ if (!bundle) return null;
22563
+ return { metadata: bundle.metadata, onboarding: bundle.onboarding };
22564
+ }
22565
+
22566
+ // src/policy-engine/null-policy.ts
22567
+ function buildNullPolicy(params) {
22568
+ const denyRule = (slot) => ({
22569
+ slot,
22570
+ mode: "deny",
22571
+ grants: []
22572
+ });
22573
+ return {
22574
+ schema_version: "0.1",
22575
+ agent_id: params.agent_id,
22576
+ fortress_id: params.fortress_id,
22577
+ policy_version: 0,
22578
+ slots: {
22579
+ memory: denyRule("memory"),
22580
+ credentials: denyRule("credentials"),
22581
+ plans: denyRule("plans"),
22582
+ outputs: denyRule("outputs")
22583
+ },
22584
+ capabilities: {
22585
+ concordia_commitment_classes: [],
22586
+ honeypot_skill_ids: [],
22587
+ is_sentinel: false
22588
+ },
22589
+ auto_trigger_ladder: {
22590
+ honeypot_auto_freeze: true,
22591
+ threshold_rule_action: "operator_approved",
22592
+ ml_anomaly_action: "operator_approved"
22593
+ },
22594
+ source_english: "(null policy \u2014 no operator authoring yet; hermetic default denies all four slots)",
22595
+ compiled_at: "1970-01-01T00:00:00.000Z"
22596
+ };
22597
+ }
22598
+
22599
+ // src/policy-engine/channel-templates.ts
22600
+ function basePolicy(params) {
22601
+ if (params.merge_into) {
22602
+ const p2 = {
22603
+ ...params.merge_into,
22604
+ policy_version: params.policy_version,
22605
+ compiled_at: (/* @__PURE__ */ new Date()).toISOString(),
22606
+ slots: {
22607
+ memory: cloneRule(params.merge_into.slots.memory),
22608
+ credentials: cloneRule(params.merge_into.slots.credentials),
22609
+ plans: cloneRule(params.merge_into.slots.plans),
22610
+ outputs: cloneRule(params.merge_into.slots.outputs)
22611
+ },
22612
+ capabilities: {
22613
+ ...params.merge_into.capabilities,
22614
+ concordia_commitment_classes: [
22615
+ ...params.merge_into.capabilities.concordia_commitment_classes
22616
+ ],
22617
+ honeypot_skill_ids: [...params.merge_into.capabilities.honeypot_skill_ids]
22618
+ },
22619
+ auto_trigger_ladder: { ...params.merge_into.auto_trigger_ladder }
22620
+ };
22621
+ if (params.parent_version !== void 0) p2.parent_version = params.parent_version;
22622
+ else delete p2.parent_version;
22623
+ return p2;
22624
+ }
22625
+ const p = buildNullPolicy({
22626
+ agent_id: params.agent_id,
22627
+ fortress_id: params.fortress_id
22628
+ });
22629
+ p.policy_version = params.policy_version;
22630
+ p.compiled_at = (/* @__PURE__ */ new Date()).toISOString();
22631
+ if (params.parent_version !== void 0) p.parent_version = params.parent_version;
22632
+ return p;
22633
+ }
22634
+ function cloneRule(r) {
22635
+ return {
22636
+ slot: r.slot,
22637
+ mode: r.mode,
22638
+ grants: r.grants.map((g) => ({ ...g, scope: g.scope ? { ...g.scope } : void 0 }))
22639
+ };
22640
+ }
22641
+ function grantOn(policy, slot, grant) {
22642
+ const rule = policy.slots[slot];
22643
+ rule.mode = "grant";
22644
+ const dup = rule.grants.find(
22645
+ (g) => g.counterparty === grant.counterparty && g.action === grant.action
22646
+ );
22647
+ if (dup) {
22648
+ if (grant.scope) {
22649
+ dup.scope = { ...dup.scope ?? {}, ...grant.scope };
22650
+ }
22651
+ return;
22652
+ }
22653
+ rule.grants.push(grant);
22654
+ rule.grants.sort((a, b) => {
22655
+ if (a.counterparty === b.counterparty) return a.action.localeCompare(b.action);
22656
+ return a.counterparty.localeCompare(b.counterparty);
22657
+ });
22658
+ }
22659
+ var readOutputsOnly = (params) => {
22660
+ const p = basePolicy(params);
22661
+ p.source_english = `${params.counterparty} may read ${params.agent_id}'s outputs \u2014 read-only, no other access.`;
22662
+ grantOn(p, "outputs", {
22663
+ counterparty: params.counterparty,
22664
+ action: "read",
22665
+ ...params.scope ? { scope: { ...params.scope } } : {}
22666
+ });
22667
+ return p;
22668
+ };
22669
+ var bidirectionalSync = (params) => {
22670
+ const p = basePolicy(params);
22671
+ p.source_english = `Bidirectional sync between ${params.agent_id} and ${params.counterparty} on memory + outputs.`;
22672
+ for (const slot of ["memory", "outputs"]) {
22673
+ for (const action of ["read", "subscribe"]) {
22674
+ grantOn(p, slot, {
22675
+ counterparty: params.counterparty,
22676
+ action,
22677
+ ...params.scope ? { scope: { ...params.scope } } : {}
22678
+ });
22679
+ }
22680
+ }
22681
+ return p;
22682
+ };
22683
+ var credentialShareScoped = (params) => {
22684
+ const p = basePolicy(params);
22685
+ const credentialId = (params.scope && typeof params.scope.credential_id === "string" ? params.scope.credential_id : void 0) ?? "(unspecified)";
22686
+ p.source_english = `${params.agent_id} may share credential "${credentialId}" with ${params.counterparty}; no other credential access.`;
22687
+ grantOn(p, "credentials", {
22688
+ counterparty: params.counterparty,
22689
+ action: "share",
22690
+ scope: {
22691
+ credential_id: credentialId,
22692
+ ...params.scope ?? {}
22693
+ }
22694
+ });
22695
+ return p;
22696
+ };
22697
+ var planInspectReadOnly = (params) => {
22698
+ const p = basePolicy(params);
22699
+ p.source_english = `${params.counterparty} may read-only inspect ${params.agent_id}'s plans.`;
22700
+ grantOn(p, "plans", {
22701
+ counterparty: params.counterparty,
22702
+ action: "read",
22703
+ ...params.scope ? { scope: { ...params.scope } } : {}
22704
+ });
22705
+ return p;
22706
+ };
22707
+ var escrowHandoff = (params) => {
22708
+ const p = basePolicy(params);
22709
+ p.source_english = `${params.agent_id} may escrow-handoff outputs and plan-read to ${params.counterparty}. Commitment class: intra-mesh-escrow.`;
22710
+ grantOn(p, "plans", {
22711
+ counterparty: params.counterparty,
22712
+ action: "read",
22713
+ ...params.scope ? { scope: { ...params.scope } } : {}
22714
+ });
22715
+ for (const action of ["read", "subscribe"]) {
22716
+ grantOn(p, "outputs", {
22717
+ counterparty: params.counterparty,
22718
+ action,
22719
+ ...params.scope ? { scope: { ...params.scope } } : {}
22720
+ });
22721
+ }
22722
+ const cls = "intra-mesh-escrow";
22723
+ if (!p.capabilities.concordia_commitment_classes.includes(cls)) {
22724
+ p.capabilities.concordia_commitment_classes.push(cls);
22725
+ p.capabilities.concordia_commitment_classes.sort();
22726
+ }
22727
+ return p;
22728
+ };
22729
+ var REGISTRY = {
22730
+ "read-outputs-only": {
22731
+ id: "read-outputs-only",
22732
+ label: "Read outputs only",
22733
+ description: "Counterparty may read this agent's outputs. No memory, credentials, or plans access.",
22734
+ factory: readOutputsOnly
22735
+ },
22736
+ "bidirectional-sync": {
22737
+ id: "bidirectional-sync",
22738
+ label: "Bidirectional memory + output sync",
22739
+ description: "Both agents may read and subscribe to each other's memory and outputs. Credentials and plans remain hermetic.",
22740
+ factory: bidirectionalSync
22741
+ },
22742
+ "credential-share-scoped": {
22743
+ id: "credential-share-scoped",
22744
+ label: "Scoped credential share",
22745
+ description: "Share one specific credential with counterparty. Requires scope.credential_id. No broad credential access.",
22746
+ factory: credentialShareScoped
22747
+ },
22748
+ "plan-inspect-read-only": {
22749
+ id: "plan-inspect-read-only",
22750
+ label: "Plan inspect (read-only)",
22751
+ description: "Counterparty may read-only inspect this agent's plans. Intended for supervisor / sentinel patterns.",
22752
+ factory: planInspectReadOnly
22753
+ },
22754
+ "escrow-handoff": {
22755
+ id: "escrow-handoff",
22756
+ label: "Escrow handoff",
22757
+ description: "Escrow-style handoff. Counterparty reads plan, reads + subscribes to outputs, and the intra-mesh-escrow commitment class is declared. Memory and credentials remain hermetic.",
22758
+ factory: escrowHandoff
22759
+ }
22760
+ };
22761
+ function applyChannelTemplate(id, params) {
22762
+ const entry = REGISTRY[id];
22763
+ if (!entry) {
22764
+ throw new Error(`unknown channel template: ${id}`);
22765
+ }
22766
+ return entry.factory(params);
22767
+ }
22768
+
22769
+ // src/mesh/errors.ts
22770
+ var MeshError = class extends Error {
22771
+ constructor(message) {
22772
+ super(message);
22773
+ this.name = "MeshError";
22774
+ }
22775
+ };
22776
+ var MeshEnvelopeError = class extends MeshError {
22777
+ constructor(message) {
22778
+ super(message);
22779
+ this.name = "MeshEnvelopeError";
22780
+ }
22781
+ };
22782
+ var MeshReservedExtensionKeyError = class extends MeshEnvelopeError {
22783
+ constructor(key) {
22784
+ super(
22785
+ `v0.1 emitters MUST NOT populate reserved extension_envelope key: ${key}`
22786
+ );
22787
+ this.name = "MeshReservedExtensionKeyError";
22788
+ }
22789
+ };
22790
+ var MeshReservedEventTypeError = class extends MeshEnvelopeError {
22791
+ constructor(eventType) {
22792
+ super(
22793
+ `v0.1 emitters MUST NOT emit reserved-namespace event_type: ${eventType}`
22794
+ );
22795
+ this.name = "MeshReservedEventTypeError";
22796
+ }
22797
+ };
22798
+
22799
+ // src/mesh/canonical-json.ts
22800
+ var MeshCanonicalJsonError = class extends MeshError {
22801
+ constructor(message) {
22802
+ super(message);
22803
+ this.name = "MeshCanonicalJsonError";
22804
+ }
22805
+ };
22806
+ function canonicalize2(value) {
22807
+ if (value === void 0) {
22808
+ throw new MeshCanonicalJsonError(
22809
+ "canonicalize(): top-level undefined is not serializable"
22810
+ );
22811
+ }
22812
+ return encode(value);
22813
+ }
22814
+ function encode(value) {
22815
+ if (value === null) return "null";
22816
+ if (typeof value === "boolean") return value ? "true" : "false";
22817
+ if (typeof value === "number") {
22818
+ if (!Number.isFinite(value)) {
22819
+ throw new MeshCanonicalJsonError(
22820
+ `canonicalize(): non-finite number (${String(value)}) is not serializable`
22821
+ );
22822
+ }
22823
+ return JSON.stringify(value);
22824
+ }
22825
+ if (typeof value === "string") return JSON.stringify(value);
22826
+ if (Array.isArray(value)) return encodeArray(value);
22827
+ if (typeof value === "object") return encodeObject(value);
22828
+ throw new MeshCanonicalJsonError(
22829
+ `canonicalize(): unsupported type ${typeof value}`
22830
+ );
22831
+ }
22832
+ function encodeArray(arr) {
22833
+ const parts = [];
22834
+ for (const item of arr) {
22835
+ parts.push(item === void 0 ? "null" : encode(item));
22836
+ }
22837
+ return "[" + parts.join(",") + "]";
22838
+ }
22839
+ function encodeObject(obj) {
22840
+ const keys = Object.keys(obj).filter((k) => obj[k] !== void 0).sort();
22841
+ const parts = [];
22842
+ for (const k of keys) {
22843
+ parts.push(JSON.stringify(k) + ":" + encode(obj[k]));
22844
+ }
22845
+ return "{" + parts.join(",") + "}";
22846
+ }
22847
+ function canonicalizeToBytes(value) {
22848
+ return new TextEncoder().encode(canonicalize2(value));
22849
+ }
22850
+
22851
+ // src/policy-engine/canonical-policy.ts
22852
+ init_encoding();
22853
+
22854
+ // src/policy-engine/errors.ts
22855
+ var PolicyEngineError = class extends Error {
22856
+ constructor(message) {
22857
+ super(message);
22858
+ this.name = "PolicyEngineError";
22859
+ }
22860
+ };
22861
+ var CompiledPolicyShapeError = class extends PolicyEngineError {
22862
+ constructor(message) {
22863
+ super(message);
22864
+ this.name = "CompiledPolicyShapeError";
22865
+ }
22866
+ };
22867
+
22868
+ // src/policy-engine/canonical-policy.ts
22869
+ function checkSlotGrant(value, path) {
22870
+ if (typeof value !== "object" || value === null) {
22871
+ throw new CompiledPolicyShapeError(`${path}: grant must be an object`);
22872
+ }
22873
+ const g = value;
22874
+ if (typeof g.counterparty !== "string" || g.counterparty.length === 0) {
22875
+ throw new CompiledPolicyShapeError(
22876
+ `${path}.counterparty must be a non-empty string`
22877
+ );
22878
+ }
22879
+ if (typeof g.action !== "string" || g.action.length === 0) {
22880
+ throw new CompiledPolicyShapeError(
22881
+ `${path}.action must be a non-empty string`
22882
+ );
22883
+ }
22884
+ if (g.scope !== void 0) {
22885
+ if (typeof g.scope !== "object" || g.scope === null || Array.isArray(g.scope)) {
22886
+ throw new CompiledPolicyShapeError(
22887
+ `${path}.scope must be an object when present`
22888
+ );
22889
+ }
22890
+ }
22891
+ if (g.max_uses_per_day !== void 0) {
22892
+ if (typeof g.max_uses_per_day !== "number" || !Number.isInteger(g.max_uses_per_day) || g.max_uses_per_day < 0) {
22893
+ throw new CompiledPolicyShapeError(
22894
+ `${path}.max_uses_per_day must be a non-negative integer when present`
22895
+ );
22896
+ }
22897
+ }
22898
+ }
22899
+ function checkSlotRule(slot, value, path) {
22900
+ if (typeof value !== "object" || value === null) {
22901
+ throw new CompiledPolicyShapeError(`${path}: slot rule must be an object`);
22902
+ }
22903
+ const r = value;
22904
+ if (r.slot !== slot) {
22905
+ throw new CompiledPolicyShapeError(
22906
+ `${path}.slot expected ${slot}, got ${String(r.slot)}`
22907
+ );
22908
+ }
22909
+ if (r.mode !== "deny" && r.mode !== "grant") {
22910
+ throw new CompiledPolicyShapeError(
22911
+ `${path}.mode must be "deny" or "grant"`
22912
+ );
22913
+ }
22914
+ if (!Array.isArray(r.grants)) {
22915
+ throw new CompiledPolicyShapeError(
22916
+ `${path}.grants must be an array (possibly empty)`
22917
+ );
22918
+ }
22919
+ if (r.mode === "deny" && r.grants.length > 0) {
22920
+ throw new CompiledPolicyShapeError(
22921
+ `${path}: deny-mode slot rule must carry zero grants`
22922
+ );
22923
+ }
22924
+ r.grants.forEach((g, i) => checkSlotGrant(g, `${path}.grants[${i}]`));
22925
+ }
22926
+ function validateCompiledPolicyShape(candidate) {
22927
+ if (typeof candidate !== "object" || candidate === null) {
22928
+ throw new CompiledPolicyShapeError("compiled policy must be an object");
22929
+ }
22930
+ const p = candidate;
22931
+ if (p.schema_version !== COMPILED_POLICY_SCHEMA_VERSION) {
22932
+ throw new CompiledPolicyShapeError(
22933
+ `schema_version ${String(p.schema_version)} not supported at v0.1 (expected "${COMPILED_POLICY_SCHEMA_VERSION}")`
22934
+ );
22935
+ }
22936
+ if (typeof p.agent_id !== "string" || p.agent_id.length === 0) {
22937
+ throw new CompiledPolicyShapeError("agent_id must be a non-empty string");
22938
+ }
22939
+ if (typeof p.fortress_id !== "string" || p.fortress_id.length === 0) {
22940
+ throw new CompiledPolicyShapeError(
22941
+ "fortress_id must be a non-empty string"
22942
+ );
22943
+ }
22944
+ if (typeof p.policy_version !== "number" || !Number.isInteger(p.policy_version) || p.policy_version < 0) {
22945
+ throw new CompiledPolicyShapeError(
22946
+ "policy_version must be a non-negative integer"
22947
+ );
22948
+ }
22949
+ if (p.parent_version !== void 0 && (typeof p.parent_version !== "number" || !Number.isInteger(p.parent_version) || p.parent_version < 0)) {
22950
+ throw new CompiledPolicyShapeError(
22951
+ "parent_version must be a non-negative integer when present"
22952
+ );
22953
+ }
22954
+ if (typeof p.slots !== "object" || p.slots === null) {
22955
+ throw new CompiledPolicyShapeError("slots must be an object");
22956
+ }
22957
+ const slots = p.slots;
22958
+ const slotKeys = Object.keys(slots).sort();
22959
+ const expectedSlotKeys = [...POLICY_SLOTS].sort();
22960
+ if (slotKeys.length !== expectedSlotKeys.length || !slotKeys.every((k, i) => k === expectedSlotKeys[i])) {
22961
+ throw new CompiledPolicyShapeError(
22962
+ `slots must contain exactly ${expectedSlotKeys.join(", ")}; got ${slotKeys.join(", ") || "(none)"}`
22963
+ );
22964
+ }
22965
+ for (const slot of POLICY_SLOTS) {
22966
+ checkSlotRule(slot, slots[slot], `slots.${slot}`);
22967
+ }
22968
+ if (typeof p.capabilities !== "object" || p.capabilities === null) {
22969
+ throw new CompiledPolicyShapeError("capabilities must be an object");
22970
+ }
22971
+ const caps = p.capabilities;
22972
+ if (!Array.isArray(caps.concordia_commitment_classes) || !caps.concordia_commitment_classes.every((c) => typeof c === "string")) {
22973
+ throw new CompiledPolicyShapeError(
22974
+ "capabilities.concordia_commitment_classes must be a string[]"
22975
+ );
22976
+ }
22977
+ if (!Array.isArray(caps.honeypot_skill_ids) || !caps.honeypot_skill_ids.every((c) => typeof c === "string")) {
22978
+ throw new CompiledPolicyShapeError(
22979
+ "capabilities.honeypot_skill_ids must be a string[]"
22980
+ );
22981
+ }
22982
+ if (typeof caps.is_sentinel !== "boolean") {
22983
+ throw new CompiledPolicyShapeError(
22984
+ "capabilities.is_sentinel must be boolean"
22985
+ );
22986
+ }
22987
+ if (typeof p.auto_trigger_ladder !== "object" || p.auto_trigger_ladder === null) {
22988
+ throw new CompiledPolicyShapeError(
22989
+ "auto_trigger_ladder must be an object"
22990
+ );
22991
+ }
22992
+ const lad = p.auto_trigger_ladder;
22993
+ if (typeof lad.honeypot_auto_freeze !== "boolean") {
22994
+ throw new CompiledPolicyShapeError(
22995
+ "auto_trigger_ladder.honeypot_auto_freeze must be boolean"
22996
+ );
22997
+ }
22998
+ if (lad.threshold_rule_action !== "operator_approved" && lad.threshold_rule_action !== "auto") {
22999
+ throw new CompiledPolicyShapeError(
23000
+ 'auto_trigger_ladder.threshold_rule_action must be "operator_approved" or "auto"'
23001
+ );
23002
+ }
23003
+ if (lad.ml_anomaly_action !== "operator_approved" && lad.ml_anomaly_action !== "auto") {
23004
+ throw new CompiledPolicyShapeError(
23005
+ 'auto_trigger_ladder.ml_anomaly_action must be "operator_approved" or "auto"'
23006
+ );
23007
+ }
23008
+ if (typeof p.source_english !== "string") {
23009
+ throw new CompiledPolicyShapeError("source_english must be a string");
23010
+ }
23011
+ if (typeof p.compiled_at !== "string" || Number.isNaN(Date.parse(p.compiled_at))) {
23012
+ throw new CompiledPolicyShapeError(
23013
+ "compiled_at must be an ISO8601 timestamp string"
23014
+ );
23015
+ }
23016
+ for (const key of slotKeys) {
23017
+ if (!isPolicySlot(key)) {
23018
+ throw new CompiledPolicyShapeError(
23019
+ `slots.${key} is not a recognized policy slot`
23020
+ );
23021
+ }
23022
+ }
23023
+ if (p.egress !== void 0) {
23024
+ checkEgressPolicy(p.egress, "egress");
23025
+ }
23026
+ if (p.budgets !== void 0) {
23027
+ checkBudgetPolicy(p.budgets, "budgets");
23028
+ }
23029
+ if (p.retention !== void 0) {
23030
+ checkRetentionPolicy(p.retention, "retention");
23031
+ }
23032
+ }
23033
+ function checkEgressPolicy(value, path) {
23034
+ if (typeof value !== "object" || value === null) {
23035
+ throw new CompiledPolicyShapeError(`${path} must be an object`);
23036
+ }
23037
+ const eg = value;
23038
+ if (!Array.isArray(eg.allowlist)) {
23039
+ throw new CompiledPolicyShapeError(`${path}.allowlist must be an array`);
23040
+ }
23041
+ for (let i = 0; i < eg.allowlist.length; i++) {
23042
+ const rule = eg.allowlist[i];
23043
+ if (typeof rule !== "object" || rule === null) {
23044
+ throw new CompiledPolicyShapeError(
23045
+ `${path}.allowlist[${i}] must be an object`
23046
+ );
23047
+ }
23048
+ const r = rule;
23049
+ if (typeof r.destination !== "string" || r.destination.length === 0) {
23050
+ throw new CompiledPolicyShapeError(
23051
+ `${path}.allowlist[${i}].destination must be a non-empty string`
23052
+ );
23053
+ }
23054
+ if (!Array.isArray(r.methods) || !r.methods.every((m) => typeof m === "string")) {
23055
+ throw new CompiledPolicyShapeError(
23056
+ `${path}.allowlist[${i}].methods must be a string[]`
23057
+ );
23058
+ }
23059
+ }
23060
+ }
23061
+ function checkBudgetLimit(value, path) {
23062
+ if (typeof value !== "object" || value === null) {
23063
+ throw new CompiledPolicyShapeError(`${path} must be an object`);
23064
+ }
23065
+ const lim = value;
23066
+ if (typeof lim.amount !== "number" || lim.amount <= 0 || !Number.isFinite(lim.amount)) {
23067
+ throw new CompiledPolicyShapeError(
23068
+ `${path}.amount must be a positive finite number`
23069
+ );
23070
+ }
23071
+ if (!BUDGET_UNITS.includes(lim.unit)) {
23072
+ throw new CompiledPolicyShapeError(
23073
+ `${path}.unit must be one of: ${BUDGET_UNITS.join(", ")}`
23074
+ );
23075
+ }
23076
+ if (lim.soft_warn_threshold !== void 0) {
23077
+ if (typeof lim.soft_warn_threshold !== "number" || lim.soft_warn_threshold <= 0 || lim.soft_warn_threshold >= 1) {
23078
+ throw new CompiledPolicyShapeError(
23079
+ `${path}.soft_warn_threshold must be in (0, 1) when present`
23080
+ );
23081
+ }
23082
+ }
23083
+ }
23084
+ function checkBudgetPolicy(value, path) {
23085
+ if (typeof value !== "object" || value === null) {
23086
+ throw new CompiledPolicyShapeError(`${path} must be an object`);
23087
+ }
23088
+ const bp = value;
23089
+ if (bp.daily !== void 0) checkBudgetLimit(bp.daily, `${path}.daily`);
23090
+ if (bp.monthly !== void 0) checkBudgetLimit(bp.monthly, `${path}.monthly`);
23091
+ if (bp.daily === void 0 && bp.monthly === void 0) {
23092
+ throw new CompiledPolicyShapeError(
23093
+ `${path} must have at least one of daily or monthly`
23094
+ );
23095
+ }
23096
+ }
23097
+ function checkRetentionPolicy(value, path) {
23098
+ if (typeof value !== "object" || value === null) {
23099
+ throw new CompiledPolicyShapeError(`${path} must be an object`);
23100
+ }
23101
+ const rp = value;
23102
+ if (typeof rp.windows !== "object" || rp.windows === null) {
23103
+ throw new CompiledPolicyShapeError(`${path}.windows must be an object`);
23104
+ }
23105
+ const wins = rp.windows;
23106
+ for (const key of Object.keys(wins)) {
23107
+ if (!isPolicySlot(key)) {
23108
+ throw new CompiledPolicyShapeError(
23109
+ `${path}.windows.${key} is not a recognized policy slot`
23110
+ );
23111
+ }
23112
+ const w = wins[key];
23113
+ if (typeof w !== "object" || w === null) {
23114
+ throw new CompiledPolicyShapeError(
23115
+ `${path}.windows.${key} must be an object`
23116
+ );
23117
+ }
23118
+ const win = w;
23119
+ if (typeof win.max_age_seconds !== "number" || !Number.isInteger(win.max_age_seconds) || win.max_age_seconds <= 0) {
23120
+ throw new CompiledPolicyShapeError(
23121
+ `${path}.windows.${key}.max_age_seconds must be a positive integer`
23122
+ );
23123
+ }
23124
+ if (win.archive !== void 0 && typeof win.archive !== "boolean") {
23125
+ throw new CompiledPolicyShapeError(
23126
+ `${path}.windows.${key}.archive must be boolean when present`
23127
+ );
23128
+ }
23129
+ }
23130
+ }
23131
+ function encodePolicyBlob(policy) {
23132
+ validateCompiledPolicyShape(policy);
23133
+ return toBase64url(canonicalizeToBytes(policy));
23134
+ }
23135
+
23136
+ // src/mesh/envelope.ts
23137
+ init_encoding();
23138
+ init_random();
23139
+
23140
+ // src/mesh/constants.ts
23141
+ var PROTOCOL_VERSION = "0.1";
23142
+ var RESERVED_EVENT_TYPE_PREFIXES = [
23143
+ "EXTENSION_",
23144
+ "cross_fortress_",
23145
+ "multi_master_"
23146
+ ];
23147
+ function isReservedEventType(s) {
23148
+ return RESERVED_EVENT_TYPE_PREFIXES.some((p) => s.startsWith(p));
23149
+ }
23150
+ var RESERVED_EXTENSION_ENVELOPE_KEYS = [
23151
+ "cross_fortress_read_grant",
23152
+ "cross_fortress_read_query",
23153
+ "cross_fortress_read_response",
23154
+ "multi_master_policy_merge",
23155
+ "audit_replication_full_n_way",
23156
+ "auto_promote_canonical_audit",
23157
+ "agent_live_migration"
23158
+ ];
23159
+ function isReservedExtensionKey(k) {
23160
+ return RESERVED_EXTENSION_ENVELOPE_KEYS.includes(k);
23161
+ }
23162
+
23163
+ // src/mesh/trust-root.ts
23164
+ init_encoding();
23165
+ init_identity();
23166
+ init_random();
23167
+
23168
+ // src/mesh/envelope.ts
23169
+ function packSignedEvent(params) {
23170
+ if (isReservedEventType(params.event_type)) {
23171
+ throw new MeshReservedEventTypeError(params.event_type);
23172
+ }
23173
+ const ext = params.extension_envelope ?? {};
23174
+ for (const key of Object.keys(ext)) {
23175
+ if (isReservedExtensionKey(key)) {
23176
+ throw new MeshReservedExtensionKeyError(key);
23177
+ }
23178
+ }
23179
+ const payloadBytes = canonicalizeToBytes(params.payload);
23180
+ const payload_hash = toBase64url(sha256.sha256(payloadBytes));
23181
+ const body = {
23182
+ protocol_version: PROTOCOL_VERSION,
23183
+ event_type: params.event_type,
23184
+ event_id: generateEventId(),
23185
+ emitter_node: params.emitter_node,
23186
+ emitter_principal: params.emitter_principal,
23187
+ fortress_id: params.fortress_id,
23188
+ causal_parents: params.causal_parents ?? [],
23189
+ payload: params.payload,
23190
+ payload_hash,
23191
+ emitted_at: (/* @__PURE__ */ new Date()).toISOString(),
23192
+ monotonic_seq: params.monotonic_seq,
23193
+ extension_envelope: ext
23194
+ };
23195
+ const bytesToSign = canonicalizeToBytes(body);
23196
+ const nodeSig = ed25519.ed25519.sign(bytesToSign, params.node_private_key);
23197
+ const evt = {
23198
+ ...body,
23199
+ node_signature: toBase64url(nodeSig)
23200
+ };
23201
+ if (params.principal_private_key) {
23202
+ const principalSig = ed25519.ed25519.sign(bytesToSign, params.principal_private_key);
23203
+ evt.principal_signature = toBase64url(principalSig);
23204
+ }
23205
+ return evt;
23206
+ }
23207
+ function generateEventId() {
23208
+ const bytes = randomBytes(16);
23209
+ let hex = "";
23210
+ for (const b of bytes) hex += b.toString(16).padStart(2, "0");
23211
+ return hex;
23212
+ }
23213
+
23214
+ // src/policy-engine/envelope.ts
23215
+ function packPolicyUpdate(params) {
23216
+ validateCompiledPolicyShape(params.policy);
23217
+ const blob = encodePolicyBlob(params.policy);
23218
+ const payload = {
23219
+ agent_id: params.policy.agent_id,
23220
+ policy_version: params.policy.policy_version,
23221
+ policy_blob: blob,
23222
+ ...params.policy.parent_version !== void 0 ? { parent_version: params.policy.parent_version } : {}
23223
+ };
23224
+ return packSignedEvent({
23225
+ event_type: POLICY_UPDATE_EVENT_TYPE,
23226
+ emitter_node: params.emitter_node,
23227
+ emitter_principal: params.emitter_principal,
23228
+ fortress_id: params.policy.fortress_id,
23229
+ causal_parents: params.causal_parents,
23230
+ payload,
23231
+ monotonic_seq: params.monotonic_seq,
23232
+ node_private_key: params.node_private_key,
23233
+ principal_private_key: params.principal_private_key
23234
+ });
23235
+ }
23236
+
23237
+ // src/templates/init.ts
23238
+ function deterministicCompiledAt(version) {
23239
+ const [major, minor, patch] = version.split(".").map(Number);
23240
+ const epoch = /* @__PURE__ */ new Date("2026-01-01T00:00:00.000Z");
23241
+ epoch.setUTCDate(epoch.getUTCDate() + (major - 1) * 365 + minor * 30 + patch);
23242
+ return epoch.toISOString();
23243
+ }
23244
+ function buildCompiledPolicyFromTemplate(bundle, params) {
23245
+ const policy = applyChannelTemplate(
23246
+ bundle.metadata.channel,
23247
+ {
23248
+ agent_id: params.agent_id,
23249
+ counterparty: params.counterparty,
23250
+ fortress_id: params.fortress_id,
23251
+ policy_version: params.policy_version
23252
+ }
23253
+ );
23254
+ policy.compiled_at = deterministicCompiledAt(bundle.metadata.version);
23255
+ policy.source_english = bundle.policy_english;
23256
+ if (bundle.defaults.egress.length > 0) {
23257
+ const egress = {
23258
+ allowlist: bundle.defaults.egress.map((e) => ({
23259
+ destination: e.destination,
23260
+ methods: [...e.methods]
23261
+ }))
23262
+ };
23263
+ policy.egress = egress;
23264
+ }
23265
+ const budgets = {};
23266
+ if (bundle.defaults.budgets.daily) {
23267
+ budgets.daily = { ...bundle.defaults.budgets.daily };
23268
+ }
23269
+ if (bundle.defaults.budgets.monthly) {
23270
+ budgets.monthly = { ...bundle.defaults.budgets.monthly };
23271
+ }
23272
+ if (budgets.daily || budgets.monthly) {
23273
+ policy.budgets = budgets;
23274
+ }
23275
+ const windows = bundle.defaults.retention.windows;
23276
+ if (Object.keys(windows).length > 0) {
23277
+ const retention = {
23278
+ windows: {}
23279
+ };
23280
+ for (const [slot, win] of Object.entries(windows)) {
23281
+ if (win) {
23282
+ retention.windows[slot] = { ...win };
23283
+ }
23284
+ }
23285
+ policy.retention = retention;
23286
+ }
23287
+ const classes = bundle.commitments.shapes.map((s) => s.commitment_class);
23288
+ for (const cls of classes) {
23289
+ if (!policy.capabilities.concordia_commitment_classes.includes(cls)) {
23290
+ policy.capabilities.concordia_commitment_classes.push(cls);
23291
+ }
23292
+ }
23293
+ policy.capabilities.concordia_commitment_classes.sort();
23294
+ validateCompiledPolicyShape(policy);
23295
+ return policy;
23296
+ }
23297
+ function initTemplate(params) {
23298
+ const bundle = getTemplate2(params.template_name);
23299
+ if (!bundle) {
23300
+ throw new Error(`unknown template: ${params.template_name}`);
23301
+ }
23302
+ const compiled = buildCompiledPolicyFromTemplate(bundle, {
23303
+ agent_id: params.agent_id,
23304
+ fortress_id: params.fortress_id,
23305
+ counterparty: params.counterparty ?? "*",
23306
+ policy_version: params.policy_version ?? 1
23307
+ });
23308
+ const signed_event = packPolicyUpdate({
23309
+ policy: compiled,
23310
+ emitter_node: params.emitter_node,
23311
+ emitter_principal: params.emitter_principal,
23312
+ monotonic_seq: params.monotonic_seq,
23313
+ node_private_key: params.node_private_key,
23314
+ principal_private_key: params.principal_private_key
23315
+ });
23316
+ return { compiled, signed_event, bundle };
23317
+ }
23318
+
22223
23319
  // src/dashboard/api.ts
22224
23320
  function constantTimeEquals(a, b) {
22225
23321
  if (a.length !== b.length) return false;
@@ -22250,6 +23346,22 @@ function writeJSON(res, status, payload) {
22250
23346
  });
22251
23347
  res.end(JSON.stringify(payload));
22252
23348
  }
23349
+ async function readJSONBody(req) {
23350
+ const chunks = [];
23351
+ let size = 0;
23352
+ const MAX = 256 * 1024;
23353
+ for await (const chunk of req) {
23354
+ size += chunk.length;
23355
+ if (size > MAX) throw new Error("request body too large");
23356
+ chunks.push(chunk);
23357
+ }
23358
+ const body = Buffer.concat(chunks).toString("utf-8");
23359
+ if (!body) return {};
23360
+ return JSON.parse(body);
23361
+ }
23362
+ function generateEphemeralKey() {
23363
+ return new Uint8Array(crypto.randomBytes(32));
23364
+ }
22253
23365
  function writeText(res, status, body, contentType = "text/plain") {
22254
23366
  res.writeHead(status, {
22255
23367
  "Content-Type": contentType,
@@ -22302,6 +23414,90 @@ async function handleRequest(deps, req, res) {
22302
23414
  await handleStream(deps, res);
22303
23415
  return true;
22304
23416
  }
23417
+ if (method === "GET" && path === "/api/templates") {
23418
+ try {
23419
+ const templates = listTemplates();
23420
+ writeJSON(res, 200, { templates });
23421
+ } catch (err) {
23422
+ writeJSON(res, 500, {
23423
+ error: "template_load_failed",
23424
+ message: err.message
23425
+ });
23426
+ }
23427
+ return true;
23428
+ }
23429
+ const templateMatch = /^\/api\/templates\/([^/]+)$/.exec(path);
23430
+ if (method === "GET" && templateMatch) {
23431
+ const name = decodeURIComponent(templateMatch[1]);
23432
+ try {
23433
+ const entry = getTemplateEntry(name);
23434
+ if (!entry) {
23435
+ writeJSON(res, 404, { error: "template_not_found", name });
23436
+ return true;
23437
+ }
23438
+ writeJSON(res, 200, entry);
23439
+ } catch (err) {
23440
+ writeJSON(res, 500, {
23441
+ error: "template_load_failed",
23442
+ message: err.message
23443
+ });
23444
+ }
23445
+ return true;
23446
+ }
23447
+ const initMatch = /^\/api\/templates\/([^/]+)\/init$/.exec(path);
23448
+ if (method === "POST" && initMatch) {
23449
+ const name = decodeURIComponent(initMatch[1]);
23450
+ try {
23451
+ const bundle = getTemplate2(name);
23452
+ if (!bundle) {
23453
+ writeJSON(res, 404, { error: "template_not_found", name });
23454
+ return true;
23455
+ }
23456
+ const body = await readJSONBody(req);
23457
+ if (!body.agent_name || typeof body.agent_name !== "string") {
23458
+ writeJSON(res, 400, {
23459
+ error: "validation_error",
23460
+ message: "agent_name is required and must be a string"
23461
+ });
23462
+ return true;
23463
+ }
23464
+ if (!/^[a-zA-Z0-9_-]+$/.test(body.agent_name)) {
23465
+ writeJSON(res, 400, {
23466
+ error: "validation_error",
23467
+ message: "agent_name must contain only alphanumeric characters, hyphens, and underscores"
23468
+ });
23469
+ return true;
23470
+ }
23471
+ const nodeId = deps.nodeId ?? "dashboard-node";
23472
+ const nodePrivateKey = deps.nodePrivateKey ?? generateEphemeralKey();
23473
+ const principalId = deps.principalId ?? "dashboard-principal";
23474
+ const fortressId = deps.fortressId ?? "default";
23475
+ const result = initTemplate({
23476
+ template_name: name,
23477
+ agent_id: body.agent_name,
23478
+ fortress_id: fortressId,
23479
+ counterparty: "*",
23480
+ policy_version: 1,
23481
+ emitter_node: nodeId,
23482
+ emitter_principal: principalId,
23483
+ monotonic_seq: 1,
23484
+ node_private_key: nodePrivateKey
23485
+ });
23486
+ writeJSON(res, 200, {
23487
+ agent_id: body.agent_name,
23488
+ signed_event_id: result.signed_event.event_id,
23489
+ policy_version: result.compiled.policy_version,
23490
+ template_name: name,
23491
+ attestation_panel_url: `/console#agent_roster`
23492
+ });
23493
+ } catch (err) {
23494
+ writeJSON(res, 500, {
23495
+ error: "template_init_failed",
23496
+ message: err.message
23497
+ });
23498
+ }
23499
+ return true;
23500
+ }
22305
23501
  return false;
22306
23502
  }
22307
23503
  async function handleStream(deps, res) {