@zortexhq/indra-v2.5 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/box-level1-setup.js +1 -1
  2. package/dist/calcom-level1-setup.js +1 -1
  3. package/dist/cli-run.js +1 -1
  4. package/dist/connector-worker.js +1 -1
  5. package/dist/discord-level1-setup.js +1 -1
  6. package/dist/dropbox-level1-setup.js +1 -1
  7. package/dist/figma-level1-setup.js +1 -1
  8. package/dist/freshdesk-level1-setup.js +1 -1
  9. package/dist/freshrss-level1-setup.js +1 -1
  10. package/dist/front-level1-setup.js +1 -1
  11. package/dist/gateway.js +1 -1
  12. package/dist/google-chat-level1-setup.js +1 -1
  13. package/dist/google-contacts-level1-setup.js +1 -1
  14. package/dist/hubspot-level1-setup.js +1 -1
  15. package/dist/joplin-selection.js +1 -1
  16. package/dist/local-cloud.js +1 -1
  17. package/dist/mattermost-level1-setup.js +1 -1
  18. package/dist/mcp.js +2 -2
  19. package/dist/measurement-context.js +1 -1
  20. package/dist/miniflux-level1-setup.js +1 -1
  21. package/dist/nextcloud-level1-setup.js +1 -1
  22. package/dist/operation-telemetry.js +1 -0
  23. package/dist/prepared-level1-setup.js +1 -0
  24. package/dist/profile.js +1 -1
  25. package/dist/proton-mail-level1-setup.js +1 -1
  26. package/dist/recovery-launch.js +10 -0
  27. package/dist/recovery-support.js +1 -1
  28. package/dist/recovery-surface.js +1 -0
  29. package/dist/recovery.js +1 -1
  30. package/dist/resident-host.js +2 -2
  31. package/dist/resident-jobs.js +1 -1
  32. package/dist/resident-platform.js +1 -1
  33. package/dist/resident-telemetry.js +1 -0
  34. package/dist/resource-telemetry.js +1 -0
  35. package/dist/salesforce-level1-setup.js +1 -1
  36. package/dist/smartsheet-level1-setup.js +1 -1
  37. package/dist/startup.js +2 -2
  38. package/dist/thunderbird-level1-setup.js +1 -1
  39. package/dist/update-cli.js +1 -1
  40. package/dist/wakatime-level1-setup.js +1 -1
  41. package/dist/wallabag-level1-setup.js +1 -1
  42. package/dist/web.js +2 -2
  43. package/dist/zendesk-level1-setup.js +1 -1
  44. package/dist/zoom-level1-setup.js +1 -1
  45. package/dist/zulip-level1-setup.js +1 -1
  46. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  47. package/node_modules/@zortexhq/plugin-connector-core/dist/operational-hub.js +1 -0
  48. package/node_modules/@zortexhq/plugin-connector-level1/dist/chatgpt.js +1 -1
  49. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  50. package/node_modules/@zortexhq/plugin-connector-level1/dist/mcp-feedback.js +1 -0
  51. package/node_modules/@zortexhq/plugin-connector-level1/dist/operational-client.js +1 -0
  52. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  53. package/node_modules/@zortexhq/plugin-connector-level1/package.json +2 -0
  54. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/index.js +1 -1
  55. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/routes.js +1 -1
  56. package/node_modules/@zortexhq/plugin-galaxy-ui/dist/server.js +1 -1
  57. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-catalog.js +1 -0
  58. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-i18n.js +1 -0
  59. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -0
  60. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-text.js +1 -0
  61. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app.html +42 -0
  62. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-client.js +1 -0
  63. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-forms.js +1 -0
  64. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/demo.js +1 -0
  65. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.css +47 -6
  66. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/shell.js +1 -1
  67. package/node_modules/@zortexhq/plugin-galaxy-ui/src/original/fonts/LICENSE.txt +92 -0
  68. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/feedback.js +1 -1
  69. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-oauth-bridge.js +1 -1
  70. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/index.js +1 -1
  71. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/browser-actions.js +1 -1
  72. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/driver.js +1 -1
  73. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/index.js +1 -1
  74. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/operational-browser.js +1 -0
  75. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/session-routes.js +1 -1
  76. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/shared-session.js +1 -1
  77. package/node_modules/@zortexhq/plugin-posthog/dist/collection-status.js +1 -0
  78. package/node_modules/@zortexhq/plugin-posthog/dist/index.js +1 -1
  79. package/node_modules/@zortexhq/plugin-posthog/dist/indra.js +1 -1
  80. package/node_modules/@zortexhq/plugin-posthog/dist/local-cloud.js +1 -1
  81. package/node_modules/@zortexhq/plugin-posthog/dist/northstar.js +1 -1
  82. package/node_modules/@zortexhq/plugin-posthog/dist/observations.js +1 -1
  83. package/node_modules/@zortexhq/plugin-posthog/dist/operational.js +1 -0
  84. package/node_modules/@zortexhq/plugin-posthog/dist/resources.js +1 -0
  85. package/node_modules/@zortexhq/plugin-posthog/dist/source-ids.js +1 -1
  86. package/node_modules/@zortexhq/plugin-process-local/dist/api/resources.js +1 -0
  87. package/node_modules/@zortexhq/plugin-process-local/dist/index.js +1 -1
  88. package/node_modules/@zortexhq/plugin-process-local/dist/resource-sampler.js +1 -0
  89. package/node_modules/@zortexhq/plugin-process-local/dist/runner.js +1 -1
  90. package/node_modules/@zortexhq/plugin-process-local/package.json +3 -0
  91. package/node_modules/@zortexhq/plugin-telemetry/dist/api/collection.js +1 -0
  92. package/node_modules/@zortexhq/plugin-telemetry/dist/api/index.js +1 -1
  93. package/node_modules/@zortexhq/plugin-telemetry/dist/api/measurement.js +1 -1
  94. package/node_modules/@zortexhq/plugin-telemetry/dist/api/observations.js +1 -1
  95. package/node_modules/@zortexhq/plugin-telemetry/dist/api/operational.js +1 -0
  96. package/node_modules/@zortexhq/plugin-telemetry/dist/api/resources.js +1 -0
  97. package/node_modules/@zortexhq/plugin-telemetry/dist/api/source-ids.js +1 -0
  98. package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
  99. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-call.js +1 -0
  100. package/node_modules/@zortexhq/plugin-telemetry/dist/api/tool-methods.js +1 -0
  101. package/node_modules/@zortexhq/plugin-telemetry/dist/api/upstream-tools.js +1 -0
  102. package/node_modules/@zortexhq/plugin-telemetry/dist/index.js +1 -1
  103. package/node_modules/@zortexhq/plugin-telemetry/dist/resources.js +1 -0
  104. package/node_modules/@zortexhq/plugin-telemetry/package.json +3 -0
  105. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/index.js +1 -1
  106. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/api/storage-metadata.js +1 -0
  107. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  108. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/storage-metadata.js +1 -0
  109. package/package.json +6 -6
  110. package/release-provenance.json +26 -26
  111. package/update-manifest.json +379 -181
  112. package/dist/recovery-page.js +0 -215
@@ -1 +1 @@
1
- import{DatabaseSync}from"node:sqlite";import{mkdir,lstat,realpath}from"node:fs/promises";import{isAbsolute,join,resolve}from"node:path";import{createHash,randomUUID}from"node:crypto";import{businessError,canonicalJson,ok}from"@zortexhq/plugin-connector-framework/api";import{isUsageEvent,isUsageContext,isUsageFeedbackInput,isFlowId,snapshotUsageRecord,currentFeedbackFlow,currentTelemetryContext,currentUsageInvocation,isUsageObservation,snapshotUsageObservation,OBSERVATION_SNAPSHOT_INTERVAL_MS,OBSERVATION_SNAPSHOT_DAILY_LIMIT,feedbackEligible,FEEDBACK_CHANNELS}from"./api/index.js";export{aggregateUsage}from"./aggregate.js";export const name="zortex-telemetry";export const TELEMETRY_RETENTION_DAYS=30,TELEMETRY_MAX_EVENTS=5e4,TELEMETRY_MAX_RECORD_BYTES=2048;const DAY=864e5,FEEDBACK_DAYS=7;export async function createTelemetry({root,enabled=true,startup=false,newInstallation=false,context=currentTelemetryContext()},runtime={}){if(typeof newInstallation!=="boolean")throw Error("newInstallation must be boolean.");if(!isAbsolute(root)||typeof enabled!=="boolean"||typeof startup!=="boolean")throw Error("Telemetry root must be absolute; enabled must be boolean.");const capturedContext=context?Object.freeze({...context}):void 0;if(context!==void 0&&!isUsageContext(capturedContext))throw Error("Invalid telemetry runtime context.");await mkdir(root,{recursive:true,mode:448});if((await lstat(root)).isSymbolicLink())throw Error("Telemetry root cannot be a link.");const file=join(await realpath(root),"telemetry.sqlite");if((await lstat(file).catch(()=>null))?.isSymbolicLink())throw Error("Telemetry database cannot be a link.");const db=new DatabaseSync(file),now=runtime.now??Date.now;let created=false,userId="",closed=false,initializing=false,nextAgeSweep=0;try{db.exec("PRAGMA busy_timeout=3000;PRAGMA journal_mode=WAL;BEGIN IMMEDIATE");initializing=true;db.exec("CREATE TABLE IF NOT EXISTS identity(id INTEGER PRIMARY KEY CHECK(id=1),user TEXT NOT NULL);CREATE TABLE IF NOT EXISTS usage(id TEXT PRIMARY KEY,at TEXT NOT NULL,operation TEXT NOT NULL,outcome TEXT NOT NULL,duration REAL NOT NULL,source TEXT,code TEXT,internal INTEGER NOT NULL DEFAULT 0);");const columns=new Set(db.prepare("PRAGMA table_info(usage)").all().map(column=>String(column.name)));for(const[column,type]of[["internal","INTEGER NOT NULL DEFAULT 0"],["trace","TEXT"],["metadata","TEXT"],["feedback_target","TEXT"],["feedback_channel","TEXT"],["observation_key","TEXT"],["observation_fingerprint","TEXT"],["observation_scope","TEXT"],["observation_recorded_at","INTEGER"]])if(!columns.has(column))db.exec(`ALTER TABLE usage ADD COLUMN ${column} ${type}`);created=Number(db.prepare("INSERT OR IGNORE INTO identity(id,user) VALUES(1,?)").run(randomUUID()).changes)===1;userId=String(db.prepare("SELECT user FROM identity").get().user);db.exec("CREATE TABLE IF NOT EXISTS usage_export_seq(seq INTEGER PRIMARY KEY AUTOINCREMENT,event_id TEXT UNIQUE NOT NULL);CREATE TABLE IF NOT EXISTS collection_state(id INTEGER PRIMARY KEY CHECK(id=1),retained_events INTEGER NOT NULL,pruned_events INTEGER NOT NULL DEFAULT 0,retention_floor INTEGER NOT NULL DEFAULT 0,sequence_backfilled INTEGER NOT NULL DEFAULT 0);");if(!db.prepare("SELECT id FROM collection_state WHERE id=1").get())db.exec("INSERT INTO collection_state(id,retained_events) SELECT 1,COUNT(*) FROM usage;");if(!db.prepare("SELECT sequence_backfilled FROM collection_state WHERE id=1").get().sequence_backfilled){db.exec("INSERT OR IGNORE INTO usage_export_seq(event_id) SELECT id FROM usage ORDER BY at,id;UPDATE collection_state SET sequence_backfilled=1 WHERE id=1;")}db.exec("CREATE INDEX IF NOT EXISTS usage_at ON usage(at,id);CREATE UNIQUE INDEX IF NOT EXISTS usage_feedback_once ON usage(feedback_target,feedback_channel) WHERE feedback_target IS NOT NULL;CREATE UNIQUE INDEX IF NOT EXISTS usage_observation_once ON usage(observation_key) WHERE observation_key IS NOT NULL;CREATE INDEX IF NOT EXISTS usage_observation_scope ON usage(observation_scope,observation_recorded_at) WHERE observation_scope IS NOT NULL;CREATE INDEX IF NOT EXISTS usage_observation_budget ON usage(observation_recorded_at) WHERE observation_scope IS NOT NULL;CREATE TABLE IF NOT EXISTS observation_counters(id INTEGER PRIMARY KEY CHECK(id=1),rate_limited INTEGER NOT NULL DEFAULT 0,budget_limited INTEGER NOT NULL DEFAULT 0,unchanged INTEGER NOT NULL DEFAULT 0,duplicates INTEGER NOT NULL DEFAULT 0,last_suppressed_at TEXT);INSERT OR IGNORE INTO observation_counters(id) VALUES(1);CREATE TRIGGER IF NOT EXISTS usage_count_insert AFTER INSERT ON usage BEGIN UPDATE collection_state SET retained_events=retained_events+1 WHERE id=1;END;CREATE TRIGGER IF NOT EXISTS usage_count_delete AFTER DELETE ON usage BEGIN UPDATE collection_state SET retained_events=retained_events-1 WHERE id=1;END;COMMIT;PRAGMA busy_timeout=20;");initializing=false}catch(error){if(initializing){try{db.exec("ROLLBACK")}catch{}}db.close();throw error}const state=db.prepare("SELECT retained_events,pruned_events,retention_floor FROM collection_state WHERE id=1");const add=db.prepare("INSERT OR IGNORE INTO usage(id,at,operation,outcome,duration,source,code,internal,trace,metadata,feedback_target,feedback_channel) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)");const addSequence=db.prepare("INSERT INTO usage_export_seq(event_id) VALUES(?)");const byId=db.prepare("SELECT * FROM usage WHERE id=?");const byFeedback=db.prepare("SELECT * FROM usage WHERE feedback_target=? AND feedback_channel=?");const pageQuery=db.prepare("SELECT s.seq,u.* FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE s.seq>? ORDER BY s.seq LIMIT ?");const pruneFacts=db.prepare("SELECT COUNT(*) AS n,COALESCE(MAX(s.seq),0) AS last_seq FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE u.id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const pruneSequences=db.prepare("DELETE FROM usage_export_seq WHERE event_id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const pruneRows=db.prepare("DELETE FROM usage WHERE id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const rememberPruning=db.prepare("UPDATE collection_state SET pruned_events=pruned_events+?,retention_floor=MAX(retention_floor,?) WHERE id=1");const oldest=db.prepare("SELECT MIN(at) AS at FROM usage WHERE id<>?");const observationByKey=db.prepare("SELECT id,observation_fingerprint FROM usage WHERE observation_key=?");const lastSnapshot=db.prepare("SELECT observation_fingerprint,observation_recorded_at FROM usage WHERE observation_scope=? ORDER BY observation_recorded_at DESC,id DESC LIMIT 1");const snapshotBudget=db.prepare("SELECT COUNT(*) AS n FROM usage WHERE observation_scope IS NOT NULL AND observation_recorded_at>=? AND observation_recorded_at<?");const observationMetadata=db.prepare("UPDATE usage SET observation_key=?,observation_fingerprint=?,observation_scope=?,observation_recorded_at=? WHERE id=?");const observationCounters=db.prepare("SELECT * FROM observation_counters WHERE id=1");const perform=async fn=>{if(closed)return businessError("unavailable","Telemetry is inactive.","storage");try{return fn()}catch(error){return businessError(error.errcode===5?"unavailable":"data_loss","Telemetry operation failed.","storage")}};function collection(after=0){const row=state.get(),stats=observationCounters.get();return{retainedEvents:Number(row.retained_events),prunedEvents:Number(row.pruned_events),retentionFloor:Number(row.retention_floor),limited:after<Number(row.retention_floor),retentionDays:TELEMETRY_RETENTION_DAYS,maxEvents:TELEMETRY_MAX_EVENTS,oldestAvailableAt:oldest.get(userId).at,observations:{snapshotRateLimited:Number(stats.rate_limited),snapshotBudgetLimited:Number(stats.budget_limited),snapshotUnchanged:Number(stats.unchanged),duplicates:Number(stats.duplicates),lastSuppressedAt:stats.last_suppressed_at}}}function decode(row){const metadata=row.metadata?JSON.parse(String(row.metadata)):{};return{id:String(row.id),at:String(row.at),operation:String(row.operation),outcome:String(row.outcome),durationMs:Number(row.duration),...row.source?{source:String(row.source)}:{},...row.code?{code:String(row.code)}:{},...row.internal?{internal:true}:{},...row.trace?{trace:JSON.parse(String(row.trace))}:{},...metadata}}function prune(cutoff,limit){const facts=pruneFacts.get(userId,cutoff,limit);if(!Number(facts.n))return;pruneSequences.run(userId,cutoff,limit);pruneRows.run(userId,cutoff,limit);rememberPruning.run(Number(facts.n),Number(facts.last_seq))}function maintain(){const now2=Date.now();if(now2>=nextAgeSweep){prune(new Date(now2-TELEMETRY_RETENTION_DAYS*DAY).toISOString(),2147483647);nextAgeSweep=now2+6e4}const excess=Number(state.get().retained_events)-TELEMETRY_MAX_EVENTS;if(excess>0)prune("9999-12-31T23:59:59.999Z",excess+Math.min(255,TELEMETRY_MAX_EVENTS-1))}function insert(event,id=randomUUID(),transaction=true,at=new Date().toISOString()){const record={...event,id,at,...capturedContext?{context:capturedContext}:{}};if(Buffer.byteLength(JSON.stringify(record))>TELEMETRY_MAX_RECORD_BYTES)throw Error("Telemetry record exceeds its closed metadata budget.");const metadata={...record.context?{context:record.context}:{},...event.result?{result:event.result}:{},...event.correlation?{correlation:event.correlation}:{},...event.errorCategory?{errorCategory:event.errorCategory}:{},...event.feedback?{feedback:event.feedback}:{},...event.observation?{observation:event.observation}:{},...event.invocation?{invocation:event.invocation}:{}};if(transaction)db.exec("BEGIN IMMEDIATE");try{const inserted=add.run(id,at,event.operation,event.outcome,event.durationMs,event.source??null,event.code??null,Number(event.internal??false),event.trace?JSON.stringify(event.trace):null,Object.keys(metadata).length?JSON.stringify(metadata):null,event.feedback?.targetReceiptId??null,event.feedback?.submissionChannel??null);if(Number(inserted.changes))addSequence.run(id);maintain();if(transaction)db.exec("COMMIT");return id}catch(error){if(transaction)db.exec("ROLLBACK");throw error}}if(enabled){try{db.exec("BEGIN IMMEDIATE");maintain();db.exec("COMMIT")}catch(error){try{db.exec("ROLLBACK")}catch{}db.close();throw error}}if(startup&&enabled){insert({operation:"product.first_start",outcome:"ok",durationMs:0,internal:true,code:created&&newInstallation?"new_install":"first_observed"},userId);insert({operation:"product.started",outcome:"ok",durationMs:0,internal:true})}const service={isEnabled:()=>enabled&&!closed,observe:input=>perform(()=>{if(!enabled)return ok({recorded:false,reason:"disabled"});const snapshot=snapshotUsageObservation(input);if(!isUsageObservation(snapshot))return businessError("invalid_argument","Observation accepts only fixed, content-free metadata and known counts.","storage");const{key,source,at,...rawFacts}=snapshot;const facts=Object.fromEntries(Object.entries(rawFacts).filter(([,value])=>value!==void 0));if(facts.kind==="connection")facts.capabilities=[...facts.capabilities].sort();const hash=value=>createHash("sha256").update(canonicalJson(value)).digest("hex");const observationKey=hash(["zortex-observation-v1",userId,snapshot.kind,source,key]);const fingerprint=hash({source,facts});const receiptId=observationKey.slice(0,8)+"-"+observationKey.slice(8,12)+"-5"+observationKey.slice(13,16)+"-a"+observationKey.slice(17,20)+"-"+observationKey.slice(20,32);const recordedAt=now(),observedAt=at??new Date(recordedAt).toISOString();const scope=facts.kind==="sync"?null:hash([facts.kind,source,facts.connectionRef??null,...facts.kind==="inventory"?[facts.population,facts.attribution]:[]]);db.exec("BEGIN IMMEDIATE");try{const prior=observationByKey.get(observationKey);if(prior){if(prior.observation_fingerprint!==fingerprint){db.exec("COMMIT");return businessError("already_exists","This observation key already has different metadata.","storage")}db.exec("UPDATE observation_counters SET duplicates=duplicates+1 WHERE id=1");db.exec("COMMIT");return ok({recorded:false,reason:"duplicate",receiptId:String(prior.id)})}if(scope){const previous=lastSnapshot.get(scope),elapsed=recordedAt-Number(previous?.observation_recorded_at??0);const unchanged=previous&&previous.observation_fingerprint===fingerprint&&elapsed<DAY;const limited=previous&&elapsed<OBSERVATION_SNAPSHOT_INTERVAL_MS;const dayStart=Math.floor(recordedAt/DAY)*DAY;const budget=Number(snapshotBudget.get(dayStart,dayStart+DAY).n)>=OBSERVATION_SNAPSHOT_DAILY_LIMIT;if(unchanged||limited||budget){const field=unchanged?"unchanged":limited?"rate_limited":"budget_limited";db.prepare(`UPDATE observation_counters SET ${field}=${field}+1,last_suppressed_at=? WHERE id=1`).run(new Date(recordedAt).toISOString());db.exec("COMMIT");return ok({recorded:false,reason:unchanged?"unchanged":"rate_limited"})}}const outcome=facts.kind!=="sync"?"ok":facts.status==="completed"?"ok":facts.status==="cancelled"?"cancelled":facts.status==="failed"||facts.status==="cleanup_blocked"?"fault":"unknown";insert({operation:"connector."+facts.kind,outcome,durationMs:facts.kind==="sync"?facts.durationMs:0,source,internal:true,observation:facts},receiptId,false,observedAt);observationMetadata.run(observationKey,fingerprint,scope,recordedAt,receiptId);db.exec("COMMIT");return ok({recorded:true,reason:"recorded",receiptId})}catch(error){db.exec("ROLLBACK");throw error}}),record:input=>perform(()=>{const snapshot=snapshotUsageRecord(input);if(!isUsageEvent(snapshot)||snapshot.operation==="product.feedback"||snapshot.operation==="product.first_start")return businessError("invalid_argument","Usage accepts only content-free fields; startup and feedback anchors are provider-owned.","storage");if(!enabled)return ok({recorded:false});const event=snapshot,flow=currentFeedbackFlow();if(!event.correlation&&flow&&(!event.source||event.source===flow.source)&&isFlowId(flow.flowId))event.correlation={flowId:flow.flowId,...isFlowId(flow.connectionFlowId)?{connectionFlowId:flow.connectionFlowId}:{}};const invocation=currentUsageInvocation();return ok({recorded:true,receiptId:insert({...event,...invocation?{invocation:{...invocation}}:{}})})}),readBatch:({after=0,limit=500})=>perform(()=>{if(!Number.isSafeInteger(after)||after<0||!Number.isInteger(limit)||limit<1||limit>1e3)return businessError("invalid_argument","Usage paging needs an ordered cursor and 1\u20131000 events.","storage");const found=pageQuery.all(after,limit+1),selected=found.slice(0,limit);return ok({format:"zortex-usage/v1",userId,enabled,cursor:selected.length?Number(selected.at(-1).seq):after,more:found.length>limit,eventCursors:selected.map(row=>Number(row.seq)),events:selected.map(decode),collection:collection(after)})}),export:()=>perform(()=>{const events=db.prepare("SELECT * FROM usage ORDER BY at,id LIMIT 100001").all().map(decode);if(events.length>1e5)return businessError("resource_exhausted","Usage export exceeds its batch limit.","storage");return ok({format:"zortex-usage/v1",userId,enabled,events,collection:collection()})}),recent:({limit=5}={})=>perform(()=>{if(!Number.isInteger(limit)||limit<1||limit>20)return businessError("invalid_argument","Recent feedback needs a limit from 1 to 20.","storage");if(!enabled)return ok({enabled,events:[]});const rows=db.prepare("SELECT * FROM usage WHERE at>=? AND at<=? AND (operation IN ('search','context','sql','connector.read','connector.invoke') OR operation='action' AND code='effective_invoke') AND (internal=0 OR operation IN ('connector.read','connector.invoke')) ORDER BY at DESC,id DESC LIMIT ?").all(new Date(Date.now()-FEEDBACK_DAYS*DAY).toISOString(),new Date().toISOString(),limit);return ok({enabled,events:rows.map(row=>{const event=decode(row);return{receiptId:event.id,at:event.at,operation:event.operation,outcome:event.outcome,durationMs:event.durationMs,...event.source?{source:event.source}:{},...event.context?{context:event.context}:{},...event.result?{result:event.result}:{}}})})}),recordFeedback:(input,channel)=>perform(()=>{input={...input};channel={...channel};if(!isUsageFeedbackInput(input)||!channel||Object.keys(channel).some(key=>key!=="submissionChannel")||!FEEDBACK_CHANNELS.includes(channel.submissionChannel))return businessError("invalid_argument","Feedback needs one recent receipt, a fixed rating and an optional fixed reason.","storage");if(!enabled)return ok({recorded:false,delivery:"disabled"});db.exec("BEGIN IMMEDIATE");try{const prior=byFeedback.get(input.receiptId,channel.submissionChannel);if(prior){const feedback2=decode(prior).feedback;db.exec("COMMIT");return feedback2.rating===input.rating&&feedback2.reason===input.reason?ok({recorded:false,delivery:"queued",receiptId:String(prior.id)}):businessError("already_exists","This operation already has a different report through this channel.","storage")}const row=byId.get(input.receiptId);if(!row){db.exec("COMMIT");return businessError("not_found","The operation receipt is not available on this installation.","storage")}const target=decode(row),age=Date.now()-Date.parse(target.at);if(!feedbackEligible(target)||age<0||age>FEEDBACK_DAYS*DAY){db.exec("COMMIT");return businessError("failed_precondition","Feedback requires an eligible operation from the last seven days.","storage")}const feedback={targetReceiptId:target.id,rating:input.rating,...input.reason?{reason:input.reason}:{},submissionChannel:channel.submissionChannel,target:{operation:target.operation,outcome:target.outcome,at:target.at,...target.source?{source:target.source}:{},...target.context?{context:target.context}:{},...target.result?{result:target.result}:{}}};const receiptId=insert({operation:"product.feedback",outcome:"ok",durationMs:0,internal:true,feedback},randomUUID(),false);db.exec("COMMIT");return ok({recorded:true,delivery:"queued",receiptId})}catch(error){db.exec("ROLLBACK");throw error}}),report:()=>perform(()=>{const total=db.prepare("SELECT COUNT(*) AS calls,COALESCE(SUM(duration),0) AS duration FROM usage WHERE internal=0 AND operation NOT IN ('flywheel.start','flywheel.run','product.feedback')").get();const flywheel=db.prepare("SELECT COUNT(*) FILTER(WHERE operation='flywheel.start') AS started,COUNT(*) FILTER(WHERE operation='flywheel.run' AND outcome IN ('ok','empty')) AS completed,COUNT(*) FILTER(WHERE operation='flywheel.run' AND outcome='fault') AS failed FROM usage").get();const rows=db.prepare("SELECT source,COUNT(*) FILTER(WHERE outcome IN ('ok','empty','fault')) AS attempted,COUNT(*) FILTER(WHERE outcome='fault') AS faults,COUNT(*) FILTER(WHERE outcome='auth-blocked') AS authBlocked,COUNT(*) FILTER(WHERE outcome='cancelled') AS cancelled,COUNT(*) FILTER(WHERE outcome='invalid') AS invalid FROM usage WHERE operation IN ('connector.read','connector.invoke') AND source IS NOT NULL GROUP BY source ORDER BY source").all();const fabrication=db.prepare("SELECT source,COUNT(*) FILTER(WHERE outcome='ok') AS completed,COUNT(*) FILTER(WHERE outcome='fault') AS failed,COALESCE(SUM(duration),0) AS duration FROM usage WHERE operation='connector.fabricate' AND source IS NOT NULL GROUP BY source ORDER BY source").all();const usable=db.prepare("SELECT COUNT(*) AS n FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE u.operation='connector.usable' AND u.source IS NOT NULL AND u.outcome='ok' AND s.seq=(SELECT MAX(s2.seq) FROM usage_export_seq s2 JOIN usage u2 ON u2.id=s2.event_id WHERE u2.operation='connector.usable' AND u2.source=u.source)").get();return ok({enabled,userId,calls:Number(total.calls),durationMs:Number(total.duration),flywheel:{started:Number(flywheel.started),completed:Number(flywheel.completed),failed:Number(flywheel.failed)},connectors:rows.map(row=>({source:String(row.source),attempted:Number(row.attempted),faults:Number(row.faults),faultRate:Number(row.attempted)?Number(row.faults)/Number(row.attempted):null,authBlocked:Number(row.authBlocked),cancelled:Number(row.cancelled),invalid:Number(row.invalid)})),fabrication:fabrication.map(row=>({source:String(row.source),completed:Number(row.completed),failed:Number(row.failed),durationMs:Number(row.duration)})),usableConnectors:Number(usable.n),collection:collection()})}),async close(){if(!closed){closed=true;db.close()}}};return service}export async function apply(ctx,config){const freshRoot=process.env.ZORTEX_TELEMETRY_NEW_INSTALL_ROOT;const newInstallation=config.newInstallation??!!(freshRoot&&isAbsolute(freshRoot)&&typeof config.root==="string"&&resolve(freshRoot)===resolve(config.root));const service=await createTelemetry({...config,newInstallation,startup:config.startup??true});ctx.provide("zortexTelemetry",service);ctx.effect(()=>()=>service.close())}
1
+ import{DatabaseSync}from"node:sqlite";import{mkdir,lstat,realpath}from"node:fs/promises";import{isAbsolute,join,resolve}from"node:path";import{createHash,createHmac,randomUUID}from"node:crypto";import{businessError,canonicalJson,ok}from"@zortexhq/plugin-connector-framework/api";import{currentOperationalExecution}from"./api/operational.js";import{isUsageEvent,isUsageContext,isUsageFeedbackInput,isFlowId,snapshotUsageRecord,currentFeedbackFlow,currentTelemetryContext,currentUsageInvocation,isUsageObservation,snapshotUsageObservation,OBSERVATION_SNAPSHOT_INTERVAL_MS,OBSERVATION_SNAPSHOT_DAILY_LIMIT,feedbackEligible,FEEDBACK_CHANNELS}from"./api/index.js";export{aggregateUsage}from"./aggregate.js";export const name="zortex-telemetry";export const TELEMETRY_RETENTION_DAYS=30,TELEMETRY_MAX_EVENTS=5e4,TELEMETRY_MAX_RECORD_BYTES=2048;const DAY=864e5,FEEDBACK_DAYS=7;export async function createTelemetry({root,enabled=true,startup=false,newInstallation=false,context=currentTelemetryContext()},runtime={}){if(typeof newInstallation!=="boolean")throw Error("newInstallation must be boolean.");if(!isAbsolute(root)||typeof enabled!=="boolean"||typeof startup!=="boolean")throw Error("Telemetry root must be absolute; enabled must be boolean.");const capturedContext=context?Object.freeze({...context}):void 0;if(context!==void 0&&!isUsageContext(capturedContext))throw Error("Invalid telemetry runtime context.");await mkdir(root,{recursive:true,mode:448});if((await lstat(root)).isSymbolicLink())throw Error("Telemetry root cannot be a link.");const file=join(await realpath(root),"telemetry.sqlite");if((await lstat(file).catch(()=>null))?.isSymbolicLink())throw Error("Telemetry database cannot be a link.");const db=new DatabaseSync(file),now=runtime.now??Date.now;let created=false,userId="",actionSalt="",closed=false,initializing=false,nextAgeSweep=0;try{db.exec("PRAGMA busy_timeout=3000;PRAGMA journal_mode=WAL;BEGIN IMMEDIATE");initializing=true;db.exec("CREATE TABLE IF NOT EXISTS identity(id INTEGER PRIMARY KEY CHECK(id=1),user TEXT NOT NULL);CREATE TABLE IF NOT EXISTS usage(id TEXT PRIMARY KEY,at TEXT NOT NULL,operation TEXT NOT NULL,outcome TEXT NOT NULL,duration REAL NOT NULL,source TEXT,code TEXT,internal INTEGER NOT NULL DEFAULT 0);");const columns=new Set(db.prepare("PRAGMA table_info(usage)").all().map(column=>String(column.name)));for(const[column,type]of[["internal","INTEGER NOT NULL DEFAULT 0"],["trace","TEXT"],["metadata","TEXT"],["feedback_target","TEXT"],["feedback_channel","TEXT"],["observation_key","TEXT"],["observation_fingerprint","TEXT"],["observation_scope","TEXT"],["observation_recorded_at","INTEGER"]])if(!columns.has(column))db.exec(`ALTER TABLE usage ADD COLUMN ${column} ${type}`);created=Number(db.prepare("INSERT OR IGNORE INTO identity(id,user) VALUES(1,?)").run(randomUUID()).changes)===1;userId=String(db.prepare("SELECT user FROM identity").get().user);if(!db.prepare("PRAGMA table_info(identity)").all().some(column=>column.name==="action_salt"))db.exec("ALTER TABLE identity ADD COLUMN action_salt TEXT");if(enabled){db.prepare("UPDATE identity SET action_salt=? WHERE id=1 AND action_salt IS NULL").run(randomUUID());actionSalt=String(db.prepare("SELECT action_salt FROM identity WHERE id=1").get().action_salt)}db.exec("CREATE TABLE IF NOT EXISTS usage_export_seq(seq INTEGER PRIMARY KEY AUTOINCREMENT,event_id TEXT UNIQUE NOT NULL);CREATE TABLE IF NOT EXISTS collection_state(id INTEGER PRIMARY KEY CHECK(id=1),retained_events INTEGER NOT NULL,pruned_events INTEGER NOT NULL DEFAULT 0,retention_floor INTEGER NOT NULL DEFAULT 0,sequence_backfilled INTEGER NOT NULL DEFAULT 0);");if(!db.prepare("SELECT id FROM collection_state WHERE id=1").get())db.exec("INSERT INTO collection_state(id,retained_events) SELECT 1,COUNT(*) FROM usage;");if(!db.prepare("SELECT sequence_backfilled FROM collection_state WHERE id=1").get().sequence_backfilled){db.exec("INSERT OR IGNORE INTO usage_export_seq(event_id) SELECT id FROM usage ORDER BY at,id;UPDATE collection_state SET sequence_backfilled=1 WHERE id=1;")}db.exec("CREATE INDEX IF NOT EXISTS usage_at ON usage(at,id);CREATE UNIQUE INDEX IF NOT EXISTS usage_feedback_once ON usage(feedback_target,feedback_channel) WHERE feedback_target IS NOT NULL;CREATE UNIQUE INDEX IF NOT EXISTS usage_observation_once ON usage(observation_key) WHERE observation_key IS NOT NULL;CREATE INDEX IF NOT EXISTS usage_observation_scope ON usage(observation_scope,observation_recorded_at) WHERE observation_scope IS NOT NULL;CREATE INDEX IF NOT EXISTS usage_observation_budget ON usage(observation_recorded_at) WHERE observation_scope IS NOT NULL;CREATE TABLE IF NOT EXISTS observation_counters(id INTEGER PRIMARY KEY CHECK(id=1),rate_limited INTEGER NOT NULL DEFAULT 0,budget_limited INTEGER NOT NULL DEFAULT 0,unchanged INTEGER NOT NULL DEFAULT 0,duplicates INTEGER NOT NULL DEFAULT 0,last_suppressed_at TEXT);INSERT OR IGNORE INTO observation_counters(id) VALUES(1);CREATE TRIGGER IF NOT EXISTS usage_count_insert AFTER INSERT ON usage BEGIN UPDATE collection_state SET retained_events=retained_events+1 WHERE id=1;END;CREATE TRIGGER IF NOT EXISTS usage_count_delete AFTER DELETE ON usage BEGIN UPDATE collection_state SET retained_events=retained_events-1 WHERE id=1;END;COMMIT;PRAGMA busy_timeout=20;");initializing=false}catch(error){if(initializing){try{db.exec("ROLLBACK")}catch{}}db.close();throw error}const state=db.prepare("SELECT retained_events,pruned_events,retention_floor FROM collection_state WHERE id=1");const add=db.prepare("INSERT OR IGNORE INTO usage(id,at,operation,outcome,duration,source,code,internal,trace,metadata,feedback_target,feedback_channel) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)");const addSequence=db.prepare("INSERT INTO usage_export_seq(event_id) VALUES(?)");const byId=db.prepare("SELECT * FROM usage WHERE id=?");const byFeedback=db.prepare("SELECT * FROM usage WHERE feedback_target=? AND feedback_channel=?");const pageQuery=db.prepare("SELECT s.seq,u.* FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE s.seq>? ORDER BY s.seq LIMIT ?");const pruneFacts=db.prepare("SELECT COUNT(*) AS n,COALESCE(MAX(s.seq),0) AS last_seq FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE u.id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const pruneSequences=db.prepare("DELETE FROM usage_export_seq WHERE event_id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const pruneRows=db.prepare("DELETE FROM usage WHERE id IN (SELECT id FROM usage WHERE id<>? AND at<? ORDER BY at,id LIMIT ?)");const rememberPruning=db.prepare("UPDATE collection_state SET pruned_events=pruned_events+?,retention_floor=MAX(retention_floor,?) WHERE id=1");const oldest=db.prepare("SELECT MIN(at) AS at FROM usage WHERE id<>?");const observationByKey=db.prepare("SELECT id,observation_fingerprint FROM usage WHERE observation_key=?");const lastSnapshot=db.prepare("SELECT observation_fingerprint,observation_recorded_at FROM usage WHERE observation_scope=? ORDER BY observation_recorded_at DESC,id DESC LIMIT 1");const snapshotBudget=db.prepare("SELECT COUNT(*) AS n FROM usage WHERE observation_scope IS NOT NULL AND observation_recorded_at>=? AND observation_recorded_at<?");const observationMetadata=db.prepare("UPDATE usage SET observation_key=?,observation_fingerprint=?,observation_scope=?,observation_recorded_at=? WHERE id=?");const observationCounters=db.prepare("SELECT * FROM observation_counters WHERE id=1");const perform=async fn=>{if(closed)return businessError("unavailable","Telemetry is inactive.","storage");try{return fn()}catch(error){return businessError(error.errcode===5?"unavailable":"data_loss","Telemetry operation failed.","storage")}};const captureIdentity=enabled?{producerRef:randomUUID(),since:new Date(now()).toISOString()}:void 0;const captureCounts={attempted:0,accepted:0,suppressed:0,rejected:0,failed:0};const capture=async fn=>{if(!enabled||closed)return perform(fn);captureCounts.attempted++;const result=await perform(fn);if("ok"in result)captureCounts[result.ok.recorded?"accepted":"suppressed"]++;else if("err"in result&&["invalid_argument","already_exists"].includes(result.err.code))captureCounts.rejected++;else captureCounts.failed++;return result};function collection(after=0){const row=state.get(),stats=observationCounters.get();return{retainedEvents:Number(row.retained_events),prunedEvents:Number(row.pruned_events),retentionFloor:Number(row.retention_floor),limited:after<Number(row.retention_floor),retentionDays:TELEMETRY_RETENTION_DAYS,maxEvents:TELEMETRY_MAX_EVENTS,oldestAvailableAt:oldest.get(userId).at,observations:{snapshotRateLimited:Number(stats.rate_limited),snapshotBudgetLimited:Number(stats.budget_limited),snapshotUnchanged:Number(stats.unchanged),duplicates:Number(stats.duplicates),lastSuppressedAt:stats.last_suppressed_at}}}function decode(row){const metadata=row.metadata?JSON.parse(String(row.metadata)):{};return{id:String(row.id),at:String(row.at),operation:String(row.operation),outcome:String(row.outcome),durationMs:Number(row.duration),...row.source?{source:String(row.source)}:{},...row.code?{code:String(row.code)}:{},...row.internal?{internal:true}:{},...row.trace?{trace:JSON.parse(String(row.trace))}:{},...metadata}}function prune(cutoff,limit){const facts=pruneFacts.get(userId,cutoff,limit);if(!Number(facts.n))return;pruneSequences.run(userId,cutoff,limit);pruneRows.run(userId,cutoff,limit);rememberPruning.run(Number(facts.n),Number(facts.last_seq))}function maintain(){const now2=Date.now();if(now2>=nextAgeSweep){prune(new Date(now2-TELEMETRY_RETENTION_DAYS*DAY).toISOString(),2147483647);nextAgeSweep=now2+6e4}const excess=Number(state.get().retained_events)-TELEMETRY_MAX_EVENTS;if(excess>0)prune("9999-12-31T23:59:59.999Z",excess+Math.min(255,TELEMETRY_MAX_EVENTS-1))}function insert(event,id=randomUUID(),transaction=true,at=new Date().toISOString()){const execution=["product.resources","product.collection"].includes(event.operation)?void 0:currentOperationalExecution();const record={...event,id,at,...capturedContext?{context:capturedContext}:{},...execution?{execution}:{}};if(Buffer.byteLength(JSON.stringify(record))>TELEMETRY_MAX_RECORD_BYTES)throw Error("Telemetry record exceeds its closed metadata budget.");const metadata={...record.context?{context:record.context}:{},...record.execution?{execution:record.execution}:{},...event.operational?{operational:event.operational}:{},...event.resource?{resource:event.resource}:{},...event.collectionStatus?{collectionStatus:event.collectionStatus}:{},...event.result?{result:event.result}:{},...event.correlation?{correlation:event.correlation}:{},...event.errorCategory?{errorCategory:event.errorCategory}:{},...event.feedback?{feedback:event.feedback}:{},...event.observation?{observation:event.observation}:{},...event.invocation?{invocation:event.invocation}:{}};if(transaction)db.exec("BEGIN IMMEDIATE");try{const inserted=add.run(id,at,event.operation,event.outcome,event.durationMs,event.source??null,event.code??null,Number(event.internal??false),event.trace?JSON.stringify(event.trace):null,Object.keys(metadata).length?JSON.stringify(metadata):null,event.feedback?.targetReceiptId??null,event.feedback?.submissionChannel??null);if(Number(inserted.changes))addSequence.run(id);maintain();if(transaction)db.exec("COMMIT");return id}catch(error){if(transaction)db.exec("ROLLBACK");throw error}}if(enabled){try{db.exec("BEGIN IMMEDIATE");maintain();db.exec("COMMIT")}catch(error){try{db.exec("ROLLBACK")}catch{}db.close();throw error}}if(startup&&enabled){insert({operation:"product.first_start",outcome:"ok",durationMs:0,internal:true,code:created&&newInstallation?"new_install":"first_observed"},userId);insert({operation:"product.started",outcome:"ok",durationMs:0,internal:true})}const service={isEnabled:()=>enabled&&!closed,collectionStats:()=>!enabled||closed||!captureIdentity?void 0:{...captureIdentity,scope:"record_and_observe_api_calls",...captureCounts,pending:captureCounts.attempted-captureCounts.accepted-captureCounts.suppressed-captureCounts.rejected-captureCounts.failed},sourceReference(source){if(!enabled||closed||!actionSalt||typeof source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(source))return;const hash=createHmac("sha256",actionSalt).update(JSON.stringify(["zortex-source-v1",source])).digest("hex");return hash.slice(0,8)+"-"+hash.slice(8,12)+"-8"+hash.slice(13,16)+"-a"+hash.slice(17,20)+"-"+hash.slice(20,32)},actionReference(source,method){if(!enabled||closed||!actionSalt||typeof source!=="string"||!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof method!=="string"||!method.length||Buffer.byteLength(method)>512)return;const hash=createHmac("sha256",actionSalt).update(JSON.stringify(["zortex-action-v2",source,method])).digest("hex");return hash.slice(0,8)+"-"+hash.slice(8,12)+"-8"+hash.slice(13,16)+"-a"+hash.slice(17,20)+"-"+hash.slice(20,32)},observe:input=>capture(()=>{if(!enabled)return ok({recorded:false,reason:"disabled"});const snapshot=snapshotUsageObservation(input);if(!isUsageObservation(snapshot))return businessError("invalid_argument","Observation accepts only fixed, content-free metadata and known counts.","storage");const{key,source,at,...rawFacts}=snapshot;const facts=Object.fromEntries(Object.entries(rawFacts).filter(([,value])=>value!==void 0));if(facts.kind==="connection")facts.capabilities=[...facts.capabilities].sort();const hash=value=>createHash("sha256").update(canonicalJson(value)).digest("hex");const observationKey=hash(["zortex-observation-v1",userId,snapshot.kind,source,key]);const fingerprint=hash({source,facts});const receiptId=observationKey.slice(0,8)+"-"+observationKey.slice(8,12)+"-5"+observationKey.slice(13,16)+"-a"+observationKey.slice(17,20)+"-"+observationKey.slice(20,32);const recordedAt=now(),observedAt=at??new Date(recordedAt).toISOString();const scope=facts.kind==="sync"?null:hash([facts.kind,source,facts.connectionRef??null,...facts.kind==="inventory"?[facts.population,facts.attribution]:[]]);db.exec("BEGIN IMMEDIATE");try{const prior=observationByKey.get(observationKey);if(prior){if(prior.observation_fingerprint!==fingerprint){db.exec("COMMIT");return businessError("already_exists","This observation key already has different metadata.","storage")}db.exec("UPDATE observation_counters SET duplicates=duplicates+1 WHERE id=1");db.exec("COMMIT");return ok({recorded:false,reason:"duplicate",receiptId:String(prior.id)})}if(scope){const previous=lastSnapshot.get(scope),elapsed=recordedAt-Number(previous?.observation_recorded_at??0);const unchanged=previous&&previous.observation_fingerprint===fingerprint&&elapsed<DAY;const limited=previous&&elapsed<OBSERVATION_SNAPSHOT_INTERVAL_MS;const dayStart=Math.floor(recordedAt/DAY)*DAY;const budget=Number(snapshotBudget.get(dayStart,dayStart+DAY).n)>=OBSERVATION_SNAPSHOT_DAILY_LIMIT;if(unchanged||limited||budget){const field=unchanged?"unchanged":limited?"rate_limited":"budget_limited";db.prepare(`UPDATE observation_counters SET ${field}=${field}+1,last_suppressed_at=? WHERE id=1`).run(new Date(recordedAt).toISOString());db.exec("COMMIT");return ok({recorded:false,reason:unchanged?"unchanged":"rate_limited"})}}const outcome=facts.kind!=="sync"?"ok":facts.status==="completed"?"ok":facts.status==="cancelled"?"cancelled":facts.status==="failed"||facts.status==="cleanup_blocked"?"fault":"unknown";insert({operation:"connector."+facts.kind,outcome,durationMs:facts.kind==="sync"?facts.durationMs:0,source,internal:true,observation:facts},receiptId,false,observedAt);observationMetadata.run(observationKey,fingerprint,scope,recordedAt,receiptId);db.exec("COMMIT");return ok({recorded:true,reason:"recorded",receiptId})}catch(error){db.exec("ROLLBACK");throw error}}),record:input=>capture(()=>{if(!enabled)return ok({recorded:false});const snapshot=snapshotUsageRecord(input);if(!isUsageEvent(snapshot)||snapshot.operation==="product.feedback"||snapshot.operation==="product.first_start")return businessError("invalid_argument","Usage accepts only content-free fields; startup and feedback anchors are provider-owned.","storage");const event=snapshot,flow=currentFeedbackFlow();if(!["product.resources","product.collection"].includes(event.operation)&&!event.correlation&&flow&&(!event.source||event.source===flow.source)&&isFlowId(flow.flowId))event.correlation={flowId:flow.flowId,...isFlowId(flow.connectionFlowId)?{connectionFlowId:flow.connectionFlowId}:{}};const invocation=["product.resources","product.collection"].includes(event.operation)?void 0:currentUsageInvocation();const measuredAt=event.resource?.asOf??event.collectionStatus?.asOf;return ok({recorded:true,receiptId:insert({...event,...invocation?{invocation:{...invocation}}:{}},void 0,true,measuredAt)})}),readBatch:({after=0,limit=500})=>perform(()=>{if(!Number.isSafeInteger(after)||after<0||!Number.isInteger(limit)||limit<1||limit>1e3)return businessError("invalid_argument","Usage paging needs an ordered cursor and 1\u20131000 events.","storage");const found=pageQuery.all(after,limit+1),selected=found.slice(0,limit);return ok({format:"zortex-usage/v1",userId,enabled,cursor:selected.length?Number(selected.at(-1).seq):after,more:found.length>limit,eventCursors:selected.map(row=>Number(row.seq)),events:selected.map(decode),collection:collection(after)})}),export:()=>perform(()=>{const events=db.prepare("SELECT * FROM usage ORDER BY at,id LIMIT 100001").all().map(decode);if(events.length>1e5)return businessError("resource_exhausted","Usage export exceeds its batch limit.","storage");return ok({format:"zortex-usage/v1",userId,enabled,events,collection:collection()})}),recent:({limit=5}={})=>perform(()=>{if(!Number.isInteger(limit)||limit<1||limit>20)return businessError("invalid_argument","Recent feedback needs a limit from 1 to 20.","storage");if(!enabled)return ok({enabled,events:[]});const rows=db.prepare("SELECT * FROM usage WHERE at>=? AND at<=? AND (operation IN ('search','context','sql','connector.read','connector.invoke') OR operation='action' AND code='effective_invoke') AND (internal=0 OR operation IN ('connector.read','connector.invoke')) ORDER BY at DESC,id DESC LIMIT ?").all(new Date(Date.now()-FEEDBACK_DAYS*DAY).toISOString(),new Date().toISOString(),limit);return ok({enabled,events:rows.map(row=>{const event=decode(row);return{receiptId:event.id,at:event.at,operation:event.operation,outcome:event.outcome,durationMs:event.durationMs,...event.source?{source:event.source}:{},...event.context?{context:event.context}:{},...event.result?{result:event.result}:{}}})})}),recordFeedback:(input,channel)=>perform(()=>{input={...input};channel={...channel};if(!isUsageFeedbackInput(input)||!channel||Object.keys(channel).some(key=>key!=="submissionChannel")||!FEEDBACK_CHANNELS.includes(channel.submissionChannel))return businessError("invalid_argument","Feedback needs one recent receipt, a fixed rating and an optional fixed reason.","storage");if(!enabled)return ok({recorded:false,delivery:"disabled"});db.exec("BEGIN IMMEDIATE");try{const prior=byFeedback.get(input.receiptId,channel.submissionChannel);if(prior){const feedback2=decode(prior).feedback;db.exec("COMMIT");return feedback2.rating===input.rating&&feedback2.reason===input.reason?ok({recorded:false,delivery:"queued",receiptId:String(prior.id)}):businessError("already_exists","This operation already has a different report through this channel.","storage")}const row=byId.get(input.receiptId);if(!row){db.exec("COMMIT");return businessError("not_found","The operation receipt is not available on this installation.","storage")}const target=decode(row),age=Date.now()-Date.parse(target.at);if(!feedbackEligible(target)||age<0||age>FEEDBACK_DAYS*DAY){db.exec("COMMIT");return businessError("failed_precondition","Feedback requires an eligible operation from the last seven days.","storage")}const feedback={targetReceiptId:target.id,rating:input.rating,...input.reason?{reason:input.reason}:{},submissionChannel:channel.submissionChannel,target:{operation:target.operation,outcome:target.outcome,at:target.at,...target.source?{source:target.source}:{},...target.context?{context:target.context}:{},...target.result?{result:target.result}:{}}};const receiptId=insert({operation:"product.feedback",outcome:"ok",durationMs:0,internal:true,feedback},randomUUID(),false);db.exec("COMMIT");return ok({recorded:true,delivery:"queued",receiptId})}catch(error){db.exec("ROLLBACK");throw error}}),report:()=>perform(()=>{const total=db.prepare("SELECT COUNT(*) AS calls,COALESCE(SUM(duration),0) AS duration FROM usage WHERE internal=0 AND operation NOT IN ('flywheel.start','flywheel.run','product.feedback')").get();const flywheel=db.prepare("SELECT COUNT(*) FILTER(WHERE operation='flywheel.start') AS started,COUNT(*) FILTER(WHERE operation='flywheel.run' AND outcome IN ('ok','empty')) AS completed,COUNT(*) FILTER(WHERE operation='flywheel.run' AND outcome='fault') AS failed FROM usage").get();const rows=db.prepare("SELECT source,COUNT(*) FILTER(WHERE outcome IN ('ok','empty','fault')) AS attempted,COUNT(*) FILTER(WHERE outcome='fault') AS faults,COUNT(*) FILTER(WHERE outcome='auth-blocked') AS authBlocked,COUNT(*) FILTER(WHERE outcome='cancelled') AS cancelled,COUNT(*) FILTER(WHERE outcome='invalid') AS invalid FROM usage WHERE operation IN ('connector.read','connector.invoke') AND source IS NOT NULL GROUP BY source ORDER BY source").all();const fabrication=db.prepare("SELECT source,COUNT(*) FILTER(WHERE outcome='ok') AS completed,COUNT(*) FILTER(WHERE outcome='fault') AS failed,COALESCE(SUM(duration),0) AS duration FROM usage WHERE operation='connector.fabricate' AND source IS NOT NULL GROUP BY source ORDER BY source").all();const usable=db.prepare("SELECT COUNT(*) AS n FROM usage_export_seq s JOIN usage u ON u.id=s.event_id WHERE u.operation='connector.usable' AND u.source IS NOT NULL AND u.outcome='ok' AND s.seq=(SELECT MAX(s2.seq) FROM usage_export_seq s2 JOIN usage u2 ON u2.id=s2.event_id WHERE u2.operation='connector.usable' AND u2.source=u.source)").get();return ok({enabled,userId,calls:Number(total.calls),durationMs:Number(total.duration),flywheel:{started:Number(flywheel.started),completed:Number(flywheel.completed),failed:Number(flywheel.failed)},connectors:rows.map(row=>({source:String(row.source),attempted:Number(row.attempted),faults:Number(row.faults),faultRate:Number(row.attempted)?Number(row.faults)/Number(row.attempted):null,authBlocked:Number(row.authBlocked),cancelled:Number(row.cancelled),invalid:Number(row.invalid)})),fabrication:fabrication.map(row=>({source:String(row.source),completed:Number(row.completed),failed:Number(row.failed),durationMs:Number(row.duration)})),usableConnectors:Number(usable.n),collection:collection()})}),async close(){if(!closed){closed=true;db.close()}}};return service}export async function apply(ctx,config){const freshRoot=process.env.ZORTEX_TELEMETRY_NEW_INSTALL_ROOT;const newInstallation=config.newInstallation??!!(freshRoot&&isAbsolute(freshRoot)&&typeof config.root==="string"&&resolve(freshRoot)===resolve(config.root));const service=await createTelemetry({...config,newInstallation,startup:config.startup??true});ctx.provide("zortexTelemetry",service);ctx.effect(()=>()=>service.close())}
@@ -0,0 +1 @@
1
+ import{randomUUID}from"node:crypto";import{cpus,freemem,totalmem}from"node:os";import{isResourceVaultMetadata,isUsageResourceSnapshot,snapshotResourceMetadata,RESOURCE_VAULT_POPULATIONS}from"./api/resources.js";export const PROCESS_RESOURCE_INTERVAL_MS=6e4,VAULT_RESOURCE_INTERVAL_MS=3e5;const nonnegative=value=>Number.isSafeInteger(value)&&Number(value)>=0;const duration=(start,clock)=>Math.min(6e4,Math.max(0,Math.round(clock()-start)));const emptyVault=at=>({schemaVersion:1,scope:"sqlite_files",asOf:at,coverage:"unavailable",sizeBasis:"logical_file_bytes",populations:RESOURCE_VAULT_POPULATIONS.map(population=>({population,coverage:"unavailable"}))});export function createResourceSampler(options,runtime={}){const now=runtime.now??Date.now,clock=runtime.monotonic??(()=>performance.now());const counters={attempts:0,queued:0,rejected:0,disabled:0,overlapping:0,timeouts:0};let processRef,storageRead;let stopped=false,started=false,busy=false,nextVault=0,timer;const enabled=()=>{try{return!stopped&&options.enabled()===true}catch{return false}};const bounded=async(promise,milliseconds)=>{let deadline;try{return await Promise.race([promise.then(value=>({done:true,value})),new Promise(resolve=>{deadline=setTimeout(()=>resolve({done:false}),milliseconds)})])}finally{if(deadline)clearTimeout(deadline)}};const queue=async value=>{if(!enabled()){counters.disabled++;return}try{const snapshot=snapshotResourceMetadata(value);if(!isUsageResourceSnapshot(snapshot)){counters.rejected++;return}const pending=await bounded(Promise.resolve(options.record(snapshot)),50);if(!pending.done){counters.timeouts++;counters.rejected++;return}const result=pending.value;if(result&&typeof result==="object"&&("err"in result||"ok"in result&&result.ok&&typeof result.ok==="object"&&"recorded"in result.ok&&result.ok.recorded===false)){counters.rejected++;return}counters.queued++}catch{counters.rejected++}};const sampleProcess=()=>{const start=clock(),metrics={};try{const memory=(runtime.memory??(()=>process.memoryUsage()))();for(const[field,value]of Object.entries({rssBytes:memory.rss,heapUsedBytes:memory.heapUsed,heapTotalBytes:memory.heapTotal,externalBytes:memory.external,arrayBuffersBytes:memory.arrayBuffers}))if(nonnegative(value))metrics[field]=value}catch{}try{const cpu=(runtime.cpu??(()=>process.cpuUsage()))();if(nonnegative(cpu.user))metrics.cpuUserMicros=cpu.user;if(nonnegative(cpu.system))metrics.cpuSystemMicros=cpu.system}catch{}try{const bytes=(runtime.usage??(()=>process.resourceUsage()))().maxRSS*1024;if(nonnegative(bytes))metrics.peakRssBytes=bytes}catch{}try{const ms=Math.round((runtime.uptime??(()=>process.uptime()))()*1e3);if(nonnegative(ms))metrics.uptimeMs=ms}catch{}try{const system=(runtime.system??(()=>({total:totalmem(),free:freemem(),cpus:cpus().length})))();if(nonnegative(system.total))metrics.systemMemoryTotalBytes=system.total;if(nonnegative(system.free))metrics.systemMemoryFreeBytes=system.free;if(nonnegative(system.cpus)&&system.cpus>0)metrics.logicalCpuCount=system.cpus}catch{}const fields=Object.keys(metrics).length;processRef??=randomUUID();return{schemaVersion:1,kind:"process",snapshotId:randomUUID(),processRef,asOf:new Date(now()).toISOString(),sampleDurationMs:duration(start,clock),role:options.role,memoryScope:"process_shared",childMemoryCoverage:"unavailable",rssBasis:"node_process",coverage:fields===12?"complete":fields?"partial":"unavailable",...metrics}};const sample=async()=>{if(!enabled()){counters.disabled++;return}if(busy){counters.overlapping++;return}busy=true;counters.attempts++;try{await queue(sampleProcess());if(!enabled()||now()<nextVault)return;nextVault=now()+VAULT_RESOURCE_INTERVAL_MS;const start=clock();let metadata=emptyVault(new Date(now()).toISOString());if(options.storageSnapshot)try{if(!storageRead){storageRead=Promise.resolve(options.storageSnapshot()).catch(()=>void 0);void storageRead.finally(()=>{storageRead=void 0})}const pending=await bounded(storageRead,100);if(!pending.done)counters.timeouts++;else{const reply=pending.value,value=snapshotResourceMetadata(reply&&typeof reply==="object"&&"ok"in reply?reply.ok:void 0);if(isResourceVaultMetadata(value))metadata=value}}catch{}await queue({...metadata,kind:"vault",snapshotId:randomUUID(),sampleDurationMs:duration(start,clock)})}catch{counters.rejected++}finally{busy=false}};return{start(){if(started||stopped)return;started=true;void sample();timer=setInterval(()=>{void sample()},PROCESS_RESOURCE_INTERVAL_MS);timer.unref()},sample,stop(){stopped=true;if(timer)clearInterval(timer);timer=void 0},stats:()=>({...counters})}}
@@ -9,6 +9,9 @@
9
9
  "./api": {
10
10
  "default": "./dist/api/index.js"
11
11
  },
12
+ "./resources": {
13
+ "default": "./dist/resources.js"
14
+ },
12
15
  "./api/*": {
13
16
  "default": "./dist/api/*.js"
14
17
  }
@@ -1 +1 @@
1
- export*from"./blob-store.js";export*from"./custody.js";export*from"./binding-custody.js";export*from"./connector-supervisor.js";export*from"./local-source.js";export*from"./sqlite-vault.js";export*from"./vault-backup.js";export*from"./vault-sql.js";export*from"./checkpoint-erasure-proof.js";export*from"./metadata.js";
1
+ export*from"./blob-store.js";export*from"./custody.js";export*from"./binding-custody.js";export*from"./connector-supervisor.js";export*from"./local-source.js";export*from"./sqlite-vault.js";export*from"./vault-backup.js";export*from"./vault-sql.js";export*from"./checkpoint-erasure-proof.js";export*from"./metadata.js";export*from"./storage-metadata.js";
@@ -0,0 +1 @@
1
+ export const VAULT_STORAGE_POPULATIONS=["stored_event_rows","live_event_rows","system_event_rows","cached_records","binding_records","stored_blobs"];
@@ -1 +1 @@
1
- import{Original,businessError,ok,canonicalJson}from"@zortexhq/plugin-connector-framework/api";import{mkdirSync}from"node:fs";import{dirname,isAbsolute}from"node:path";import{createHash,randomUUID}from"node:crypto";import{Database}from"./sqlite.js";import{assertNotRecovery}from"./recovery-guard.js";import{SCHEMA}from"./schema.js";import{LiftedRecordRules}from"./record-rules.js";import{createSqliteAppendPort}from"./append-port.js";import{createIdReader}from"./id-read.js";import{createProcessJournal,PROCESS_JOURNAL_SCHEMA}from"./process-journal.js";import{createLocalSourceRegistry,LOCAL_SOURCE_SCHEMA}from"./local-source-registry.js";import{createSqlReader,sqlLimits,DEFAULT_SQL_LIMITS}from"./sql.js";import{createBlobPort}from"./blob-port.js";import{createSourcePrincipalPort}from"./source-principal-port.js";import{createSnapshotReader}from"./snapshot.js";import{createCheckpointErasureProof}from"./checkpoint-erasure-proof.js";export const name="zortex-sqlite-vault";export{createVaultMcp,startVaultMcp,vaultTools}from"./mcp.js";const inactive=()=>Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"SQLite Vault is closed."});export class SqliteVault{identity;db;records;facts;closed=false;declarations=new Map;authorities=new Map;requiredAuthorities=new Set;bindingEpochs=new Map;readPageRows;reader;snapshots;constructor(config){if(!config||typeof config.file!=="string"||!isAbsolute(config.file)||!Array.isArray(config.streams))throw Error("SQLite Vault requires an absolute file and declared streams.");const backupNamespaces=config.backupPrivateNamespaces??[];if(!Array.isArray(backupNamespaces)||backupNamespaces.length>64||backupNamespaces.some(n=>typeof n!=="string"||!/^[a-z][a-z0-9.-]{0,63}$/.test(n)))throw Error("Invalid trusted backup namespace policy.");const busy=config.busyTimeoutMs??3e3;if(!Number.isSafeInteger(busy)||busy<1||busy>6e4)throw Error("SQLite busy timeout must be 1\u201360000 ms.");const pageRows=config.readPageRows??128;if(!Number.isSafeInteger(pageRows)||pageRows<1||pageRows>4096)throw Error("SQLite read page must be 1\u20134096 rows.");this.readPageRows=pageRows;const readLimits=sqlLimits(config.sql??DEFAULT_SQL_LIMITS);if(config.execution&&(!config.execution.runId||!config.execution.codeVersion))throw Error("Execution binding requires run identity and code version.");assertNotRecovery(config.file,busy);mkdirSync(dirname(config.file),{recursive:true});this.db=new Database(config.file);try{this.db.exec(`PRAGMA busy_timeout=${busy};`);const version=this.db.query("PRAGMA user_version").get().user_version;if(version!==0&&version!==1)throw Error("Unsupported SQLite Vault schema version.");const populated=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get()!==null;if(populated){const hasMeta=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta'").get()!==null;if(!hasMeta||this.db.query("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error("Different SQLite format; select a new Vault file.")}this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;");this.db.exec("BEGIN IMMEDIATE");try{this.db.exec(SCHEMA+PROCESS_JOURNAL_SCHEMA+LOCAL_SOURCE_SCHEMA);this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('zortex-sqlite-vault-format','1')").run();this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('vault-identity',?)").run(randomUUID());this.db.exec("PRAGMA user_version=1; COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}this.identity=this.db.query("SELECT value FROM meta WHERE key='vault-identity'").get().value;this.snapshots=createSnapshotReader(config.file,this.identity,[...backupNamespaces]);const now=config.now??(()=>new Date().toISOString());const saved=this.db.query("SELECT definition FROM source_streams ORDER BY source,stream").all().map(row=>JSON.parse(row.definition));for(const row of this.db.query("SELECT source FROM source_authority_required").all())this.requiredAuthorities.add(row.source);this.records=new LiftedRecordRules(this.db,saved,now,"events",config.execution,origin=>{const binding=this.authorities.get(origin.source);return!binding&&!this.requiredAuthorities.has(origin.source)&&!this.db.query("SELECT 1 FROM source_authority_required WHERE source=?").get(origin.source)?Original.ok(true):binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Required source append authority is inactive."})});this.facts=new LiftedRecordRules(this.db,saved,now,"system_events");for(const row of saved)this.declarations.set(row.source+"\0"+row.stream,row);const admitted=this.registerStreams(config.streams);if(!Original.isOk(admitted))throw Error("Source stream declaration changed or is invalid.");this.reader=createSqlReader(config.file,readLimits)}catch(error){this.db.close();throw error}}createAppendPort(){return createSqliteAppendPort(this.db,this,()=>this.closed,this.readPageRows)}createBlobPort(){return createBlobPort(this.db,()=>this.closed,origin=>{const binding=this.authorities.get(origin.source);return binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Connector blob bytes require a current trusted source authority binding."})})}createSourcePrincipalPort(){return createSourcePrincipalPort(this.db,()=>this.closed)}registerConnectorAuthority(source,authorize){return this.registerAuthority(source,authorize,false)}registerAuthority(source,authorize,bindingAuthority){if(this.closed||!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof authorize!=="function")throw Error("Invalid trusted source authority binding.");if(this.authorities.get(source)?.active)throw Error("Source authority is already bound.");if(!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source))throw Error("Isolated source requires binding authority.");this.db.query("INSERT OR IGNORE INTO source_authority_required(source) VALUES(?)").run(source);this.requiredAuthorities.add(source);const binding={authorize:origin=>!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source)?Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Isolated source requires binding authority."}):authorize(origin),active:true};this.authorities.set(source,binding);return()=>{binding.active=false}}registerConnectedSourceAuthority(source,expected){if(!Original.isUlid(expected?.grant)||typeof expected.account!=="string"||!expected.account||typeof expected.updatedAt!=="string"||!Number.isFinite(Date.parse(expected.updatedAt))||!Array.isArray(expected.scopes)||!expected.scopes.length||expected.scopes.some(scope=>typeof scope!=="string"||!scope))throw Error("Invalid connected source authority epoch.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Source identity or consent changed before append."});return this.registerConnectorAuthority(source,origin=>{if(origin.grant!==expected.grant)return denied();const row=this.db.query("SELECT metadata FROM connections WHERE source=?").get(source);if(!row)return denied();let current;try{current=JSON.parse(row.metadata)}catch{return denied()}if(!current||typeof current!=="object"||Array.isArray(current))return denied();const info=current;const scopes=info.scopes;if(info.source!==source||info.provider!=="google"||info.state!=="connected"||info.updatedAt!==expected.updatedAt||(info.accountId??info.account)!==expected.account||!Array.isArray(scopes)||expected.scopes.some(scope=>!scopes.includes(scope)))return denied();return Original.ok(true)})}registerBindingSourceAuthority(source,expected){const positive=value=>Number.isSafeInteger(value)&&Number(value)>0;const text=value=>typeof value==="string"&&value.length>0&&value.length<=2048;if(!expected||!Original.isUlid(expected.grant)||![expected.bindingId,expected.subject,expected.custodyGrantId,expected.audience].every(text)||![expected.bindingRevision,expected.custodyGrantRevision,expected.selectionRevision].every(positive)||!Number.isSafeInteger(expected.scopeEpoch)||expected.scopeEpoch<0||!Array.isArray(expected.scopes)||!expected.scopes.length||!expected.scopes.every(text))throw Error("Invalid binding source authority epoch.");if((expected.credentialResourceId!==void 0||expected.credentialResourceRevision!==void 0)&&(!text(expected.credentialResourceId)||!positive(expected.credentialResourceRevision)))throw Error("Invalid credential resource epoch.");const epoch={...expected,scopes:[...new Set(expected.scopes)].sort()};const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==epoch.subject)throw Error("Isolated source is pinned to a different subject.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Selected source identity or consent changed before append."});const withdraw=this.registerAuthority(source,origin=>{if(origin.grant!==epoch.grant)return denied();try{const pin2=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin2&&pin2.subject!==epoch.subject)return denied();const selection=this.db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const binding=this.db.query("SELECT source,subject,revision,metadata FROM account_bindings WHERE id=?").get(epoch.bindingId);const grant=this.db.query("SELECT binding_id,revision,metadata FROM authorization_grants WHERE id=?").get(epoch.custodyGrantId);if(!selection||selection.binding_id!==epoch.bindingId||selection.revision!==epoch.selectionRevision||!binding||binding.source!==source||binding.subject!==epoch.subject||binding.revision!==epoch.bindingRevision||!grant||grant.binding_id!==epoch.bindingId||grant.revision!==epoch.custodyGrantRevision)return denied();if(epoch.credentialResourceId!==void 0){const resource=this.db.query("SELECT binding_id,kind,owner_key,revision FROM credential_resources WHERE id=?").get(epoch.credentialResourceId);if(!resource||resource.binding_id!==epoch.bindingId||resource.kind!=="oauth"||resource.owner_key!=="resident"||resource.revision!==epoch.credentialResourceRevision)return denied()}const b=JSON.parse(binding.metadata),g=JSON.parse(grant.metadata);if(b.id!==epoch.bindingId||b.revision!==epoch.bindingRevision||b.state!=="connected"||b.identity?.source!==source||b.identity?.subject!==epoch.subject||!Number.isFinite(Date.parse(b.verifiedAt))||g.id!==epoch.custodyGrantId||g.revision!==epoch.custodyGrantRevision||g.bindingId!==epoch.bindingId||g.state!=="active"||g.purpose!=="L1"||g.audience!==epoch.audience||g.scopeEpoch!==epoch.scopeEpoch||!Array.isArray(g.scopes)||JSON.stringify([...new Set(g.scopes)].sort())!==JSON.stringify(epoch.scopes))return denied();return Original.ok(true)}catch{return denied()}},true);this.bindingEpochs.set(source,epoch);return()=>{withdraw();if(this.bindingEpochs.get(source)===epoch)this.bindingEpochs.delete(source)}}registerIsolatedBindingSourceAuthority(source,expected){let withdraw;let begun=false;const wasRequired=this.requiredAuthorities.has(source);try{this.db.exec("BEGIN IMMEDIATE");begun=true;withdraw=this.registerBindingSourceAuthority(source,expected);const authority=this.authorities.get(source);if(!authority?.active||!Original.isOk(authority.authorize({kind:"connector",source,grant:expected.grant})))throw Error("Selected binding is not currently authorized.");const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==expected.subject)throw Error("Isolated source is pinned to a different subject.");if(!pin){if(this.db.query("SELECT 1 FROM events WHERE source=? LIMIT 1").get(source)||this.db.query("SELECT 1 FROM system_events WHERE json_valid(payload) AND json_extract(payload,'$.source')=? LIMIT 1").get(source)||this.db.query("SELECT 1 FROM binding_sync_checkpoints LIMIT 1").get())throw Error("Cannot pin a vault with existing source data or checkpoints.");this.db.query("INSERT INTO isolated_source_subjects(source,subject) VALUES(?,?)").run(source,expected.subject)}this.db.exec("COMMIT");begun=false;return withdraw}catch(error){if(begun)this.db.exec("ROLLBACK");withdraw?.();if(!wasRequired)this.requiredAuthorities.delete(source);throw error}}recordIsolatedVerifiedGrant(source){const epoch=this.bindingEpochs.get(source),authority=this.authorities.get(source);const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Verified grant authority changed."});if(!epoch?.credentialResourceId||!authority?.active)return denied();try{this.db.exec("BEGIN IMMEDIATE");const admitted=authority.authorize({kind:"connector",source,grant:epoch.grant});if(!Original.isOk(admitted)){this.db.exec("ROLLBACK");return denied()}const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(!pin||pin.subject!==epoch.subject){this.db.exec("ROLLBACK");return denied()}const old=this.db.query("SELECT binding_id,subject FROM isolated_verified_grants WHERE source=? AND grant_id=?").get(source,epoch.grant);if(old&&(old.binding_id!==epoch.bindingId||old.subject!==epoch.subject)){this.db.exec("ROLLBACK");return denied()}if(!old)this.db.query("INSERT INTO isolated_verified_grants(source,grant_id,binding_id,subject) VALUES(?,?,?,?)").run(source,epoch.grant,epoch.bindingId,epoch.subject);this.db.exec("COMMIT");return Original.ok(true)}catch{try{this.db.exec("ROLLBACK")}catch{}return denied()}}matchesReadGeneration(generation){const row=this.db.query("SELECT (SELECT value FROM meta WHERE key='watermark') AS watermark,(SELECT value FROM meta WHERE key='projection-epoch') AS epoch").get();return!!row&&Original.isUlid(generation.untilSeq)&&Number.isSafeInteger(generation.projectionEpoch)&&row.epoch!==null&&(row.watermark??"00000000000000000000000000")===generation.untilSeq&&Number(row.epoch)===generation.projectionEpoch}readIsolatedVerifiedGrants(source,generation){const fail=()=>Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Source history or generation lacks verified binding provenance."});const ctx=this.checkpointContext(source,true);if(!ctx?.epoch.credentialResourceId)return fail();try{this.db.exec("BEGIN IMMEDIATE");if(!this.matchesReadGeneration(generation)||!ctx.authority.active||!Original.isOk(ctx.authority.authorize({kind:"connector",source,grant:ctx.epoch.grant}))){this.db.exec("ROLLBACK");return fail()}const rows=this.db.query("SELECT grant_id FROM isolated_verified_grants WHERE source=? AND binding_id=? AND subject=? ORDER BY grant_id").all(source,ctx.epoch.bindingId,ctx.epoch.subject);const ids=rows.map(row=>row.grant_id);if(!ids.includes(ctx.epoch.grant)||ids.some(id=>!Original.isUlid(id))){this.db.exec("ROLLBACK");return fail()}const allowed=new Set(ids);for(const row of this.db.query("SELECT origin FROM events WHERE source=? AND erased=0 AND id<=?").all(source,generation.untilSeq)){let origin;try{origin=JSON.parse(row.origin)}catch{this.db.exec("ROLLBACK");return fail()}if(origin?.kind!=="connector"||origin.source!==source||!allowed.has(origin.grant)){this.db.exec("ROLLBACK");return fail()}}this.db.exec("COMMIT");return Original.ok([...ids.filter(id=>id!==ctx.epoch.grant),ctx.epoch.grant])}catch{try{this.db.exec("ROLLBACK")}catch{}return fail()}}checkpointContext(source,audit=false){const epoch=this.bindingEpochs.get(source),authority=this.authorities.get(source);if(!epoch||!authority?.active)return null;const stamp=canonicalJson(epoch);const auditEpoch=createHash("sha256").update(stamp).digest("hex");return{epoch,authority,key:JSON.stringify(audit?[source,epoch.bindingId,"audit",auditEpoch]:[source,epoch.bindingId]),stamp}}validCheckpoint(value,stamp,source,grant){if(!value||value.epoch!==stamp||!(value.cursor===null||typeof value.cursor==="string")||!Number.isSafeInteger(value.sequence)||value.sequence<0||!Original.isUlid(value.factId))return false;const row=this.db.query("SELECT kind,payload FROM system_events WHERE id=? AND erased=0").get(value.factId);if(!row||row.kind!=="sync.cursor.advanced")return false;try{const payload=JSON.parse(row.payload);return Original.isOk(Original.validateSyncEventPayload(row.kind,payload))&&payload.source===source&&payload.grantId===grant&&payload.cursor===value.cursor&&payload.stateSequence===value.sequence}catch{return false}}readBindingCheckpoint(source){return this.readBindingCheckpointInternal(source,false)}readBindingAuditCheckpoint(source){return this.readBindingCheckpointInternal(source,true)}readBindingCheckpointInternal(source,audit){if(this.closed)return inactive();const ctx=this.checkpointContext(source,audit);if(!ctx)return Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Binding checkpoint authority unavailable."});try{this.db.exec("BEGIN IMMEDIATE")}catch{return Original.errResult({code:"unavailable",layer:"storage",retryability:"transient",message:"SQLite writer busy."})}try{const admitted=ctx.authority.authorize({kind:"connector",source,grant:ctx.epoch.grant});if(!Original.isOk(admitted)){this.db.exec("ROLLBACK");return admitted}const row=this.db.query("SELECT revision,value FROM binding_sync_checkpoints WHERE key=?").get(ctx.key);if(!row){this.db.exec("COMMIT");return Original.ok(null)}const value=JSON.parse(row.value);if(value.epoch!==ctx.stamp){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Checkpoint belongs to a different authority epoch."})}if(!this.validCheckpoint(value,ctx.stamp,source,ctx.epoch.grant))throw Error("Invalid checkpoint");this.db.exec("COMMIT");return Original.ok({revision:row.revision,cursor:value.cursor})}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Binding checkpoint is invalid."})}}writeBindingCheckpoint(source,expectedRevision,fact){return this.writeBindingCheckpointInternal(source,expectedRevision,fact,false,false)}writeBindingCheckpointInternal(source,expectedRevision,fact,withinTransaction,audit){if(this.closed)return inactive();const ctx=this.checkpointContext(source,audit);const invalid=()=>Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid binding checkpoint fact."});if(!ctx)return Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Binding checkpoint authority unavailable."});if(!Number.isSafeInteger(expectedRevision)||expectedRevision<0||!fact||fact.kind!=="sync.cursor.advanced"||fact.nk?.source!=="zortex"||fact.nk?.stream!=="sync"||!fact.payload||typeof fact.payload!=="object"||Array.isArray(fact.payload))return invalid();const payload=fact.payload;if(payload.source!==source||payload.grantId!==ctx.epoch.grant||!Number.isSafeInteger(payload.stateSequence)||Number(payload.stateSequence)<0||!Original.isOk(Original.validateSyncEventPayload(fact.kind,fact.payload)))return invalid();return this.facts.appendCore([fact],{kind:"kernel"},true,{before:()=>ctx.authority.active?ctx.authority.authorize({kind:"connector",source,grant:ctx.epoch.grant}):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Binding checkpoint authority inactive."}),after:results=>{if(results.length!==1||results[0]?.outcome!=="appended")return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Checkpoint fact was not newly appended."});const prior=this.db.query("SELECT revision,value FROM binding_sync_checkpoints WHERE key=?").get(ctx.key);if((prior?.revision??0)!==expectedRevision)return Original.errResult({code:"aborted",layer:"storage",retryability:"retry-at-higher-level",message:"Checkpoint revision changed."});if(prior){let previous;try{previous=JSON.parse(prior.value)}catch{return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Previous checkpoint is invalid."})}if(previous.epoch!==ctx.stamp)return Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Checkpoint belongs to a different authority epoch."});if(!this.validCheckpoint(previous,ctx.stamp,source,ctx.epoch.grant))return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Previous checkpoint fact does not match."});if(Number(payload.stateSequence)<=previous.sequence)return Original.errResult({code:"aborted",layer:"storage",retryability:"non-retryable",message:"Checkpoint state sequence did not advance."})}const value=canonicalJson({epoch:ctx.stamp,cursor:payload.cursor,sequence:payload.stateSequence,factId:results[0].id});this.db.query("INSERT INTO binding_sync_checkpoints(key,revision,value) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET revision=excluded.revision,value=excluded.value").run(ctx.key,expectedRevision+1,value);return Original.ok(true)}},withinTransaction)}writeBindingPage(source,expectedRevision,records,fact){return this.writeBindingPageInternal(source,expectedRevision,records,fact,false)}writeBindingRunnerPage(source,revision,records,facts,checkpoint){if(this.closed)return inactive();const ctx=this.checkpointContext(source),invalid=()=>Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid isolated runner page."});if(!ctx||!Number.isSafeInteger(revision)||revision<0||!Array.isArray(records)||!Array.isArray(facts)||records.some(r=>r?.nk?.source!==source)||facts.some(f=>f?.nk?.source!=="zortex"||!["identity.rebind","sync.identity.rebound","sync.coverage.omission.observed","sync.security.token-carryover"].includes(f.kind)))return invalid();try{this.db.exec("BEGIN IMMEDIATE")}catch{return Original.errResult({code:"unavailable",layer:"storage",retryability:"transient",message:"SQLite writer busy."})}try{const admitted=ctx.authority.active?ctx.authority.authorize({kind:"connector",source,grant:ctx.epoch.grant}):inactive();if(!Original.isOk(admitted)){this.db.exec("ROLLBACK");return admitted}const previous=this.db.query("SELECT revision,value FROM binding_sync_checkpoints WHERE key=?").get(ctx.key);if((previous?.revision??0)!==revision){this.db.exec("ROLLBACK");return Original.errResult({code:"aborted",layer:"storage",retryability:"retry-at-higher-level",message:"Checkpoint revision changed."})}if(previous){const parsed=JSON.parse(previous.value);if(!this.validCheckpoint(parsed,ctx.stamp,source,ctx.epoch.grant)){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Checkpoint belongs to another epoch or is invalid."})}}let results=[];for(let i=0;i<records.length;i+=500){const batch=records.slice(i,i+500),appended=this.records.appendCore(batch,{kind:"connector",source,grant:ctx.epoch.grant},false,void 0,true);if(!Original.isOk(appended)){this.db.exec("ROLLBACK");return appended}if(!Array.isArray(appended.ok)||appended.ok.length!==batch.length||appended.ok.some(result=>!result||!["appended","duplicate","head-noop","erased-suppressed","anomaly"].includes(result.outcome))){this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Runner page append returned invalid outcomes."})}results.push(...appended.ok)}for(let i=0;i<facts.length;i+=500){const appended=this.facts.appendCore(facts.slice(i,i+500),{kind:"kernel"},true,void 0,true);if(!Original.isOk(appended)){this.db.exec("ROLLBACK");return appended}}if(checkpoint){const advanced=this.writeBindingCheckpointInternal(source,revision,checkpoint,true,false);if(!Original.isOk(advanced)){this.db.exec("ROLLBACK");return advanced}}const final=ctx.authority.active?ctx.authority.authorize({kind:"connector",source,grant:ctx.epoch.grant}):inactive();if(!Original.isOk(final)){this.db.exec("ROLLBACK");return final}this.db.exec("COMMIT");return Original.ok(results)}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"internal",layer:"storage",retryability:"transient",message:"Binding runner page transaction rolled back."})}}writeBindingAuditPage(source,expectedRevision,records,fact,generation){return this.writeBindingPageInternal(source,expectedRevision,records,fact,true,generation)}writeBindingPageInternal(source,expectedRevision,records,fact,audit,generation){const invalid=()=>Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid isolated binding page."});const ctx=this.checkpointContext(source,audit);if(!ctx||!Array.isArray(records)||records.some(record=>record?.nk?.source!==source))return invalid();try{this.db.exec("BEGIN IMMEDIATE")}catch{return Original.errResult({code:"unavailable",layer:"storage",retryability:"transient",message:"SQLite writer busy."})}try{if(generation&&!this.matchesReadGeneration(generation)){this.db.exec("ROLLBACK");return Original.errResult({code:"aborted",layer:"storage",retryability:"retry-at-higher-level",message:"Audit read generation changed before commit."})}if(records.length){const appended=this.records.appendCore(records,{kind:"connector",source,grant:ctx.epoch.grant},false,void 0,true);if(!Original.isOk(appended)){this.db.exec("ROLLBACK");return appended}if(appended.ok.some(result=>!["appended","duplicate","head-noop"].includes(result.outcome))){this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Page contains an unaccepted event outcome; checkpoint was not advanced."})}}const advanced=this.writeBindingCheckpointInternal(source,expectedRevision,fact,true,audit);if(!Original.isOk(advanced)){this.db.exec("ROLLBACK");return advanced}this.db.exec("COMMIT");return Original.ok(true)}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"internal",layer:"storage",retryability:"transient",message:"Binding page transaction rolled back."})}}createOriginalLogPort(){const port=this.createAppendPort();return{append:(batch,origin)=>origin.kind==="kernel"||origin.kind==="derivation"?this.appendSystem(batch,origin):this.append(batch,origin),readGeneration:port.readGeneration,scan:port.scan,scanMetadata:port.scanMetadata,headById:createIdReader(this.db,()=>this.closed),beginCooperativePageDrain:port.beginCooperativePageDrain,finishCooperativePageDrain:port.finishCooperativePageDrain,cancelCooperativePageDrain:port.cancelCooperativePageDrain}}createCheckpointErasureProof(){return createCheckpointErasureProof(this)}registerStreams(streams){if(this.closed)return inactive();if(!Array.isArray(streams)||streams.length>1e3)return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Source declaration batch is invalid."});const incoming=new Map;for(const row of streams){if(!row||Object.keys(row).some(key2=>!["source","stream","revOrder","comparator","quality","noneIdentity"].includes(key2))||typeof row.source!=="string"||!row.source||typeof row.stream!=="string"||!row.stream||!Original.REV_ORDERS.includes(row.revOrder)||row.comparator!==void 0&&!["numeric","lex"].includes(row.comparator)||row.quality!==void 0&&!Original.DECLARABLE_IDENTITY_QUALITIES.includes(row.quality))return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid source stream declaration."});const key=row.source+"\0"+row.stream,prior=incoming.get(key)??this.declarations.get(key);if(prior&&canonicalJson(prior)!==canonicalJson(row))return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Existing source stream authority changed; explicit migration is required."});incoming.set(key,JSON.parse(canonicalJson(row)))}this.db.exec("BEGIN IMMEDIATE");try{for(const row of incoming.values()){const existing=this.db.query("SELECT definition FROM source_streams WHERE source=? AND stream=?").get(row.source,row.stream);if(existing&&existing.definition!==canonicalJson(row)){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Another owner declared a different stream authority."})}this.db.query("INSERT OR IGNORE INTO source_streams(source,stream,definition) VALUES(?,?,?)").run(row.source,row.stream,canonicalJson(row))}this.db.exec("COMMIT")}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Stream binding did not commit."})}for(const[key,row]of incoming){this.declarations.set(key,row);this.records.registerStream(row);this.facts.registerStream(row)}return Original.ok(true)}createProcessJournal(){return createProcessJournal(this.db,()=>this.closed)}createPrivateStore(namespace){if(!/^[a-z][a-z0-9.-]{0,63}$/.test(namespace))throw Error("Private storage namespace must be declared by the trusted host.");const valid=key=>typeof key==="string"&&key.length>0&&key.length<=500,invalid=()=>businessError("invalid_argument","Invalid private key, value or revision.","storage");const unavailable=error=>businessError("unavailable",`Private state is temporarily busy${error instanceof Error&&error.message.includes("locked")?" (locked)":""}.`,"storage");const busy=error=>error instanceof Error&&(/SQLITE_BUSY|database is locked|database is busy/i.test(error.message)||error.code==="SQLITE_BUSY");const read=key=>{const row=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key=?").get(namespace,key);return row?{key:row.key,revision:row.revision,value:JSON.parse(row.value)}:null};const decode=row=>({key:row.key,revision:row.revision,value:JSON.parse(row.value)});const listPage=(options={})=>{if(this.closed)return inactive();const after=options.after??"",limit=options.limit??100;if(options.after!==void 0&&!valid(options.after)||!Number.isSafeInteger(limit)||limit<1||limit>1e3)return invalid();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key>? ORDER BY key LIMIT ?").all(namespace,after,limit+1),more=rows.length>limit,items=rows.slice(0,limit).map(decode);return ok({items,...more&&items.length?{next:items.at(-1).key}:{}})}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state page could not be read.","storage")}};return{get:key=>{if(this.closed)return inactive();if(!valid(key))return invalid();try{return ok(read(key))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be read.","storage")}},list:()=>{if(this.closed)return inactive();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? ORDER BY key LIMIT 10001").all(namespace);if(rows.length>1e4)return businessError("resource_exhausted","Private namespace exceeds the complete-read budget; use listPage.","storage");return ok(rows.map(decode))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be listed.","storage")}},listPage,put:(key,value,expected)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0)return invalid();let encoded;try{encoded=canonicalJson(value);if(Buffer.byteLength(encoded)>4*1024*1024)return businessError("resource_exhausted","Private state exceeds its complete-value budget.","storage")}catch{return invalid()}let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before applying this transition.","storage")}const revision=expected+1;this.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET revision=excluded.revision,value=excluded.value").run(namespace,key,revision,encoded);this.db.exec("COMMIT");begun=false;return ok({key,revision,value:JSON.parse(encoded)})}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state transaction did not complete.","storage")}}}}createLocalSourceRegistry(){return createLocalSourceRegistry(this.db,()=>this.closed)}sql(request,signal){return this.closed?Promise.resolve(inactive()):this.reader.sql(request,signal)}exportDataSnapshot(...args){return this.snapshots.exportDataSnapshot(...args)}append(batch,origin){return this.closed?inactive():this.records.appendCore(batch,origin)}appendFacts(batch){return this.closed?inactive():this.facts.appendCore(batch,{kind:"kernel"},true)}appendSystem(batch,origin){if(this.closed)return inactive();if(origin?.kind==="connector")return Original.errResult({code:"permission_denied",layer:"storage",retryability:"non-retryable",message:"Connector authority cannot write system facts."});return this.facts.appendCore(batch,origin)}importErasureDecisions(decisions){if(this.closed)throw Error("SQLite Vault is closed.");for(const row of decisions)if(!row||typeof row.source!=="string"||typeof row.stream!=="string"||typeof row.source_id!=="string"||typeof row.rev!=="string"||typeof row.kind!=="string"||!/^[0-9a-f]{64}$/.test(row.content_hash)||!Original.isUlid(row.tomb_id)||row.future_too!==0&&row.future_too!==1||Number.isNaN(Date.parse(row.ts)))throw Error("Invalid erasure decision.");this.db.exec("BEGIN IMMEDIATE");try{if(this.db.query("SELECT 1 FROM events LIMIT 1").get()!==null)throw Error("Erasure decisions must be imported before user records.");const put=this.db.query("INSERT OR REPLACE INTO tombstones(source,stream,source_id,rev,content_hash,tomb_id,future_too,ts,kind) VALUES (?,?,?,?,?,?,?,?,?)");for(const row of decisions)put.run(row.source,row.stream,row.source_id,row.rev,row.content_hash,row.tomb_id,row.future_too,row.ts,row.kind);this.db.exec("COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}}close(){if(!this.closed){this.closed=true;void this.reader.close();void this.snapshots.close();this.db.close()}}async closeAsync(){this.close();await Promise.all([this.reader.close(),this.snapshots.close()])}}export async function apply(ctx,config){const vault=new SqliteVault(config);ctx.reflect.provide("zortexSqliteVault",vault);ctx.reflect.provide("zortexConnectorStorage",{identity:vault.identity,appendPort:vault.createAppendPort(),declareStreams:streams=>vault.registerStreams(streams)});ctx.reflect.provide("zortexConnectorProcessJournal",vault.createProcessJournal());ctx.reflect.provide("zortexLocalSourceRegistry",vault.createLocalSourceRegistry());return()=>vault.closeAsync()}
1
+ import{Original,businessError,ok,canonicalJson}from"@zortexhq/plugin-connector-framework/api";import{mkdirSync}from"node:fs";import{dirname,isAbsolute}from"node:path";import{createHash,randomUUID}from"node:crypto";import{Database}from"./sqlite.js";import{assertNotRecovery}from"./recovery-guard.js";import{SCHEMA}from"./schema.js";import{LiftedRecordRules}from"./record-rules.js";import{createSqliteAppendPort}from"./append-port.js";import{createIdReader}from"./id-read.js";import{createProcessJournal,PROCESS_JOURNAL_SCHEMA}from"./process-journal.js";import{createLocalSourceRegistry,LOCAL_SOURCE_SCHEMA}from"./local-source-registry.js";import{createSqlReader,sqlLimits,DEFAULT_SQL_LIMITS}from"./sql.js";import{createBlobPort}from"./blob-port.js";import{createSourcePrincipalPort}from"./source-principal-port.js";import{createSnapshotReader}from"./snapshot.js";import{createCheckpointErasureProof}from"./checkpoint-erasure-proof.js";import{createStorageMetadataReader}from"./storage-metadata.js";export const name="zortex-sqlite-vault";export{createVaultMcp,startVaultMcp,vaultTools}from"./mcp.js";const inactive=()=>Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"SQLite Vault is closed."});export class SqliteVault{identity;db;records;facts;closed=false;declarations=new Map;authorities=new Map;requiredAuthorities=new Set;bindingEpochs=new Map;readPageRows;reader;snapshots;storageMetadata;constructor(config){if(!config||typeof config.file!=="string"||!isAbsolute(config.file)||!Array.isArray(config.streams))throw Error("SQLite Vault requires an absolute file and declared streams.");const backupNamespaces=config.backupPrivateNamespaces??[];if(!Array.isArray(backupNamespaces)||backupNamespaces.length>64||backupNamespaces.some(n=>typeof n!=="string"||!/^[a-z][a-z0-9.-]{0,63}$/.test(n)))throw Error("Invalid trusted backup namespace policy.");const busy=config.busyTimeoutMs??3e3;if(!Number.isSafeInteger(busy)||busy<1||busy>6e4)throw Error("SQLite busy timeout must be 1\u201360000 ms.");const pageRows=config.readPageRows??128;if(!Number.isSafeInteger(pageRows)||pageRows<1||pageRows>4096)throw Error("SQLite read page must be 1\u20134096 rows.");this.readPageRows=pageRows;const readLimits=sqlLimits(config.sql??DEFAULT_SQL_LIMITS);if(config.execution&&(!config.execution.runId||!config.execution.codeVersion))throw Error("Execution binding requires run identity and code version.");assertNotRecovery(config.file,busy);mkdirSync(dirname(config.file),{recursive:true});this.db=new Database(config.file);try{this.db.exec(`PRAGMA busy_timeout=${busy};`);const version=this.db.query("PRAGMA user_version").get().user_version;if(version!==0&&version!==1)throw Error("Unsupported SQLite Vault schema version.");const populated=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' LIMIT 1").get()!==null;if(populated){const hasMeta=this.db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta'").get()!==null;if(!hasMeta||this.db.query("SELECT value FROM meta WHERE key='zortex-sqlite-vault-format'").get()?.value!=="1")throw Error("Different SQLite format; select a new Vault file.")}this.db.exec("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;");this.db.exec("BEGIN IMMEDIATE");try{this.db.exec(SCHEMA+PROCESS_JOURNAL_SCHEMA+LOCAL_SOURCE_SCHEMA);this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('zortex-sqlite-vault-format','1')").run();this.db.query("INSERT OR IGNORE INTO meta(key,value) VALUES ('vault-identity',?)").run(randomUUID());this.db.exec("PRAGMA user_version=1; COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}this.identity=this.db.query("SELECT value FROM meta WHERE key='vault-identity'").get().value;this.snapshots=createSnapshotReader(config.file,this.identity,[...backupNamespaces]);this.storageMetadata=createStorageMetadataReader(this.db,config.file,()=>this.closed);const now=config.now??(()=>new Date().toISOString());const saved=this.db.query("SELECT definition FROM source_streams ORDER BY source,stream").all().map(row=>JSON.parse(row.definition));for(const row of this.db.query("SELECT source FROM source_authority_required").all())this.requiredAuthorities.add(row.source);this.records=new LiftedRecordRules(this.db,saved,now,"events",config.execution,origin=>{const binding=this.authorities.get(origin.source);return!binding&&!this.requiredAuthorities.has(origin.source)&&!this.db.query("SELECT 1 FROM source_authority_required WHERE source=?").get(origin.source)?Original.ok(true):binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Required source append authority is inactive."})});this.facts=new LiftedRecordRules(this.db,saved,now,"system_events");for(const row of saved)this.declarations.set(row.source+"\0"+row.stream,row);const admitted=this.registerStreams(config.streams);if(!Original.isOk(admitted))throw Error("Source stream declaration changed or is invalid.");this.reader=createSqlReader(config.file,readLimits)}catch(error){this.db.close();throw error}}createAppendPort(){return createSqliteAppendPort(this.db,this,()=>this.closed,this.readPageRows)}storageSnapshot(){return this.storageMetadata()}createBlobPort(){return createBlobPort(this.db,()=>this.closed,origin=>{const binding=this.authorities.get(origin.source);return binding?.active?binding.authorize(origin):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Connector blob bytes require a current trusted source authority binding."})})}createSourcePrincipalPort(){return createSourcePrincipalPort(this.db,()=>this.closed)}registerConnectorAuthority(source,authorize){return this.registerAuthority(source,authorize,false)}registerAuthority(source,authorize,bindingAuthority){if(this.closed||!/^[a-z][a-z0-9-]{0,63}$/.test(source)||typeof authorize!=="function")throw Error("Invalid trusted source authority binding.");if(this.authorities.get(source)?.active)throw Error("Source authority is already bound.");if(!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source))throw Error("Isolated source requires binding authority.");this.db.query("INSERT OR IGNORE INTO source_authority_required(source) VALUES(?)").run(source);this.requiredAuthorities.add(source);const binding={authorize:origin=>!bindingAuthority&&this.db.query("SELECT 1 FROM isolated_source_subjects WHERE source=?").get(source)?Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Isolated source requires binding authority."}):authorize(origin),active:true};this.authorities.set(source,binding);return()=>{binding.active=false}}registerConnectedSourceAuthority(source,expected){if(!Original.isUlid(expected?.grant)||typeof expected.account!=="string"||!expected.account||typeof expected.updatedAt!=="string"||!Number.isFinite(Date.parse(expected.updatedAt))||!Array.isArray(expected.scopes)||!expected.scopes.length||expected.scopes.some(scope=>typeof scope!=="string"||!scope))throw Error("Invalid connected source authority epoch.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Source identity or consent changed before append."});return this.registerConnectorAuthority(source,origin=>{if(origin.grant!==expected.grant)return denied();const row=this.db.query("SELECT metadata FROM connections WHERE source=?").get(source);if(!row)return denied();let current;try{current=JSON.parse(row.metadata)}catch{return denied()}if(!current||typeof current!=="object"||Array.isArray(current))return denied();const info=current;const scopes=info.scopes;if(info.source!==source||info.provider!=="google"||info.state!=="connected"||info.updatedAt!==expected.updatedAt||(info.accountId??info.account)!==expected.account||!Array.isArray(scopes)||expected.scopes.some(scope=>!scopes.includes(scope)))return denied();return Original.ok(true)})}registerBindingSourceAuthority(source,expected){const positive=value=>Number.isSafeInteger(value)&&Number(value)>0;const text=value=>typeof value==="string"&&value.length>0&&value.length<=2048;if(!expected||!Original.isUlid(expected.grant)||![expected.bindingId,expected.subject,expected.custodyGrantId,expected.audience].every(text)||![expected.bindingRevision,expected.custodyGrantRevision,expected.selectionRevision].every(positive)||!Number.isSafeInteger(expected.scopeEpoch)||expected.scopeEpoch<0||!Array.isArray(expected.scopes)||!expected.scopes.length||!expected.scopes.every(text))throw Error("Invalid binding source authority epoch.");if((expected.credentialResourceId!==void 0||expected.credentialResourceRevision!==void 0)&&(!text(expected.credentialResourceId)||!positive(expected.credentialResourceRevision)))throw Error("Invalid credential resource epoch.");const epoch={...expected,scopes:[...new Set(expected.scopes)].sort()};const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==epoch.subject)throw Error("Isolated source is pinned to a different subject.");const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Selected source identity or consent changed before append."});const withdraw=this.registerAuthority(source,origin=>{if(origin.grant!==epoch.grant)return denied();try{const pin2=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin2&&pin2.subject!==epoch.subject)return denied();const selection=this.db.query("SELECT binding_id,revision FROM source_selections WHERE source=?").get(source);const binding=this.db.query("SELECT source,subject,revision,metadata FROM account_bindings WHERE id=?").get(epoch.bindingId);const grant=this.db.query("SELECT binding_id,revision,metadata FROM authorization_grants WHERE id=?").get(epoch.custodyGrantId);if(!selection||selection.binding_id!==epoch.bindingId||selection.revision!==epoch.selectionRevision||!binding||binding.source!==source||binding.subject!==epoch.subject||binding.revision!==epoch.bindingRevision||!grant||grant.binding_id!==epoch.bindingId||grant.revision!==epoch.custodyGrantRevision)return denied();if(epoch.credentialResourceId!==void 0){const resource=this.db.query("SELECT binding_id,kind,owner_key,revision FROM credential_resources WHERE id=?").get(epoch.credentialResourceId);if(!resource||resource.binding_id!==epoch.bindingId||resource.kind!=="oauth"||resource.owner_key!=="resident"||resource.revision!==epoch.credentialResourceRevision)return denied()}const b=JSON.parse(binding.metadata),g=JSON.parse(grant.metadata);if(b.id!==epoch.bindingId||b.revision!==epoch.bindingRevision||b.state!=="connected"||b.identity?.source!==source||b.identity?.subject!==epoch.subject||!Number.isFinite(Date.parse(b.verifiedAt))||g.id!==epoch.custodyGrantId||g.revision!==epoch.custodyGrantRevision||g.bindingId!==epoch.bindingId||g.state!=="active"||g.purpose!=="L1"||g.audience!==epoch.audience||g.scopeEpoch!==epoch.scopeEpoch||!Array.isArray(g.scopes)||JSON.stringify([...new Set(g.scopes)].sort())!==JSON.stringify(epoch.scopes))return denied();return Original.ok(true)}catch{return denied()}},true);this.bindingEpochs.set(source,epoch);return()=>{withdraw();if(this.bindingEpochs.get(source)===epoch)this.bindingEpochs.delete(source)}}registerIsolatedBindingSourceAuthority(source,expected){let withdraw;let begun=false;const wasRequired=this.requiredAuthorities.has(source);try{this.db.exec("BEGIN IMMEDIATE");begun=true;withdraw=this.registerBindingSourceAuthority(source,expected);const authority=this.authorities.get(source);if(!authority?.active||!Original.isOk(authority.authorize({kind:"connector",source,grant:expected.grant})))throw Error("Selected binding is not currently authorized.");const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(pin&&pin.subject!==expected.subject)throw Error("Isolated source is pinned to a different subject.");if(!pin){if(this.db.query("SELECT 1 FROM events WHERE source=? LIMIT 1").get(source)||this.db.query("SELECT 1 FROM system_events WHERE json_valid(payload) AND json_extract(payload,'$.source')=? LIMIT 1").get(source)||this.db.query("SELECT 1 FROM binding_sync_checkpoints LIMIT 1").get())throw Error("Cannot pin a vault with existing source data or checkpoints.");this.db.query("INSERT INTO isolated_source_subjects(source,subject) VALUES(?,?)").run(source,expected.subject)}this.db.exec("COMMIT");begun=false;return withdraw}catch(error){if(begun)this.db.exec("ROLLBACK");withdraw?.();if(!wasRequired)this.requiredAuthorities.delete(source);throw error}}recordIsolatedVerifiedGrant(source){const epoch=this.bindingEpochs.get(source),authority=this.authorities.get(source);const denied=()=>Original.errResult({code:"permission_denied",layer:"auth",retryability:"non-retryable",message:"Verified grant authority changed."});if(!epoch?.credentialResourceId||!authority?.active)return denied();try{this.db.exec("BEGIN IMMEDIATE");const admitted=authority.authorize({kind:"connector",source,grant:epoch.grant});if(!Original.isOk(admitted)){this.db.exec("ROLLBACK");return denied()}const pin=this.db.query("SELECT subject FROM isolated_source_subjects WHERE source=?").get(source);if(!pin||pin.subject!==epoch.subject){this.db.exec("ROLLBACK");return denied()}const old=this.db.query("SELECT binding_id,subject FROM isolated_verified_grants WHERE source=? AND grant_id=?").get(source,epoch.grant);if(old&&(old.binding_id!==epoch.bindingId||old.subject!==epoch.subject)){this.db.exec("ROLLBACK");return denied()}if(!old)this.db.query("INSERT INTO isolated_verified_grants(source,grant_id,binding_id,subject) VALUES(?,?,?,?)").run(source,epoch.grant,epoch.bindingId,epoch.subject);this.db.exec("COMMIT");return Original.ok(true)}catch{try{this.db.exec("ROLLBACK")}catch{}return denied()}}matchesReadGeneration(generation){const row=this.db.query("SELECT (SELECT value FROM meta WHERE key='watermark') AS watermark,(SELECT value FROM meta WHERE key='projection-epoch') AS epoch").get();return!!row&&Original.isUlid(generation.untilSeq)&&Number.isSafeInteger(generation.projectionEpoch)&&row.epoch!==null&&(row.watermark??"00000000000000000000000000")===generation.untilSeq&&Number(row.epoch)===generation.projectionEpoch}readIsolatedVerifiedGrants(source,generation){const fail=()=>Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Source history or generation lacks verified binding provenance."});const ctx=this.checkpointContext(source,true);if(!ctx?.epoch.credentialResourceId)return fail();try{this.db.exec("BEGIN IMMEDIATE");if(!this.matchesReadGeneration(generation)||!ctx.authority.active||!Original.isOk(ctx.authority.authorize({kind:"connector",source,grant:ctx.epoch.grant}))){this.db.exec("ROLLBACK");return fail()}const rows=this.db.query("SELECT grant_id FROM isolated_verified_grants WHERE source=? AND binding_id=? AND subject=? ORDER BY grant_id").all(source,ctx.epoch.bindingId,ctx.epoch.subject);const ids=rows.map(row=>row.grant_id);if(!ids.includes(ctx.epoch.grant)||ids.some(id=>!Original.isUlid(id))){this.db.exec("ROLLBACK");return fail()}const allowed=new Set(ids);for(const row of this.db.query("SELECT origin FROM events WHERE source=? AND erased=0 AND id<=?").all(source,generation.untilSeq)){let origin;try{origin=JSON.parse(row.origin)}catch{this.db.exec("ROLLBACK");return fail()}if(origin?.kind!=="connector"||origin.source!==source||!allowed.has(origin.grant)){this.db.exec("ROLLBACK");return fail()}}this.db.exec("COMMIT");return Original.ok([...ids.filter(id=>id!==ctx.epoch.grant),ctx.epoch.grant])}catch{try{this.db.exec("ROLLBACK")}catch{}return fail()}}checkpointContext(source,audit=false){const epoch=this.bindingEpochs.get(source),authority=this.authorities.get(source);if(!epoch||!authority?.active)return null;const stamp=canonicalJson(epoch);const auditEpoch=createHash("sha256").update(stamp).digest("hex");return{epoch,authority,key:JSON.stringify(audit?[source,epoch.bindingId,"audit",auditEpoch]:[source,epoch.bindingId]),stamp}}validCheckpoint(value,stamp,source,grant){if(!value||value.epoch!==stamp||!(value.cursor===null||typeof value.cursor==="string")||!Number.isSafeInteger(value.sequence)||value.sequence<0||!Original.isUlid(value.factId))return false;const row=this.db.query("SELECT kind,payload FROM system_events WHERE id=? AND erased=0").get(value.factId);if(!row||row.kind!=="sync.cursor.advanced")return false;try{const payload=JSON.parse(row.payload);return Original.isOk(Original.validateSyncEventPayload(row.kind,payload))&&payload.source===source&&payload.grantId===grant&&payload.cursor===value.cursor&&payload.stateSequence===value.sequence}catch{return false}}readBindingCheckpoint(source){return this.readBindingCheckpointInternal(source,false)}readBindingAuditCheckpoint(source){return this.readBindingCheckpointInternal(source,true)}readBindingCheckpointInternal(source,audit){if(this.closed)return inactive();const ctx=this.checkpointContext(source,audit);if(!ctx)return Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Binding checkpoint authority unavailable."});try{this.db.exec("BEGIN IMMEDIATE")}catch{return Original.errResult({code:"unavailable",layer:"storage",retryability:"transient",message:"SQLite writer busy."})}try{const admitted=ctx.authority.authorize({kind:"connector",source,grant:ctx.epoch.grant});if(!Original.isOk(admitted)){this.db.exec("ROLLBACK");return admitted}const row=this.db.query("SELECT revision,value FROM binding_sync_checkpoints WHERE key=?").get(ctx.key);if(!row){this.db.exec("COMMIT");return Original.ok(null)}const value=JSON.parse(row.value);if(value.epoch!==ctx.stamp){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Checkpoint belongs to a different authority epoch."})}if(!this.validCheckpoint(value,ctx.stamp,source,ctx.epoch.grant))throw Error("Invalid checkpoint");this.db.exec("COMMIT");return Original.ok({revision:row.revision,cursor:value.cursor})}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Binding checkpoint is invalid."})}}writeBindingCheckpoint(source,expectedRevision,fact){return this.writeBindingCheckpointInternal(source,expectedRevision,fact,false,false)}writeBindingCheckpointInternal(source,expectedRevision,fact,withinTransaction,audit){if(this.closed)return inactive();const ctx=this.checkpointContext(source,audit);const invalid=()=>Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid binding checkpoint fact."});if(!ctx)return Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Binding checkpoint authority unavailable."});if(!Number.isSafeInteger(expectedRevision)||expectedRevision<0||!fact||fact.kind!=="sync.cursor.advanced"||fact.nk?.source!=="zortex"||fact.nk?.stream!=="sync"||!fact.payload||typeof fact.payload!=="object"||Array.isArray(fact.payload))return invalid();const payload=fact.payload;if(payload.source!==source||payload.grantId!==ctx.epoch.grant||!Number.isSafeInteger(payload.stateSequence)||Number(payload.stateSequence)<0||!Original.isOk(Original.validateSyncEventPayload(fact.kind,fact.payload)))return invalid();return this.facts.appendCore([fact],{kind:"kernel"},true,{before:()=>ctx.authority.active?ctx.authority.authorize({kind:"connector",source,grant:ctx.epoch.grant}):Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Binding checkpoint authority inactive."}),after:results=>{if(results.length!==1||results[0]?.outcome!=="appended")return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Checkpoint fact was not newly appended."});const prior=this.db.query("SELECT revision,value FROM binding_sync_checkpoints WHERE key=?").get(ctx.key);if((prior?.revision??0)!==expectedRevision)return Original.errResult({code:"aborted",layer:"storage",retryability:"retry-at-higher-level",message:"Checkpoint revision changed."});if(prior){let previous;try{previous=JSON.parse(prior.value)}catch{return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Previous checkpoint is invalid."})}if(previous.epoch!==ctx.stamp)return Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Checkpoint belongs to a different authority epoch."});if(!this.validCheckpoint(previous,ctx.stamp,source,ctx.epoch.grant))return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Previous checkpoint fact does not match."});if(Number(payload.stateSequence)<=previous.sequence)return Original.errResult({code:"aborted",layer:"storage",retryability:"non-retryable",message:"Checkpoint state sequence did not advance."})}const value=canonicalJson({epoch:ctx.stamp,cursor:payload.cursor,sequence:payload.stateSequence,factId:results[0].id});this.db.query("INSERT INTO binding_sync_checkpoints(key,revision,value) VALUES(?,?,?) ON CONFLICT(key) DO UPDATE SET revision=excluded.revision,value=excluded.value").run(ctx.key,expectedRevision+1,value);return Original.ok(true)}},withinTransaction)}writeBindingPage(source,expectedRevision,records,fact){return this.writeBindingPageInternal(source,expectedRevision,records,fact,false)}writeBindingRunnerPage(source,revision,records,facts,checkpoint){if(this.closed)return inactive();const ctx=this.checkpointContext(source),invalid=()=>Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid isolated runner page."});if(!ctx||!Number.isSafeInteger(revision)||revision<0||!Array.isArray(records)||!Array.isArray(facts)||records.some(r=>r?.nk?.source!==source)||facts.some(f=>f?.nk?.source!=="zortex"||!["identity.rebind","sync.identity.rebound","sync.coverage.omission.observed","sync.security.token-carryover"].includes(f.kind)))return invalid();try{this.db.exec("BEGIN IMMEDIATE")}catch{return Original.errResult({code:"unavailable",layer:"storage",retryability:"transient",message:"SQLite writer busy."})}try{const admitted=ctx.authority.active?ctx.authority.authorize({kind:"connector",source,grant:ctx.epoch.grant}):inactive();if(!Original.isOk(admitted)){this.db.exec("ROLLBACK");return admitted}const previous=this.db.query("SELECT revision,value FROM binding_sync_checkpoints WHERE key=?").get(ctx.key);if((previous?.revision??0)!==revision){this.db.exec("ROLLBACK");return Original.errResult({code:"aborted",layer:"storage",retryability:"retry-at-higher-level",message:"Checkpoint revision changed."})}if(previous){const parsed=JSON.parse(previous.value);if(!this.validCheckpoint(parsed,ctx.stamp,source,ctx.epoch.grant)){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"auth",retryability:"non-retryable",message:"Checkpoint belongs to another epoch or is invalid."})}}let results=[];for(let i=0;i<records.length;i+=500){const batch=records.slice(i,i+500),appended=this.records.appendCore(batch,{kind:"connector",source,grant:ctx.epoch.grant},false,void 0,true);if(!Original.isOk(appended)){this.db.exec("ROLLBACK");return appended}if(!Array.isArray(appended.ok)||appended.ok.length!==batch.length||appended.ok.some(result=>!result||!["appended","duplicate","head-noop","erased-suppressed","anomaly"].includes(result.outcome))){this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Runner page append returned invalid outcomes."})}results.push(...appended.ok)}for(let i=0;i<facts.length;i+=500){const appended=this.facts.appendCore(facts.slice(i,i+500),{kind:"kernel"},true,void 0,true);if(!Original.isOk(appended)){this.db.exec("ROLLBACK");return appended}}if(checkpoint){const advanced=this.writeBindingCheckpointInternal(source,revision,checkpoint,true,false);if(!Original.isOk(advanced)){this.db.exec("ROLLBACK");return advanced}}const final=ctx.authority.active?ctx.authority.authorize({kind:"connector",source,grant:ctx.epoch.grant}):inactive();if(!Original.isOk(final)){this.db.exec("ROLLBACK");return final}this.db.exec("COMMIT");return Original.ok(results)}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"internal",layer:"storage",retryability:"transient",message:"Binding runner page transaction rolled back."})}}writeBindingAuditPage(source,expectedRevision,records,fact,generation){return this.writeBindingPageInternal(source,expectedRevision,records,fact,true,generation)}writeBindingPageInternal(source,expectedRevision,records,fact,audit,generation){const invalid=()=>Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid isolated binding page."});const ctx=this.checkpointContext(source,audit);if(!ctx||!Array.isArray(records)||records.some(record=>record?.nk?.source!==source))return invalid();try{this.db.exec("BEGIN IMMEDIATE")}catch{return Original.errResult({code:"unavailable",layer:"storage",retryability:"transient",message:"SQLite writer busy."})}try{if(generation&&!this.matchesReadGeneration(generation)){this.db.exec("ROLLBACK");return Original.errResult({code:"aborted",layer:"storage",retryability:"retry-at-higher-level",message:"Audit read generation changed before commit."})}if(records.length){const appended=this.records.appendCore(records,{kind:"connector",source,grant:ctx.epoch.grant},false,void 0,true);if(!Original.isOk(appended)){this.db.exec("ROLLBACK");return appended}if(appended.ok.some(result=>!["appended","duplicate","head-noop"].includes(result.outcome))){this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Page contains an unaccepted event outcome; checkpoint was not advanced."})}}const advanced=this.writeBindingCheckpointInternal(source,expectedRevision,fact,true,audit);if(!Original.isOk(advanced)){this.db.exec("ROLLBACK");return advanced}this.db.exec("COMMIT");return Original.ok(true)}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"internal",layer:"storage",retryability:"transient",message:"Binding page transaction rolled back."})}}createOriginalLogPort(){const port=this.createAppendPort();return{append:(batch,origin)=>origin.kind==="kernel"||origin.kind==="derivation"?this.appendSystem(batch,origin):this.append(batch,origin),readGeneration:port.readGeneration,scan:port.scan,scanMetadata:port.scanMetadata,headById:createIdReader(this.db,()=>this.closed),beginCooperativePageDrain:port.beginCooperativePageDrain,finishCooperativePageDrain:port.finishCooperativePageDrain,cancelCooperativePageDrain:port.cancelCooperativePageDrain}}createCheckpointErasureProof(){return createCheckpointErasureProof(this)}registerStreams(streams){if(this.closed)return inactive();if(!Array.isArray(streams)||streams.length>1e3)return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Source declaration batch is invalid."});const incoming=new Map;for(const row of streams){if(!row||Object.keys(row).some(key2=>!["source","stream","revOrder","comparator","quality","noneIdentity"].includes(key2))||typeof row.source!=="string"||!row.source||typeof row.stream!=="string"||!row.stream||!Original.REV_ORDERS.includes(row.revOrder)||row.comparator!==void 0&&!["numeric","lex"].includes(row.comparator)||row.quality!==void 0&&!Original.DECLARABLE_IDENTITY_QUALITIES.includes(row.quality))return Original.errResult({code:"invalid_argument",layer:"storage",retryability:"non-retryable",message:"Invalid source stream declaration."});const key=row.source+"\0"+row.stream,prior=incoming.get(key)??this.declarations.get(key);if(prior&&canonicalJson(prior)!==canonicalJson(row))return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Existing source stream authority changed; explicit migration is required."});incoming.set(key,JSON.parse(canonicalJson(row)))}this.db.exec("BEGIN IMMEDIATE");try{for(const row of incoming.values()){const existing=this.db.query("SELECT definition FROM source_streams WHERE source=? AND stream=?").get(row.source,row.stream);if(existing&&existing.definition!==canonicalJson(row)){this.db.exec("ROLLBACK");return Original.errResult({code:"failed_precondition",layer:"storage",retryability:"non-retryable",message:"Another owner declared a different stream authority."})}this.db.query("INSERT OR IGNORE INTO source_streams(source,stream,definition) VALUES(?,?,?)").run(row.source,row.stream,canonicalJson(row))}this.db.exec("COMMIT")}catch{this.db.exec("ROLLBACK");return Original.errResult({code:"data_loss",layer:"storage",retryability:"non-retryable",message:"Stream binding did not commit."})}for(const[key,row]of incoming){this.declarations.set(key,row);this.records.registerStream(row);this.facts.registerStream(row)}return Original.ok(true)}createProcessJournal(){return createProcessJournal(this.db,()=>this.closed)}createPrivateStore(namespace){if(!/^[a-z][a-z0-9.-]{0,63}$/.test(namespace))throw Error("Private storage namespace must be declared by the trusted host.");const valid=key=>typeof key==="string"&&key.length>0&&key.length<=500,invalid=()=>businessError("invalid_argument","Invalid private key, value or revision.","storage");const unavailable=error=>businessError("unavailable",`Private state is temporarily busy${error instanceof Error&&error.message.includes("locked")?" (locked)":""}.`,"storage");const busy=error=>error instanceof Error&&(/SQLITE_BUSY|database is locked|database is busy/i.test(error.message)||error.code==="SQLITE_BUSY");const read=key=>{const row=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key=?").get(namespace,key);return row?{key:row.key,revision:row.revision,value:JSON.parse(row.value)}:null};const decode=row=>({key:row.key,revision:row.revision,value:JSON.parse(row.value)});const listPage=(options={})=>{if(this.closed)return inactive();const after=options.after??"",limit=options.limit??100;if(options.after!==void 0&&!valid(options.after)||!Number.isSafeInteger(limit)||limit<1||limit>1e3)return invalid();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? AND key>? ORDER BY key LIMIT ?").all(namespace,after,limit+1),more=rows.length>limit,items=rows.slice(0,limit).map(decode);return ok({items,...more&&items.length?{next:items.at(-1).key}:{}})}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state page could not be read.","storage")}};return{get:key=>{if(this.closed)return inactive();if(!valid(key))return invalid();try{return ok(read(key))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be read.","storage")}},list:()=>{if(this.closed)return inactive();try{const rows=this.db.query("SELECT key,revision,value FROM private_state WHERE namespace=? ORDER BY key LIMIT 10001").all(namespace);if(rows.length>1e4)return businessError("resource_exhausted","Private namespace exceeds the complete-read budget; use listPage.","storage");return ok(rows.map(decode))}catch(error){return busy(error)?unavailable(error):businessError("data_loss","Private state could not be listed.","storage")}},listPage,put:(key,value,expected)=>{if(this.closed)return inactive();if(!valid(key)||!Number.isSafeInteger(expected)||expected<0)return invalid();let encoded;try{encoded=canonicalJson(value);if(Buffer.byteLength(encoded)>4*1024*1024)return businessError("resource_exhausted","Private state exceeds its complete-value budget.","storage")}catch{return invalid()}let begun=false;try{this.db.exec("BEGIN IMMEDIATE");begun=true;const prior=read(key);if((prior?.revision??0)!==expected){this.db.exec("ROLLBACK");begun=false;return businessError("aborted","Private state changed; reload before applying this transition.","storage")}const revision=expected+1;this.db.query("INSERT INTO private_state(namespace,key,revision,value) VALUES(?,?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET revision=excluded.revision,value=excluded.value").run(namespace,key,revision,encoded);this.db.exec("COMMIT");begun=false;return ok({key,revision,value:JSON.parse(encoded)})}catch(error){if(begun)try{this.db.exec("ROLLBACK")}catch{}return busy(error)?unavailable(error):businessError("data_loss","Private state transaction did not complete.","storage")}}}}createLocalSourceRegistry(){return createLocalSourceRegistry(this.db,()=>this.closed)}sql(request,signal){return this.closed?Promise.resolve(inactive()):this.reader.sql(request,signal)}exportDataSnapshot(...args){return this.snapshots.exportDataSnapshot(...args)}append(batch,origin){return this.closed?inactive():this.records.appendCore(batch,origin)}appendFacts(batch){return this.closed?inactive():this.facts.appendCore(batch,{kind:"kernel"},true)}appendSystem(batch,origin){if(this.closed)return inactive();if(origin?.kind==="connector")return Original.errResult({code:"permission_denied",layer:"storage",retryability:"non-retryable",message:"Connector authority cannot write system facts."});return this.facts.appendCore(batch,origin)}importErasureDecisions(decisions){if(this.closed)throw Error("SQLite Vault is closed.");for(const row of decisions)if(!row||typeof row.source!=="string"||typeof row.stream!=="string"||typeof row.source_id!=="string"||typeof row.rev!=="string"||typeof row.kind!=="string"||!/^[0-9a-f]{64}$/.test(row.content_hash)||!Original.isUlid(row.tomb_id)||row.future_too!==0&&row.future_too!==1||Number.isNaN(Date.parse(row.ts)))throw Error("Invalid erasure decision.");this.db.exec("BEGIN IMMEDIATE");try{if(this.db.query("SELECT 1 FROM events LIMIT 1").get()!==null)throw Error("Erasure decisions must be imported before user records.");const put=this.db.query("INSERT OR REPLACE INTO tombstones(source,stream,source_id,rev,content_hash,tomb_id,future_too,ts,kind) VALUES (?,?,?,?,?,?,?,?,?)");for(const row of decisions)put.run(row.source,row.stream,row.source_id,row.rev,row.content_hash,row.tomb_id,row.future_too,row.ts,row.kind);this.db.exec("COMMIT")}catch(error){this.db.exec("ROLLBACK");throw error}}close(){if(!this.closed){this.closed=true;void this.reader.close();void this.snapshots.close();this.db.close()}}async closeAsync(){this.close();await Promise.all([this.reader.close(),this.snapshots.close()])}}export async function apply(ctx,config){const vault=new SqliteVault(config);ctx.reflect.provide("zortexSqliteVault",vault);ctx.reflect.provide("zortexConnectorStorage",{identity:vault.identity,appendPort:vault.createAppendPort(),declareStreams:streams=>vault.registerStreams(streams)});ctx.reflect.provide("zortexConnectorProcessJournal",vault.createProcessJournal());ctx.reflect.provide("zortexLocalSourceRegistry",vault.createLocalSourceRegistry());return()=>vault.closeAsync()}
@@ -0,0 +1 @@
1
+ import{lstat}from"node:fs/promises";import{businessError,ok}from"@zortexhq/plugin-connector-framework/api";const CACHE_MS=3e5,COUNT_LIMIT=2e4;const counts=[["stored_event_rows","events","sqlite_autoindex_events_1"],["live_event_rows","events","idx_events_live_source","erased=0"],["system_event_rows","system_events","sqlite_autoindex_system_events_1"],["cached_records","records","sqlite_autoindex_records_1"],["binding_records","binding_records","sqlite_autoindex_binding_records_1"],["stored_blobs","user_blob_contents","sqlite_autoindex_user_blob_contents_1"]];const safeNumber=value=>Number.isSafeInteger(value)&&Number(value)>=0;const unavailable=()=>businessError("unavailable","Vault storage metadata is unavailable.","storage");export function createStorageMetadataReader(db,file,closed=()=>false){let cached,cachedAt=0,inFlight;const read=async()=>{if(closed())return unavailable();const now=Date.now();if(cached&&now>=cachedAt&&now-cachedAt<CACHE_MS)return ok(structuredClone(cached));let populations=counts.map(([population])=>({population,coverage:"unavailable"}));let begun=false,priorBusy;try{priorBusy=db.query("PRAGMA busy_timeout").get()?.timeout;db.exec("PRAGMA busy_timeout=20;BEGIN");begun=true;const started=performance.now();populations=counts.map(([population,table,index,where])=>{try{if(performance.now()-started>25||!db.query("SELECT 1 FROM sqlite_master WHERE type='index' AND name=?").get(index))return{population,coverage:"unavailable"};const row=db.query(`SELECT count(*) AS n FROM (SELECT 1 FROM ${table} INDEXED BY ${index}${where?" WHERE "+where:""} LIMIT ?)`).get(COUNT_LIMIT+1);if(!row||!safeNumber(row.n))return{population,coverage:"unavailable"};return{population,count:Math.min(row.n,COUNT_LIMIT),coverage:row.n>COUNT_LIMIT?"lower_bound":"complete"}}catch{return{population,coverage:"unavailable"}}});db.exec("COMMIT");begun=false}catch{if(begun)try{db.exec("ROLLBACK")}catch{}}finally{if(safeNumber(priorBusy))try{db.exec(`PRAGMA busy_timeout=${priorBusy}`)}catch{}}const observed=await Promise.all(["","-wal","-shm"].map(async(suffix,index)=>{try{const value2=await lstat(file+suffix);return value2.isFile()&&!value2.isSymbolicLink()&&safeNumber(value2.size)?{bytes:value2.size,exists:1}:void 0}catch(error){return index>0&&error.code==="ENOENT"?{bytes:0,exists:0}:void 0}}));if(closed())return unavailable();const[database,wal,shm]=observed,physicalKnown=!!database&&!!wal&&!!shm;const value={schemaVersion:1,scope:"sqlite_files",asOf:new Date(now).toISOString(),coverage:physicalKnown&&populations.every(row=>row.coverage==="complete")?"complete":observed.some(Boolean)||populations.some(row=>row.coverage!=="unavailable")?"partial":"unavailable",sizeBasis:"logical_file_bytes",...database?{databaseBytes:database.bytes}:{},...wal?{walBytes:wal.bytes}:{},...shm?{shmBytes:shm.bytes}:{},...physicalKnown?{totalBytes:database.bytes+wal.bytes+shm.bytes,fileCount:database.exists+wal.exists+shm.exists}:{},populations};if(physicalKnown&&!safeNumber(value.totalBytes)){delete value.totalBytes;value.coverage="partial"}cached=value;cachedAt=now;return ok(structuredClone(value))};return()=>{if(closed())return Promise.resolve(unavailable());if(inFlight)return inFlight.then(result=>"ok"in result?ok(structuredClone(result.ok)):result);inFlight=read().catch(()=>unavailable()).finally(()=>{inFlight=void 0});return inFlight}}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zortexhq/indra-v2.5",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "private": false,
5
5
  "license": "UNLICENSED",
6
6
  "publishConfig": {
@@ -9,7 +9,7 @@
9
9
  "tag": "next"
10
10
  },
11
11
  "type": "module",
12
- "description": "Zortex daily 2026-11-20 (source 0.2.0)",
12
+ "description": "Zortex daily 2026-11-21 (source 0.2.0)",
13
13
  "repository": {
14
14
  "type": "git",
15
15
  "url": "https://github.com/ZortexHQ/indra-v2.git",
@@ -1027,9 +1027,9 @@
1027
1027
  "zortexRelease": {
1028
1028
  "schemaVersion": 1,
1029
1029
  "sourceVersion": "0.2.0",
1030
- "sourceSha": "50417b0e49acbfb971a2538dc82ef3fbbdf81098",
1031
- "sourceDate": "2026-11-20T06:39:25.000Z",
1032
- "version": "0.2.1"
1030
+ "sourceSha": "0e20bc0a76239a6e5f6262a7a8128e55992acbc9",
1031
+ "sourceDate": "2026-11-21T17:32:06.000Z",
1032
+ "version": "0.2.3"
1033
1033
  },
1034
1034
  "zortex": {
1035
1035
  "role": "app"
@@ -1040,6 +1040,6 @@
1040
1040
  "zortexUpdate": {
1041
1041
  "schemaVersion": 1,
1042
1042
  "manifest": "update-manifest.json",
1043
- "sha256": "23e77e89a5d1a7febc501d3ab8257b5792a9d986dc42c43d44162fa7168193ac"
1043
+ "sha256": "a62cda7439d165001861d44650d520d05b08a6528a9a7f502fa9dbff7a3d9548"
1044
1044
  }
1045
1045
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 3,
3
3
  "name": "@zortexhq/indra-v2.5",
4
- "version": "0.2.1",
4
+ "version": "0.2.3",
5
5
  "platforms": [
6
6
  "win32-x64",
7
7
  "win32-arm64",
@@ -15,16 +15,16 @@
15
15
  "sharp"
16
16
  ]
17
17
  },
18
- "commit": "50417b0e49acbfb971a2538dc82ef3fbbdf81098",
19
- "lockSha256": "ef1532a71ad1cb969ee98b81d0eb95a053b9a4295c9e647a9721742c46fcf46c",
18
+ "commit": "0e20bc0a76239a6e5f6262a7a8128e55992acbc9",
19
+ "lockSha256": "9c6259007f2ecd65db9911ad5d7a151e87cd2d0c79d4d901ede2dd40ae9f4053",
20
20
  "platform": "linux",
21
21
  "arch": "x64",
22
22
  "zortexRelease": {
23
23
  "schemaVersion": 1,
24
24
  "sourceVersion": "0.2.0",
25
- "sourceSha": "50417b0e49acbfb971a2538dc82ef3fbbdf81098",
26
- "sourceDate": "2026-11-20T06:39:25.000Z",
27
- "version": "0.2.1"
25
+ "sourceSha": "0e20bc0a76239a6e5f6262a7a8128e55992acbc9",
26
+ "sourceDate": "2026-11-21T17:32:06.000Z",
27
+ "version": "0.2.3"
28
28
  },
29
29
  "npm": {
30
30
  "externalDependencies": {
@@ -907,10 +907,10 @@
907
907
  "packages": [
908
908
  {
909
909
  "name": "@zortexhq/indra-v2.5",
910
- "version": "0.2.1",
910
+ "version": "0.2.3",
911
911
  "target": "",
912
- "fileCount": 130,
913
- "filesSha256": "309858189429b0fd251676ba12fd419013170068c95c2e14f4e0d275196caa81"
912
+ "fileCount": 135,
913
+ "filesSha256": "6fad563212f3aa1cba949103179853554150a0d41ad3a907a13827dc5e2432f1"
914
914
  },
915
915
  {
916
916
  "name": "@abd-enterprises/zendesk-mcp",
@@ -1000,8 +1000,8 @@
1000
1000
  "name": "@zortexhq/plugin-connector-core",
1001
1001
  "version": "0.1.0",
1002
1002
  "target": "node_modules/@zortexhq/plugin-connector-core",
1003
- "fileCount": 26,
1004
- "filesSha256": "0859dea024f3aef457ffafb30264880c597635be635219806b80ae1b7549fbe6"
1003
+ "fileCount": 27,
1004
+ "filesSha256": "5123306811e0e6ff095021dc11f5012c984afbee14cc8a26cc44303107811e1a"
1005
1005
  },
1006
1006
  {
1007
1007
  "name": "@zortexhq/plugin-connector-drive",
@@ -1049,8 +1049,8 @@
1049
1049
  "name": "@zortexhq/plugin-connector-level1",
1050
1050
  "version": "0.1.0",
1051
1051
  "target": "node_modules/@zortexhq/plugin-connector-level1",
1052
- "fileCount": 141,
1053
- "filesSha256": "8cd534a559f846f1d60925b5f27efb28f7726dc91228a29d6a133c0e9c4cb0e0"
1052
+ "fileCount": 143,
1053
+ "filesSha256": "b1d1bb358732653cb4c3290203943fd52618c25c23b7d1cce03f16ef715bbbaf"
1054
1054
  },
1055
1055
  {
1056
1056
  "name": "@zortexhq/plugin-connector-netease",
@@ -1154,8 +1154,8 @@
1154
1154
  "name": "@zortexhq/plugin-galaxy-ui",
1155
1155
  "version": "0.1.0",
1156
1156
  "target": "node_modules/@zortexhq/plugin-galaxy-ui",
1157
- "fileCount": 187,
1158
- "filesSha256": "99b3ef6a76c60aa70c49c60cefddc28c07d1f0370438e7166c27954f8868c1b0"
1157
+ "fileCount": 196,
1158
+ "filesSha256": "1a87a07782d8c053cbd79a9a934aa1816ec61cb0d37f8609c637311815e80582"
1159
1159
  },
1160
1160
  {
1161
1161
  "name": "@zortexhq/plugin-google-auth",
@@ -1169,14 +1169,14 @@
1169
1169
  "version": "0.1.0",
1170
1170
  "target": "node_modules/@zortexhq/plugin-jev-autopilot",
1171
1171
  "fileCount": 18,
1172
- "filesSha256": "acb5287540aef1fc05df7d8f308464227bd4c04a30ed499fa32dd696c202896b"
1172
+ "filesSha256": "35ddfe7d8e35f5345611029206929876f422c358c7850f6854a189593ecaefa0"
1173
1173
  },
1174
1174
  {
1175
1175
  "name": "@zortexhq/plugin-jev-browser-driver",
1176
1176
  "version": "0.1.0",
1177
1177
  "target": "node_modules/@zortexhq/plugin-jev-browser-driver",
1178
- "fileCount": 27,
1179
- "filesSha256": "79175f92b43e0fb40a604150481fa16af8e49746958dc7538d181f3efb872b9f"
1178
+ "fileCount": 28,
1179
+ "filesSha256": "a4effc580fe443958ba0cfd9bcf28f058fa2f50fb9bd1575dbee8ebc1a06601e"
1180
1180
  },
1181
1181
  {
1182
1182
  "name": "@zortexhq/plugin-local-source-access",
@@ -1196,15 +1196,15 @@
1196
1196
  "name": "@zortexhq/plugin-posthog",
1197
1197
  "version": "0.1.0",
1198
1198
  "target": "node_modules/@zortexhq/plugin-posthog",
1199
- "fileCount": 14,
1200
- "filesSha256": "92452d732ace039872f300c62ada80e85d84baae40ca2341c964bb437df11f74"
1199
+ "fileCount": 17,
1200
+ "filesSha256": "eb64fb686b1ad2aeaebec1abf6a59e89cdb4a56c15742958639215d24e5cf0e7"
1201
1201
  },
1202
1202
  {
1203
1203
  "name": "@zortexhq/plugin-process-local",
1204
1204
  "version": "0.1.0",
1205
1205
  "target": "node_modules/@zortexhq/plugin-process-local",
1206
- "fileCount": 4,
1207
- "filesSha256": "d3034b21732d5d8c67a345c113bd424bd83b24258c38c3a74f754baf16447351"
1206
+ "fileCount": 6,
1207
+ "filesSha256": "72f6b00f276a22ba2c6bcc941a76ee618910b75cd6d00b0a8cebe9d089fea519"
1208
1208
  },
1209
1209
  {
1210
1210
  "name": "@zortexhq/plugin-product-account",
@@ -1217,8 +1217,8 @@
1217
1217
  "name": "@zortexhq/plugin-telemetry",
1218
1218
  "version": "0.1.0",
1219
1219
  "target": "node_modules/@zortexhq/plugin-telemetry",
1220
- "fileCount": 8,
1221
- "filesSha256": "740966049003f941541f52b39b7b5ad9d268a94f60bde4b28d45d5dbfb2527b2"
1220
+ "fileCount": 16,
1221
+ "filesSha256": "8d762234b883c426638dd5e63ce36ec885f2cad88496b3dc4bb6e0184ddcaa29"
1222
1222
  },
1223
1223
  {
1224
1224
  "name": "@zortexhq/plugin-tunnel-frp",
@@ -1231,8 +1231,8 @@
1231
1231
  "name": "@zortexhq/plugin-vault-sqlite",
1232
1232
  "version": "0.1.0",
1233
1233
  "target": "node_modules/@zortexhq/plugin-vault-sqlite",
1234
- "fileCount": 40,
1235
- "filesSha256": "7e482f70265fc8f47eba1941dc848f448c7da0b89fc68b578b88b28faf58e735"
1234
+ "fileCount": 42,
1235
+ "filesSha256": "fd08d068e110d8a4f4daa2cb1e665dcd3e39f6e8e946dec74c7aa34e904775ec"
1236
1236
  },
1237
1237
  {
1238
1238
  "name": "@zortexhq/rooktrail",