dotmem 0.1.7 → 0.1.8

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/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { store as store$1, hlc, dispatch, session, state, temporal } from 'memorio';
2
- import fs2 from 'fs';
2
+ import fs2, { readFileSync } from 'fs';
3
3
  import path2 from 'path';
4
4
  import { fileURLToPath } from 'url';
5
5
  import crypto2 from 'crypto';
@@ -33,18 +33,6 @@ var __copyProps = (to, from, except, desc) => {
33
33
  };
34
34
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
35
35
 
36
- // core/suppress-idb-warning.ts
37
- var orig;
38
- var init_suppress_idb_warning = __esm({
39
- "core/suppress-idb-warning.ts"() {
40
- orig = console.warn.bind(console);
41
- console.warn = (...args) => {
42
- if (typeof args[0] === "string" && args[0].includes("IndexedDB is not available")) return;
43
- orig(...args);
44
- };
45
- }
46
- });
47
-
48
36
  // core/env.ts
49
37
  var DEV;
50
38
  var init_env = __esm({
@@ -79,7 +67,6 @@ function configure(opts) {
79
67
  var g, STORE_PREFIX, INDEX_KEY, journal, journal_default;
80
68
  var init_journal = __esm({
81
69
  "core/memory/journal.ts"() {
82
- init_suppress_idb_warning();
83
70
  init_env();
84
71
  g = globalThis;
85
72
  __name(namespace, "namespace");
@@ -327,6 +314,60 @@ var init_storage_paths = __esm({
327
314
  }
328
315
  });
329
316
 
317
+ // core/knowledge/text-encoding.ts
318
+ function detectBom(bytes) {
319
+ if (bytes.length >= 3 && bytes[0] === BOM_UTF8 && bytes[1] === 187 && bytes[2] === 191) {
320
+ return "utf-8";
321
+ }
322
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16LE_FIRST && bytes[1] === BOM_UTF16LE_SECOND) {
323
+ return "utf-16le";
324
+ }
325
+ if (bytes.length >= 2 && bytes[0] === BOM_UTF16BE_FIRST && bytes[1] === BOM_UTF16BE_SECOND) {
326
+ return "utf-16be";
327
+ }
328
+ return null;
329
+ }
330
+ function encodeText(value) {
331
+ return encoder.encode(value);
332
+ }
333
+ function decodeText(bytes, options = {}) {
334
+ const bom = detectBom(bytes);
335
+ if (bom === "utf-16le" || bom === "utf-16be") {
336
+ throw new UnsupportedEncodingError(
337
+ `UTF-16 encoded content detected in ${options.source ?? "unknown"}; dotmem persists UTF-8 only. Re-save the file as UTF-8 without BOM.`
338
+ );
339
+ }
340
+ let content = bytes;
341
+ if (bom === "utf-8") {
342
+ content = bytes.subarray(3);
343
+ }
344
+ return strictDecoder.decode(content);
345
+ }
346
+ var encoder, strictDecoder, UnsupportedEncodingError, BOM_UTF8, BOM_UTF16LE_FIRST, BOM_UTF16LE_SECOND, BOM_UTF16BE_FIRST, BOM_UTF16BE_SECOND;
347
+ var init_text_encoding = __esm({
348
+ "core/knowledge/text-encoding.ts"() {
349
+ encoder = new TextEncoder();
350
+ strictDecoder = new TextDecoder("utf-8", { fatal: true });
351
+ UnsupportedEncodingError = class extends Error {
352
+ static {
353
+ __name(this, "UnsupportedEncodingError");
354
+ }
355
+ constructor(message) {
356
+ super(message);
357
+ this.name = "UnsupportedEncodingError";
358
+ }
359
+ };
360
+ BOM_UTF8 = 239;
361
+ BOM_UTF16LE_FIRST = 255;
362
+ BOM_UTF16LE_SECOND = 254;
363
+ BOM_UTF16BE_FIRST = 254;
364
+ BOM_UTF16BE_SECOND = 255;
365
+ __name(detectBom, "detectBom");
366
+ __name(encodeText, "encodeText");
367
+ __name(decodeText, "decodeText");
368
+ }
369
+ });
370
+
330
371
  // core/knowledge/storage-settings.ts
331
372
  var DOTMEM_STORAGE_SETTINGS_FILE_NAME, DOTMEM_STORAGE_SETTINGS_VERSION, SETTINGS_MODES, projectRoot, findProjectSettingsFile, resolveProjectSettingsFilePath, discoverProjectSettingsFilePath, resolveUserSettingsFilePath, invalidSettings, parseSettings, resolveSettingsEntry, readTextFile, readStorageSettings;
332
373
  var init_storage_settings = __esm({
@@ -460,15 +501,19 @@ function readDotMemStorageLocator() {
460
501
  const locatorFile = resolveLocatorFilePath(anchor);
461
502
  let raw;
462
503
  try {
463
- raw = fs7.readFileSync(locatorFile, "utf8");
504
+ raw = decodeText(fs7.readFileSync(locatorFile), { source: locatorFile });
464
505
  } catch (error) {
506
+ if (error instanceof UnsupportedEncodingError) {
507
+ throw new DotMemStorageLocationError(
508
+ `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} is UTF-16 encoded; dotmem persists UTF-8 only. Re-save the locator as UTF-8 without BOM.`
509
+ );
510
+ }
465
511
  const code = error?.code;
466
512
  if (code === "ENOENT") return null;
467
513
  throw new DotMemStorageLocationError(
468
514
  `dotmem storage location cannot be resolved: the user locator file at ${locatorFile} cannot be read (${describeAccessFailure(error)}). No alternative location was selected automatically.`
469
515
  );
470
516
  }
471
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
472
517
  let parsed;
473
518
  try {
474
519
  parsed = JSON.parse(raw);
@@ -754,6 +799,7 @@ var DOTMEM_USER_ANCHOR_DIR_NAME, DOTMEM_STORAGE_LOCATOR_FILE_NAME, DOTMEM_STORAG
754
799
  var init_storage_location = __esm({
755
800
  "core/knowledge/storage-location.ts"() {
756
801
  init_storage_paths();
802
+ init_text_encoding();
757
803
  init_storage_settings();
758
804
  init_storage_paths();
759
805
  DOTMEM_USER_ANCHOR_DIR_NAME = ".dotmem";
@@ -1955,6 +2001,12 @@ var init_state = __esm({
1955
2001
  if (claim.sourceProject !== void 0 && !requiredText(claim.sourceProject)) {
1956
2002
  throw new Error(`Claim ${claim.id} has an invalid sourceProject`);
1957
2003
  }
2004
+ if (claim.check !== void 0) {
2005
+ const check = claim.check;
2006
+ if (!check || typeof check !== "object" || Array.isArray(check) || check.kind !== "regex" || !requiredText(check.pattern) || !["staged", "committed", "working-tree"].includes(check.on) || check.description !== void 0 && !requiredText(check.description)) {
2007
+ throw new Error(`Claim ${claim.id} has an invalid check`);
2008
+ }
2009
+ }
1958
2010
  return claim;
1959
2011
  }, "validateClaim");
1960
2012
  validateKnowledgeState = /* @__PURE__ */ __name((value) => {
@@ -2260,6 +2312,50 @@ var init_scope_eligibility = __esm({
2260
2312
  }
2261
2313
  });
2262
2314
 
2315
+ // core/knowledge/currentness.ts
2316
+ var asRecord, verifiedAtOf, findContestedIds, deriveCurrentness;
2317
+ var init_currentness = __esm({
2318
+ "core/knowledge/currentness.ts"() {
2319
+ asRecord = /* @__PURE__ */ __name((value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0, "asRecord");
2320
+ verifiedAtOf = /* @__PURE__ */ __name((claim) => {
2321
+ const value = asRecord(claim.knowledge)?.verifiedAt;
2322
+ if (typeof value !== "string") return void 0;
2323
+ const parsed = Date.parse(value);
2324
+ return Number.isNaN(parsed) ? void 0 : parsed;
2325
+ }, "verifiedAtOf");
2326
+ findContestedIds = /* @__PURE__ */ __name((claims) => {
2327
+ const retracting = /* @__PURE__ */ new Map();
2328
+ for (const claim of claims) {
2329
+ if (claim.revision?.kind === "retracts" && claim.revision.claimIds.length > 0) {
2330
+ retracting.set(claim.id, new Set(claim.revision.claimIds));
2331
+ }
2332
+ }
2333
+ const contested = /* @__PURE__ */ new Set();
2334
+ for (const [id, targets] of retracting) {
2335
+ for (const target of targets) {
2336
+ if (retracting.get(target)?.has(id)) {
2337
+ contested.add(id);
2338
+ contested.add(target);
2339
+ }
2340
+ }
2341
+ }
2342
+ return contested;
2343
+ }, "findContestedIds");
2344
+ deriveCurrentness = /* @__PURE__ */ __name((claim, context2 = {}) => {
2345
+ const now2 = context2.now ?? Date.now();
2346
+ if (context2.contestedIds?.has(claim.id)) return "contested";
2347
+ if (claim.revision?.kind === "retracts") return "historical";
2348
+ if (context2.retractedIds?.has(claim.id)) return "historical";
2349
+ if (context2.supersededIds?.has(claim.id)) return "superseded";
2350
+ if (claim.expiresAt !== void 0 && now2 >= claim.expiresAt) return "expired";
2351
+ const verifiedAt = verifiedAtOf(claim);
2352
+ if (verifiedAt !== void 0) return "verified";
2353
+ if (claim.epistemicType === "verified") return "unverified";
2354
+ return "unknown-currentness";
2355
+ }, "deriveCurrentness");
2356
+ }
2357
+ });
2358
+
2263
2359
  // core/knowledge/discover.ts
2264
2360
  var diagnostic, DEFAULT_LIMITS, FIELD_ORDER, FIELD_WEIGHT, normalize, discoveryTerms, jsonText, fieldText, acquiredTime, isExpired, rankCandidate, discoverAcquiredExperience;
2265
2361
  var init_discover = __esm({
@@ -2267,6 +2363,7 @@ var init_discover = __esm({
2267
2363
  init_state();
2268
2364
  init_applicability();
2269
2365
  init_scope_eligibility();
2366
+ init_currentness();
2270
2367
  init_env();
2271
2368
  diagnostic = /* @__PURE__ */ __name((message) => {
2272
2369
  if (typeof process !== "undefined" && typeof process.stderr?.write === "function") {
@@ -2379,11 +2476,78 @@ var init_discover = __esm({
2379
2476
  throw new Error("Discovery maxCandidates must be a positive integer");
2380
2477
  }
2381
2478
  const queryTerms = discoveryTerms(situation);
2479
+ const offset = options.cursor?.offset ?? 0;
2480
+ if (!Number.isInteger(offset) || offset < 0) {
2481
+ throw new Error("Discovery cursor offset must be a non-negative integer");
2482
+ }
2483
+ if (options.cursor && options.cursor.knowledgeVersion !== validated.version) {
2484
+ return {
2485
+ knowledgeVersion: validated.version,
2486
+ depth,
2487
+ queryTerms,
2488
+ candidates: [],
2489
+ omissions: [],
2490
+ offset: 0,
2491
+ snapshotChanged: true
2492
+ };
2493
+ }
2382
2494
  const available = activeClaims(validated);
2495
+ const availableIds = new Set(available.map((claim) => claim.id));
2496
+ const retractedIds = /* @__PURE__ */ new Set();
2497
+ const supersededIds = /* @__PURE__ */ new Set();
2498
+ const contestedIds = findContestedIds(validated.claims);
2499
+ for (const claim of validated.claims) {
2500
+ if (claim.revision?.kind === "retracts") {
2501
+ for (const id of claim.revision.claimIds) retractedIds.add(id);
2502
+ }
2503
+ if (claim.revision?.kind === "supersedes") {
2504
+ for (const id of claim.revision.claimIds) supersededIds.add(id);
2505
+ }
2506
+ }
2507
+ const revisionOmissions = validated.claims.filter((claim) => !availableIds.has(claim.id)).map((claim) => {
2508
+ const retracted = retractedIds.has(claim.id);
2509
+ const superseded = supersededIds.has(claim.id);
2510
+ return {
2511
+ id: claim.id,
2512
+ reason: retracted ? "retracted" : superseded ? "superseded" : "retracted",
2513
+ gate: "revision-resolution",
2514
+ ...retracted || superseded ? {} : { detail: "the claim itself retracts prior knowledge and is kept as history" }
2515
+ };
2516
+ }).sort((left, right) => left.id.localeCompare(right.id));
2383
2517
  const scopeEligible = options.currentProjectId === void 0 ? available : available.filter((claim) => isScopeEligible(claim, options.currentProjectId, sources.get(claim.id)));
2384
2518
  const freshEligible = scopeEligible.filter((claim) => !isExpired(claim));
2519
+ const scopeEligibleIds = new Set(scopeEligible.map((claim) => claim.id));
2520
+ const scopeOmissions = available.filter((claim) => !scopeEligibleIds.has(claim.id)).map((claim) => {
2521
+ const owner = claimOwnerProject(claim, sources.get(claim.id));
2522
+ return {
2523
+ id: claim.id,
2524
+ reason: "scope",
2525
+ gate: "scope",
2526
+ detail: owner === void 0 ? "owner project could not be resolved" : `owned by project ${owner}`
2527
+ };
2528
+ }).sort((left, right) => left.id.localeCompare(right.id));
2529
+ const freshIds = new Set(freshEligible.map((claim) => claim.id));
2530
+ const freshnessOmissions = scopeEligible.filter((claim) => !freshIds.has(claim.id)).map((claim) => ({
2531
+ id: claim.id,
2532
+ reason: "expired",
2533
+ gate: "freshness",
2534
+ detail: `expired at ${new Date(claim.expiresAt).toISOString()}`
2535
+ })).sort((left, right) => left.id.localeCompare(right.id));
2385
2536
  const situationApplicability = deriveSituationApplicability(situation, options.facts);
2386
- const eligible = freshEligible.map((claim) => ({ claim, match: isEligibleByApplicability(claim, situationApplicability) })).filter((candidate) => candidate.match.eligible);
2537
+ const applicabilityMatches = new Map(
2538
+ freshEligible.map((claim) => [claim.id, isEligibleByApplicability(claim, situationApplicability)])
2539
+ );
2540
+ const eligible = freshEligible.map((claim) => ({ claim, match: applicabilityMatches.get(claim.id) })).filter((candidate) => candidate.match.eligible);
2541
+ const applicabilityOmissions = freshEligible.filter((claim) => !applicabilityMatches.get(claim.id).eligible).map((claim) => {
2542
+ const match = applicabilityMatches.get(claim.id);
2543
+ const mismatched = Object.entries(match.dimensions).filter(([, state3]) => state3 === "MISMATCH").map(([dimension]) => dimension);
2544
+ return {
2545
+ id: claim.id,
2546
+ reason: "applicability-mismatch",
2547
+ gate: "applicability",
2548
+ detail: `mismatching dimensions: ${mismatched.length > 0 ? mismatched.join(", ") : "none recorded"}`
2549
+ };
2550
+ }).sort((left, right) => left.id.localeCompare(right.id));
2387
2551
  if (DEV) {
2388
2552
  diagnostic(
2389
2553
  "[dotmem discovery] ACTIVE=" + JSON.stringify(
@@ -2395,12 +2559,15 @@ var init_discover = __esm({
2395
2559
  )
2396
2560
  );
2397
2561
  }
2562
+ const currentnessOf = /* @__PURE__ */ __name((claim) => deriveCurrentness(claim, { retractedIds, supersededIds, contestedIds }), "currentnessOf");
2398
2563
  if (queryTerms.length === 0) {
2399
- const baseline = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
2564
+ const baselineAll = eligible.filter((candidate) => candidate.claim.applicability?.baseline === true).map((candidate) => candidate.claim).sort((left, right) => {
2400
2565
  const leftTime = acquiredTime(left);
2401
2566
  const rightTime = acquiredTime(right);
2402
2567
  return rightTime - leftTime || Number(right.scope === "project") - Number(left.scope === "project") || left.id.localeCompare(right.id);
2403
- }).slice(0, maxCandidates);
2568
+ });
2569
+ const baseline = baselineAll.slice(offset, offset + maxCandidates);
2570
+ const limitOmissions = baselineAll.slice(offset + maxCandidates).map((claim) => ({ id: claim.id, reason: "limit", gate: "ranking" })).sort((left, right) => left.id.localeCompare(right.id));
2404
2571
  const baselineCandidates = baseline.map((claim) => {
2405
2572
  const explanation = {
2406
2573
  matchedTerms: [],
@@ -2413,7 +2580,8 @@ var init_discover = __esm({
2413
2580
  }
2414
2581
  return {
2415
2582
  claim,
2416
- explanation
2583
+ explanation,
2584
+ currentness: currentnessOf(claim)
2417
2585
  };
2418
2586
  });
2419
2587
  if (DEV) {
@@ -2426,10 +2594,18 @@ var init_discover = __esm({
2426
2594
  depth,
2427
2595
  queryTerms,
2428
2596
  situationApplicability,
2429
- candidates: baselineCandidates
2597
+ candidates: baselineCandidates,
2598
+ offset,
2599
+ omissions: [
2600
+ ...revisionOmissions,
2601
+ ...scopeOmissions,
2602
+ ...freshnessOmissions,
2603
+ ...applicabilityOmissions,
2604
+ ...limitOmissions
2605
+ ]
2430
2606
  };
2431
2607
  }
2432
- const candidates = eligible.map(
2608
+ const ranked = eligible.map(
2433
2609
  (candidate) => rankCandidate(
2434
2610
  candidate.claim,
2435
2611
  situation,
@@ -2441,16 +2617,40 @@ var init_discover = __esm({
2441
2617
  (candidate) => candidate !== null
2442
2618
  ).sort(
2443
2619
  (left, right) => Number(right.directPhrase) - Number(left.directPhrase) || right.matchedTermCount - left.matchedTermCount || right.fieldWeight - left.fieldWeight || Number(right.claim.scope === "project") - Number(left.claim.scope === "project") || right.acquiredTime - left.acquiredTime || left.claim.id.localeCompare(right.claim.id)
2444
- ).slice(0, maxCandidates).map(({ claim, explanation }) => ({
2620
+ );
2621
+ const rankedIds = new Set(ranked.map((candidate) => candidate.claim.id));
2622
+ const rankingOmissions = [
2623
+ ...eligible.filter((candidate) => !rankedIds.has(candidate.claim.id)).map((candidate) => ({
2624
+ id: candidate.claim.id,
2625
+ reason: "no-term-match",
2626
+ gate: "ranking",
2627
+ detail: "passed every gate but shares no query term"
2628
+ })),
2629
+ ...ranked.slice(offset + maxCandidates).map((candidate) => ({
2630
+ id: candidate.claim.id,
2631
+ reason: "limit",
2632
+ gate: "ranking"
2633
+ }))
2634
+ ].sort((left, right) => left.id.localeCompare(right.id));
2635
+ const candidates = ranked.slice(offset, offset + maxCandidates).map(({ claim, explanation }) => ({
2445
2636
  claim,
2446
- explanation
2637
+ explanation,
2638
+ currentness: currentnessOf(claim)
2447
2639
  }));
2448
2640
  return {
2449
2641
  knowledgeVersion: validated.version,
2450
2642
  depth,
2451
2643
  queryTerms,
2452
2644
  situationApplicability,
2453
- candidates
2645
+ candidates,
2646
+ offset,
2647
+ omissions: [
2648
+ ...revisionOmissions,
2649
+ ...scopeOmissions,
2650
+ ...freshnessOmissions,
2651
+ ...applicabilityOmissions,
2652
+ ...rankingOmissions
2653
+ ]
2454
2654
  };
2455
2655
  }, "discoverAcquiredExperience");
2456
2656
  }
@@ -3507,7 +3707,7 @@ var init_policy_store = __esm({
3507
3707
  });
3508
3708
 
3509
3709
  // core/knowledge/acquisition-limits.ts
3510
- var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder, serializedBytes, measureKnowledge, checkAcquireLimits;
3710
+ var MEMORY_ACQUIRE_LIMITS, MEMORY_ACQUIRE_LIMITS_MCP, MEMORY_STORE_LIMITS, DOTMEM_ACQUIRE_ERROR_CODES, MemoryAcquireLimitError, MemoryAcquireConcurrencyError, MemoryAcquireDuplicateClaimError, encoder2, serializedBytes, measureKnowledge, checkAcquireLimits;
3511
3711
  var init_acquisition_limits = __esm({
3512
3712
  "core/knowledge/acquisition-limits.ts"() {
3513
3713
  MEMORY_ACQUIRE_LIMITS = Object.freeze({
@@ -3566,10 +3766,10 @@ var init_acquisition_limits = __esm({
3566
3766
  this.name = "MemoryAcquireDuplicateClaimError";
3567
3767
  }
3568
3768
  };
3569
- encoder = new TextEncoder();
3769
+ encoder2 = new TextEncoder();
3570
3770
  serializedBytes = /* @__PURE__ */ __name((value) => {
3571
3771
  const json = JSON.stringify(value);
3572
- return json === void 0 ? 0 : encoder.encode(json).length;
3772
+ return json === void 0 ? 0 : encoder2.encode(json).length;
3573
3773
  }, "serializedBytes");
3574
3774
  measureKnowledge = /* @__PURE__ */ __name((knowledge) => {
3575
3775
  const claimBytes = serializedBytes(knowledge);
@@ -3664,7 +3864,7 @@ var init_context_constants = __esm({
3664
3864
  });
3665
3865
 
3666
3866
  // core/knowledge/project.ts
3667
- var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_MAX_CHARACTERS, projectCandidate, GIST_MAX_LENGTH, GIST_KEYS, deriveIndexTopic, deriveIndexStatus, deriveGist, renderHeader, renderExperience, renderText, projectDiscoveredExperience, renderContextIndex, renderSizeDisclosure, renderProfileDocuments;
3867
+ var FORMAT, STATUS, NOTICE, DEFAULT_MAX_CANDIDATES, DEFAULT_MAX_CHARACTERS, MIN_MAX_CHARACTERS, projectCandidate, GIST_MAX_LENGTH, GIST_KEYS, MANIFEST_ID_LIMIT, deriveIndexTopic, deriveIndexStatus, deriveGist, renderHeader, renderExperience, renderText, byteLength, summarizeOmissions, renderManifestFitting, renderCompactExperience, projectDiscoveredExperience, renderContextIndex, renderExpandedClaim, renderSizeDisclosure, renderProfileDocuments;
3668
3868
  var init_project = __esm({
3669
3869
  "core/knowledge/project.ts"() {
3670
3870
  init_state();
@@ -3689,11 +3889,13 @@ var init_project = __esm({
3689
3889
  ...claim.provenance ? { provenance: claim.provenance } : {},
3690
3890
  ...claim.acquiredAt ? { acquiredAt: claim.acquiredAt } : {},
3691
3891
  ...claim.revision ? { revision: claim.revision } : {},
3692
- ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {}
3892
+ ...candidate.explanation.sourceId ? { sourceId: candidate.explanation.sourceId } : {},
3893
+ ...candidate.currentness ? { currentness: candidate.currentness } : {}
3693
3894
  });
3694
3895
  }, "projectCandidate");
3695
3896
  GIST_MAX_LENGTH = 80;
3696
3897
  GIST_KEYS = ["gist", "summary", "statement", "title", "reason", "principle", "finding", "detail"];
3898
+ MANIFEST_ID_LIMIT = 40;
3697
3899
  deriveIndexTopic = /* @__PURE__ */ __name((applicability) => {
3698
3900
  const topic = applicability.topic;
3699
3901
  if (typeof topic === "string" && topic.length > 0) return topic;
@@ -3743,27 +3945,70 @@ var init_project = __esm({
3743
3945
  evidence.supports ?? null
3744
3946
  ]),
3745
3947
  ...experience.epistemicType ? { epistemic: experience.epistemicType } : {},
3948
+ ...experience.currentness ? { currentness: experience.currentness } : {},
3746
3949
  ...experience.provenance ? { provenance: [experience.provenance.source, experience.provenance.detail ?? null] } : {},
3747
3950
  ...experience.acquiredAt ? { acquiredAt: experience.acquiredAt } : {},
3748
3951
  ...experience.revision ? { revision: experience.revision } : {},
3749
3952
  ...experience.sourceId ? { source: experience.sourceId } : {}
3750
3953
  }), "renderExperience");
3751
- renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates) => `${header}${experiences.length ? `
3752
- ${experiences.map(renderExperience).join("\n")}` : ""}
3753
- OMITTED:${omittedCandidates}`, "renderText");
3954
+ renderText = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, render = renderExperience, currentnessSummary) => {
3955
+ const lines = [header];
3956
+ if (experiences.length > 0) lines.push(...experiences.map(render));
3957
+ lines.push(`OMITTED:${omittedCandidates}`);
3958
+ if (manifest && manifest.byReason.length > 0) {
3959
+ lines.push(`OMITTED_BY_REASON:${manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`);
3960
+ }
3961
+ if (manifest && manifest.items.length > 0) {
3962
+ lines.push(`OMITTED_IDS:${manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`);
3963
+ if (manifest.items.length > MANIFEST_ID_LIMIT) {
3964
+ lines.push(`OMITTED_IDS_TRUNCATED:${manifest.items.length - MANIFEST_ID_LIMIT}`);
3965
+ }
3966
+ }
3967
+ if (currentnessSummary) {
3968
+ lines.push(`CURRENTNESS:${currentnessSummary}`);
3969
+ }
3970
+ return lines.join("\n");
3971
+ }, "renderText");
3972
+ byteLength = /* @__PURE__ */ __name((value) => new TextEncoder().encode(value).length, "byteLength");
3973
+ summarizeOmissions = /* @__PURE__ */ __name((items) => {
3974
+ const counts = /* @__PURE__ */ new Map();
3975
+ for (const item of items) counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
3976
+ return [...counts.entries()].map(([reason, count]) => ({ reason, count })).sort((left, right) => left.reason.localeCompare(right.reason));
3977
+ }, "summarizeOmissions");
3978
+ renderManifestFitting = /* @__PURE__ */ __name((header, experiences, omittedCandidates, manifest, maxCharacters, render, currentnessSummary) => {
3979
+ const full = renderText(header, experiences, omittedCandidates, manifest, render, currentnessSummary);
3980
+ if (byteLength(full) <= maxCharacters) return full;
3981
+ const withoutIds = { ...manifest, items: [] };
3982
+ return renderText(header, experiences, omittedCandidates, withoutIds, render, currentnessSummary);
3983
+ }, "renderManifestFitting");
3984
+ renderCompactExperience = /* @__PURE__ */ __name((experience) => JSON.stringify({
3985
+ id: experience.id,
3986
+ status: "candidate",
3987
+ gist: deriveGist(experience.experience),
3988
+ epistemic: experience.epistemicType ?? null,
3989
+ currentness: experience.currentness ?? null,
3990
+ ...experience.revision ? { revision: experience.revision.kind } : {}
3991
+ }), "renderCompactExperience");
3754
3992
  projectDiscoveredExperience = /* @__PURE__ */ __name((discovery, options = {}) => {
3755
3993
  if (!discovery || !Number.isInteger(discovery.knowledgeVersion) || discovery.knowledgeVersion < 0 || !Array.isArray(discovery.candidates)) {
3756
3994
  throw new Error("Valid DiscoveryResult is required for context projection");
3757
3995
  }
3758
3996
  const maxCandidates = options.maxCandidates ?? DEFAULT_MAX_CANDIDATES;
3759
3997
  const maxCharacters = options.maxCharacters ?? DEFAULT_MAX_CHARACTERS;
3998
+ const format = options.format ?? "compact";
3999
+ if (format !== "compact" && format !== "standard" && format !== "full") {
4000
+ throw new Error("Projection format must be compact, standard or full");
4001
+ }
3760
4002
  if (!Number.isInteger(maxCandidates) || maxCandidates < 1) throw new Error("Projection maxCandidates must be a positive integer");
3761
4003
  if (!Number.isInteger(maxCharacters) || maxCharacters < MIN_MAX_CHARACTERS) {
3762
4004
  throw new Error(`Projection maxCharacters must be an integer of at least ${MIN_MAX_CHARACTERS}`);
3763
4005
  }
3764
- const totalCandidates = discovery.candidates.length;
4006
+ const render = /* @__PURE__ */ __name((experience) => format === "compact" ? renderCompactExperience(experience) : renderExperience(experience), "render");
4007
+ const gateOmissions = discovery.omissions ?? [];
4008
+ const totalCandidates = discovery.candidates.length + gateOmissions.length;
3765
4009
  const header = renderHeader(discovery.knowledgeVersion, totalCandidates);
3766
- if (renderText(header, [], totalCandidates).length > maxCharacters) {
4010
+ const emptyManifest = { considered: totalCandidates, included: 0, items: [], byReason: [] };
4011
+ if (byteLength(renderText(header, [], totalCandidates, emptyManifest)) > maxCharacters) {
3767
4012
  throw new Error("Projection maxCharacters is too small for the projection envelope");
3768
4013
  }
3769
4014
  const experiences = [];
@@ -3772,12 +4017,49 @@ OMITTED:${omittedCandidates}`, "renderText");
3772
4017
  const projected = projectCandidate(candidate);
3773
4018
  const possibleExperiences = [...experiences, projected];
3774
4019
  const possibleOmitted = totalCandidates - possibleExperiences.length;
3775
- if (renderText(header, possibleExperiences, possibleOmitted).length <= maxCharacters) {
4020
+ const candidateManifest = {
4021
+ considered: totalCandidates,
4022
+ included: possibleExperiences.length,
4023
+ items: gateOmissions,
4024
+ byReason: summarizeOmissions(gateOmissions)
4025
+ };
4026
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, candidateManifest, render)) <= maxCharacters) {
4027
+ experiences.push(projected);
4028
+ continue;
4029
+ }
4030
+ if (byteLength(renderText(header, possibleExperiences, possibleOmitted, void 0, render)) <= maxCharacters) {
3776
4031
  experiences.push(projected);
3777
4032
  }
3778
4033
  }
4034
+ const projectedIds = new Set(experiences.map((experience) => experience.id));
4035
+ const budgetOmissions = discovery.candidates.filter((candidate) => !projectedIds.has(candidate.claim.id)).map((candidate) => ({ id: candidate.claim.id, reason: "budget", gate: "projection" }));
4036
+ const items = [...gateOmissions, ...budgetOmissions];
3779
4037
  const omittedCandidates = totalCandidates - experiences.length;
3780
- const text = renderText(header, experiences, omittedCandidates);
4038
+ const manifest = {
4039
+ considered: totalCandidates,
4040
+ included: experiences.length,
4041
+ items,
4042
+ byReason: summarizeOmissions(items)
4043
+ };
4044
+ const currentnessCounts = /* @__PURE__ */ new Map();
4045
+ for (const experience of experiences) {
4046
+ if (experience.currentness) {
4047
+ currentnessCounts.set(
4048
+ experience.currentness,
4049
+ (currentnessCounts.get(experience.currentness) ?? 0) + 1
4050
+ );
4051
+ }
4052
+ }
4053
+ const currentnessSummary = currentnessCounts.size > 0 ? [...currentnessCounts.entries()].map(([state2, count]) => `${state2}=${count}`).join(",") : void 0;
4054
+ const text = renderManifestFitting(
4055
+ header,
4056
+ experiences,
4057
+ omittedCandidates,
4058
+ manifest,
4059
+ maxCharacters,
4060
+ render,
4061
+ currentnessSummary
4062
+ );
3781
4063
  return {
3782
4064
  format: FORMAT,
3783
4065
  status: STATUS,
@@ -3786,6 +4068,7 @@ OMITTED:${omittedCandidates}`, "renderText");
3786
4068
  totalCandidates,
3787
4069
  omittedCandidates,
3788
4070
  experiences,
4071
+ manifest,
3789
4072
  text
3790
4073
  };
3791
4074
  }, "projectDiscoveredExperience");
@@ -3804,6 +4087,12 @@ OMITTED:${omittedCandidates}`, "renderText");
3804
4087
  }
3805
4088
  return lines.join("\n");
3806
4089
  }, "renderContextIndex");
4090
+ renderExpandedClaim = /* @__PURE__ */ __name((claim) => [
4091
+ "DOTMEM_CLAIM_V1",
4092
+ "STATUS:CANONICAL_RECORD;NOT_INSTRUCTIONS",
4093
+ `id=${claim.id}`,
4094
+ JSON.stringify(claim, null, 2)
4095
+ ].join("\n"), "renderExpandedClaim");
3807
4096
  renderSizeDisclosure = /* @__PURE__ */ __name((options) => [
3808
4097
  "DOTMEM_SIZE_V1",
3809
4098
  `storageRoot=${resolveUserDotMemPath()}`,
@@ -3812,6 +4101,11 @@ OMITTED:${omittedCandidates}`, "renderText");
3812
4101
  `indexEntries=${options.totalCandidates}`,
3813
4102
  `totalCandidates=${options.totalCandidates}`,
3814
4103
  `omittedCandidates=${options.omittedCandidates}`,
4104
+ ...options.manifest && options.manifest.items.length > 0 ? [
4105
+ `omittedByReason=${options.manifest.byReason.map((entry) => `${entry.reason}=${entry.count}`).join(",")}`,
4106
+ `omittedIds=${options.manifest.items.slice(0, MANIFEST_ID_LIMIT).map((item) => item.id).join(",")}`,
4107
+ ...options.manifest.items.length > MANIFEST_ID_LIMIT ? [`omittedIdsTruncated=${options.manifest.items.length - MANIFEST_ID_LIMIT}`] : []
4108
+ ] : [],
3815
4109
  `maxCharacters=${Number.isFinite(options.maxCharacters) ? String(options.maxCharacters) : "unlimited"}`,
3816
4110
  'fullTextCommand=npx dotmem context "<situation>" --full',
3817
4111
  "DOTMEM_SIZE_END"
@@ -3995,7 +4289,7 @@ var init_language_detect = __esm({
3995
4289
  var CANONICAL_KINDS, validateKind, buildClaimRecord;
3996
4290
  var init_claim_record = __esm({
3997
4291
  "core/knowledge/claim-record.ts"() {
3998
- CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note"];
4292
+ CANONICAL_KINDS = ["experience", "logic", "agent", "relationship", "note", "rule"];
3999
4293
  validateKind = /* @__PURE__ */ __name((kind) => {
4000
4294
  if (!CANONICAL_KINDS.includes(kind)) {
4001
4295
  throw new Error(
@@ -5401,8 +5695,8 @@ var init_browser = __esm({
5401
5695
  this.p = null;
5402
5696
  }
5403
5697
  };
5404
- Unzip2.prototype.register = function(decoder2) {
5405
- this.o[decoder2.compression] = decoder2;
5698
+ Unzip2.prototype.register = function(decoder) {
5699
+ this.o[decoder.compression] = decoder;
5406
5700
  };
5407
5701
  return Unzip2;
5408
5702
  })();
@@ -5422,6 +5716,15 @@ function encodeMemFile(stateValue, preserved) {
5422
5716
  if (!map.claim.includes("kind")) {
5423
5717
  map.claim.push("kind");
5424
5718
  }
5719
+ if (!map.claim.includes("expires-at")) {
5720
+ map.claim.push("expires-at");
5721
+ }
5722
+ if (!map.claim.includes("bootstrap-priority")) {
5723
+ map.claim.push("bootstrap-priority");
5724
+ }
5725
+ if (!map.claim.includes("check")) {
5726
+ map.claim.push("check");
5727
+ }
5425
5728
  const indexes = Object.fromEntries(Object.keys(expectedFields).map((name) => [name, fieldIndexes(map, name)]));
5426
5729
  validateVocabulary(map.epistemicType, epistemicTypes, "epistemicType");
5427
5730
  validateVocabulary(map.revisionKind, revisionKinds, "revisionKind");
@@ -5471,6 +5774,15 @@ function encodeMemFile(stateValue, preserved) {
5471
5774
  if (indexes.claim.has("kind")) {
5472
5775
  putOptional(record, indexes.claim, "kind", claim.kind ?? void 0, original !== void 0);
5473
5776
  }
5777
+ if (indexes.claim.has("expires-at")) {
5778
+ putOptional(record, indexes.claim, "expires-at", claim.expiresAt, original !== void 0);
5779
+ }
5780
+ if (indexes.claim.has("bootstrap-priority")) {
5781
+ putOptional(record, indexes.claim, "bootstrap-priority", claim.bootstrapPriority, original !== void 0);
5782
+ }
5783
+ if (indexes.claim.has("check")) {
5784
+ putOptional(record, indexes.claim, "check", claim.check, original !== void 0);
5785
+ }
5474
5786
  return original ? record : trimRecord(record);
5475
5787
  }, "encodeClaim");
5476
5788
  const stateRecord = structuredClone(preserved?.data ?? []);
@@ -5539,8 +5851,37 @@ function decodeMemDocument(value) {
5539
5851
  const scope = optionalGet(record, indexes.claim, "scope");
5540
5852
  const sourceProject = optionalGet(record, indexes.claim, "source-project");
5541
5853
  const kindValue = optionalGet(record, indexes.claim, "kind");
5854
+ const expiresAtValue = indexes.claim.has("expires-at") ? optionalGet(record, indexes.claim, "expires-at") : void 0;
5855
+ const bootstrapPriorityValue = indexes.claim.has("bootstrap-priority") ? optionalGet(record, indexes.claim, "bootstrap-priority") : void 0;
5856
+ const checkValue = indexes.claim.has("check") ? optionalGet(record, indexes.claim, "check") : void 0;
5542
5857
  if (epistemicIndex !== void 0 && (!Number.isInteger(epistemicIndex) || epistemicIndex < 0 || epistemicIndex >= epistemic.length)) throw new Error("Invalid .mem epistemic value");
5543
5858
  if (kindIndex !== void 0 && (!Number.isInteger(kindIndex) || kindIndex < 0 || kindIndex >= revisions.length)) throw new Error("Invalid .mem revision value");
5859
+ if (expiresAtValue !== void 0 && (!Number.isInteger(expiresAtValue) || expiresAtValue < 0)) {
5860
+ throw new Error("Invalid .mem expiresAt value");
5861
+ }
5862
+ if (bootstrapPriorityValue !== void 0 && !bootstrapPriorities.includes(bootstrapPriorityValue)) {
5863
+ throw new Error("Invalid .mem bootstrapPriority value");
5864
+ }
5865
+ let check;
5866
+ if (checkValue !== void 0) {
5867
+ if (!checkValue || typeof checkValue !== "object" || Array.isArray(checkValue)) {
5868
+ throw new Error("Invalid .mem check record");
5869
+ }
5870
+ const checkRecord = checkValue;
5871
+ const description = checkRecord.description;
5872
+ if (typeof description !== "undefined" && typeof description !== "string") {
5873
+ throw new Error("Invalid .mem check record");
5874
+ }
5875
+ if (checkRecord.kind !== "regex" || typeof checkRecord.pattern !== "string" || checkRecord.pattern.length === 0 || !checkTargets.includes(checkRecord.on)) {
5876
+ throw new Error("Invalid .mem check record");
5877
+ }
5878
+ check = {
5879
+ kind: "regex",
5880
+ pattern: checkRecord.pattern,
5881
+ on: checkRecord.on,
5882
+ ...typeof description === "string" ? { description } : {}
5883
+ };
5884
+ }
5544
5885
  const understoodEpistemic = typeof epistemicIndex === "number" && epistemicTypes.includes(epistemic[epistemicIndex]) ? epistemic[epistemicIndex] : void 0;
5545
5886
  const understoodRevision = typeof kindIndex === "number" && revisionKinds.includes(revisions[kindIndex]);
5546
5887
  const claim = {
@@ -5565,6 +5906,9 @@ function decodeMemDocument(value) {
5565
5906
  } : {},
5566
5907
  ...scope === void 0 ? {} : { scope },
5567
5908
  ...sourceProject === void 0 ? {} : { sourceProject },
5909
+ ...expiresAtValue === void 0 ? {} : { expiresAt: expiresAtValue },
5910
+ ...bootstrapPriorityValue === void 0 ? {} : { bootstrapPriority: bootstrapPriorityValue },
5911
+ ...check === void 0 ? {} : { check },
5568
5912
  ...claimKinds.includes(kindValue) ? { kind: kindValue } : {}
5569
5913
  };
5570
5914
  return validateClaim(claim);
@@ -5574,7 +5918,7 @@ function decodeMemDocument(value) {
5574
5918
  preserved: { map: structuredClone(map), data: structuredClone(stateRecord) }
5575
5919
  };
5576
5920
  }
5577
- var MEM_FORMAT, MEM_FORMAT_LEGACY, MEM_FORMAT_VERSION, MEM_FORMAT_VERSION_V1, expectedFields, epistemicTypes, revisionKinds, claimKinds, isJsonValue2, createMemInterpretationMap, validateSourceState, trimRecord, fieldIndexes, validateVocabulary, put, get, optionalGet, requireRecord, putOptional;
5921
+ var MEM_FORMAT, MEM_FORMAT_LEGACY, MEM_FORMAT_VERSION, MEM_FORMAT_VERSION_V1, expectedFields, epistemicTypes, revisionKinds, claimKinds, bootstrapPriorities, checkTargets, isJsonValue2, createMemInterpretationMap, validateSourceState, trimRecord, fieldIndexes, validateVocabulary, put, get, optionalGet, requireRecord, putOptional;
5578
5922
  var init_mem_codec = __esm({
5579
5923
  "core/knowledge/mem-codec.ts"() {
5580
5924
  init_state();
@@ -5591,7 +5935,9 @@ var init_mem_codec = __esm({
5591
5935
  };
5592
5936
  epistemicTypes = ["observed", "inferred", "human-stated", "verified"];
5593
5937
  revisionKinds = ["refines", "supersedes", "retracts"];
5594
- claimKinds = ["experience", "agent", "relationship", "logic", "note"];
5938
+ claimKinds = ["experience", "agent", "relationship", "logic", "note", "rule"];
5939
+ bootstrapPriorities = ["P1", "P2", "P3", "P4", "P5", "unclassified"];
5940
+ checkTargets = ["staged", "committed", "working-tree"];
5595
5941
  isJsonValue2 = /* @__PURE__ */ __name((value) => {
5596
5942
  if (value === null || typeof value === "string" || typeof value === "boolean") return true;
5597
5943
  if (typeof value === "number") return Number.isFinite(value);
@@ -5695,14 +6041,14 @@ async function signMemPackage(input, privateKey, publicKey) {
5695
6041
  });
5696
6042
  }
5697
6043
  async function decodeMemArtifact(input) {
5698
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
6044
+ const bytes = typeof input === "string" ? encoder3.encode(input) : input;
5699
6045
  if (isZip(bytes)) {
5700
6046
  const { parts: _parts, integrity: _integrity, ...artifact } = await decodePackage(bytes);
5701
6047
  return artifact;
5702
6048
  }
5703
6049
  let value;
5704
6050
  try {
5705
- value = JSON.parse(decoder.decode(bytes).replace(/^\uFEFF/, ""));
6051
+ value = JSON.parse(decodeText(bytes));
5706
6052
  } catch (error) {
5707
6053
  throw new MemArtifactError("corrupt", `Unsupported or corrupt MEM artifact: ${error.message}`);
5708
6054
  }
@@ -5717,7 +6063,7 @@ async function decodeMemArtifact(input) {
5717
6063
  }
5718
6064
  async function inspectMem(input) {
5719
6065
  try {
5720
- const bytes = typeof input === "string" ? encoder2.encode(input) : input;
6066
+ const bytes = typeof input === "string" ? encodeText(input) : input;
5721
6067
  if (isZip(bytes)) {
5722
6068
  const artifact2 = await decodePackage(bytes);
5723
6069
  const knownMapKeys = /* @__PURE__ */ new Set(["state", "claim", "evidence", "provenance", "revision", "epistemicType", "revisionKind"]);
@@ -5758,11 +6104,12 @@ async function inspectMem(input) {
5758
6104
  return { status: artifactError.code, representation: "unknown", message: artifactError.message, parts: [] };
5759
6105
  }
5760
6106
  }
5761
- var MEM_PACKAGE_FORMAT, MEM_PACKAGE_FORMAT_LEGACY, MEM_PACKAGE_VERSION, MEM_PACKAGE_LIMITS, MEM_PACKAGE_WRITE_MARGIN_BYTES, MEM_PACKAGE_WRITE_LIMITS, MANIFEST_PATH, MAP_PATH, DATA_PATH, INTEGRITY_PATH, requiredParts, encoder2, decoder, MemArtifactError, stableValue, jsonBytes, sha256, parseJson, validEntryPath, concatenate, readZipParts, createManifest, digestTableIdentity, signaturePayload, base64UrlEncode, base64UrlDecode, keyIdentity, signaturePath, encodePackage, isZip, decodePackage, verifySignature;
6107
+ var MEM_PACKAGE_FORMAT, MEM_PACKAGE_FORMAT_LEGACY, MEM_PACKAGE_VERSION, MEM_PACKAGE_LIMITS, MEM_PACKAGE_WRITE_MARGIN_BYTES, MEM_PACKAGE_WRITE_LIMITS, MANIFEST_PATH, MAP_PATH, DATA_PATH, INTEGRITY_PATH, requiredParts, encoder3, MemArtifactError, stableValue, jsonBytes, sha256, parseJson, validEntryPath, concatenate, readZipParts, createManifest, digestTableIdentity, signaturePayload, base64UrlEncode, base64UrlDecode, keyIdentity, signaturePath, encodePackage, isZip, decodePackage, verifySignature;
5762
6108
  var init_mem_package = __esm({
5763
6109
  "core/knowledge/mem-package.ts"() {
5764
6110
  init_browser();
5765
6111
  init_mem_codec();
6112
+ init_text_encoding();
5766
6113
  MEM_PACKAGE_FORMAT = "dotmem.package";
5767
6114
  MEM_PACKAGE_FORMAT_LEGACY = "memorio.package";
5768
6115
  MEM_PACKAGE_VERSION = 1;
@@ -5786,8 +6133,7 @@ var init_mem_package = __esm({
5786
6133
  DATA_PATH = "memory/data.json";
5787
6134
  INTEGRITY_PATH = "security/integrity.json";
5788
6135
  requiredParts = [MANIFEST_PATH, MAP_PATH, DATA_PATH];
5789
- encoder2 = new TextEncoder();
5790
- decoder = new TextDecoder("utf-8", { fatal: true });
6136
+ encoder3 = new TextEncoder();
5791
6137
  MemArtifactError = class extends Error {
5792
6138
  constructor(code, message) {
5793
6139
  super(message);
@@ -5806,7 +6152,7 @@ var init_mem_package = __esm({
5806
6152
  }
5807
6153
  return value;
5808
6154
  }, "stableValue");
5809
- jsonBytes = /* @__PURE__ */ __name((value) => encoder2.encode(`${JSON.stringify(stableValue(value), null, 2)}
6155
+ jsonBytes = /* @__PURE__ */ __name((value) => encoder3.encode(`${JSON.stringify(stableValue(value), null, 2)}
5810
6156
  `), "jsonBytes");
5811
6157
  sha256 = /* @__PURE__ */ __name(async (data) => {
5812
6158
  if (!globalThis.crypto?.subtle) throw new MemArtifactError("unsupported", "SHA-256 is unavailable in this runtime");
@@ -5815,7 +6161,7 @@ var init_mem_package = __esm({
5815
6161
  }, "sha256");
5816
6162
  parseJson = /* @__PURE__ */ __name((bytes, path5) => {
5817
6163
  try {
5818
- return JSON.parse(decoder.decode(bytes));
6164
+ return JSON.parse(decodeText(bytes));
5819
6165
  } catch (error) {
5820
6166
  throw new MemArtifactError("invalid", `Invalid UTF-8 JSON in ${path5}: ${error.message}`);
5821
6167
  }
@@ -5881,7 +6227,7 @@ var init_mem_package = __esm({
5881
6227
  parts: { map: MAP_PATH, data: DATA_PATH, integrity: INTEGRITY_PATH }
5882
6228
  }), "createManifest");
5883
6229
  digestTableIdentity = /* @__PURE__ */ __name((files) => sha256(jsonBytes(files)), "digestTableIdentity");
5884
- signaturePayload = /* @__PURE__ */ __name((contentId) => encoder2.encode(`DOTMEM-PACKAGE-SIGNATURE-V1
6230
+ signaturePayload = /* @__PURE__ */ __name((contentId) => encoder3.encode(`DOTMEM-PACKAGE-SIGNATURE-V1
5885
6231
  ${contentId}
5886
6232
  `), "signaturePayload");
5887
6233
  base64UrlEncode = /* @__PURE__ */ __name((value) => {
@@ -6071,10 +6417,12 @@ ${contentId}
6071
6417
  });
6072
6418
 
6073
6419
  // core/storage-coordinator/index.ts
6074
- var nodeFs4, withStorageLock, readStorageGeneration, writeStorageGeneration;
6420
+ var nodeFs4, heldLocks, withStorageLock, readStorageGeneration, writeStorageGeneration;
6075
6421
  var init_storage_coordinator = __esm({
6076
6422
  "core/storage-coordinator/index.ts"() {
6423
+ init_text_encoding();
6077
6424
  nodeFs4 = /* @__PURE__ */ __name(async () => import('fs/promises'), "nodeFs");
6425
+ heldLocks = /* @__PURE__ */ new Map();
6078
6426
  withStorageLock = /* @__PURE__ */ __name(async (directoryPath, operationOrOptions, operation, _options = {}) => {
6079
6427
  const opts = typeof operationOrOptions === "function" ? operation ?? {} : operationOrOptions ?? {};
6080
6428
  const op = typeof operationOrOptions === "function" ? operationOrOptions : operation;
@@ -6084,6 +6432,15 @@ var init_storage_coordinator = __esm({
6084
6432
  const lockPath = `${directoryPath}/${lockName}`;
6085
6433
  const fs7 = await nodeFs4();
6086
6434
  const started = Date.now();
6435
+ const heldDepth = heldLocks.get(lockPath) ?? 0;
6436
+ if (heldDepth > 0) {
6437
+ heldLocks.set(lockPath, heldDepth + 1);
6438
+ try {
6439
+ return await op();
6440
+ } finally {
6441
+ heldLocks.set(lockPath, heldDepth);
6442
+ }
6443
+ }
6087
6444
  await fs7.mkdir(directoryPath, { recursive: true });
6088
6445
  while (true) {
6089
6446
  try {
@@ -6097,8 +6454,8 @@ var init_storage_coordinator = __esm({
6097
6454
  let stale = false;
6098
6455
  let processDead = false;
6099
6456
  try {
6100
- const raw = await fs7.readFile(`${lockPath}/owner.json`, "utf8");
6101
- const parsed = JSON.parse(raw);
6457
+ const raw = await fs7.readFile(`${lockPath}/owner.json`);
6458
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
6102
6459
  const ageStale = typeof parsed.createdAt === "number" && Date.now() - parsed.createdAt > staleMs;
6103
6460
  if (typeof parsed.pid === "number") {
6104
6461
  try {
@@ -6135,17 +6492,19 @@ var init_storage_coordinator = __esm({
6135
6492
  }
6136
6493
  let token = "";
6137
6494
  try {
6138
- const raw = await fs7.readFile(`${lockPath}/owner.json`, "utf8");
6139
- token = JSON.parse(raw).token ?? "";
6495
+ const raw = await fs7.readFile(`${lockPath}/owner.json`);
6496
+ token = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` })).token ?? "";
6140
6497
  } catch {
6141
6498
  token = "";
6142
6499
  }
6143
6500
  try {
6501
+ heldLocks.set(lockPath, 1);
6144
6502
  return await op();
6145
6503
  } finally {
6504
+ heldLocks.delete(lockPath);
6146
6505
  try {
6147
- const raw = await fs7.readFile(`${lockPath}/owner.json`, "utf8");
6148
- const parsed = JSON.parse(raw);
6506
+ const raw = await fs7.readFile(`${lockPath}/owner.json`);
6507
+ const parsed = JSON.parse(decodeText(raw, { source: `${lockPath}/owner.json` }));
6149
6508
  if (parsed.token === token && token) {
6150
6509
  await fs7.rm(lockPath, { recursive: true, force: true });
6151
6510
  }
@@ -6156,8 +6515,8 @@ var init_storage_coordinator = __esm({
6156
6515
  readStorageGeneration = /* @__PURE__ */ __name(async (directoryPath) => {
6157
6516
  const fs7 = await nodeFs4();
6158
6517
  try {
6159
- const raw = await fs7.readFile(`${directoryPath}/.storage.generation`, "utf8");
6160
- const value = Number(raw.trim());
6518
+ const raw = await fs7.readFile(`${directoryPath}/.storage.generation`);
6519
+ const value = Number(decodeText(raw, { source: `${directoryPath}/.storage.generation` }).trim());
6161
6520
  return Number.isFinite(value) && value >= 0 ? value : 0;
6162
6521
  } catch {
6163
6522
  return 0;
@@ -6686,12 +7045,11 @@ function readJsonFile(path5) {
6686
7045
  if (!fs7) return null;
6687
7046
  let raw;
6688
7047
  try {
6689
- raw = fs7.readFileSync(path5, "utf8");
7048
+ raw = decodeText(fs7.readFileSync(path5), { source: path5 });
6690
7049
  } catch {
6691
7050
  return null;
6692
7051
  }
6693
7052
  if (typeof raw !== "string") return null;
6694
- if (raw.charCodeAt(0) === 65279) raw = raw.slice(1);
6695
7053
  try {
6696
7054
  return JSON.parse(raw);
6697
7055
  } catch {
@@ -6815,6 +7173,7 @@ var init_user_language = __esm({
6815
7173
  "core/knowledge/user-language.ts"() {
6816
7174
  init_user_paths();
6817
7175
  init_storage_paths();
7176
+ init_text_encoding();
6818
7177
  USER_LANGUAGE_FILE_NAME = "language.json";
6819
7178
  USER_LANGUAGE_PREFERENCE_FILE_NAME = "user-language.json";
6820
7179
  LANGUAGE_PREFERENCE_FILE_NAME = "language-preference.json";
@@ -10970,10 +11329,13 @@ var init_staging = __esm({
10970
11329
  epistemicType: sanitizedClaim.epistemicType,
10971
11330
  provenance: sanitizedClaim.provenance,
10972
11331
  acquiredAt: sanitizedClaim.acquiredAt,
11332
+ ...sanitizedClaim.expiresAt === void 0 ? {} : { expiresAt: sanitizedClaim.expiresAt },
11333
+ ...sanitizedClaim.bootstrapPriority === void 0 ? {} : { bootstrapPriority: sanitizedClaim.bootstrapPriority },
10973
11334
  revision,
10974
11335
  scope,
10975
11336
  sourceProject,
10976
- kind
11337
+ kind,
11338
+ ...sanitizedClaim.check === void 0 ? {} : { check: sanitizedClaim.check }
10977
11339
  });
10978
11340
  await withStoreQueue(acquisitionStoreKey(kind, scope, sourceProject), async () => {
10979
11341
  const state2 = await target.runtime.select([]);
@@ -12267,87 +12629,6 @@ var init_incidents = __esm({
12267
12629
  }
12268
12630
  });
12269
12631
 
12270
- // core/knowledge/rules-loader.ts
12271
- function isRuleClaim(claim) {
12272
- const knowledge = claim.knowledge;
12273
- return knowledge?.kind === "rule";
12274
- }
12275
- function isIronRule(claim) {
12276
- return claim.epistemicType === "human-stated" && isRuleClaim(claim);
12277
- }
12278
- function extractIronRules(state2) {
12279
- const validated = validateKnowledgeState(state2);
12280
- const claims = activeClaims(validated);
12281
- const rules = [];
12282
- for (const claim of claims) {
12283
- if (!isIronRule(claim)) continue;
12284
- const knowledge = claim.knowledge;
12285
- const applicability = claim.applicability;
12286
- const iron = applicability.iron === true || applicability.priority === "iron";
12287
- if (!iron) continue;
12288
- rules.push({
12289
- id: claim.id,
12290
- text: String(knowledge.text ?? knowledge.rule ?? claim.id),
12291
- why: String(knowledge.why ?? knowledge.reason ?? ""),
12292
- appliesWhen: String(knowledge.appliesWhen ?? knowledge.when ?? ""),
12293
- violatedOn: Array.isArray(knowledge.violatedOn) ? knowledge.violatedOn : void 0,
12294
- lastViolation: typeof knowledge.lastViolation === "string" ? knowledge.lastViolation : void 0,
12295
- frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : 0
12296
- });
12297
- }
12298
- return rules;
12299
- }
12300
- function sortRulesByViolationFrequency(rules) {
12301
- return [...rules].sort((a, b) => {
12302
- if (b.frequency !== a.frequency) return b.frequency - a.frequency;
12303
- if (a.lastViolation && b.lastViolation) {
12304
- return b.lastViolation.localeCompare(a.lastViolation);
12305
- }
12306
- return 0;
12307
- });
12308
- }
12309
- function loadIronRules(state2) {
12310
- const rules = sortRulesByViolationFrequency(extractIronRules(state2));
12311
- return {
12312
- rules,
12313
- count: rules.length,
12314
- sortedBy: "violation-frequency"
12315
- };
12316
- }
12317
- function formatRulesForSessionStart(rules) {
12318
- if (rules.length === 0) {
12319
- return "";
12320
- }
12321
- const lines = ["---", "IRON RULES (must always arrive)", "---"];
12322
- for (const rule of rules) {
12323
- lines.push(`${rule.id}: ${rule.text}`);
12324
- }
12325
- return lines.join("\n");
12326
- }
12327
- function formatRuleWithExplanation(rule) {
12328
- const parts = [];
12329
- parts.push(`[${rule.id}] ${rule.text}`);
12330
- if (rule.why) parts.push(` WHY: ${rule.why}`);
12331
- if (rule.appliesWhen) parts.push(` APPLIES WHEN: ${rule.appliesWhen}`);
12332
- if (rule.violatedOn && rule.violatedOn.length > 0) {
12333
- parts.push(` VIOLATED ${rule.violatedOn.length} TIME(S)`);
12334
- if (rule.lastViolation) parts.push(` Last: ${rule.lastViolation}`);
12335
- }
12336
- return parts.join("\n");
12337
- }
12338
- var init_rules_loader = __esm({
12339
- "core/knowledge/rules-loader.ts"() {
12340
- init_state();
12341
- __name(isRuleClaim, "isRuleClaim");
12342
- __name(isIronRule, "isIronRule");
12343
- __name(extractIronRules, "extractIronRules");
12344
- __name(sortRulesByViolationFrequency, "sortRulesByViolationFrequency");
12345
- __name(loadIronRules, "loadIronRules");
12346
- __name(formatRulesForSessionStart, "formatRulesForSessionStart");
12347
- __name(formatRuleWithExplanation, "formatRuleWithExplanation");
12348
- }
12349
- });
12350
-
12351
12632
  // core/knowledge/violations.ts
12352
12633
  function joinPath8(base, child) {
12353
12634
  const separator3 = process.platform === "win32" ? "\\" : "/";
@@ -12443,6 +12724,122 @@ var init_violations = __esm({
12443
12724
  __name(clearViolations, "clearViolations");
12444
12725
  }
12445
12726
  });
12727
+ function isRuleClaim(claim) {
12728
+ const knowledge = claim.knowledge;
12729
+ return knowledge?.kind === "rule";
12730
+ }
12731
+ function isIronRule(claim) {
12732
+ return claim.epistemicType === "human-stated" && isRuleClaim(claim);
12733
+ }
12734
+ function extractIronRules(state2, violations = {}) {
12735
+ const validated = validateKnowledgeState(state2);
12736
+ const claims = activeClaims(validated);
12737
+ const rules = [];
12738
+ for (const claim of claims) {
12739
+ if (!isIronRule(claim)) continue;
12740
+ const knowledge = claim.knowledge;
12741
+ const applicability = claim.applicability;
12742
+ const iron = applicability.iron === true || applicability.priority === "iron";
12743
+ if (!iron) continue;
12744
+ rules.push({
12745
+ id: claim.id,
12746
+ text: String(knowledge.text ?? knowledge.rule ?? claim.id),
12747
+ why: String(knowledge.why ?? knowledge.reason ?? ""),
12748
+ appliesWhen: String(knowledge.appliesWhen ?? knowledge.when ?? ""),
12749
+ violatedOn: Array.isArray(knowledge.violatedOn) ? knowledge.violatedOn : void 0,
12750
+ lastViolation: typeof knowledge.lastViolation === "string" ? knowledge.lastViolation : void 0,
12751
+ frequency: typeof knowledge.frequency === "number" ? knowledge.frequency : violations[claim.id] ?? 0
12752
+ });
12753
+ }
12754
+ return rules;
12755
+ }
12756
+ function sortRulesByViolationFrequency(rules) {
12757
+ return [...rules].sort((a, b) => {
12758
+ if (b.frequency !== a.frequency) return b.frequency - a.frequency;
12759
+ if (a.lastViolation && b.lastViolation) {
12760
+ return b.lastViolation.localeCompare(a.lastViolation);
12761
+ }
12762
+ return 0;
12763
+ });
12764
+ }
12765
+ function loadIronRules(state2) {
12766
+ const rules = sortRulesByViolationFrequency(
12767
+ extractIronRules(state2, readViolationCounts(`${resolveUserDotMemPath()}/${VIOLATION_FILE_NAME}`))
12768
+ );
12769
+ return {
12770
+ rules,
12771
+ count: rules.length,
12772
+ sortedBy: "violation-frequency"
12773
+ };
12774
+ }
12775
+ function formatRulesForSessionStart(rules) {
12776
+ if (rules.length === 0) {
12777
+ return "";
12778
+ }
12779
+ const lines = ["---", "IRON RULES (must always arrive)", "---"];
12780
+ for (const rule of rules) {
12781
+ lines.push(`${rule.id}: ${rule.text}`);
12782
+ }
12783
+ return lines.join("\n");
12784
+ }
12785
+ function formatRuleWithExplanation(rule) {
12786
+ const parts = [];
12787
+ parts.push(`[${rule.id}] ${rule.text}`);
12788
+ if (rule.why) parts.push(` WHY: ${rule.why}`);
12789
+ if (rule.appliesWhen) parts.push(` APPLIES WHEN: ${rule.appliesWhen}`);
12790
+ if (rule.violatedOn && rule.violatedOn.length > 0) {
12791
+ parts.push(` VIOLATED ${rule.violatedOn.length} TIME(S)`);
12792
+ if (rule.lastViolation) parts.push(` Last: ${rule.lastViolation}`);
12793
+ }
12794
+ return parts.join("\n");
12795
+ }
12796
+ var readViolationCounts, ruleSetSignature, formatRulesReference;
12797
+ var init_rules_loader = __esm({
12798
+ "core/knowledge/rules-loader.ts"() {
12799
+ init_state();
12800
+ init_user_paths();
12801
+ init_violations();
12802
+ __name(isRuleClaim, "isRuleClaim");
12803
+ __name(isIronRule, "isIronRule");
12804
+ __name(extractIronRules, "extractIronRules");
12805
+ readViolationCounts = /* @__PURE__ */ __name((file) => {
12806
+ try {
12807
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
12808
+ const counts = {};
12809
+ for (const violation of Array.isArray(parsed.violations) ? parsed.violations : []) {
12810
+ const ruleId = typeof violation?.ruleId === "string" ? violation.ruleId : "";
12811
+ if (!ruleId) continue;
12812
+ counts[ruleId] = (counts[ruleId] ?? 0) + 1;
12813
+ }
12814
+ return counts;
12815
+ } catch {
12816
+ return {};
12817
+ }
12818
+ }, "readViolationCounts");
12819
+ __name(sortRulesByViolationFrequency, "sortRulesByViolationFrequency");
12820
+ __name(loadIronRules, "loadIronRules");
12821
+ ruleSetSignature = /* @__PURE__ */ __name((rules) => {
12822
+ const material = rules.map((rule) => `${rule.id}\0${rule.text}`).join("");
12823
+ let hash = 2166136261;
12824
+ for (let index = 0; index < material.length; index += 1) {
12825
+ hash ^= material.charCodeAt(index);
12826
+ hash = Math.imul(hash, 16777619) >>> 0;
12827
+ }
12828
+ return hash.toString(16).padStart(8, "0");
12829
+ }, "ruleSetSignature");
12830
+ formatRulesReference = /* @__PURE__ */ __name((rules) => {
12831
+ if (rules.length === 0) return "DOTMEM_IRON_RULES_V1\ncount=0";
12832
+ return [
12833
+ "DOTMEM_IRON_RULES_V1",
12834
+ `count=${rules.length}`,
12835
+ `signature=${ruleSetSignature(rules)}`,
12836
+ `ids=${rules.map((rule) => rule.id).join(",")}`
12837
+ ].join("\n");
12838
+ }, "formatRulesReference");
12839
+ __name(formatRulesForSessionStart, "formatRulesForSessionStart");
12840
+ __name(formatRuleWithExplanation, "formatRuleWithExplanation");
12841
+ }
12842
+ });
12446
12843
 
12447
12844
  // core/knowledge/session.ts
12448
12845
  function joinPath9(base, child) {
@@ -13138,8 +13535,8 @@ function loadBuiltInContext() {
13138
13535
  for (const candidate of candidates) {
13139
13536
  if (!fs2.existsSync(candidate)) continue;
13140
13537
  try {
13141
- const raw = fs2.readFileSync(candidate, "utf8");
13142
- const parsed = JSON.parse(raw);
13538
+ const raw = fs2.readFileSync(candidate);
13539
+ const parsed = JSON.parse(decodeText(raw, { source: candidate }));
13143
13540
  const artifact = validateArtifact(parsed);
13144
13541
  cached = artifact;
13145
13542
  cachedStatus = {
@@ -13222,6 +13619,7 @@ function resetBuiltInContextCache() {
13222
13619
  var BUILT_IN_CONTEXT_FORMAT, BUILT_IN_CONTEXT_FORMAT_VERSION, cached, cachedStatus, _artifactPathOverride;
13223
13620
  var init_built_in_context = __esm({
13224
13621
  "core/knowledge/built-in-context.ts"() {
13622
+ init_text_encoding();
13225
13623
  BUILT_IN_CONTEXT_FORMAT = "dotmem.built-in-context";
13226
13624
  BUILT_IN_CONTEXT_FORMAT_VERSION = 1;
13227
13625
  cached = null;
@@ -13421,6 +13819,7 @@ __export(knowledge_exports, {
13421
13819
  defaultIdentityGovernance: () => defaultIdentityGovernance,
13422
13820
  defaultOverrideId: () => defaultOverrideId,
13423
13821
  defaultPolicyId: () => defaultPolicyId,
13822
+ deriveCurrentness: () => deriveCurrentness,
13424
13823
  deriveSituationApplicability: () => deriveSituationApplicability,
13425
13824
  describeDotMemStorage: () => describeDotMemStorage,
13426
13825
  detectAuthorityEscalationAttempt: () => detectAuthorityEscalationAttempt,
@@ -13447,6 +13846,7 @@ __export(knowledge_exports, {
13447
13846
  explainDiscovery: () => explainDiscovery,
13448
13847
  explainIdentityResolution: () => explainIdentityResolution,
13449
13848
  extractIronRules: () => extractIronRules,
13849
+ findContestedIds: () => findContestedIds,
13450
13850
  findExemplar: () => findExemplar,
13451
13851
  findIncidentById: () => findIncidentById,
13452
13852
  fingerprintFromState: () => fingerprintFromState,
@@ -13522,6 +13922,7 @@ __export(knowledge_exports, {
13522
13922
  relocateDotMemStorage: () => relocateDotMemStorage,
13523
13923
  removeExemplar: () => removeExemplar,
13524
13924
  renderAgentRules: () => renderAgentRules,
13925
+ renderExpandedClaim: () => renderExpandedClaim,
13525
13926
  renderExplanation: () => renderExplanation,
13526
13927
  renderMarkdownIndex: () => renderMarkdownIndex,
13527
13928
  renderOperatorContract: () => renderOperatorContract,
@@ -13625,6 +14026,7 @@ var init_knowledge = __esm({
13625
14026
  init_state();
13626
14027
  init_select();
13627
14028
  init_discover();
14029
+ init_currentness();
13628
14030
  init_project();
13629
14031
  init_applicability();
13630
14032
  init_policy();
@@ -13732,7 +14134,6 @@ function _inferConfidence(claim) {
13732
14134
  var LOGIC_MEM_FILE, nodeCwd2, cachedRuntime, LogicEngine, logic, logic_default;
13733
14135
  var init_logic = __esm({
13734
14136
  "core/logic/index.ts"() {
13735
- init_suppress_idb_warning();
13736
14137
  init_knowledge();
13737
14138
  init_mem_repository();
13738
14139
  init_acquisition_boundary();
@@ -14120,7 +14521,6 @@ async function loadCombinedKnowledgeState() {
14120
14521
  var EmptyLogicRepository, KNOWLEDGE_STATE_KEY, knowledgeSaveQueue, StoreKnowledgeRepository, RuntimeSlot, projectSlot, userSlot, installDotMemReadme;
14121
14522
  var init_knowledge_runtime = __esm({
14122
14523
  "core/memory/knowledge-runtime.ts"() {
14123
- init_suppress_idb_warning();
14124
14524
  init_knowledge();
14125
14525
  init_project_identity();
14126
14526
  init_user_paths();
@@ -14501,6 +14901,7 @@ var init_durable_store = __esm({
14501
14901
  "core/memory/durable-store.ts"() {
14502
14902
  init_storage_coordinator();
14503
14903
  init_store_queue();
14904
+ init_text_encoding();
14504
14905
  DurableStorageUnavailableError = class extends Error {
14505
14906
  static {
14506
14907
  __name(this, "DurableStorageUnavailableError");
@@ -14555,11 +14956,11 @@ var init_durable_store = __esm({
14555
14956
  }
14556
14957
  let parsed;
14557
14958
  try {
14558
- parsed = JSON.parse(new TextDecoder().decode(raw));
14959
+ parsed = JSON.parse(decodeText(raw, { source: this.filePath }));
14559
14960
  } catch {
14560
14961
  try {
14561
14962
  const bakRaw = await fs7.readFile(`${this.filePath}.bak`);
14562
- parsed = JSON.parse(new TextDecoder().decode(bakRaw));
14963
+ parsed = JSON.parse(decodeText(bakRaw, { source: `${this.filePath}.bak` }));
14563
14964
  } catch {
14564
14965
  throw new DurableStorageUnavailableError(
14565
14966
  "Durable memory store is corrupt and no backup is available."
@@ -14976,7 +15377,6 @@ async function getEntry(key) {
14976
15377
  var MEMORY_INDEX_KEY, SUPERSEDED_PREFIX, durableStoreInstance, entries;
14977
15378
  var init_entries = __esm({
14978
15379
  "core/memory/entries.ts"() {
14979
- init_suppress_idb_warning();
14980
15380
  init_env();
14981
15381
  init_journal();
14982
15382
  init_durable_store();
@@ -15354,7 +15754,6 @@ async function findClaimAcrossAllSources(claimId, scope, sourceProject) {
15354
15754
  var acquire;
15355
15755
  var init_acquire = __esm({
15356
15756
  "core/memory/acquire.ts"() {
15357
- init_suppress_idb_warning();
15358
15757
  init_env();
15359
15758
  init_built_in_context();
15360
15759
  init_project_identity();
@@ -15475,15 +15874,15 @@ var init_profile2 = __esm({
15475
15874
 
15476
15875
  // core/knowledge/note-types.ts
15477
15876
  async function sha256HexOfText(text) {
15478
- const encoder3 = new TextEncoder();
15479
- const bytes = encoder3.encode(text);
15877
+ const encoder4 = new TextEncoder();
15878
+ const bytes = encoder4.encode(text);
15480
15879
  const hashArray = await crypto.subtle.digest("SHA-256", bytes);
15481
15880
  return Array.from(new Uint8Array(hashArray)).map((b) => b.toString(16).padStart(2, "0")).join("");
15482
15881
  }
15483
15882
  async function buildNoteKnowledge(title, content, origin, tag) {
15484
15883
  const sha2563 = await sha256HexOfText(content);
15485
- const encoder3 = new TextEncoder();
15486
- const size = encoder3.encode(content).byteLength;
15884
+ const encoder4 = new TextEncoder();
15885
+ const size = encoder4.encode(content).byteLength;
15487
15886
  return {
15488
15887
  title,
15489
15888
  content,
@@ -16961,7 +17360,6 @@ async function bootstrapProject() {
16961
17360
  var pendingDetectionEvents, detectionFlushScheduled, flushDetectionEvents, memory;
16962
17361
  var init_memory = __esm({
16963
17362
  "core/memory/index.ts"() {
16964
- init_suppress_idb_warning();
16965
17363
  init_journal();
16966
17364
  init_brain();
16967
17365
  init_knowledge_runtime();
@@ -17085,7 +17483,7 @@ var init_memory = __esm({
17085
17483
  resetPolicyStoreCache();
17086
17484
  },
17087
17485
  // ----- namespaced surfaces -----
17088
- /** Local operation journal (namespaced). No-op substrate when sqlite/idb unavailable. */
17486
+ /** Local operation journal (namespaced). Persisted on `store`. */
17089
17487
  journal: journal_default,
17090
17488
  /** Configure the optional cloud-sync layer (namespace + provider). Chainable. */
17091
17489
  configure(opts) {
@@ -17220,7 +17618,7 @@ function readStdin() {
17220
17618
  });
17221
17619
  }
17222
17620
  function parseContextArgs(args) {
17223
- const options = { explain: false, json: false, full: false, claimsOnly: false };
17621
+ const options = { explain: false, json: false, full: false, claimsOnly: false, manifest: false };
17224
17622
  const positional = [];
17225
17623
  let i2 = 0;
17226
17624
  while (i2 < args.length) {
@@ -17229,7 +17627,16 @@ function parseContextArgs(args) {
17229
17627
  else if (arg === "--json") options.json = true;
17230
17628
  else if (arg === "--full") options.full = true;
17231
17629
  else if (arg === "--claims-only") options.claimsOnly = true;
17232
- else if (arg === "--limit") {
17630
+ else if (arg === "--manifest") options.manifest = true;
17631
+ else if (arg === "--claim") {
17632
+ i2++;
17633
+ const value = args[i2];
17634
+ if (!value) {
17635
+ console.error("Missing value for --claim");
17636
+ process14.exit(1);
17637
+ }
17638
+ options.claimId = value;
17639
+ } else if (arg === "--limit") {
17233
17640
  const value = args[i2 + 1];
17234
17641
  if (value === void 0 || value.startsWith("--")) {
17235
17642
  console.error("Missing value for --limit");
@@ -17244,6 +17651,21 @@ function parseContextArgs(args) {
17244
17651
  }
17245
17652
  options.limit = parsed;
17246
17653
  i2++;
17654
+ } else if (arg === "--offset") {
17655
+ const value = args[i2 + 1];
17656
+ if (value === void 0 || value.startsWith("--")) {
17657
+ console.error("Missing value for --offset");
17658
+ process14.exitCode = 1;
17659
+ process14.exit(1);
17660
+ }
17661
+ const parsed = parseInt(value, 10);
17662
+ if (Number.isNaN(parsed) || parsed < 0) {
17663
+ console.error(`Invalid --offset value: ${value}. Must be a non-negative integer.`);
17664
+ process14.exitCode = 1;
17665
+ process14.exit(1);
17666
+ }
17667
+ options.offset = parsed;
17668
+ i2++;
17247
17669
  } else if (arg === "--format") {
17248
17670
  const value = args[i2 + 1];
17249
17671
  if (value === void 0 || value.startsWith("--")) {
@@ -17261,7 +17683,7 @@ function parseContextArgs(args) {
17261
17683
  i2++;
17262
17684
  } else if (arg.startsWith("--")) {
17263
17685
  console.error(`Unknown context option: ${arg}`);
17264
- console.error('Usage: npx dotmem context "<situation>" [--explain] [--json] [--full] [--claims-only] [--limit <N>] [--format brief]');
17686
+ console.error('Usage: npx dotmem context "<situation>" [--explain] [--json] [--full] [--claims-only] [--limit <N>] [--offset <N>] [--format brief] [--manifest] [--claim <id>]');
17265
17687
  process14.exit(1);
17266
17688
  } else positional.push(arg);
17267
17689
  i2++;
@@ -17876,7 +18298,6 @@ var init_policy3 = __esm({
17876
18298
  });
17877
18299
 
17878
18300
  // core/cli/index.ts
17879
- init_suppress_idb_warning();
17880
18301
  init_memory();
17881
18302
 
17882
18303
  // core/continuity/freshness.ts
@@ -19487,7 +19908,8 @@ async function runContext(situation, _cwd, options = {}) {
19487
19908
  await getBrainDocument();
19488
19909
  const discovery = discoverAcquiredExperience(combined, situation, {
19489
19910
  currentProjectId: await resolveProjectIdentity(process.cwd()),
19490
- ...options.limit !== void 0 ? { maxCandidates: options.limit } : {}
19911
+ ...options.limit !== void 0 ? { maxCandidates: options.limit } : {},
19912
+ ...options.offset !== void 0 ? { cursor: { knowledgeVersion: combined.version, offset: options.offset } } : {}
19491
19913
  }, sources);
19492
19914
  if (options.explain) {
19493
19915
  const report = explainDiscovery(combined, discovery, situation);
@@ -19616,6 +20038,20 @@ async function runContext(situation, _cwd, options = {}) {
19616
20038
  claims: projection
19617
20039
  }, null, 2);
19618
20040
  }
20041
+ if (options.manifest) {
20042
+ return JSON.stringify({
20043
+ knowledgeVersion: projection.knowledgeVersion,
20044
+ totalCandidates: projection.totalCandidates,
20045
+ included: projection.experiences.length,
20046
+ omittedCandidates: projection.omittedCandidates,
20047
+ manifest: projection.manifest ?? {
20048
+ considered: projection.totalCandidates,
20049
+ included: projection.experiences.length,
20050
+ items: [],
20051
+ byReason: []
20052
+ }
20053
+ }, null, 2);
20054
+ }
19619
20055
  if (options.format === "brief") {
19620
20056
  const header = options.claimsOnly ? renderBriefClaimsHeader() : `${identityChannel.text}
19621
20057
  ${profileText}
@@ -19646,9 +20082,10 @@ ${projection.text}`;
19646
20082
  const sizeText = renderSizeDisclosure({
19647
20083
  totalCandidates: projection.totalCandidates,
19648
20084
  omittedCandidates: projection.omittedCandidates,
19649
- projectedBytes: projectedBody.length,
19650
- maxCharacters: options.full ? Infinity : DOTMEM_CONTEXT_DEFAULT_MAX_CHARACTERS,
19651
- hostCeilingBytes: DOTMEM_HOST_TRUNCATION_CEILING_BYTES
20085
+ projectedBytes: new TextEncoder().encode(projectedBody).length,
20086
+ maxCharacters: options.full ? Number.MAX_SAFE_INTEGER : DOTMEM_CONTEXT_DEFAULT_MAX_CHARACTERS,
20087
+ hostCeilingBytes: DOTMEM_HOST_TRUNCATION_CEILING_BYTES,
20088
+ manifest: projection.manifest
19652
20089
  });
19653
20090
  return `${identityChannel.text}
19654
20091
  ${profileText}
@@ -19746,6 +20183,8 @@ __name(topLevelUsage, "topLevelUsage");
19746
20183
 
19747
20184
  // core/cli/commands/context.ts
19748
20185
  init_memory();
20186
+ init_memory();
20187
+ init_project();
19749
20188
 
19750
20189
  // core/functions/profile-request.ts
19751
20190
  init_profile();
@@ -19808,6 +20247,17 @@ async function runContextCli(situation, options = {}) {
19808
20247
  console.info(gate.text);
19809
20248
  return;
19810
20249
  }
20250
+ if (options.claimId) {
20251
+ const state2 = await loadCombinedKnowledgeState();
20252
+ const claim = state2.claims.find((candidate) => candidate.id === options.claimId);
20253
+ if (!claim) {
20254
+ console.error(`No claim with id ${options.claimId} is present in the loaded stores.`);
20255
+ process.exitCode = 1;
20256
+ return;
20257
+ }
20258
+ console.info(renderExpandedClaim(claim));
20259
+ return;
20260
+ }
19811
20261
  const text = await runContext(situation ?? "", void 0, {
19812
20262
  ...options,
19813
20263
  handshake: gate.record ?? void 0,
@@ -20819,6 +21269,7 @@ init_memory();
20819
21269
  init_rules_loader();
20820
21270
  async function runRulesCli(args) {
20821
21271
  const json = args.includes("--json");
21272
+ const expand = args.includes("--expand");
20822
21273
  try {
20823
21274
  const state2 = await loadCombinedKnowledgeState();
20824
21275
  const report = loadIronRules(state2);
@@ -20830,7 +21281,7 @@ async function runRulesCli(args) {
20830
21281
  console.info("No iron rules found.");
20831
21282
  return;
20832
21283
  }
20833
- console.info(formatRulesForSessionStart(report.rules));
21284
+ console.info(expand ? formatRulesForSessionStart(report.rules) : formatRulesReference(report.rules));
20834
21285
  } catch (error) {
20835
21286
  console.error(`Rules loading failed: ${error instanceof Error ? error.message : String(error)}`);
20836
21287
  process.exitCode = 1;
@@ -21652,9 +22103,12 @@ Record operator feedback about how an acquired claim performed.
21652
22103
  }
21653
22104
  if (command === "rules") {
21654
22105
  if (args[0] === "--help" || args[0] === "-h") {
21655
- console.info(`Usage: npx dotmem rules [--json]
22106
+ console.info(`Usage: npx dotmem rules [--json] [--expand]
22107
+
22108
+ Print iron rules (human-stated, kind: 'rule') sorted by violation frequency.
21656
22109
 
21657
- Print iron rules (human-stated, kind: 'rule') sorted by violation frequency.`);
22110
+ --json output structured report (count, signature, ids, rules)
22111
+ --expand print full rule bodies instead of the compact reference`);
21658
22112
  process14.exit(0);
21659
22113
  return;
21660
22114
  }