@neuroverseos/governance 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/radiant/index.ts
@@ -24,11 +34,13 @@ __export(radiant_exports, {
24
34
  DEFAULT_SIGNAL_EXTRACTORS: () => DEFAULT_SIGNAL_EXTRACTORS,
25
35
  LENSES: () => LENSES,
26
36
  RADIANT_PACKAGE_VERSION: () => RADIANT_PACKAGE_VERSION,
37
+ auditGovernance: () => auditGovernance,
27
38
  aukiBuilderLens: () => aukiBuilderLens,
28
39
  checkForbiddenPhrases: () => checkForbiddenPhrases,
29
40
  classifyActorDomain: () => classifyActorDomain,
30
41
  classifyEvents: () => classifyEvents,
31
42
  composeSystemPrompt: () => composeSystemPrompt,
43
+ computePersistence: () => computePersistence,
32
44
  createAnthropicAI: () => createAnthropicAI,
33
45
  createMockAI: () => createMockAI,
34
46
  createMockGitHubAdapter: () => createMockGitHubAdapter,
@@ -36,6 +48,7 @@ __export(radiant_exports, {
36
48
  extractSignals: () => extractSignals,
37
49
  fetchGitHubActivity: () => fetchGitHubActivity,
38
50
  formatExocortexForPrompt: () => formatExocortexForPrompt,
51
+ formatPriorReadsForPrompt: () => formatPriorReadsForPrompt,
39
52
  formatScope: () => formatScope,
40
53
  getLens: () => getLens,
41
54
  interpretPatterns: () => interpretPatterns,
@@ -43,6 +56,7 @@ __export(radiant_exports, {
43
56
  isScored: () => isScored,
44
57
  isSentinel: () => isSentinel,
45
58
  listLenses: () => listLenses,
59
+ loadPriorReads: () => loadPriorReads,
46
60
  parseRepoScope: () => parseRepoScope,
47
61
  presenceAverage: () => presenceAverage,
48
62
  readExocortex: () => readExocortex,
@@ -52,7 +66,9 @@ __export(radiant_exports, {
52
66
  scoreLife: () => scoreLife,
53
67
  scoreNeuroVerse: () => scoreNeuroVerse,
54
68
  summarizeExocortex: () => summarizeExocortex,
55
- think: () => think
69
+ think: () => think,
70
+ updateKnowledge: () => updateKnowledge,
71
+ writeRead: () => writeRead
56
72
  });
57
73
  module.exports = __toCommonJS(radiant_exports);
58
74
 
@@ -1212,7 +1228,7 @@ Only recommend a move when the evidence actually calls for one.
1212
1228
  }
1213
1229
  ],
1214
1230
  "meaning": "3-5 sentences. Weave the patterns into ONE strategic thesis. Compress. The reader should finish this paragraph and understand the one thing that matters most in this read. Plain English \u2014 no system jargon.",
1215
- "move": "1-3 direct imperatives, OR explicit 'nothing to act on' if the read is healthy. Do not fabricate urgency. Examples: 'Force cross-module ownership this sprint.' / 'Nothing's broken. Keep shipping.' / 'If you want future reads to track this pattern by name, add a line to your strategy file.'"
1231
+ "move": "1-3 direct imperatives, OR explicit 'nothing to act on' if the read is healthy. Do not fabricate urgency. When a candidate pattern has high confidence (>0.6), tell the reader EXACTLY where to declare it: 'If you want Radiant to track [pattern_name] over time, add it to auki-strategy.worldmodel.md under Evolution Layer \u2192 Drift Behaviors (or Aligned Behaviors if it is positive). If you don't, Radiant will rediscover it from scratch next run.' Be specific about the file and section \u2014 don't make them guess."
1216
1232
  }
1217
1233
  \`\`\`
1218
1234
 
@@ -1368,6 +1384,27 @@ Lens: ${input.lens.name}`
1368
1384
  ` Composite: ${formatScore(input.scores.R)}`
1369
1385
  ].join("\n");
1370
1386
  sections.push(alignBlock);
1387
+ if (input.governance && input.governance.totalEvents > 0) {
1388
+ const gov = input.governance;
1389
+ const govLines = ["GOVERNANCE", "", ` ${gov.summary}`];
1390
+ const showSide = (label, side) => {
1391
+ if (side.allow + side.modify + side.block === 0) return;
1392
+ govLines.push("");
1393
+ govLines.push(` ${label}:`);
1394
+ govLines.push(` ${side.allow} ALLOW \xB7 ${side.modify} MODIFY \xB7 ${side.block} BLOCK`);
1395
+ for (const d of side.details.slice(0, 3)) {
1396
+ const reason = d.reason ? ` \u2192 ${d.reason}` : "";
1397
+ govLines.push(` ${d.status}: ${d.eventId}${reason}`);
1398
+ }
1399
+ if (side.details.length > 3) {
1400
+ govLines.push(` ... and ${side.details.length - 3} more`);
1401
+ }
1402
+ };
1403
+ showSide("Human side", gov.human);
1404
+ showSide("AI side", gov.cyber);
1405
+ showSide("Human\u2013AI joint", gov.joint);
1406
+ sections.push(govLines.join("\n"));
1407
+ }
1371
1408
  sections.push(renderDepth(input.priorReadCount ?? 0, input.windowDays));
1372
1409
  return sections.join("\n\n");
1373
1410
  }
@@ -1531,6 +1568,1481 @@ function serializeYAML(obj, indent = 0) {
1531
1568
  `;
1532
1569
  }
1533
1570
 
1571
+ // src/engine/text-utils.ts
1572
+ function normalizeEventText(event) {
1573
+ return [
1574
+ event.intent,
1575
+ event.tool ?? "",
1576
+ event.scope ?? ""
1577
+ ].join(" ").toLowerCase();
1578
+ }
1579
+ function extractKeywords(text, minLength = 3) {
1580
+ return text.toLowerCase().split(/\s+/).filter((w) => w.length > minLength);
1581
+ }
1582
+ function matchesAllKeywords(eventText, ruleText) {
1583
+ const keywords = extractKeywords(ruleText);
1584
+ if (keywords.length === 0) return false;
1585
+ return keywords.every((kw) => eventText.includes(kw));
1586
+ }
1587
+ function matchesKeywordThreshold(eventText, ruleText, threshold = 0.5) {
1588
+ const keywords = extractKeywords(ruleText);
1589
+ if (keywords.length === 0) return false;
1590
+ const matched = keywords.filter((kw) => eventText.includes(kw));
1591
+ return matched.length >= Math.ceil(keywords.length * threshold);
1592
+ }
1593
+ function tokenSimilarity(a, b) {
1594
+ const tokensA = new Set(a.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
1595
+ const tokensB = new Set(b.toLowerCase().split(/\s+/).filter((w) => w.length > 2));
1596
+ if (tokensA.size === 0 || tokensB.size === 0) return 0;
1597
+ let intersection = 0;
1598
+ for (const t of tokensA) {
1599
+ if (tokensB.has(t)) intersection++;
1600
+ }
1601
+ const union = (/* @__PURE__ */ new Set([...tokensA, ...tokensB])).size;
1602
+ return union > 0 ? intersection / union : 0;
1603
+ }
1604
+
1605
+ // src/engine/plan-engine.ts
1606
+ function keywordMatch(eventText, step) {
1607
+ const stepText = [
1608
+ step.label,
1609
+ step.description ?? "",
1610
+ ...step.tags ?? []
1611
+ ].join(" ");
1612
+ return matchesKeywordThreshold(eventText, stepText, 0.5);
1613
+ }
1614
+ function tokenSimilarity2(a, b) {
1615
+ return tokenSimilarity(a, b);
1616
+ }
1617
+ function findMatchingStep(eventText, event, steps) {
1618
+ const pendingOrActive = steps.filter((s) => s.status === "pending" || s.status === "active");
1619
+ if (pendingOrActive.length === 0) {
1620
+ return { matched: null, closest: null, closestScore: 0 };
1621
+ }
1622
+ for (const step of pendingOrActive) {
1623
+ if (keywordMatch(eventText, step)) {
1624
+ if (step.tools && event.tool && !step.tools.includes(event.tool)) {
1625
+ continue;
1626
+ }
1627
+ return { matched: step, closest: step, closestScore: 1 };
1628
+ }
1629
+ }
1630
+ const intentText = [event.intent, event.tool ?? "", event.scope ?? ""].join(" ");
1631
+ let bestStep = null;
1632
+ let bestScore = 0;
1633
+ for (const step of pendingOrActive) {
1634
+ const stepText = [step.label, step.description ?? "", ...step.tags ?? []].join(" ");
1635
+ const score = tokenSimilarity2(intentText, stepText);
1636
+ if (score > bestScore) {
1637
+ bestScore = score;
1638
+ bestStep = step;
1639
+ }
1640
+ }
1641
+ const SIMILARITY_THRESHOLD = 0.35;
1642
+ if (bestScore >= SIMILARITY_THRESHOLD && bestStep) {
1643
+ if (bestStep.tools && event.tool && !bestStep.tools.includes(event.tool)) {
1644
+ return { matched: null, closest: bestStep, closestScore: bestScore };
1645
+ }
1646
+ return { matched: bestStep, closest: bestStep, closestScore: bestScore };
1647
+ }
1648
+ return { matched: null, closest: bestStep, closestScore: bestScore };
1649
+ }
1650
+ function isSequenceValid(step, plan) {
1651
+ if (!plan.sequential) return true;
1652
+ if (!step.requires || step.requires.length === 0) return true;
1653
+ return step.requires.every((reqId) => {
1654
+ const reqStep = plan.steps.find((s) => s.id === reqId);
1655
+ return reqStep?.status === "completed";
1656
+ });
1657
+ }
1658
+ function checkConstraints(event, eventText, constraints) {
1659
+ const checks = [];
1660
+ for (const constraint of constraints) {
1661
+ if (constraint.type === "approval") {
1662
+ if (constraint.trigger && eventText.includes(constraint.trigger.substring(0, 10).toLowerCase())) {
1663
+ checks.push({ constraintId: constraint.id, passed: false, reason: constraint.description });
1664
+ return { violated: constraint, checks };
1665
+ }
1666
+ const keywords = constraint.description.toLowerCase().split(/\s+/).filter((w) => w.length > 3);
1667
+ const relevant = keywords.some((kw) => eventText.includes(kw));
1668
+ if (relevant) {
1669
+ checks.push({ constraintId: constraint.id, passed: false, reason: constraint.description });
1670
+ return { violated: constraint, checks };
1671
+ }
1672
+ checks.push({ constraintId: constraint.id, passed: true });
1673
+ continue;
1674
+ }
1675
+ if (constraint.type === "scope" && constraint.trigger) {
1676
+ const keywords = extractKeywords(constraint.trigger);
1677
+ const violated = keywords.length > 0 && keywords.every((kw) => eventText.includes(kw));
1678
+ checks.push({
1679
+ constraintId: constraint.id,
1680
+ passed: !violated,
1681
+ reason: violated ? constraint.description : void 0
1682
+ });
1683
+ if (violated) {
1684
+ return { violated: constraint, checks };
1685
+ }
1686
+ continue;
1687
+ }
1688
+ checks.push({ constraintId: constraint.id, passed: true });
1689
+ }
1690
+ return { violated: null, checks };
1691
+ }
1692
+ function getPlanProgress(plan) {
1693
+ const completed = plan.steps.filter((s) => s.status === "completed").length;
1694
+ const total = plan.steps.length;
1695
+ return {
1696
+ completed,
1697
+ total,
1698
+ percentage: total > 0 ? Math.round(completed / total * 100) : 0
1699
+ };
1700
+ }
1701
+ function evaluatePlan(event, plan) {
1702
+ const progress = getPlanProgress(plan);
1703
+ if (plan.expires_at) {
1704
+ const expiresAt = new Date(plan.expires_at).getTime();
1705
+ if (Date.now() > expiresAt) {
1706
+ return {
1707
+ allowed: true,
1708
+ status: "PLAN_COMPLETE",
1709
+ reason: "Plan has expired.",
1710
+ progress
1711
+ };
1712
+ }
1713
+ }
1714
+ if (progress.completed === progress.total) {
1715
+ return {
1716
+ allowed: true,
1717
+ status: "PLAN_COMPLETE",
1718
+ reason: "All plan steps are completed.",
1719
+ progress
1720
+ };
1721
+ }
1722
+ const eventText = normalizeEventText(event);
1723
+ const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
1724
+ if (!matched) {
1725
+ return {
1726
+ allowed: false,
1727
+ status: "OFF_PLAN",
1728
+ reason: "Action does not match any plan step.",
1729
+ closestStep: closest?.label,
1730
+ similarityScore: closestScore,
1731
+ progress
1732
+ };
1733
+ }
1734
+ if (!isSequenceValid(matched, plan)) {
1735
+ const pendingDeps = (matched.requires ?? []).filter((reqId) => plan.steps.find((s) => s.id === reqId)?.status !== "completed").join(", ");
1736
+ return {
1737
+ allowed: false,
1738
+ status: "OFF_PLAN",
1739
+ reason: `Step "${matched.label}" requires completion of: ${pendingDeps}`,
1740
+ matchedStep: matched.id,
1741
+ progress
1742
+ };
1743
+ }
1744
+ const { violated } = checkConstraints(event, eventText, plan.constraints);
1745
+ if (violated) {
1746
+ return {
1747
+ allowed: false,
1748
+ status: "CONSTRAINT_VIOLATED",
1749
+ reason: violated.description,
1750
+ matchedStep: matched.id,
1751
+ progress
1752
+ };
1753
+ }
1754
+ return {
1755
+ allowed: true,
1756
+ status: "ON_PLAN",
1757
+ reason: `Matches step: ${matched.label}`,
1758
+ matchedStep: matched.id,
1759
+ progress
1760
+ };
1761
+ }
1762
+ function buildPlanCheck(event, plan, verdict) {
1763
+ const eventText = normalizeEventText(event);
1764
+ const { matched, closest, closestScore } = findMatchingStep(eventText, event, plan.steps);
1765
+ const { checks: constraintChecks } = checkConstraints(event, eventText, plan.constraints);
1766
+ const progress = getPlanProgress(plan);
1767
+ return {
1768
+ planId: plan.plan_id,
1769
+ matched: !!matched,
1770
+ matchedStepId: matched?.id,
1771
+ matchedStepLabel: matched?.label,
1772
+ closestStepId: !matched ? closest?.id : void 0,
1773
+ closestStepLabel: !matched ? closest?.label : void 0,
1774
+ similarityScore: !matched ? closestScore : void 0,
1775
+ sequenceValid: matched ? isSequenceValid(matched, plan) : void 0,
1776
+ constraintsChecked: constraintChecks,
1777
+ progress: { completed: progress.completed, total: progress.total }
1778
+ };
1779
+ }
1780
+
1781
+ // src/engine/guard-engine.ts
1782
+ var PROMPT_INJECTION_PATTERNS = [
1783
+ // Instruction override
1784
+ { pattern: /ignore\s+(previous|all|prior|above)\s+(instructions?|rules?)/i, label: "ignore-instructions" },
1785
+ { pattern: /disregard\s+(your|the)\s+(rules|constraints)/i, label: "disregard-rules" },
1786
+ { pattern: /new\s+instructions?:/i, label: "new-instructions" },
1787
+ // Identity manipulation
1788
+ { pattern: /you\s+are\s+now/i, label: "identity-override" },
1789
+ { pattern: /new\s+persona/i, label: "new-persona" },
1790
+ { pattern: /act\s+as\s+if/i, label: "act-as-if" },
1791
+ { pattern: /pretend\s+(you|to\s+be|you\s+are\s+unrestricted)/i, label: "pretend-to-be" },
1792
+ // Context reset
1793
+ { pattern: /forget\s+(everything|all|your)/i, label: "forget-context" },
1794
+ { pattern: /system\s*:\s*override/i, label: "system-override" },
1795
+ // Constraint bypass
1796
+ { pattern: /override\s+(your|the)\s+(programming|constraints)/i, label: "override-constraints" },
1797
+ { pattern: /bypass\s+(your|the)\s+(filters|constraints|rules)/i, label: "bypass-filters" },
1798
+ // Prompt extraction
1799
+ { pattern: /system\s+prompt/i, label: "system-prompt-probe" },
1800
+ { pattern: /reveal\s+your\s+(instructions?|prompt|rules)/i, label: "reveal-instructions" },
1801
+ // Known jailbreak terms
1802
+ { pattern: /jailbreak/i, label: "jailbreak" },
1803
+ { pattern: /DAN\s+mode/i, label: "dan-mode" },
1804
+ { pattern: /developer\s+mode/i, label: "developer-mode" }
1805
+ ];
1806
+ var EXECUTION_CLAIM_PATTERNS = [
1807
+ { pattern: /I have (executed|completed|performed|done|made|created|sent|deleted|modified|updated)/i, label: "claim-i-have" },
1808
+ { pattern: /Successfully (created|deleted|modified|updated|sent|executed|performed)/i, label: "claim-successfully" },
1809
+ { pattern: /The file has been/i, label: "claim-file-modified" },
1810
+ { pattern: /I've made the changes/i, label: "claim-made-changes" },
1811
+ { pattern: /I('ve| have) (sent|posted|submitted|uploaded|downloaded)/i, label: "claim-sent" },
1812
+ { pattern: /Your (email|message|file|request) has been (sent|submitted)/i, label: "claim-your-sent" },
1813
+ { pattern: /Transaction complete/i, label: "claim-transaction" },
1814
+ { pattern: /Order placed/i, label: "claim-order" },
1815
+ { pattern: /Payment processed/i, label: "claim-payment" }
1816
+ ];
1817
+ var EXECUTION_INTENT_PATTERNS = [
1818
+ { pattern: /^(execute|run|perform|do this)/i, label: "intent-execute" },
1819
+ { pattern: /^(create|write|delete|modify) (a |the )?(file|folder|document)/i, label: "intent-file-ops" },
1820
+ { pattern: /^(send|post|submit) (a |an |the )?(email|message|tweet|post)/i, label: "intent-send" },
1821
+ { pattern: /^(search|look up|browse) (the )?web/i, label: "intent-web-search" },
1822
+ { pattern: /^(make|call|invoke) (a |an )?(api|http|rest) (call|request)/i, label: "intent-api-call" },
1823
+ { pattern: /^(buy|purchase|order|pay|transfer|send money)/i, label: "intent-financial" },
1824
+ { pattern: /^(book|schedule|reserve)/i, label: "intent-booking" },
1825
+ { pattern: /^(download|upload|save to|export to)/i, label: "intent-transfer" }
1826
+ ];
1827
+ var SCOPE_ESCAPE_PATTERNS = [
1828
+ { pattern: /\.\.\//, label: "parent-traversal" },
1829
+ { pattern: /^\/(?!home|project|workspace)/i, label: "absolute-path-outside-safe" },
1830
+ { pattern: /~\//, label: "home-directory" },
1831
+ { pattern: /\/etc\//i, label: "system-config" },
1832
+ { pattern: /\/usr\//i, label: "system-binaries" },
1833
+ { pattern: /\/var\//i, label: "system-variable-data" }
1834
+ ];
1835
+ var NEUTRAL_MESSAGES = {
1836
+ "prompt-injection": "This input contains patterns that could alter agent behavior.",
1837
+ "scope-escape": "This action would affect resources outside the declared scope.",
1838
+ "execution-claim": "This response claims to have performed an action.",
1839
+ "execution-intent": "This input requests execution in a thinking-only environment.",
1840
+ "delete": "This action would remove files. Confirmation needed.",
1841
+ "write-external": "This action would write outside the project folder.",
1842
+ "network-mutate": "This action would send data to an external service.",
1843
+ "credential-access": "This action would access stored credentials."
1844
+ };
1845
+ function levelRequiresConfirmation(level, actionType) {
1846
+ if (level === "strict") return true;
1847
+ if (level === "standard") {
1848
+ return actionType === "delete" || actionType === "credential-access";
1849
+ }
1850
+ return false;
1851
+ }
1852
+ function isExternalScope(scope) {
1853
+ const internalPatterns = [
1854
+ /^\.?\/?src\//i,
1855
+ /^\.?\/?lib\//i,
1856
+ /^\.?\/?app\//i,
1857
+ /^\.?\/?components\//i,
1858
+ /^\.?\/?pages\//i,
1859
+ /^\.?\/?public\//i,
1860
+ /^\.?\/?assets\//i,
1861
+ /^\.\//
1862
+ ];
1863
+ return !internalPatterns.some((p) => p.test(scope));
1864
+ }
1865
+ var MAX_INPUT_LENGTH = 1e5;
1866
+ function evaluateGuard(event, world, options = {}) {
1867
+ const startTime = performance.now();
1868
+ const level = options.level ?? "standard";
1869
+ const includeTrace = options.trace ?? false;
1870
+ if (!event.intent || typeof event.intent !== "string") {
1871
+ return {
1872
+ status: "BLOCK",
1873
+ reason: "GuardEvent.intent is required and must be a string",
1874
+ ruleId: "safety-input-validation",
1875
+ evidence: {
1876
+ worldId: world.world?.world_id ?? "",
1877
+ worldName: world.world?.name ?? "",
1878
+ worldVersion: world.world?.version ?? "",
1879
+ evaluatedAt: Date.now(),
1880
+ invariantsSatisfied: 0,
1881
+ invariantsTotal: 0,
1882
+ guardsMatched: [],
1883
+ rulesMatched: [],
1884
+ enforcementLevel: level
1885
+ }
1886
+ };
1887
+ }
1888
+ const inputLength = event.intent.length + (event.tool?.length ?? 0) + (event.scope?.length ?? 0) + (event.payload ? JSON.stringify(event.payload).length : 0);
1889
+ if (inputLength > MAX_INPUT_LENGTH) {
1890
+ return {
1891
+ status: "BLOCK",
1892
+ reason: `Input exceeds maximum allowed length (${MAX_INPUT_LENGTH} characters)`,
1893
+ ruleId: "safety-input-length",
1894
+ evidence: {
1895
+ worldId: world.world?.world_id ?? "",
1896
+ worldName: world.world?.name ?? "",
1897
+ worldVersion: world.world?.version ?? "",
1898
+ evaluatedAt: Date.now(),
1899
+ invariantsSatisfied: 0,
1900
+ invariantsTotal: 0,
1901
+ guardsMatched: [],
1902
+ rulesMatched: [],
1903
+ enforcementLevel: level
1904
+ }
1905
+ };
1906
+ }
1907
+ const eventText = normalizeEventText(event);
1908
+ const invariantChecks = [];
1909
+ const safetyChecks = [];
1910
+ let planCheckResult;
1911
+ const roleChecks = [];
1912
+ const guardChecks = [];
1913
+ const kernelRuleChecks = [];
1914
+ const levelChecks = [];
1915
+ let decidingLayer = "default-allow";
1916
+ let decidingId;
1917
+ const guardsMatched = [];
1918
+ const rulesMatched = [];
1919
+ if (options.emergencyOverride) {
1920
+ checkInvariantCoverage(world, invariantChecks);
1921
+ return buildVerdict(
1922
+ "ALLOW",
1923
+ void 0,
1924
+ "emergency-override",
1925
+ "Emergency override active \u2014 all governance rules suspended. Platform constraints still apply.",
1926
+ world,
1927
+ level,
1928
+ invariantChecks,
1929
+ guardsMatched,
1930
+ rulesMatched,
1931
+ includeTrace ? buildTrace(
1932
+ invariantChecks,
1933
+ safetyChecks,
1934
+ planCheckResult,
1935
+ roleChecks,
1936
+ guardChecks,
1937
+ kernelRuleChecks,
1938
+ levelChecks,
1939
+ "session-allowlist",
1940
+ "emergency-override",
1941
+ startTime
1942
+ ) : void 0,
1943
+ event.intent
1944
+ );
1945
+ }
1946
+ checkInvariantCoverage(world, invariantChecks);
1947
+ if (event.roleId && options.agentStates) {
1948
+ const agentState = options.agentStates.get(event.roleId);
1949
+ if (agentState && agentState.cooldownRemaining > 0) {
1950
+ decidingLayer = "safety";
1951
+ decidingId = `penalize-cooldown-${event.roleId}`;
1952
+ const verdict = buildVerdict(
1953
+ "PENALIZE",
1954
+ `Agent "${event.roleId}" is frozen for ${agentState.cooldownRemaining} more round(s) due to prior penalty.`,
1955
+ `penalize-cooldown-${event.roleId}`,
1956
+ void 0,
1957
+ world,
1958
+ level,
1959
+ invariantChecks,
1960
+ guardsMatched,
1961
+ rulesMatched,
1962
+ includeTrace ? buildTrace(
1963
+ invariantChecks,
1964
+ safetyChecks,
1965
+ planCheckResult,
1966
+ roleChecks,
1967
+ guardChecks,
1968
+ kernelRuleChecks,
1969
+ levelChecks,
1970
+ decidingLayer,
1971
+ decidingId,
1972
+ startTime
1973
+ ) : void 0
1974
+ );
1975
+ verdict.intentRecord = {
1976
+ originalIntent: event.intent,
1977
+ finalAction: "blocked (agent frozen)",
1978
+ enforcement: "PENALIZE",
1979
+ consequence: { type: "freeze", rounds: agentState.cooldownRemaining, description: "Agent still in cooldown from prior penalty" }
1980
+ };
1981
+ return verdict;
1982
+ }
1983
+ }
1984
+ if (options.sessionAllowlist) {
1985
+ const key = eventToAllowlistKey(event);
1986
+ if (options.sessionAllowlist.has(key)) {
1987
+ decidingLayer = "session-allowlist";
1988
+ decidingId = `allowlist:${key}`;
1989
+ return buildVerdict(
1990
+ "ALLOW",
1991
+ void 0,
1992
+ `allowlist:${key}`,
1993
+ void 0,
1994
+ world,
1995
+ level,
1996
+ invariantChecks,
1997
+ guardsMatched,
1998
+ rulesMatched,
1999
+ includeTrace ? buildTrace(
2000
+ invariantChecks,
2001
+ safetyChecks,
2002
+ planCheckResult,
2003
+ roleChecks,
2004
+ guardChecks,
2005
+ kernelRuleChecks,
2006
+ levelChecks,
2007
+ decidingLayer,
2008
+ decidingId,
2009
+ startTime
2010
+ ) : void 0,
2011
+ event.intent
2012
+ );
2013
+ }
2014
+ }
2015
+ const safetyVerdict = checkSafety(event, eventText, safetyChecks);
2016
+ if (safetyVerdict) {
2017
+ decidingLayer = "safety";
2018
+ decidingId = safetyVerdict.ruleId;
2019
+ return buildVerdict(
2020
+ safetyVerdict.status,
2021
+ safetyVerdict.reason,
2022
+ safetyVerdict.ruleId,
2023
+ void 0,
2024
+ world,
2025
+ level,
2026
+ invariantChecks,
2027
+ guardsMatched,
2028
+ rulesMatched,
2029
+ includeTrace ? buildTrace(
2030
+ invariantChecks,
2031
+ safetyChecks,
2032
+ planCheckResult,
2033
+ roleChecks,
2034
+ guardChecks,
2035
+ kernelRuleChecks,
2036
+ levelChecks,
2037
+ decidingLayer,
2038
+ decidingId,
2039
+ startTime
2040
+ ) : void 0,
2041
+ event.intent
2042
+ );
2043
+ }
2044
+ if (options.plan) {
2045
+ const planVerdict = evaluatePlan(event, options.plan);
2046
+ planCheckResult = buildPlanCheck(event, options.plan, planVerdict);
2047
+ if (!planVerdict.allowed && planVerdict.status !== "PLAN_COMPLETE") {
2048
+ decidingLayer = "plan-enforcement";
2049
+ decidingId = `plan-${options.plan.plan_id}`;
2050
+ const planStatus = planVerdict.status === "CONSTRAINT_VIOLATED" ? "PAUSE" : "BLOCK";
2051
+ let reason = planVerdict.reason ?? "Action blocked by plan.";
2052
+ if (planVerdict.status === "OFF_PLAN" && planVerdict.closestStep) {
2053
+ reason += ` Closest step: "${planVerdict.closestStep}" (similarity: ${(planVerdict.similarityScore ?? 0).toFixed(2)})`;
2054
+ }
2055
+ return buildVerdict(
2056
+ planStatus,
2057
+ reason,
2058
+ `plan-${options.plan.plan_id}`,
2059
+ void 0,
2060
+ world,
2061
+ level,
2062
+ invariantChecks,
2063
+ guardsMatched,
2064
+ rulesMatched,
2065
+ includeTrace ? buildTrace(
2066
+ invariantChecks,
2067
+ safetyChecks,
2068
+ planCheckResult,
2069
+ roleChecks,
2070
+ guardChecks,
2071
+ kernelRuleChecks,
2072
+ levelChecks,
2073
+ decidingLayer,
2074
+ decidingId,
2075
+ startTime
2076
+ ) : void 0,
2077
+ event.intent
2078
+ );
2079
+ }
2080
+ }
2081
+ const roleVerdict = checkRoleRules(event, eventText, world, roleChecks);
2082
+ if (roleVerdict) {
2083
+ decidingLayer = "role";
2084
+ decidingId = roleVerdict.ruleId;
2085
+ return buildVerdict(
2086
+ roleVerdict.status,
2087
+ roleVerdict.reason,
2088
+ roleVerdict.ruleId,
2089
+ void 0,
2090
+ world,
2091
+ level,
2092
+ invariantChecks,
2093
+ guardsMatched,
2094
+ rulesMatched,
2095
+ includeTrace ? buildTrace(
2096
+ invariantChecks,
2097
+ safetyChecks,
2098
+ planCheckResult,
2099
+ roleChecks,
2100
+ guardChecks,
2101
+ kernelRuleChecks,
2102
+ levelChecks,
2103
+ decidingLayer,
2104
+ decidingId,
2105
+ startTime
2106
+ ) : void 0,
2107
+ event.intent
2108
+ );
2109
+ }
2110
+ const guardVerdict = checkGuards(event, eventText, world, guardChecks, guardsMatched);
2111
+ if (guardVerdict) {
2112
+ if (guardVerdict.status !== "ALLOW") {
2113
+ decidingLayer = "guard";
2114
+ decidingId = guardVerdict.ruleId;
2115
+ const intentRecord = {
2116
+ originalIntent: event.intent,
2117
+ finalAction: guardVerdict.status === "MODIFY" ? guardVerdict.modifiedTo ?? "modified" : guardVerdict.status === "PENALIZE" ? "blocked + penalized" : guardVerdict.status === "REWARD" ? event.intent : guardVerdict.status === "NEUTRAL" ? event.intent : guardVerdict.status === "BLOCK" ? "blocked" : "paused",
2118
+ ruleApplied: guardVerdict.ruleId,
2119
+ enforcement: guardVerdict.status,
2120
+ modifiedTo: guardVerdict.modifiedTo,
2121
+ consequence: guardVerdict.consequence,
2122
+ reward: guardVerdict.reward
2123
+ };
2124
+ const verdict = buildVerdict(
2125
+ guardVerdict.status,
2126
+ guardVerdict.reason,
2127
+ guardVerdict.ruleId,
2128
+ void 0,
2129
+ world,
2130
+ level,
2131
+ invariantChecks,
2132
+ guardsMatched,
2133
+ rulesMatched,
2134
+ includeTrace ? buildTrace(
2135
+ invariantChecks,
2136
+ safetyChecks,
2137
+ planCheckResult,
2138
+ roleChecks,
2139
+ guardChecks,
2140
+ kernelRuleChecks,
2141
+ levelChecks,
2142
+ decidingLayer,
2143
+ decidingId,
2144
+ startTime
2145
+ ) : void 0,
2146
+ event.intent
2147
+ );
2148
+ verdict.intentRecord = intentRecord;
2149
+ if (guardVerdict.consequence) verdict.consequence = guardVerdict.consequence;
2150
+ if (guardVerdict.reward) verdict.reward = guardVerdict.reward;
2151
+ return verdict;
2152
+ }
2153
+ }
2154
+ const kernelVerdict = checkKernelRules(eventText, world, kernelRuleChecks, rulesMatched);
2155
+ if (kernelVerdict) {
2156
+ decidingLayer = "kernel-rule";
2157
+ decidingId = kernelVerdict.ruleId;
2158
+ return buildVerdict(
2159
+ kernelVerdict.status,
2160
+ kernelVerdict.reason,
2161
+ kernelVerdict.ruleId,
2162
+ void 0,
2163
+ world,
2164
+ level,
2165
+ invariantChecks,
2166
+ guardsMatched,
2167
+ rulesMatched,
2168
+ includeTrace ? buildTrace(
2169
+ invariantChecks,
2170
+ safetyChecks,
2171
+ planCheckResult,
2172
+ roleChecks,
2173
+ guardChecks,
2174
+ kernelRuleChecks,
2175
+ levelChecks,
2176
+ decidingLayer,
2177
+ decidingId,
2178
+ startTime
2179
+ ) : void 0,
2180
+ event.intent
2181
+ );
2182
+ }
2183
+ const levelVerdict = checkLevelConstraints(event, level, levelChecks);
2184
+ if (levelVerdict) {
2185
+ decidingLayer = "level-constraint";
2186
+ decidingId = levelVerdict.ruleId;
2187
+ return buildVerdict(
2188
+ levelVerdict.status,
2189
+ levelVerdict.reason,
2190
+ levelVerdict.ruleId,
2191
+ void 0,
2192
+ world,
2193
+ level,
2194
+ invariantChecks,
2195
+ guardsMatched,
2196
+ rulesMatched,
2197
+ includeTrace ? buildTrace(
2198
+ invariantChecks,
2199
+ safetyChecks,
2200
+ planCheckResult,
2201
+ roleChecks,
2202
+ guardChecks,
2203
+ kernelRuleChecks,
2204
+ levelChecks,
2205
+ decidingLayer,
2206
+ decidingId,
2207
+ startTime
2208
+ ) : void 0,
2209
+ event.intent
2210
+ );
2211
+ }
2212
+ const warning = guardVerdict?.warning;
2213
+ return buildVerdict(
2214
+ "ALLOW",
2215
+ void 0,
2216
+ void 0,
2217
+ warning,
2218
+ world,
2219
+ level,
2220
+ invariantChecks,
2221
+ guardsMatched,
2222
+ rulesMatched,
2223
+ includeTrace ? buildTrace(
2224
+ invariantChecks,
2225
+ safetyChecks,
2226
+ planCheckResult,
2227
+ roleChecks,
2228
+ guardChecks,
2229
+ kernelRuleChecks,
2230
+ levelChecks,
2231
+ decidingLayer,
2232
+ decidingId,
2233
+ startTime
2234
+ ) : void 0,
2235
+ event.intent
2236
+ );
2237
+ }
2238
+ function checkInvariantCoverage(world, checks) {
2239
+ const invariants = world.invariants ?? [];
2240
+ const guards = world.guards?.guards ?? [];
2241
+ for (const invariant of invariants) {
2242
+ const coveringGuard = guards.find(
2243
+ (g) => g.invariant_ref === invariant.id && g.immutable
2244
+ );
2245
+ checks.push({
2246
+ invariantId: invariant.id,
2247
+ label: invariant.label,
2248
+ hasGuardCoverage: !!coveringGuard,
2249
+ coveringGuardId: coveringGuard?.id
2250
+ });
2251
+ }
2252
+ }
2253
+ function checkSafety(event, eventText, checks) {
2254
+ const textToCheck = event.intent + (event.payload ? JSON.stringify(event.payload) : "");
2255
+ for (const { pattern, label } of PROMPT_INJECTION_PATTERNS) {
2256
+ const triggered = pattern.test(textToCheck);
2257
+ checks.push({
2258
+ checkType: "prompt-injection",
2259
+ triggered,
2260
+ matchedPattern: triggered ? label : void 0
2261
+ });
2262
+ if (triggered) {
2263
+ for (const remaining of PROMPT_INJECTION_PATTERNS.filter((p) => p.label !== label)) {
2264
+ checks.push({
2265
+ checkType: "prompt-injection",
2266
+ triggered: remaining.pattern.test(textToCheck),
2267
+ matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
2268
+ });
2269
+ }
2270
+ return {
2271
+ status: "PAUSE",
2272
+ reason: NEUTRAL_MESSAGES["prompt-injection"],
2273
+ ruleId: `safety-injection-${label}`
2274
+ };
2275
+ }
2276
+ }
2277
+ const scopeToCheck = event.scope ?? event.intent;
2278
+ for (const { pattern, label } of SCOPE_ESCAPE_PATTERNS) {
2279
+ const triggered = pattern.test(scopeToCheck);
2280
+ checks.push({
2281
+ checkType: "scope-escape",
2282
+ triggered,
2283
+ matchedPattern: triggered ? label : void 0
2284
+ });
2285
+ if (triggered) {
2286
+ for (const remaining of SCOPE_ESCAPE_PATTERNS.filter((p) => p.label !== label)) {
2287
+ checks.push({
2288
+ checkType: "scope-escape",
2289
+ triggered: remaining.pattern.test(scopeToCheck),
2290
+ matchedPattern: remaining.pattern.test(scopeToCheck) ? remaining.label : void 0
2291
+ });
2292
+ }
2293
+ return {
2294
+ status: "PAUSE",
2295
+ reason: NEUTRAL_MESSAGES["scope-escape"],
2296
+ ruleId: `safety-scope-${label}`
2297
+ };
2298
+ }
2299
+ }
2300
+ if (event.direction === "output") {
2301
+ for (const { pattern, label } of EXECUTION_CLAIM_PATTERNS) {
2302
+ const triggered = pattern.test(textToCheck);
2303
+ checks.push({
2304
+ checkType: "execution-claim",
2305
+ triggered,
2306
+ matchedPattern: triggered ? label : void 0
2307
+ });
2308
+ if (triggered) {
2309
+ for (const remaining of EXECUTION_CLAIM_PATTERNS.filter((p) => p.label !== label)) {
2310
+ checks.push({
2311
+ checkType: "execution-claim",
2312
+ triggered: remaining.pattern.test(textToCheck),
2313
+ matchedPattern: remaining.pattern.test(textToCheck) ? remaining.label : void 0
2314
+ });
2315
+ }
2316
+ return {
2317
+ status: "PAUSE",
2318
+ reason: NEUTRAL_MESSAGES["execution-claim"],
2319
+ ruleId: `safety-execution-claim-${label}`
2320
+ };
2321
+ }
2322
+ }
2323
+ }
2324
+ if (event.direction === "input") {
2325
+ const intentTrimmed = event.intent.trim();
2326
+ for (const { pattern, label } of EXECUTION_INTENT_PATTERNS) {
2327
+ const triggered = pattern.test(intentTrimmed);
2328
+ checks.push({
2329
+ checkType: "execution-intent",
2330
+ triggered,
2331
+ matchedPattern: triggered ? label : void 0
2332
+ });
2333
+ if (triggered) {
2334
+ for (const remaining of EXECUTION_INTENT_PATTERNS.filter((p) => p.label !== label)) {
2335
+ checks.push({
2336
+ checkType: "execution-intent",
2337
+ triggered: remaining.pattern.test(intentTrimmed),
2338
+ matchedPattern: remaining.pattern.test(intentTrimmed) ? remaining.label : void 0
2339
+ });
2340
+ }
2341
+ return {
2342
+ status: "PAUSE",
2343
+ reason: NEUTRAL_MESSAGES["execution-intent"],
2344
+ ruleId: `safety-execution-intent-${label}`
2345
+ };
2346
+ }
2347
+ }
2348
+ }
2349
+ return null;
2350
+ }
2351
+ function checkRoleRules(event, eventText, world, checks) {
2352
+ if (!event.roleId || !world.roles) return null;
2353
+ const role = world.roles.roles.find((r) => r.id === event.roleId);
2354
+ if (!role) return null;
2355
+ if (role.requiresApproval) {
2356
+ checks.push({
2357
+ roleId: role.id,
2358
+ roleName: role.name,
2359
+ rule: "All actions require approval",
2360
+ ruleType: "requiresApproval",
2361
+ matched: true
2362
+ });
2363
+ return {
2364
+ status: "PAUSE",
2365
+ reason: `Role "${role.name}" requires approval for all actions.`,
2366
+ ruleId: `role-${role.id}-requires-approval`
2367
+ };
2368
+ }
2369
+ for (const rule of role.cannotDo) {
2370
+ const matched = matchesKeywords(eventText, rule);
2371
+ checks.push({
2372
+ roleId: role.id,
2373
+ roleName: role.name,
2374
+ rule,
2375
+ ruleType: "cannotDo",
2376
+ matched
2377
+ });
2378
+ if (matched) {
2379
+ return {
2380
+ status: "BLOCK",
2381
+ reason: `Role "${role.name}" cannot: ${rule}`,
2382
+ ruleId: `role-${role.id}-cannotdo`
2383
+ };
2384
+ }
2385
+ }
2386
+ for (const rule of role.canDo) {
2387
+ checks.push({
2388
+ roleId: role.id,
2389
+ roleName: role.name,
2390
+ rule,
2391
+ ruleType: "canDo",
2392
+ matched: matchesKeywords(eventText, rule)
2393
+ });
2394
+ }
2395
+ return null;
2396
+ }
2397
+ function checkGuards(event, eventText, world, checks, guardsMatched) {
2398
+ if (!world.guards) return null;
2399
+ const guardsConfig = world.guards;
2400
+ let warnResult = null;
2401
+ const compiledPatterns = /* @__PURE__ */ new Map();
2402
+ for (const [key, def] of Object.entries(guardsConfig.intent_vocabulary)) {
2403
+ try {
2404
+ compiledPatterns.set(key, new RegExp(def.pattern, "i"));
2405
+ } catch {
2406
+ }
2407
+ }
2408
+ const eventTool = (event.tool ?? "").toLowerCase();
2409
+ for (const guard of guardsConfig.guards) {
2410
+ if (guard.appliesTo && guard.appliesTo.length > 0) {
2411
+ const normalizedAppliesTo = guard.appliesTo.map((t) => t.toLowerCase());
2412
+ if (!normalizedAppliesTo.includes(eventTool)) {
2413
+ continue;
2414
+ }
2415
+ }
2416
+ const enabled = guard.immutable || guard.default_enabled !== false;
2417
+ const matchedPatterns = [];
2418
+ for (const patternKey of guard.intent_patterns) {
2419
+ const regex = compiledPatterns.get(patternKey);
2420
+ if (regex?.test(eventText)) {
2421
+ matchedPatterns.push(patternKey);
2422
+ }
2423
+ }
2424
+ const matched = matchedPatterns.length > 0 && enabled;
2425
+ let roleGated = false;
2426
+ if (matched && guard.required_roles && guard.required_roles.length > 0 && event.roleId && guard.required_roles.includes(event.roleId)) {
2427
+ roleGated = true;
2428
+ }
2429
+ checks.push({
2430
+ guardId: guard.id,
2431
+ label: guard.label,
2432
+ category: guard.category,
2433
+ enabled,
2434
+ matched: matched && !roleGated,
2435
+ enforcement: guard.enforcement,
2436
+ matchedPatterns,
2437
+ roleGated
2438
+ });
2439
+ if (!matched || roleGated) continue;
2440
+ guardsMatched.push(guard.id);
2441
+ const actionMode = guard.player_modes?.action ?? guard.enforcement;
2442
+ const reason = guard.redirect ? `${guard.description} \u2014 ${guard.redirect}` : guard.description;
2443
+ if (actionMode === "block") {
2444
+ return { status: "BLOCK", reason, ruleId: `guard-${guard.id}` };
2445
+ }
2446
+ if (actionMode === "pause") {
2447
+ return { status: "PAUSE", reason, ruleId: `guard-${guard.id}` };
2448
+ }
2449
+ if (actionMode === "penalize") {
2450
+ const consequence = guard.consequence ? { ...guard.consequence } : { type: "freeze", rounds: 1, description: `Penalized for violating: ${guard.label}` };
2451
+ return { status: "PENALIZE", reason, ruleId: `guard-${guard.id}`, consequence };
2452
+ }
2453
+ if (actionMode === "reward") {
2454
+ const reward = guard.reward ? { ...guard.reward } : { type: "boost_influence", magnitude: 0.1, description: `Rewarded for: ${guard.label}` };
2455
+ return { status: "REWARD", reason, ruleId: `guard-${guard.id}`, reward };
2456
+ }
2457
+ if (actionMode === "modify") {
2458
+ const modifiedTo = guard.modify_to ?? guard.redirect ?? "hold";
2459
+ return { status: "MODIFY", reason: `${reason} \u2192 Modified to: ${modifiedTo}`, ruleId: `guard-${guard.id}`, modifiedTo };
2460
+ }
2461
+ if (actionMode === "neutral") {
2462
+ return { status: "NEUTRAL", reason, ruleId: `guard-${guard.id}` };
2463
+ }
2464
+ if (actionMode === "warn" && !warnResult) {
2465
+ warnResult = { status: "ALLOW", warning: reason, ruleId: `guard-${guard.id}` };
2466
+ }
2467
+ }
2468
+ return warnResult;
2469
+ }
2470
+ function checkKernelRules(eventText, world, checks, rulesMatched) {
2471
+ if (!world.kernel) return null;
2472
+ const forbidden = world.kernel.input_boundaries?.forbidden_patterns ?? [];
2473
+ const output = world.kernel.output_boundaries?.forbidden_patterns ?? [];
2474
+ for (const rule of forbidden) {
2475
+ let matched = false;
2476
+ let matchMethod = "none";
2477
+ if (rule.pattern) {
2478
+ try {
2479
+ matched = new RegExp(rule.pattern, "i").test(eventText);
2480
+ matchMethod = "pattern";
2481
+ } catch {
2482
+ }
2483
+ }
2484
+ if (!matched && rule.reason) {
2485
+ matched = matchesKeywords(eventText, rule.reason);
2486
+ if (matched) matchMethod = "keyword";
2487
+ }
2488
+ checks.push({
2489
+ ruleId: rule.id,
2490
+ text: rule.reason,
2491
+ category: "forbidden",
2492
+ matched,
2493
+ matchMethod
2494
+ });
2495
+ if (matched) {
2496
+ rulesMatched.push(rule.id);
2497
+ if (rule.action === "BLOCK") {
2498
+ return {
2499
+ status: "BLOCK",
2500
+ reason: rule.reason,
2501
+ ruleId: `kernel-${rule.id}`
2502
+ };
2503
+ }
2504
+ }
2505
+ }
2506
+ return null;
2507
+ }
2508
+ function checkLevelConstraints(event, level, checks) {
2509
+ if (level === "basic") return null;
2510
+ const intent = event.intent.toLowerCase();
2511
+ const tool = (event.tool ?? "").toLowerCase();
2512
+ const isDelete = intent.includes("delete") || intent.includes("remove") || intent.includes("rm ") || tool === "delete";
2513
+ const deleteTriggered = isDelete && levelRequiresConfirmation(level, "delete");
2514
+ checks.push({
2515
+ checkType: "delete",
2516
+ level,
2517
+ triggered: deleteTriggered,
2518
+ reason: deleteTriggered ? NEUTRAL_MESSAGES["delete"] : void 0
2519
+ });
2520
+ if (deleteTriggered) {
2521
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["delete"], ruleId: "level-delete-check" };
2522
+ }
2523
+ const isExternal = event.scope ? isExternalScope(event.scope) : false;
2524
+ const externalTriggered = isExternal && levelRequiresConfirmation(level, "write-external");
2525
+ checks.push({
2526
+ checkType: "write-external",
2527
+ level,
2528
+ triggered: externalTriggered,
2529
+ reason: externalTriggered ? NEUTRAL_MESSAGES["write-external"] : void 0
2530
+ });
2531
+ if (externalTriggered) {
2532
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["write-external"], ruleId: "level-external-write-check" };
2533
+ }
2534
+ const isNetwork = tool === "http" || tool === "fetch" || tool === "request" || intent.includes("post ") || intent.includes("sending");
2535
+ const networkTriggered = isNetwork && levelRequiresConfirmation(level, "network-mutate");
2536
+ checks.push({
2537
+ checkType: "network-mutate",
2538
+ level,
2539
+ triggered: networkTriggered,
2540
+ reason: networkTriggered ? NEUTRAL_MESSAGES["network-mutate"] : void 0
2541
+ });
2542
+ if (networkTriggered) {
2543
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["network-mutate"], ruleId: "level-network-mutate-check" };
2544
+ }
2545
+ const isCredential = intent.includes("credential") || intent.includes("password") || intent.includes("secret") || intent.includes("api key") || intent.includes("token");
2546
+ const credentialTriggered = isCredential && levelRequiresConfirmation(level, "credential-access");
2547
+ checks.push({
2548
+ checkType: "credential-access",
2549
+ level,
2550
+ triggered: credentialTriggered,
2551
+ reason: credentialTriggered ? NEUTRAL_MESSAGES["credential-access"] : void 0
2552
+ });
2553
+ if (credentialTriggered) {
2554
+ return { status: "PAUSE", reason: NEUTRAL_MESSAGES["credential-access"], ruleId: "level-credential-check" };
2555
+ }
2556
+ const irreversibleTriggered = !!event.irreversible && level !== "basic";
2557
+ checks.push({
2558
+ checkType: "irreversible",
2559
+ level,
2560
+ triggered: irreversibleTriggered,
2561
+ reason: irreversibleTriggered ? "This action is marked as irreversible." : void 0
2562
+ });
2563
+ if (irreversibleTriggered) {
2564
+ return {
2565
+ status: "PAUSE",
2566
+ reason: "This action is marked as irreversible.",
2567
+ ruleId: "level-irreversible-check"
2568
+ };
2569
+ }
2570
+ return null;
2571
+ }
2572
+ function matchesKeywords(eventText, ruleText) {
2573
+ return matchesAllKeywords(eventText, ruleText);
2574
+ }
2575
+ function eventToAllowlistKey(event) {
2576
+ return `${(event.tool ?? "*").toLowerCase()}::${event.intent.toLowerCase().trim()}`;
2577
+ }
2578
+ function buildTrace(invariantChecks, safetyChecks, planCheck, roleChecks, guardChecks, kernelRuleChecks, levelChecks, decidingLayer, decidingId, startTime) {
2579
+ const trace = {
2580
+ invariantChecks,
2581
+ safetyChecks,
2582
+ roleChecks,
2583
+ guardChecks,
2584
+ kernelRuleChecks,
2585
+ levelChecks,
2586
+ precedenceResolution: {
2587
+ decidingLayer,
2588
+ decidingId,
2589
+ strategy: "first-match-wins",
2590
+ chainOrder: [
2591
+ "invariant-coverage",
2592
+ "session-allowlist",
2593
+ "safety-injection",
2594
+ "safety-scope-escape",
2595
+ "safety-execution-claim",
2596
+ "safety-execution-intent",
2597
+ "plan-enforcement",
2598
+ "role-rules",
2599
+ "declarative-guards",
2600
+ "kernel-rules",
2601
+ "level-constraints",
2602
+ "default-allow"
2603
+ ]
2604
+ },
2605
+ durationMs: performance.now() - startTime
2606
+ };
2607
+ if (planCheck) {
2608
+ trace.planCheck = planCheck;
2609
+ }
2610
+ return trace;
2611
+ }
2612
+ function buildVerdict(status, reason, ruleId, warning, world, level, invariantChecks, guardsMatched, rulesMatched, trace, eventIntent) {
2613
+ const evidence = {
2614
+ worldId: world.world.world_id,
2615
+ worldName: world.world.name,
2616
+ worldVersion: world.world.version,
2617
+ evaluatedAt: Date.now(),
2618
+ invariantsSatisfied: invariantChecks.filter((c) => c.hasGuardCoverage).length,
2619
+ invariantsTotal: invariantChecks.length,
2620
+ guardsMatched,
2621
+ rulesMatched,
2622
+ enforcementLevel: level
2623
+ };
2624
+ const verdict = {
2625
+ status,
2626
+ evidence
2627
+ };
2628
+ if (reason) verdict.reason = reason;
2629
+ if (ruleId) verdict.ruleId = ruleId;
2630
+ if (warning) verdict.warning = warning;
2631
+ if (trace) verdict.trace = trace;
2632
+ verdict.event = verdictToEvent(status, eventIntent);
2633
+ return verdict;
2634
+ }
2635
+ function verdictToEvent(status, intent) {
2636
+ const statusEventMap = {
2637
+ ALLOW: "action_allowed",
2638
+ BLOCK: "action_blocked",
2639
+ PAUSE: "action_paused",
2640
+ MODIFY: "action_modified",
2641
+ PENALIZE: "action_penalized",
2642
+ REWARD: "action_rewarded",
2643
+ NEUTRAL: "action_neutral"
2644
+ };
2645
+ return {
2646
+ type: intent || statusEventMap[status] || "unknown_action",
2647
+ actor: "agent",
2648
+ source: "guard",
2649
+ timestamp: Date.now(),
2650
+ guardStatus: status
2651
+ };
2652
+ }
2653
+
2654
+ // src/loader/world-loader.ts
2655
+ async function loadWorldFromDirectory(dirPath) {
2656
+ const { readFile } = await import("fs/promises");
2657
+ const { join: join3 } = await import("path");
2658
+ const { readdirSync: readdirSync2 } = await import("fs");
2659
+ async function readJson(filename) {
2660
+ const filePath = join3(dirPath, filename);
2661
+ try {
2662
+ const content = await readFile(filePath, "utf-8");
2663
+ return JSON.parse(content);
2664
+ } catch (err) {
2665
+ if (err instanceof Error && "code" in err && err.code === "ENOENT") {
2666
+ return void 0;
2667
+ }
2668
+ process.stderr.write(
2669
+ `[neuroverse] Warning: Failed to read ${filename}: ${err instanceof Error ? err.message : String(err)}
2670
+ `
2671
+ );
2672
+ return void 0;
2673
+ }
2674
+ }
2675
+ const worldJson = await readJson("world.json");
2676
+ if (!worldJson) {
2677
+ throw new Error(`Cannot read world.json in ${dirPath}`);
2678
+ }
2679
+ const invariantsJson = await readJson("invariants.json");
2680
+ const assumptionsJson = await readJson("assumptions.json");
2681
+ const stateSchemaJson = await readJson("state-schema.json");
2682
+ const gatesJson = await readJson("gates.json");
2683
+ const outcomesJson = await readJson("outcomes.json");
2684
+ const guardsJson = await readJson("guards.json");
2685
+ const rolesJson = await readJson("roles.json");
2686
+ const kernelJson = await readJson("kernel.json");
2687
+ const metadataJson = await readJson("metadata.json");
2688
+ const rules = [];
2689
+ try {
2690
+ const rulesDir = join3(dirPath, "rules");
2691
+ const ruleFiles = readdirSync2(rulesDir).filter((f) => f.endsWith(".json")).sort();
2692
+ for (const file of ruleFiles) {
2693
+ try {
2694
+ const content = await readFile(join3(rulesDir, file), "utf-8");
2695
+ rules.push(JSON.parse(content));
2696
+ } catch (err) {
2697
+ process.stderr.write(
2698
+ `[neuroverse] Warning: Failed to parse rule ${file}: ${err instanceof Error ? err.message : String(err)}
2699
+ `
2700
+ );
2701
+ }
2702
+ }
2703
+ } catch (err) {
2704
+ if (!(err instanceof Error && "code" in err && err.code === "ENOENT")) {
2705
+ process.stderr.write(
2706
+ `[neuroverse] Warning: Failed to read rules directory: ${err instanceof Error ? err.message : String(err)}
2707
+ `
2708
+ );
2709
+ }
2710
+ }
2711
+ return {
2712
+ world: worldJson,
2713
+ invariants: invariantsJson?.invariants ?? [],
2714
+ assumptions: assumptionsJson ?? { profiles: {}, parameter_definitions: {} },
2715
+ stateSchema: stateSchemaJson ?? { variables: {}, presets: {} },
2716
+ rules,
2717
+ gates: gatesJson ?? {
2718
+ viability_classification: [],
2719
+ structural_override: { description: "", enforcement: "mandatory" },
2720
+ sustainability_threshold: 0,
2721
+ collapse_visual: { background: "", text: "", border: "", label: "" }
2722
+ },
2723
+ outcomes: outcomesJson ?? {
2724
+ computed_outcomes: [],
2725
+ comparison_layout: { primary_card: "", status_badge: "", structural_indicators: [] }
2726
+ },
2727
+ guards: guardsJson,
2728
+ roles: rolesJson,
2729
+ kernel: kernelJson,
2730
+ metadata: metadataJson ?? {
2731
+ format_version: "1.0.0",
2732
+ created_at: "",
2733
+ last_modified: "",
2734
+ authoring_method: "manual-authoring"
2735
+ }
2736
+ };
2737
+ }
2738
+ async function loadWorld(worldPath) {
2739
+ const { stat } = await import("fs/promises");
2740
+ const info = await stat(worldPath);
2741
+ if (info.isDirectory()) {
2742
+ return loadWorldFromDirectory(worldPath);
2743
+ }
2744
+ throw new Error(`Cannot load world from: ${worldPath} \u2014 expected a directory`);
2745
+ }
2746
+
2747
+ // src/radiant/core/governance.ts
2748
+ async function auditGovernance(events, worldPath) {
2749
+ let world;
2750
+ try {
2751
+ world = await loadWorld(worldPath);
2752
+ } catch {
2753
+ return emptyAudit(events.length, "Could not load compiled worldmodel for governance audit.");
2754
+ }
2755
+ const verdicts = [];
2756
+ for (const ce of events) {
2757
+ const intent = ce.event.content?.slice(0, 500) || ce.event.kind || "activity";
2758
+ const scope = ce.event.metadata?.scope || void 0;
2759
+ try {
2760
+ const result = evaluateGuard(
2761
+ {
2762
+ intent,
2763
+ scope,
2764
+ actionCategory: mapKindToCategory(ce.event.kind)
2765
+ },
2766
+ world
2767
+ );
2768
+ verdicts.push({
2769
+ eventId: ce.event.id,
2770
+ domain: ce.domain,
2771
+ status: result.status,
2772
+ reason: result.reason,
2773
+ ruleId: result.ruleId,
2774
+ warning: result.warning
2775
+ });
2776
+ } catch {
2777
+ verdicts.push({
2778
+ eventId: ce.event.id,
2779
+ domain: ce.domain,
2780
+ status: "ALLOW",
2781
+ reason: "guard evaluation skipped (error)"
2782
+ });
2783
+ }
2784
+ }
2785
+ const human = bucketVerdicts(verdicts.filter((v) => v.domain === "life"));
2786
+ const cyber = bucketVerdicts(verdicts.filter((v) => v.domain === "cyber"));
2787
+ const joint = bucketVerdicts(verdicts.filter((v) => v.domain === "joint"));
2788
+ const summary = buildSummary(human, cyber, joint, events.length);
2789
+ return {
2790
+ totalEvents: events.length,
2791
+ human,
2792
+ cyber,
2793
+ joint,
2794
+ summary
2795
+ };
2796
+ }
2797
+ function bucketVerdicts(verdicts) {
2798
+ const nonAllow = verdicts.filter((v) => v.status !== "ALLOW");
2799
+ return {
2800
+ allow: verdicts.filter((v) => v.status === "ALLOW").length,
2801
+ modify: verdicts.filter((v) => v.status === "MODIFY").length,
2802
+ block: verdicts.filter((v) => v.status === "BLOCK").length,
2803
+ details: nonAllow
2804
+ };
2805
+ }
2806
+ function buildSummary(human, cyber, joint, total) {
2807
+ const humanTriggered = human.modify + human.block;
2808
+ const cyberTriggered = cyber.modify + cyber.block;
2809
+ const jointTriggered = joint.modify + joint.block;
2810
+ const totalTriggered = humanTriggered + cyberTriggered + jointTriggered;
2811
+ if (totalTriggered === 0) {
2812
+ return `${total} events evaluated. All passed. The cocoon held \u2014 no governance triggered.`;
2813
+ }
2814
+ const parts = [];
2815
+ parts.push(`${total} events evaluated. ${totalTriggered} triggered governance.`);
2816
+ if (humanTriggered > 0) {
2817
+ parts.push(`Human side: ${humanTriggered} (${human.block} blocked, ${human.modify} modified).`);
2818
+ }
2819
+ if (cyberTriggered > 0) {
2820
+ parts.push(`AI side: ${cyberTriggered} (${cyber.block} blocked, ${cyber.modify} modified).`);
2821
+ }
2822
+ if (jointTriggered > 0) {
2823
+ parts.push(`Joint work: ${jointTriggered} (${joint.block} blocked, ${joint.modify} modified).`);
2824
+ }
2825
+ if (humanTriggered > 0 && cyberTriggered > 0) {
2826
+ const ratio = humanTriggered / cyberTriggered;
2827
+ if (ratio > 2) {
2828
+ parts.push("Human side is testing the frame more than AI. Either the worldmodel needs calibrating for human workflows, or humans are genuinely drifting.");
2829
+ } else if (ratio < 0.5) {
2830
+ parts.push("AI side is testing the frame more than humans. Check whether the AI's output patterns match the declared invariants.");
2831
+ } else {
2832
+ parts.push("Roughly balanced between human and AI \u2014 both sides are testing the frame.");
2833
+ }
2834
+ }
2835
+ return parts.join(" ");
2836
+ }
2837
+ function mapKindToCategory(kind) {
2838
+ if (!kind) return "other";
2839
+ if (kind.includes("commit") || kind.includes("merge")) return "write";
2840
+ if (kind.includes("review") || kind.includes("comment")) return "read";
2841
+ return "other";
2842
+ }
2843
+ function emptyAudit(total, reason) {
2844
+ return {
2845
+ totalEvents: total,
2846
+ human: { allow: 0, modify: 0, block: 0, details: [] },
2847
+ cyber: { allow: 0, modify: 0, block: 0, details: [] },
2848
+ joint: { allow: 0, modify: 0, block: 0, details: [] },
2849
+ summary: reason
2850
+ };
2851
+ }
2852
+
2853
+ // src/radiant/memory/palace.ts
2854
+ var import_fs2 = require("fs");
2855
+ var import_path2 = require("path");
2856
+ function writeRead(exocortexDir, frontmatter, text) {
2857
+ const dir = (0, import_path2.resolve)(exocortexDir, "radiant", "reads");
2858
+ (0, import_fs2.mkdirSync)(dir, { recursive: true });
2859
+ const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
2860
+ const filename = `${date}.md`;
2861
+ const filepath = (0, import_path2.join)(dir, filename);
2862
+ const content = `${frontmatter}
2863
+
2864
+ ${text}
2865
+ `;
2866
+ (0, import_fs2.writeFileSync)(filepath, content, "utf-8");
2867
+ return filepath;
2868
+ }
2869
+ function updateKnowledge(exocortexDir, persistence, options) {
2870
+ const dir = (0, import_path2.resolve)(exocortexDir, "radiant");
2871
+ (0, import_fs2.mkdirSync)(dir, { recursive: true });
2872
+ const filepath = (0, import_path2.join)(dir, "knowledge.md");
2873
+ const totalReads = options?.totalReads ?? 0;
2874
+ const existingUntriggered = loadUntriggeredCounts(filepath);
2875
+ const lines = [
2876
+ "# Radiant \u2014 Accumulated Behavioral Knowledge",
2877
+ "",
2878
+ `Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
2879
+ `Total reads: ${totalReads}`,
2880
+ "",
2881
+ "---",
2882
+ "",
2883
+ "## Evolution proposals",
2884
+ ""
2885
+ ];
2886
+ const addCandidates = persistence.filter((p) => p.occurrences >= 3);
2887
+ if (addCandidates.length > 0) {
2888
+ lines.push("### Consider adding");
2889
+ lines.push("");
2890
+ lines.push("These candidate patterns keep recurring. They are not yet in the worldmodel.");
2891
+ lines.push("If they represent real behavioral patterns worth tracking, add them.");
2892
+ lines.push("If they were temporary, dismiss them.");
2893
+ lines.push("");
2894
+ for (const p of addCandidates) {
2895
+ lines.push(
2896
+ `- **${p.name}** \u2014 observed ${p.occurrences} times (${p.dates.join(", ")}). Add to auki-strategy.worldmodel.md \u2192 Evolution Layer \u2192 Drift Behaviors (if concerning) or Aligned Behaviors (if healthy).`
2897
+ );
2898
+ }
2899
+ lines.push("");
2900
+ }
2901
+ if (options?.declaredItems && options.declaredItems.length > 0) {
2902
+ const triggered = new Set(options.triggeredItems ?? []);
2903
+ const removeCandidates = [];
2904
+ for (const item of options.declaredItems) {
2905
+ if (!triggered.has(item.name)) {
2906
+ const prior = existingUntriggered.get(item.name) ?? 0;
2907
+ const count = prior + 1;
2908
+ existingUntriggered.set(item.name, count);
2909
+ if (count >= 4) {
2910
+ removeCandidates.push({ item, weeksSilent: count });
2911
+ }
2912
+ } else {
2913
+ existingUntriggered.set(item.name, 0);
2914
+ }
2915
+ }
2916
+ if (removeCandidates.length > 0) {
2917
+ lines.push("### Consider removing");
2918
+ lines.push("");
2919
+ lines.push("These items are declared in the worldmodel but haven't triggered in multiple reads.");
2920
+ lines.push("Either the team has internalized them (the rule is redundant) or they haven't been tested.");
2921
+ lines.push("A lean worldmodel with 5 sharp invariants is stronger than a bloated one with 20.");
2922
+ lines.push("");
2923
+ for (const { item, weeksSilent } of removeCandidates) {
2924
+ lines.push(
2925
+ `- **${item.name}** (${item.type}) \u2014 hasn't triggered in ${weeksSilent} reads. Internalized or untested? Review whether it still earns its place.`
2926
+ );
2927
+ }
2928
+ lines.push("");
2929
+ }
2930
+ }
2931
+ if (options?.triggeredItems && options.triggeredItems.length > 0) {
2932
+ lines.push("### Keep (recently active)");
2933
+ lines.push("");
2934
+ lines.push("These worldmodel items triggered governance in the most recent read. They're earning their place.");
2935
+ lines.push("");
2936
+ for (const name of options.triggeredItems) {
2937
+ lines.push(`- **${name}** \u2014 triggered this read. Holding.`);
2938
+ }
2939
+ lines.push("");
2940
+ }
2941
+ lines.push("---");
2942
+ lines.push("");
2943
+ lines.push("## Pattern persistence (all observed)");
2944
+ lines.push("");
2945
+ for (const p of persistence) {
2946
+ const status = p.occurrences >= 4 ? "**persistent**" : p.occurrences >= 2 ? "recurring" : "observed once";
2947
+ lines.push(`### ${p.name}`);
2948
+ lines.push(`- Status: ${status}`);
2949
+ lines.push(`- Observed ${p.occurrences} time${p.occurrences > 1 ? "s" : ""}: ${p.dates.join(", ")}`);
2950
+ lines.push("");
2951
+ }
2952
+ lines.push("---");
2953
+ lines.push("");
2954
+ lines.push("<!-- untriggered_counts (machine-readable, do not edit)");
2955
+ for (const [name, count] of existingUntriggered.entries()) {
2956
+ lines.push(`${name}=${count}`);
2957
+ }
2958
+ lines.push("-->");
2959
+ (0, import_fs2.writeFileSync)(filepath, lines.join("\n"), "utf-8");
2960
+ return filepath;
2961
+ }
2962
+ function loadUntriggeredCounts(filepath) {
2963
+ const counts = /* @__PURE__ */ new Map();
2964
+ if (!(0, import_fs2.existsSync)(filepath)) return counts;
2965
+ try {
2966
+ const content = (0, import_fs2.readFileSync)(filepath, "utf-8");
2967
+ const match = content.match(
2968
+ /<!-- untriggered_counts[\s\S]*?-->/
2969
+ );
2970
+ if (match) {
2971
+ const lines = match[0].split("\n");
2972
+ for (const line of lines) {
2973
+ const eq = line.match(/^([^=]+)=(\d+)$/);
2974
+ if (eq) {
2975
+ counts.set(eq[1], parseInt(eq[2], 10));
2976
+ }
2977
+ }
2978
+ }
2979
+ } catch {
2980
+ }
2981
+ return counts;
2982
+ }
2983
+ function loadPriorReads(exocortexDir) {
2984
+ const dir = (0, import_path2.resolve)(exocortexDir, "radiant", "reads");
2985
+ if (!(0, import_fs2.existsSync)(dir)) return [];
2986
+ const files = (0, import_fs2.readdirSync)(dir).filter((f) => f.endsWith(".md")).sort();
2987
+ const reads = [];
2988
+ for (const filename of files) {
2989
+ const filepath = (0, import_path2.join)(dir, filename);
2990
+ const content = (0, import_fs2.readFileSync)(filepath, "utf-8");
2991
+ const date = filename.replace(".md", "");
2992
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
2993
+ const frontmatter = fmMatch ? fmMatch[1] : "";
2994
+ const patternNames = [];
2995
+ const nameMatches = frontmatter.matchAll(/- name: ["']?([^"'\n]+)["']?/g);
2996
+ for (const m of nameMatches) {
2997
+ patternNames.push(m[1].trim());
2998
+ }
2999
+ reads.push({ date, filename, patternNames, frontmatter });
3000
+ }
3001
+ return reads;
3002
+ }
3003
+ function computePersistence(priorReads, currentPatternNames) {
3004
+ const allPatterns = /* @__PURE__ */ new Map();
3005
+ for (const read of priorReads) {
3006
+ for (const name of read.patternNames) {
3007
+ const dates = allPatterns.get(name) ?? [];
3008
+ if (!dates.includes(read.date)) dates.push(read.date);
3009
+ allPatterns.set(name, dates);
3010
+ }
3011
+ }
3012
+ const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
3013
+ for (const name of currentPatternNames) {
3014
+ const dates = allPatterns.get(name) ?? [];
3015
+ if (!dates.includes(today)) dates.push(today);
3016
+ allPatterns.set(name, dates);
3017
+ }
3018
+ return Array.from(allPatterns.entries()).map(([name, dates]) => ({
3019
+ name,
3020
+ occurrences: dates.length,
3021
+ dates: dates.sort()
3022
+ })).sort((a, b) => b.occurrences - a.occurrences);
3023
+ }
3024
+ function formatPriorReadsForPrompt(priorReads) {
3025
+ if (priorReads.length === 0) return "";
3026
+ const lines = [
3027
+ "## Prior Radiant reads (history)",
3028
+ "",
3029
+ `Radiant has run ${priorReads.length} time${priorReads.length > 1 ? "s" : ""} before on this scope.`,
3030
+ "If you see patterns that appeared in prior reads, note their persistence.",
3031
+ "Patterns that recur across 3+ reads are strong candidates for declaration in the strategy file.",
3032
+ ""
3033
+ ];
3034
+ for (const read of priorReads.slice(-4)) {
3035
+ lines.push(`### Read from ${read.date}`);
3036
+ if (read.patternNames.length > 0) {
3037
+ lines.push(`Patterns observed: ${read.patternNames.join(", ")}`);
3038
+ } else {
3039
+ lines.push("No patterns extracted from frontmatter.");
3040
+ }
3041
+ lines.push("");
3042
+ }
3043
+ return lines.join("\n");
3044
+ }
3045
+
1534
3046
  // src/radiant/commands/think.ts
1535
3047
  async function think(input) {
1536
3048
  const lens = resolveLens(input.lensId);
@@ -1568,10 +3080,15 @@ async function emergent(input) {
1568
3080
  const windowDays = input.windowDays ?? 14;
1569
3081
  let statedIntent;
1570
3082
  let exocortexContext;
3083
+ let priorReadContext = "";
1571
3084
  if (input.exocortexPath) {
1572
3085
  exocortexContext = readExocortex(input.exocortexPath);
1573
3086
  const formatted = formatExocortexForPrompt(exocortexContext);
1574
3087
  if (formatted) statedIntent = formatted;
3088
+ const priorReads = loadPriorReads(input.exocortexPath);
3089
+ if (priorReads.length > 0) {
3090
+ priorReadContext = formatPriorReadsForPrompt(priorReads);
3091
+ }
1575
3092
  }
1576
3093
  const events = await fetchGitHubActivity(input.scope, input.githubToken, {
1577
3094
  windowDays
@@ -1586,11 +3103,18 @@ async function emergent(input) {
1586
3103
  lens,
1587
3104
  ai: input.ai,
1588
3105
  canonicalPatterns: input.canonicalPatterns,
1589
- statedIntent
3106
+ statedIntent: statedIntent ? statedIntent + (priorReadContext ? "\n\n" + priorReadContext : "") : priorReadContext || void 0
1590
3107
  });
1591
3108
  const rewrittenPatterns = patterns.map((p) => lens.rewrite(p));
1592
3109
  const allDescriptions = rewrittenPatterns.map((p) => p.description).join("\n");
1593
3110
  const voiceViolations = checkForbiddenPhrases(lens, allDescriptions);
3111
+ let governance;
3112
+ if (input.worldPath) {
3113
+ try {
3114
+ governance = await auditGovernance(classified, input.worldPath);
3115
+ } catch {
3116
+ }
3117
+ }
1594
3118
  const rendered = render({
1595
3119
  scope: input.scope,
1596
3120
  windowDays,
@@ -1600,8 +3124,27 @@ async function emergent(input) {
1600
3124
  scores,
1601
3125
  lens,
1602
3126
  meaning: meaning || void 0,
1603
- move: move || void 0
3127
+ move: move || void 0,
3128
+ governance
1604
3129
  });
3130
+ if (input.exocortexPath) {
3131
+ try {
3132
+ const readPath = writeRead(input.exocortexPath, rendered.frontmatter, rendered.text);
3133
+ const priorReads = loadPriorReads(input.exocortexPath);
3134
+ const currentPatternNames = rewrittenPatterns.map((p) => p.name);
3135
+ const persistence = computePersistence(priorReads, currentPatternNames);
3136
+ const triggeredItems = governance ? [
3137
+ ...governance.human.details.map((d) => d.ruleId).filter(Boolean),
3138
+ ...governance.cyber.details.map((d) => d.ruleId).filter(Boolean),
3139
+ ...governance.joint.details.map((d) => d.ruleId).filter(Boolean)
3140
+ ] : [];
3141
+ updateKnowledge(input.exocortexPath, persistence, {
3142
+ triggeredItems,
3143
+ totalReads: priorReads.length + 1
3144
+ });
3145
+ } catch {
3146
+ }
3147
+ }
1605
3148
  return {
1606
3149
  text: rendered.text,
1607
3150
  frontmatter: rendered.frontmatter,
@@ -1668,11 +3211,13 @@ var RADIANT_PACKAGE_VERSION = "0.0.0";
1668
3211
  DEFAULT_SIGNAL_EXTRACTORS,
1669
3212
  LENSES,
1670
3213
  RADIANT_PACKAGE_VERSION,
3214
+ auditGovernance,
1671
3215
  aukiBuilderLens,
1672
3216
  checkForbiddenPhrases,
1673
3217
  classifyActorDomain,
1674
3218
  classifyEvents,
1675
3219
  composeSystemPrompt,
3220
+ computePersistence,
1676
3221
  createAnthropicAI,
1677
3222
  createMockAI,
1678
3223
  createMockGitHubAdapter,
@@ -1680,6 +3225,7 @@ var RADIANT_PACKAGE_VERSION = "0.0.0";
1680
3225
  extractSignals,
1681
3226
  fetchGitHubActivity,
1682
3227
  formatExocortexForPrompt,
3228
+ formatPriorReadsForPrompt,
1683
3229
  formatScope,
1684
3230
  getLens,
1685
3231
  interpretPatterns,
@@ -1687,6 +3233,7 @@ var RADIANT_PACKAGE_VERSION = "0.0.0";
1687
3233
  isScored,
1688
3234
  isSentinel,
1689
3235
  listLenses,
3236
+ loadPriorReads,
1690
3237
  parseRepoScope,
1691
3238
  presenceAverage,
1692
3239
  readExocortex,
@@ -1696,5 +3243,7 @@ var RADIANT_PACKAGE_VERSION = "0.0.0";
1696
3243
  scoreLife,
1697
3244
  scoreNeuroVerse,
1698
3245
  summarizeExocortex,
1699
- think
3246
+ think,
3247
+ updateKnowledge,
3248
+ writeRead
1700
3249
  });