signetai 0.214.41 → 0.216.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp-stdio.js CHANGED
@@ -6640,16 +6640,17 @@ import { fileURLToPath } from "node:url";
6640
6640
  import { createHash } from "node:crypto";
6641
6641
  import { execFileSync } from "node:child_process";
6642
6642
  import { statfsSync } from "node:fs";
6643
- import { homedir as homedir2 } from "os";
6644
- import { join as join2 } from "path";
6643
+ import { existsSync as existsSync2, readFileSync } from "node:fs";
6644
+ import { homedir as homedir2 } from "node:os";
6645
+ import { join as join2, resolve } from "node:path";
6645
6646
  import {
6646
6647
  chmodSync,
6647
6648
  closeSync,
6648
- existsSync as existsSync3,
6649
+ existsSync as existsSync4,
6649
6650
  fsyncSync,
6650
6651
  mkdirSync as mkdirSync2,
6651
6652
  openSync,
6652
- readFileSync as readFileSync2,
6653
+ readFileSync as readFileSync3,
6653
6654
  readdirSync as readdirSync2,
6654
6655
  renameSync,
6655
6656
  rmdirSync,
@@ -6661,12 +6662,26 @@ import { join as join4 } from "node:path";
6661
6662
  import { execFileSync as execFileSync2 } from "node:child_process";
6662
6663
  import { createHash as createHash2 } from "node:crypto";
6663
6664
  import { createRequire as createRequire2 } from "node:module";
6665
+ import {
6666
+ closeSync as closeSync2,
6667
+ existsSync as existsSync6,
6668
+ fsyncSync as fsyncSync2,
6669
+ mkdirSync as mkdirSync3,
6670
+ openSync as openSync2,
6671
+ readFileSync as readFileSync5,
6672
+ renameSync as renameSync2,
6673
+ rmSync,
6674
+ statSync as statSync3,
6675
+ writeSync
6676
+ } from "node:fs";
6677
+ import { homedir as homedir4 } from "node:os";
6678
+ import { dirname as dirname3, join as join7, resolve as resolve2 } from "node:path";
6664
6679
  import { createRequire as createRequire3 } from "node:module";
6665
- import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync5, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
6680
+ import { existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync6, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
6666
6681
  import { homedir as homedir5 } from "node:os";
6667
- import { dirname as dirname4, join as join8, resolve as resolve2 } from "node:path";
6682
+ import { dirname as dirname4, join as join8, resolve as resolve3 } from "node:path";
6668
6683
  import { homedir as homedir6, platform as platform2 } from "node:os";
6669
- import { basename, dirname as dirname5, resolve as resolve4 } from "node:path";
6684
+ import { basename, dirname as dirname5, resolve as resolve5 } from "node:path";
6670
6685
  import { homedir as homedir10 } from "node:os";
6671
6686
  function __accessProp2(key) {
6672
6687
  return this[key];
@@ -15620,7 +15635,27 @@ function findSqliteVecExtension() {
15620
15635
  return null;
15621
15636
  }
15622
15637
  function resolveDefaultBasePath() {
15623
- return process.env.SIGNET_PATH || join2(homedir2(), ".agents");
15638
+ const envPath = process.env.SIGNET_PATH?.trim() || process.env.SIGNET_WORKSPACE?.trim();
15639
+ if (envPath)
15640
+ return resolve(expandHome(envPath));
15641
+ const home = homedir2();
15642
+ const configHome = process.env.XDG_CONFIG_HOME?.trim() ? resolve(expandHome(process.env.XDG_CONFIG_HOME.trim(), home)) : join2(home, ".config");
15643
+ const configPath = join2(configHome, "signet", "workspace.json");
15644
+ if (existsSync2(configPath)) {
15645
+ try {
15646
+ const value = JSON.parse(readFileSync(configPath, "utf8"));
15647
+ if (typeof value.workspace === "string" && value.workspace.trim())
15648
+ return resolve(expandHome(value.workspace, home));
15649
+ } catch {}
15650
+ }
15651
+ return join2(home, ".agents");
15652
+ }
15653
+ function expandHome(p2, home = homedir2()) {
15654
+ if (p2 === "~")
15655
+ return home;
15656
+ if (p2.startsWith("~/") || p2.startsWith("~\\"))
15657
+ return join2(home, p2.slice(2));
15658
+ return p2;
15624
15659
  }
15625
15660
  function workspaceAccount(workspace) {
15626
15661
  return createHash2("sha256").update(workspace).digest("hex").slice(0, 32);
@@ -15828,11 +15863,11 @@ function cleanupStaleSecretStoreTemps() {
15828
15863
  function loadStore() {
15829
15864
  cleanupStaleSecretStoreTemps();
15830
15865
  const file2 = getSecretsFile();
15831
- if (!existsSync3(file2)) {
15866
+ if (!existsSync4(file2)) {
15832
15867
  return { version: 1, secrets: {} };
15833
15868
  }
15834
15869
  try {
15835
- return parseSecretsStore(JSON.parse(readFileSync2(file2, "utf-8")));
15870
+ return parseSecretsStore(JSON.parse(readFileSync3(file2, "utf-8")));
15836
15871
  } catch (err) {
15837
15872
  const message = err instanceof Error ? err.message : String(err);
15838
15873
  throw new Error(`Failed to read secrets store: ${message}`);
@@ -15852,7 +15887,7 @@ function healthForKeyringState(result) {
15852
15887
  function getLocalSecretProviderHealth() {
15853
15888
  try {
15854
15889
  const store = loadStore();
15855
- if (existsSync3(join4(getSecretsDir(), DEGRADED_WARNING_FILE))) {
15890
+ if (existsSync4(join4(getSecretsDir(), DEGRADED_WARNING_FILE))) {
15856
15891
  return {
15857
15892
  status: "degraded",
15858
15893
  message: "Using legacy machine-id-obfuscated secrets encryption because no native keyring is available",
@@ -16015,6 +16050,146 @@ function resolveSignetDaemonUrl(opts = {}) {
16015
16050
  const port = normalizePort(readEnv(env, "SIGNET_PORT"), fallbackPort);
16016
16051
  return normalizeDaemonUrl(`http://${bracketIpv6Host(host)}:${port}`, "SIGNET_HOST/SIGNET_PORT");
16017
16052
  }
16053
+ function normalizeWorkspacePath(pathValue, home = homedir4()) {
16054
+ return resolve2(expandHome(pathValue.trim(), home));
16055
+ }
16056
+ function readTrimmedEnv(env, name) {
16057
+ const value = env[name];
16058
+ if (typeof value !== "string")
16059
+ return;
16060
+ const trimmed = value.trim();
16061
+ return trimmed.length > 0 ? trimmed : undefined;
16062
+ }
16063
+ function readConfigHome(env, home) {
16064
+ const raw = env.XDG_CONFIG_HOME;
16065
+ if (typeof raw !== "string")
16066
+ return join7(home, ".config");
16067
+ const trimmed = raw.trim();
16068
+ return trimmed.length > 0 ? normalizeWorkspacePath(trimmed, home) : join7(home, ".config");
16069
+ }
16070
+ function isExistingDirectory(path) {
16071
+ try {
16072
+ return statSync3(path).isDirectory();
16073
+ } catch {
16074
+ return false;
16075
+ }
16076
+ }
16077
+ function isRecord5(value) {
16078
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16079
+ }
16080
+ function getWorkspaceConfigPath(env = process.env, home = homedir4()) {
16081
+ return join7(readConfigHome(env, home), "signet", "workspace.json");
16082
+ }
16083
+ function readConfiguredWorkspacePath(env = process.env, home = homedir4(), options = {}) {
16084
+ const strict = options.strict ?? true;
16085
+ const configPath = getWorkspaceConfigPath(env, home);
16086
+ if (!existsSync6(configPath))
16087
+ return null;
16088
+ let raw;
16089
+ try {
16090
+ raw = JSON.parse(readFileSync5(configPath, "utf-8"));
16091
+ } catch (err) {
16092
+ if (!strict)
16093
+ return null;
16094
+ const detail = err instanceof Error ? err.message : String(err);
16095
+ throw new Error(`Invalid Signet workspace config at ${configPath}: ${detail}`);
16096
+ }
16097
+ if (!isRecord5(raw) || !("workspace" in raw)) {
16098
+ if (!strict)
16099
+ return null;
16100
+ throw new Error(`Invalid Signet workspace config at ${configPath}: missing workspace`);
16101
+ }
16102
+ const workspace = raw.workspace;
16103
+ if (typeof workspace !== "string" || workspace.trim().length === 0) {
16104
+ if (!strict)
16105
+ return null;
16106
+ throw new Error(`Invalid Signet workspace config at ${configPath}: workspace must be a non-empty string`);
16107
+ }
16108
+ return normalizeWorkspacePath(workspace, home);
16109
+ }
16110
+ function resolveWorkspacePath(options = {}) {
16111
+ const env = options.env ?? process.env;
16112
+ const home = options.home ?? homedir4();
16113
+ const strict = options.strict ?? true;
16114
+ const requireExistingEnvPath = options.requireExistingEnvPath ?? false;
16115
+ const configPath = getWorkspaceConfigPath(env, home);
16116
+ const envPath = resolveEnvWorkspace(env, home, requireExistingEnvPath);
16117
+ const configValue = readConfiguredWorkspacePath(env, home, { strict: envPath ? false : strict });
16118
+ if (envPath) {
16119
+ return {
16120
+ path: envPath,
16121
+ source: "env",
16122
+ configPath,
16123
+ configuredPath: configValue
16124
+ };
16125
+ }
16126
+ if (configValue) {
16127
+ return {
16128
+ path: configValue,
16129
+ source: "config",
16130
+ configPath,
16131
+ configuredPath: configValue
16132
+ };
16133
+ }
16134
+ return {
16135
+ path: join7(home, DEFAULT_AGENTS_DIRNAME),
16136
+ source: "default",
16137
+ configPath,
16138
+ configuredPath: configValue
16139
+ };
16140
+ }
16141
+ function preflightWorkspace(options = {}) {
16142
+ const env = options.env ?? process.env;
16143
+ const home = options.home ?? homedir4();
16144
+ let resolution;
16145
+ try {
16146
+ resolution = resolveWorkspacePath({ ...options, strict: true });
16147
+ } catch (error51) {
16148
+ const detail = error51 instanceof Error ? error51.message : String(error51);
16149
+ return {
16150
+ path: join7(home, DEFAULT_AGENTS_DIRNAME),
16151
+ source: "default",
16152
+ configPath: getWorkspaceConfigPath(env, home),
16153
+ configuredPath: null,
16154
+ status: "incomplete",
16155
+ reasons: [detail]
16156
+ };
16157
+ }
16158
+ const reasons = [];
16159
+ const hasExplicitConfiguration = resolution.source === "env" || resolution.configuredPath !== null;
16160
+ if (!isExistingDirectory(resolution.path)) {
16161
+ if (hasExplicitConfiguration) {
16162
+ reasons.push("configured workspace directory is missing");
16163
+ return { ...resolution, status: "missing", reasons };
16164
+ }
16165
+ return { ...resolution, status: "fresh", reasons };
16166
+ }
16167
+ const hasAgentConfig = existsSync6(join7(resolution.path, "agent.yaml")) || existsSync6(join7(resolution.path, "config.yaml"));
16168
+ const hasMemoryDb = existsSync6(join7(resolution.path, "memory", "memories.db"));
16169
+ if (hasAgentConfig && hasMemoryDb) {
16170
+ return { ...resolution, status: "ready", reasons };
16171
+ }
16172
+ if (!hasExplicitConfiguration && !hasAgentConfig && !hasMemoryDb) {
16173
+ return { ...resolution, status: "fresh", reasons };
16174
+ }
16175
+ if (!hasAgentConfig)
16176
+ reasons.push("workspace configuration is missing (agent.yaml or config.yaml)");
16177
+ if (!hasMemoryDb)
16178
+ reasons.push("workspace database is missing (memory/memories.db)");
16179
+ return { ...resolution, status: "incomplete", reasons };
16180
+ }
16181
+ function resolveEnvWorkspace(env, home, requireExisting) {
16182
+ for (const key of WORKSPACE_ENV_KEYS) {
16183
+ const raw = readTrimmedEnv(env, key);
16184
+ if (!raw)
16185
+ continue;
16186
+ const normalized = normalizeWorkspacePath(raw, home);
16187
+ if (!requireExisting || isExistingDirectory(normalized))
16188
+ return normalized;
16189
+ console.warn(`[signet] ${key}="${raw}" does not point to an existing workspace directory; using the default workspace resolution instead.`);
16190
+ }
16191
+ return null;
16192
+ }
16018
16193
  function blobToVector(blob) {
16019
16194
  if (blob instanceof ArrayBuffer) {
16020
16195
  return new Float32Array(blob);
@@ -16175,10 +16350,10 @@ function emptyGraphiqState(now = new Date) {
16175
16350
  }
16176
16351
  function readGraphiqState(basePath) {
16177
16352
  const path = getGraphiqStatePath(basePath);
16178
- if (!existsSync6(path))
16353
+ if (!existsSync7(path))
16179
16354
  return emptyGraphiqState();
16180
16355
  try {
16181
- const parsed = JSON.parse(readFileSync5(path, "utf-8"));
16356
+ const parsed = JSON.parse(readFileSync6(path, "utf-8"));
16182
16357
  return parseGraphiqState(parsed);
16183
16358
  } catch {
16184
16359
  return emptyGraphiqState();
@@ -16224,11 +16399,11 @@ function isRecord6(value) {
16224
16399
  function defaultDiscordDesktopCachePath() {
16225
16400
  switch (platform2()) {
16226
16401
  case "darwin":
16227
- return resolve4(homedir6(), "Library", "Application Support", "discord");
16402
+ return resolve5(homedir6(), "Library", "Application Support", "discord");
16228
16403
  case "win32":
16229
- return resolve4(process.env.APPDATA || resolve4(homedir6(), "AppData", "Roaming"), "discord");
16404
+ return resolve5(process.env.APPDATA || resolve5(homedir6(), "AppData", "Roaming"), "discord");
16230
16405
  default:
16231
- return resolve4(process.env.XDG_CONFIG_HOME || resolve4(homedir6(), ".config"), "discord");
16406
+ return resolve5(process.env.XDG_CONFIG_HOME || resolve5(homedir6(), ".config"), "discord");
16232
16407
  }
16233
16408
  }
16234
16409
  var __create2, __getProtoOf2, __defProp2, __getOwnPropNames2, __hasOwnProp2, __toESMCache_node2, __toESMCache_esm2, __toESM2 = (mod, isNodeMode, target) => {
@@ -16258,7 +16433,7 @@ var __create2, __getProtoOf2, __defProp2, __getOwnPropNames2, __hasOwnProp2, __t
16258
16433
  configurable: true,
16259
16434
  set: __exportSetter2.bind(all, name)
16260
16435
  });
16261
- }, __esm2 = (fn, res) => () => (fn && (res = fn(fn = 0)), res), __require, require_identity, require_visit, require_directives, require_anchors, require_applyReviver, require_toJS, require_Node, require_Alias, require_Scalar, require_createNode, require_Collection, require_stringifyComment, require_foldFlowLines, require_stringifyString, require_stringify, require_stringifyPair, require_log, require_merge, require_addPairToJSMap, require_Pair, require_stringifyCollection, require_YAMLMap, require_map, require_YAMLSeq, require_seq, require_string, require_null, require_bool, require_stringifyNumber, require_float, require_int, require_schema, require_schema2, require_binary, require_pairs, require_omap, require_bool2, require_float2, require_int2, require_set, require_timestamp, require_schema3, require_tags, require_Schema, require_stringifyDocument, require_Document, require_errors2, require_resolve_props, require_util_contains_newline, require_util_flow_indent_check, require_util_map_includes, require_resolve_block_map, require_resolve_block_seq, require_resolve_end, require_resolve_flow_collection, require_compose_collection, require_resolve_block_scalar, require_resolve_flow_scalar, require_compose_scalar, require_util_empty_scalar_position, require_compose_node, require_compose_doc, require_composer, require_cst_scalar, require_cst_stringify, require_cst_visit, require_cst, require_lexer, require_line_counter, require_parser, require_public_api, require_dist2, require_keyring_linux_x64_musl, require_package, require_keyring_linux_x64_gnu, require_package2, require_keyring, libsodium_default, init_libsodium, exports_libsodium_wrappers, r, t, a, _, n, s, m, libsodium_wrappers_default, init_libsodium_wrappers, PIPELINE_PROVIDER_CHOICES, SYNTHESIS_PROVIDER_CHOICES, DEFAULT_PIPELINE_TIMEOUT_MS = 90000, PIPELINE_PROVIDER_SET, SYNTHESIS_PROVIDER_SET, MEMORY_CONTENT_SAFETY_POLICY_VERSION = "memory-content-safety-v1", MEMORY_CONTENT_WITHHELD_NOTICE = "[memory content withheld by safety policy]", MEMORY_CONTENT_SAFETY_REASONS, INVISIBLE_UNICODE_RE, STRONG_DEFENSIVE_CONTEXT_RE, REPORTING_CONTEXT_RE, REPORTING_BEFORE_RE, REPORTING_AFTER_RE, NEGATED_DIRECTIVE_RE, PROMPT_INJECTION_RES, TOOL_DIRECTIVE_RES, EXFILTRATION_RE, EXFILTRATION_REVERSE, CREDENTIAL_HARVESTING_RE, DANGEROUS_SHELL_RE, DAEMON_DERIVED_MEMORY_SOURCE_TYPES, MEMORIES_FTS_TOKENIZER = "unicode61", FTS_STATE_TABLE = "memories_fts_state", COLUMNS, DEPENDENCY_TYPES, DERIVED_SOURCE_TYPES, TOKEN_COLUMNS, COLUMNS2, COMPLETION_BOUNDARY_REASONS, MIGRATIONS, LATEST_SCHEMA_VERSION, NETWORK_FILESYSTEM_TYPES, __filename2, __dirname2, import_yaml, DEFAULT_EMBEDDING_DIMENSIONS = 768, SERVICE = "ai.signet.secrets", require2, modulePromise = null, syncModule, adapterForTests = null, secretEventRecorder = () => {}, SECRET_STORE_TEMP_PREFIX = "secrets.enc.tmp-", NATIVE_STORE_VERSION = 2, DEGRADED_WARNING_FILE = ".degraded-warning", KEYRING_ACCOUNT_SCOPE = "workspace", SecretKeyringError, NAME_RE, DEFAULT_TELEMETRY_POSTHOG_HOST = "https://us.i.posthog.com", DEFAULT_TELEMETRY_POSTHOG_API_KEY = "phc_mLsvJmbmp6e9UarrX9Cq5QtTjVNiiphM9mvi5Xnddd8Q", DEFAULT_TELEMETRY_FLUSH_INTERVAL_MS = 60000, DEFAULT_TELEMETRY_FLUSH_BATCH_SIZE = 50, DEFAULT_PROVIDER_RATE_LIMIT, TELEMETRY_DEPLOYMENT_ROLES, TELEMETRY_INSTALL_CHANNELS, ENTITY_TYPES, ATTRIBUTE_KINDS, DEPENDENCY_TYPES2, ONTOLOGY_PROPOSAL_OPERATIONS, LOOPBACK_HOST = "127.0.0.1", LOCAL_BINDS, import_yaml2, native = null, SIGNET_SECRETS_PLUGIN_ID = "signet.secrets", SIGNET_GRAPHIQ_PLUGIN_ID = "signet.graphiq", SIGNET_PLUGIN_REGISTRY_DIR = ".daemon/plugins", SIGNET_PLUGIN_REGISTRY_FILE = "registry-v1.json", SIGNET_GRAPHIQ_STATE_FILE = ".daemon/graphiq/state.json", GRAPHIQ_DEFAULT_INSTALL_DIR, SIGNET_SOURCE_CHECKOUT_DIRNAME = "signetai", SIGNET_GIT_ALLOWED_DIRECTORIES, SIGNET_GIT_PROTECTED_PATHS, SIGNET_GIT_TRACKED_PATHS, SIGNET_GITIGNORE_PROTECTED_PATTERNS, DEFAULT_DISCORD_DESKTOP_CACHE_PATH, DEFAULT_GITHUB_RESOURCE_TYPES, VALID_GITHUB_RESOURCE_TYPES, IDENTITY_FILES, REQUIRED_IDENTITY_KEYS, OPTIONAL_IDENTITY_KEYS, home, SOURCE_NATIVE_TOPOLOGY_ENTITY_TYPES;
16436
+ }, __esm2 = (fn, res) => () => (fn && (res = fn(fn = 0)), res), __require, require_identity, require_visit, require_directives, require_anchors, require_applyReviver, require_toJS, require_Node, require_Alias, require_Scalar, require_createNode, require_Collection, require_stringifyComment, require_foldFlowLines, require_stringifyString, require_stringify, require_stringifyPair, require_log, require_merge, require_addPairToJSMap, require_Pair, require_stringifyCollection, require_YAMLMap, require_map, require_YAMLSeq, require_seq, require_string, require_null, require_bool, require_stringifyNumber, require_float, require_int, require_schema, require_schema2, require_binary, require_pairs, require_omap, require_bool2, require_float2, require_int2, require_set, require_timestamp, require_schema3, require_tags, require_Schema, require_stringifyDocument, require_Document, require_errors2, require_resolve_props, require_util_contains_newline, require_util_flow_indent_check, require_util_map_includes, require_resolve_block_map, require_resolve_block_seq, require_resolve_end, require_resolve_flow_collection, require_compose_collection, require_resolve_block_scalar, require_resolve_flow_scalar, require_compose_scalar, require_util_empty_scalar_position, require_compose_node, require_compose_doc, require_composer, require_cst_scalar, require_cst_stringify, require_cst_visit, require_cst, require_lexer, require_line_counter, require_parser, require_public_api, require_dist2, require_keyring_linux_x64_musl, require_package, require_keyring_linux_x64_gnu, require_package2, require_keyring, libsodium_default, init_libsodium, exports_libsodium_wrappers, r, t, a, _, n, s, m, libsodium_wrappers_default, init_libsodium_wrappers, PIPELINE_PROVIDER_CHOICES, SYNTHESIS_PROVIDER_CHOICES, DEFAULT_PIPELINE_TIMEOUT_MS = 90000, PIPELINE_PROVIDER_SET, SYNTHESIS_PROVIDER_SET, MEMORY_CONTENT_SAFETY_POLICY_VERSION = "memory-content-safety-v1", MEMORY_CONTENT_WITHHELD_NOTICE = "[memory content withheld by safety policy]", MEMORY_CONTENT_SAFETY_REASONS, INVISIBLE_UNICODE_RE, STRONG_DEFENSIVE_CONTEXT_RE, REPORTING_CONTEXT_RE, REPORTING_BEFORE_RE, REPORTING_AFTER_RE, NEGATED_DIRECTIVE_RE, PROMPT_INJECTION_RES, TOOL_DIRECTIVE_RES, EXFILTRATION_RE, EXFILTRATION_REVERSE, CREDENTIAL_HARVESTING_RE, DANGEROUS_SHELL_RE, DAEMON_DERIVED_MEMORY_SOURCE_TYPES, MEMORIES_FTS_TOKENIZER = "unicode61", FTS_STATE_TABLE = "memories_fts_state", COLUMNS, DEPENDENCY_TYPES, DERIVED_SOURCE_TYPES, TOKEN_COLUMNS, COLUMNS2, COMPLETION_BOUNDARY_REASONS, MIGRATIONS, LATEST_SCHEMA_VERSION, NETWORK_FILESYSTEM_TYPES, __filename2, __dirname2, import_yaml, DEFAULT_EMBEDDING_DIMENSIONS = 768, SERVICE = "ai.signet.secrets", require2, modulePromise = null, syncModule, adapterForTests = null, secretEventRecorder = () => {}, SECRET_STORE_TEMP_PREFIX = "secrets.enc.tmp-", NATIVE_STORE_VERSION = 2, DEGRADED_WARNING_FILE = ".degraded-warning", KEYRING_ACCOUNT_SCOPE = "workspace", SecretKeyringError, NAME_RE, DEFAULT_TELEMETRY_POSTHOG_HOST = "https://us.i.posthog.com", DEFAULT_TELEMETRY_POSTHOG_API_KEY = "phc_mLsvJmbmp6e9UarrX9Cq5QtTjVNiiphM9mvi5Xnddd8Q", DEFAULT_TELEMETRY_FLUSH_INTERVAL_MS = 60000, DEFAULT_TELEMETRY_FLUSH_BATCH_SIZE = 50, DEFAULT_PROVIDER_RATE_LIMIT, TELEMETRY_DEPLOYMENT_ROLES, TELEMETRY_INSTALL_CHANNELS, ENTITY_TYPES, ATTRIBUTE_KINDS, DEPENDENCY_TYPES2, ONTOLOGY_PROPOSAL_OPERATIONS, LOOPBACK_HOST = "127.0.0.1", LOCAL_BINDS, import_yaml2, WORKSPACE_ENV_KEYS, DEFAULT_AGENTS_DIRNAME = ".agents", native = null, SIGNET_SECRETS_PLUGIN_ID = "signet.secrets", SIGNET_GRAPHIQ_PLUGIN_ID = "signet.graphiq", SIGNET_PLUGIN_REGISTRY_DIR = ".daemon/plugins", SIGNET_PLUGIN_REGISTRY_FILE = "registry-v1.json", SIGNET_GRAPHIQ_STATE_FILE = ".daemon/graphiq/state.json", GRAPHIQ_DEFAULT_INSTALL_DIR, SIGNET_SOURCE_CHECKOUT_DIRNAME = "signetai", SIGNET_GIT_ALLOWED_DIRECTORIES, SIGNET_GIT_PROTECTED_PATHS, SIGNET_GIT_TRACKED_PATHS, SIGNET_GITIGNORE_PROTECTED_PATTERNS, DEFAULT_DISCORD_DESKTOP_CACHE_PATH, DEFAULT_GITHUB_RESOURCE_TYPES, VALID_GITHUB_RESOURCE_TYPES, IDENTITY_FILES, REQUIRED_IDENTITY_KEYS, OPTIONAL_IDENTITY_KEYS, home, SOURCE_NATIVE_TOPOLOGY_ENTITY_TYPES;
16262
16437
  var init_dist = __esm(() => {
16263
16438
  __create2 = Object.create;
16264
16439
  __getProtoOf2 = Object.getPrototypeOf;
@@ -23198,7 +23373,7 @@ ${end.comment}` : end.comment;
23198
23373
  var __filename2 = "/home/runner/work/signetai/signetai/node_modules/.bun/@napi-rs+keyring@1.3.0/node_modules/@napi-rs/keyring/index.js";
23199
23374
  var { createRequire: createRequire22 } = __require("node:module");
23200
23375
  __require = createRequire22(__filename2);
23201
- var { readFileSync: readFileSync22 } = __require("node:fs");
23376
+ var { readFileSync: readFileSync32 } = __require("node:fs");
23202
23377
  var nativeBinding = null;
23203
23378
  var loadErrors = [];
23204
23379
  var isMusl = () => {
@@ -23217,7 +23392,7 @@ ${end.comment}` : end.comment;
23217
23392
  var isFileMusl = (f) => f.includes("libc.musl-") || f.includes("ld-musl-");
23218
23393
  var isMuslFromFilesystem = () => {
23219
23394
  try {
23220
- return readFileSync22("/usr/bin/ldd", "utf-8").includes("musl");
23395
+ return readFileSync32("/usr/bin/ldd", "utf-8").includes("musl");
23221
23396
  } catch {
23222
23397
  return null;
23223
23398
  }
@@ -25250,6 +25425,7 @@ ${end.comment}` : end.comment;
25250
25425
  ];
25251
25426
  LOCAL_BINDS = new Set([LOOPBACK_HOST, "localhost", "::1", "::ffff:127.0.0.1"]);
25252
25427
  import_yaml2 = __toESM2(require_dist2(), 1);
25428
+ WORKSPACE_ENV_KEYS = ["SIGNET_PATH", "SIGNET_WORKSPACE"];
25253
25429
  try {
25254
25430
  const esmRequire = createRequire3(import.meta.url);
25255
25431
  native = esmRequire("@signet/native");
@@ -25386,16 +25562,7 @@ ${end.comment}` : end.comment;
25386
25562
 
25387
25563
  // ../../platform/daemon/src/logger.ts
25388
25564
  import { EventEmitter } from "node:events";
25389
- import {
25390
- appendFileSync,
25391
- existsSync as existsSync2,
25392
- mkdirSync,
25393
- readFileSync,
25394
- readdirSync as readdirSync3,
25395
- renameSync as renameSync2,
25396
- statSync as statSync2,
25397
- unlinkSync as unlinkSync2
25398
- } from "node:fs";
25565
+ import { appendFileSync, existsSync as existsSync3, readFileSync as readFileSync2, readdirSync as readdirSync3, renameSync as renameSync4, statSync as statSync2, unlinkSync as unlinkSync2 } from "node:fs";
25399
25566
  import { homedir as homedir3 } from "node:os";
25400
25567
  import { basename as basename2, dirname as dirname2, join as join3 } from "node:path";
25401
25568
  function resolveLoggerConfig(env = process.env, homeDir = homedir3()) {
@@ -25443,20 +25610,8 @@ var init_logger = __esm(() => {
25443
25610
  super();
25444
25611
  this.config = { ...DEFAULT_CONFIG, ...config2 };
25445
25612
  this.currentLogFile = this.getLogFileName();
25446
- this.ensureLogDir();
25447
25613
  this.startFlushTimer();
25448
25614
  }
25449
- ensureLogDir() {
25450
- try {
25451
- const dir = this.config.logFilePath ? dirname2(this.config.logFilePath) : this.config.logDir;
25452
- if (!existsSync2(dir)) {
25453
- mkdirSync(dir, { recursive: true });
25454
- }
25455
- } catch (e) {
25456
- this.fileOutputEnabled = false;
25457
- console.error("Failed to initialize log directory, disabling file logging:", e);
25458
- }
25459
- }
25460
25615
  getLogFileName() {
25461
25616
  if (this.config.logFilePath) {
25462
25617
  return this.config.logFilePath;
@@ -25504,7 +25659,7 @@ var init_logger = __esm(() => {
25504
25659
  return [];
25505
25660
  }
25506
25661
  if (this.config.logFilePath) {
25507
- if (!existsSync2(this.config.logFilePath))
25662
+ if (!existsSync3(this.config.logFilePath))
25508
25663
  return [];
25509
25664
  return [
25510
25665
  {
@@ -25513,7 +25668,7 @@ var init_logger = __esm(() => {
25513
25668
  }
25514
25669
  ];
25515
25670
  }
25516
- if (!existsSync2(this.config.logDir))
25671
+ if (!existsSync3(this.config.logDir))
25517
25672
  return [];
25518
25673
  return readdirSync3(this.config.logDir).filter((f2) => this.parseLogFileName(f2) !== null).map((f2) => ({
25519
25674
  name: f2,
@@ -25551,7 +25706,11 @@ var init_logger = __esm(() => {
25551
25706
  }
25552
25707
  write(entry) {
25553
25708
  if (this.config.consoleOutput) {
25554
- console.log(this.formatConsole(entry));
25709
+ const message = this.formatConsole(entry);
25710
+ if (process.env.SIGNET_DB_OWNER_WORKER === "1")
25711
+ console.error(message);
25712
+ else
25713
+ console.log(message);
25555
25714
  }
25556
25715
  this.buffer.push(entry);
25557
25716
  this.emit("log", entry);
@@ -25606,7 +25765,7 @@ var init_logger = __esm(() => {
25606
25765
  if (this.config.logFilePath)
25607
25766
  return;
25608
25767
  try {
25609
- if (!existsSync2(this.currentLogFile))
25768
+ if (!existsSync3(this.currentLogFile))
25610
25769
  return;
25611
25770
  const stats = statSync2(this.currentLogFile);
25612
25771
  if (stats.size > this.config.maxFileSize) {
@@ -25618,7 +25777,7 @@ var init_logger = __esm(() => {
25618
25777
  const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
25619
25778
  const rotatedName = this.currentLogFile.replace(".log", `-${timestamp}.log`);
25620
25779
  try {
25621
- renameSync2(this.currentLogFile, rotatedName);
25780
+ renameSync4(this.currentLogFile, rotatedName);
25622
25781
  this.cleanOldLogs();
25623
25782
  } catch {}
25624
25783
  }
@@ -25751,7 +25910,7 @@ var init_logger = __esm(() => {
25751
25910
  if (results.length >= limit * 2)
25752
25911
  break;
25753
25912
  try {
25754
- const content = readFileSync(file2.path, "utf-8");
25913
+ const content = readFileSync2(file2.path, "utf-8");
25755
25914
  const lines = content.trim().split(`
25756
25915
  `).filter(Boolean);
25757
25916
  const recentLines = lines.slice(-(limit * 2));
@@ -25773,8 +25932,9 @@ var init_logger = __esm(() => {
25773
25932
  } catch {}
25774
25933
  return results.slice(-limit);
25775
25934
  }
25776
- shutdown() {
25777
- this.flush(true);
25935
+ shutdown(flush = true) {
25936
+ if (flush)
25937
+ this.flush(true);
25778
25938
  if (this.flushTimer) {
25779
25939
  clearInterval(this.flushTimer);
25780
25940
  }
@@ -25784,8 +25944,8 @@ var init_logger = __esm(() => {
25784
25944
  });
25785
25945
 
25786
25946
  // ../../platform/daemon/src/db-vacuum.ts
25787
- import { statSync as statSync3, statfsSync as statfsSync2 } from "node:fs";
25788
- import { dirname as dirname3 } from "node:path";
25947
+ import { statSync as statSync4, statfsSync as statfsSync2 } from "node:fs";
25948
+ import { dirname as dirname6 } from "node:path";
25789
25949
  function isDbFullError(error51) {
25790
25950
  if (!(error51 instanceof Error))
25791
25951
  return false;
@@ -25795,7 +25955,7 @@ function isDbFullError(error51) {
25795
25955
  function measureDbSpace(dbPath, deps) {
25796
25956
  try {
25797
25957
  const dbBytes = deps.statSync(dbPath).size;
25798
- const directory = dirname3(dbPath);
25958
+ const directory = dirname6(dbPath);
25799
25959
  const stats = deps.statfsSync(directory);
25800
25960
  const freeBytes = Number.isFinite(stats.bavail) && stats.bavail >= 0 && Number.isFinite(stats.bsize) && stats.bsize > 0 ? stats.bavail * stats.bsize : null;
25801
25961
  return { dbBytes, freeBytes, requiredBytes: dbBytes * 2 };
@@ -25970,7 +26130,7 @@ var init_db_vacuum = __esm(() => {
25970
26130
  this.name = "DbSpacePreflightError";
25971
26131
  }
25972
26132
  };
25973
- dbSpaceDeps = { statSync: statSync3, statfsSync: statfsSync2 };
26133
+ dbSpaceDeps = { statSync: statSync4, statfsSync: statfsSync2 };
25974
26134
  UNKNOWN_DB_SPACE_METRICS = { dbBytes: 0, freeBytes: null, requiredBytes: 0 };
25975
26135
  STATE_TABLE_SQL = `
25976
26136
  CREATE TABLE IF NOT EXISTS ${VACUUM_CONVERSION_STATE_TABLE} (
@@ -26303,7 +26463,7 @@ var init_auth = __esm(() => {
26303
26463
  });
26304
26464
 
26305
26465
  // ../../platform/daemon/src/memory-config.ts
26306
- import { existsSync as existsSync4, readFileSync as readFileSync3 } from "node:fs";
26466
+ import { existsSync as existsSync5, readFileSync as readFileSync4 } from "node:fs";
26307
26467
  import { join as join6 } from "node:path";
26308
26468
  function detectLocalTimeZone() {
26309
26469
  try {
@@ -26728,10 +26888,10 @@ function loadMemoryConfig(agentsDir) {
26728
26888
  const paths = [join6(agentsDir, "agent.yaml"), join6(agentsDir, "AGENT.yaml"), join6(agentsDir, "config.yaml")];
26729
26889
  const envWarmNative = envBool("SIGNET_EMBEDDING_WARM_NATIVE");
26730
26890
  for (const path of paths) {
26731
- if (!existsSync4(path))
26891
+ if (!existsSync5(path))
26732
26892
  continue;
26733
26893
  try {
26734
- const yaml = parseSimpleYaml(readFileSync3(path, "utf-8"));
26894
+ const yaml = parseSimpleYaml(readFileSync4(path, "utf-8"));
26735
26895
  if (isRecord3(yaml))
26736
26896
  rejectRetiredEmbeddingConfig(yaml);
26737
26897
  const emb = yaml.embedding ?? {};
@@ -27338,8 +27498,8 @@ function createDbAccessorLifecycle() {
27338
27498
  const participants = [...closeParticipants.values()].sort((left, right) => left.order - right.order || left.name.localeCompare(right.name));
27339
27499
  let resolveClose;
27340
27500
  let rejectClose;
27341
- const pendingClose = new Promise((resolve, reject) => {
27342
- resolveClose = resolve;
27501
+ const pendingClose = new Promise((resolve4, reject) => {
27502
+ resolveClose = resolve4;
27343
27503
  rejectClose = reject;
27344
27504
  });
27345
27505
  closePromise = pendingClose;
@@ -27446,12 +27606,12 @@ __export(exports_db_accessor, {
27446
27606
  });
27447
27607
  import {
27448
27608
  copyFileSync,
27449
- existsSync as existsSync7,
27609
+ existsSync as existsSync8,
27450
27610
  lstatSync,
27451
- mkdirSync as mkdirSync3,
27452
- readFileSync as readFileSync6,
27611
+ mkdirSync,
27612
+ readFileSync as readFileSync7,
27453
27613
  readdirSync as readdirSync5,
27454
- statSync as statSync4,
27614
+ statSync as statSync6,
27455
27615
  statfsSync as statfsSync3,
27456
27616
  truncateSync,
27457
27617
  unlinkSync as unlinkSync3
@@ -27466,7 +27626,7 @@ import {
27466
27626
  } from "node:fs/promises";
27467
27627
  import { createRequire as createRequire4 } from "node:module";
27468
27628
  import { homedir as homedir7 } from "node:os";
27469
- import { basename as basename3, dirname as dirname6, join as join7 } from "node:path";
27629
+ import { basename as basename3, dirname as dirname8, join as join9 } from "node:path";
27470
27630
  function prepareTypedStatement(db, sql) {
27471
27631
  return db.prepare(sql);
27472
27632
  }
@@ -27493,7 +27653,7 @@ function assertDatabaseIntegrityWritesAllowed() {
27493
27653
  }
27494
27654
  function configurePragmas(db, path) {
27495
27655
  db.exec("PRAGMA auto_vacuum = INCREMENTAL");
27496
- const journal = resolveSqliteJournalConfig({ directory: dirname6(path) });
27656
+ const journal = resolveSqliteJournalConfig({ directory: dirname8(path) });
27497
27657
  db.exec(`PRAGMA journal_mode = ${journal.journalMode}`);
27498
27658
  db.exec("PRAGMA busy_timeout = 5000");
27499
27659
  db.exec(`PRAGMA synchronous = ${journal.networkFilesystem ? "FULL" : "NORMAL"}`);
@@ -27545,17 +27705,17 @@ function readTrimmed(env, key) {
27545
27705
  const trimmed = value.trim();
27546
27706
  return trimmed.length > 0 ? trimmed : null;
27547
27707
  }
27548
- function readConfigHome(env) {
27708
+ function readConfigHome2(env) {
27549
27709
  const dir = readTrimmed(env, "XDG_CONFIG_HOME");
27550
27710
  if (dir !== null)
27551
27711
  return dir;
27552
- return join7(homedir7(), ".config");
27712
+ return join9(homedir7(), ".config");
27553
27713
  }
27554
27714
  function readWorkspaceConfig(path) {
27555
- if (!existsSync7(path))
27715
+ if (!existsSync8(path))
27556
27716
  return null;
27557
27717
  try {
27558
- const raw = JSON.parse(readFileSync6(path, "utf8"));
27718
+ const raw = JSON.parse(readFileSync7(path, "utf8"));
27559
27719
  if (typeof raw !== "object" || raw === null)
27560
27720
  return null;
27561
27721
  if (!("workspace" in raw))
@@ -27574,17 +27734,17 @@ function resolveSqliteAgentsDir(opts) {
27574
27734
  const path = readTrimmed(env, "SIGNET_PATH");
27575
27735
  if (path !== null)
27576
27736
  return path;
27577
- const cfg = readWorkspaceConfig(join7(readConfigHome(env), "signet", "workspace.json"));
27737
+ const cfg = readWorkspaceConfig(join9(readConfigHome2(env), "signet", "workspace.json"));
27578
27738
  if (cfg !== null)
27579
27739
  return cfg;
27580
- return join7((opts?.home ?? homedir7)(), ".agents");
27740
+ return join9((opts?.home ?? homedir7)(), ".agents");
27581
27741
  }
27582
27742
  function resolveCustomSqlitePath(opts) {
27583
27743
  const platform3 = opts?.platform ?? process.platform;
27584
27744
  if (platform3 !== "darwin")
27585
27745
  return null;
27586
27746
  const env = opts?.env ?? process.env;
27587
- const exists = opts?.exists ?? existsSync7;
27747
+ const exists = opts?.exists ?? existsSync8;
27588
27748
  const agentsDir = opts?.agentsDir ?? resolveSqliteAgentsDir({ env });
27589
27749
  const envPath = env.SIGNET_SQLITE_PATH;
27590
27750
  if (envPath) {
@@ -27593,7 +27753,7 @@ function resolveCustomSqlitePath(opts) {
27593
27753
  }
27594
27754
  return null;
27595
27755
  }
27596
- const local = join7(agentsDir, "libsqlite3.dylib");
27756
+ const local = join9(agentsDir, "libsqlite3.dylib");
27597
27757
  if (exists(local)) {
27598
27758
  return { path: local, source: "workspace" };
27599
27759
  }
@@ -27628,7 +27788,7 @@ function resolveSqliteRuntimeConfig(opts) {
27628
27788
  };
27629
27789
  }
27630
27790
  const env = opts?.env ?? process.env;
27631
- const exists = opts?.exists ?? existsSync7;
27791
+ const exists = opts?.exists ?? existsSync8;
27632
27792
  const set3 = opts?.set ?? ((path) => {
27633
27793
  const sqliteCtor = getDatabaseConstructor();
27634
27794
  if (typeof sqliteCtor.setCustomSQLite === "function") {
@@ -27755,11 +27915,11 @@ function isMissingPathError(err) {
27755
27915
  return err instanceof Error && "code" in err && (err.code === "ENOENT" || err.code === "ENOTDIR");
27756
27916
  }
27757
27917
  function migrationBackups(dbPath2, deps) {
27758
- const dir = dirname6(dbPath2);
27918
+ const dir = dirname8(dbPath2);
27759
27919
  const base = basename3(dbPath2);
27760
27920
  return deps.readdirSync(dir).filter((f2) => isGeneratedMigrationBackupName(base, f2) && !f2.endsWith(".cursor.json") && !f2.includes(".probe-") && !f2.includes(".space-probe-")).flatMap((f2) => {
27761
27921
  try {
27762
- const path = join7(dir, f2);
27922
+ const path = join9(dir, f2);
27763
27923
  if (deps.lstatSync !== undefined) {
27764
27924
  const stat2 = deps.lstatSync(path);
27765
27925
  if (!stat2.isFile()) {
@@ -27779,7 +27939,7 @@ function migrationBackups(dbPath2, deps) {
27779
27939
  }
27780
27940
  function readMigrationBackupVerdictStatus(backupPath) {
27781
27941
  try {
27782
- const parsed = JSON.parse(readFileSync6(`${backupPath}.verdict.json`, "utf8"));
27942
+ const parsed = JSON.parse(readFileSync7(`${backupPath}.verdict.json`, "utf8"));
27783
27943
  return typeof parsed.status === "string" ? parsed.status : undefined;
27784
27944
  } catch {
27785
27945
  return;
@@ -27806,7 +27966,7 @@ function readMigrationBackupCheckpointStatus(backupPath, db, deps) {
27806
27966
  }
27807
27967
  function migrationBackupCursor(dbPath2, backupPath) {
27808
27968
  try {
27809
- const parsed = JSON.parse(readFileSync6(`${backupPath}.cursor.json`, "utf8"));
27969
+ const parsed = JSON.parse(readFileSync7(`${backupPath}.cursor.json`, "utf8"));
27810
27970
  if (parsed.sourcePath !== dbPath2 || parsed.destination !== backupPath || typeof parsed.sourceSize !== "number" || !Number.isFinite(parsed.sourceSize) || typeof parsed.sourceMtimeMs !== "number" || !Number.isFinite(parsed.sourceMtimeMs) || typeof parsed.offset !== "number" || !Number.isInteger(parsed.offset) || parsed.offset < 0 || parsed.offset > parsed.sourceSize)
27811
27971
  return;
27812
27972
  return { sourceSize: parsed.sourceSize, sourceMtimeMs: parsed.sourceMtimeMs, offset: parsed.offset };
@@ -27815,11 +27975,11 @@ function migrationBackupCursor(dbPath2, backupPath) {
27815
27975
  }
27816
27976
  }
27817
27977
  function isCursorlessLegacyMigrationBackup(backupPath, cursor) {
27818
- return cursor === undefined && !existsSync7(`${backupPath}.cursor.json`);
27978
+ return cursor === undefined && !existsSync8(`${backupPath}.cursor.json`);
27819
27979
  }
27820
27980
  function pruneStaleMigrationBackups(dbPath2, sourceSize, sourceMtimeMs, deps, db) {
27821
27981
  for (const backup of migrationBackups(dbPath2, deps)) {
27822
- const backupPath = join7(dirname6(dbPath2), backup.name);
27982
+ const backupPath = join9(dirname8(dbPath2), backup.name);
27823
27983
  const cursor = migrationBackupCursor(dbPath2, backupPath);
27824
27984
  if (isCursorlessLegacyMigrationBackup(backupPath, cursor)) {
27825
27985
  const legacyStatus = readMigrationBackupCheckpointStatus(backupPath, db, deps);
@@ -27859,7 +28019,7 @@ function pruneStaleMigrationBackups(dbPath2, sourceSize, sourceMtimeMs, deps, db
27859
28019
  }
27860
28020
  function assertNoRetainedUnverifiedMigrationBackup(dbPath2, sourceSize, sourceMtimeMs, deps, db) {
27861
28021
  for (const backup of migrationBackups(dbPath2, deps)) {
27862
- const backupPath = join7(dirname6(dbPath2), backup.name);
28022
+ const backupPath = join9(dirname8(dbPath2), backup.name);
27863
28023
  const cursor = migrationBackupCursor(dbPath2, backupPath);
27864
28024
  if (isCursorlessLegacyMigrationBackup(backupPath, cursor)) {
27865
28025
  const legacyStatus = readMigrationBackupCheckpointStatus(backupPath, db, deps);
@@ -27876,12 +28036,12 @@ function assertNoRetainedUnverifiedMigrationBackup(dbPath2, sourceSize, sourceMt
27876
28036
  }
27877
28037
  }
27878
28038
  function shouldDeferPendingMigration(dbPath2, db, deps) {
27879
- if (!existsSync7(dbPath2) || !hasPendingMigrations(db))
28039
+ if (!existsSync8(dbPath2) || !hasPendingMigrations(db))
27880
28040
  return false;
27881
28041
  const source = deps.statSync(dbPath2);
27882
28042
  let deferred = false;
27883
28043
  for (const backup of migrationBackups(dbPath2, deps)) {
27884
- const backupPath = join7(dirname6(dbPath2), backup.name);
28044
+ const backupPath = join9(dirname8(dbPath2), backup.name);
27885
28045
  const cursor = migrationBackupCursor(dbPath2, backupPath);
27886
28046
  if (isCursorlessLegacyMigrationBackup(backupPath, cursor)) {
27887
28047
  const legacyStatus = readMigrationBackupCheckpointStatus(backupPath, db, deps);
@@ -27917,10 +28077,10 @@ function shouldDeferPendingMigration(dbPath2, db, deps) {
27917
28077
  return deferred;
27918
28078
  }
27919
28079
  function pruneMigrationBackups(dbPath2, keep, deps, keepName, strict = false, db, verifiedBackupPath) {
27920
- const dir = dirname6(dbPath2);
28080
+ const dir = dirname8(dbPath2);
27921
28081
  for (const old of migrationBackups(dbPath2, deps).filter((backup) => backup.name !== keepName).slice(Math.max(0, keep))) {
27922
28082
  try {
27923
- const backupPath = join7(dir, old.name);
28083
+ const backupPath = join9(dir, old.name);
27924
28084
  const cursor = migrationBackupCursor(dbPath2, backupPath);
27925
28085
  const legacyUnverified = isCursorlessLegacyMigrationBackup(backupPath, cursor) && backupPath !== verifiedBackupPath;
27926
28086
  if ((legacyUnverified || cursor !== undefined) && backupPath !== verifiedBackupPath && readMigrationBackupCheckpointStatus(backupPath, db, deps) !== MIGRATION_CHECKPOINT_COMPLETE_STATUS) {
@@ -27980,7 +28140,7 @@ function isDbFullError2(err) {
27980
28140
  }
27981
28141
  function preflightMigrationBackupSpace(dbPath2, deps) {
27982
28142
  const dbBytes = fileSize(dbPath2, deps);
27983
- const freeBytes = availableBytes(dirname6(dbPath2), deps);
28143
+ const freeBytes = availableBytes(dirname8(dbPath2), deps);
27984
28144
  if (dbBytes === null)
27985
28145
  return null;
27986
28146
  const metrics = {
@@ -27997,7 +28157,7 @@ function preflightMigrationBackupSpace(dbPath2, deps) {
27997
28157
  return metrics;
27998
28158
  }
27999
28159
  function migrationBackupSpaceError(dbPath2, metrics, deps, err) {
28000
- const freeBytes = availableBytes(dirname6(dbPath2), deps) ?? metrics.freeBytes;
28160
+ const freeBytes = availableBytes(dirname8(dbPath2), deps) ?? metrics.freeBytes;
28001
28161
  return new DbSpacePreflightError("migration_backup", { ...metrics, freeBytes }, err);
28002
28162
  }
28003
28163
  function backupBeforeMigration(db, dbPath2, schemaVersion, deps = migrationBackupDeps) {
@@ -28039,7 +28199,7 @@ async function streamedMigrationBackup(db, dbPath2, schemaVersion, deadlineAt) {
28039
28199
  try {
28040
28200
  db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
28041
28201
  } catch {}
28042
- const sourceStat = statSync4(dbPath2);
28202
+ const sourceStat = statSync6(dbPath2);
28043
28203
  const sourceSize = sourceStat.size;
28044
28204
  const sourceMtimeMs = sourceStat.mtimeMs;
28045
28205
  const sourceMode = sourceStat.mode & 4095;
@@ -28068,15 +28228,15 @@ async function streamedMigrationBackup(db, dbPath2, schemaVersion, deadlineAt) {
28068
28228
  return backupDest;
28069
28229
  }
28070
28230
  async function readMigrationBackupCursor(dbPath2, sourceSize, sourceMtimeMs) {
28071
- const dir = dirname6(dbPath2);
28231
+ const dir = dirname8(dbPath2);
28072
28232
  const base = basename3(dbPath2);
28073
28233
  for (const name of readdirSync5(dir).filter((entry) => entry.endsWith(".cursor.json") && isGeneratedMigrationBackupName(base, entry.slice(0, -".cursor.json".length)))) {
28074
- const cursorPath = join7(dir, name);
28234
+ const cursorPath = join9(dir, name);
28075
28235
  try {
28076
28236
  const parsed = JSON.parse(await readFileAsync(cursorPath, "utf8"));
28077
28237
  const cursorMatchesSource = parsed.sourcePath === dbPath2 && parsed.sourceSize === sourceSize && parsed.sourceMtimeMs === sourceMtimeMs;
28078
28238
  const destination = typeof parsed.destination === "string" ? parsed.destination : undefined;
28079
- const safeDestination = destination !== undefined && destination === join7(dir, basename3(destination)) && basename3(destination).startsWith(`${base}.bak-v`);
28239
+ const safeDestination = destination !== undefined && destination === join9(dir, basename3(destination)) && basename3(destination).startsWith(`${base}.bak-v`);
28080
28240
  let destinationStat;
28081
28241
  let destinationExists = false;
28082
28242
  if (destination !== undefined) {
@@ -28231,7 +28391,7 @@ async function copyMigrationBackupChunks(dbPath2, backupDest, sourceSize, source
28231
28391
  }
28232
28392
  }
28233
28393
  function sweepStaleMigrationBackupProbes(dbPath2, deps) {
28234
- const dir = dirname6(dbPath2);
28394
+ const dir = dirname8(dbPath2);
28235
28395
  const base = basename3(dbPath2);
28236
28396
  let entries;
28237
28397
  try {
@@ -28244,7 +28404,7 @@ function sweepStaleMigrationBackupProbes(dbPath2, deps) {
28244
28404
  const probeName = entry.includes(".space-probe-") ? entry.slice(0, entry.indexOf(".space-probe-")) : entry.slice(0, entry.indexOf(".probe-"));
28245
28405
  if (!isGeneratedMigrationBackupName(base, probeName) || !isProbe || entry.endsWith(`.probe-${process.pid}`) || entry.endsWith(`.space-probe-${process.pid}`))
28246
28406
  continue;
28247
- const path = join7(dir, entry);
28407
+ const path = join9(dir, entry);
28248
28408
  try {
28249
28409
  deps.unlinkSync(path);
28250
28410
  deps.log(`[db-accessor] Reclaimed stale migration backup probe: ${entry}`);
@@ -28272,7 +28432,7 @@ function preflightResumedMigrationBackupSpace(dbPath2, sourceSize, offset, deps)
28272
28432
  const remaining = sourceSize - offset;
28273
28433
  if (remaining <= 0)
28274
28434
  return;
28275
- const freeBytes = availableBytes(dirname6(dbPath2), deps);
28435
+ const freeBytes = availableBytes(dirname8(dbPath2), deps);
28276
28436
  const metrics = {
28277
28437
  dbBytes: sourceSize,
28278
28438
  freeBytes,
@@ -28312,7 +28472,7 @@ function hasPendingMigrationBackup(dbPath2) {
28312
28472
  }
28313
28473
  function pendingMigrationBackupPath(dbPath2) {
28314
28474
  const pending = migrationBackups(dbPath2, migrationBackupDeps)[0];
28315
- return pending === undefined ? null : join7(dirname6(dbPath2), pending.name);
28475
+ return pending === undefined ? null : join9(dirname8(dbPath2), pending.name);
28316
28476
  }
28317
28477
  function pendingMigrationBackupSizeBytes(dbPath2) {
28318
28478
  const pending = migrationBackups(dbPath2, migrationBackupDeps)[0];
@@ -28320,14 +28480,14 @@ function pendingMigrationBackupSizeBytes(dbPath2) {
28320
28480
  }
28321
28481
  function pruneMigrationBackupsAfterIntegrity(dbPath2, deps = migrationBackupDeps, verifiedBackupPath) {
28322
28482
  pruneMigrationBackups(dbPath2, 0, deps, undefined, true, undefined, verifiedBackupPath);
28323
- const dir = dirname6(dbPath2);
28483
+ const dir = dirname8(dbPath2);
28324
28484
  const base = basename3(dbPath2);
28325
28485
  for (const name of deps.readdirSync(dir).filter((entry) => entry.endsWith(".cursor.json") && isGeneratedMigrationBackupName(base, entry.slice(0, -".cursor.json".length)))) {
28326
28486
  const backupName = name.slice(0, -".cursor.json".length);
28327
28487
  if (migrationBackups(dbPath2, deps).some((backup) => backup.name === backupName))
28328
28488
  continue;
28329
28489
  try {
28330
- deps.unlinkSync(join7(dir, name));
28490
+ deps.unlinkSync(join9(dir, name));
28331
28491
  } catch {}
28332
28492
  }
28333
28493
  }
@@ -28405,9 +28565,9 @@ function openDbAccessorConnection(path, opts) {
28405
28565
  if (accessor) {
28406
28566
  throw new Error("DbAccessor already initialised");
28407
28567
  }
28408
- const dir = dirname6(path);
28409
- if (!existsSync7(dir)) {
28410
- mkdirSync3(dir, { recursive: true });
28568
+ const dir = dirname8(path);
28569
+ if (!existsSync8(dir)) {
28570
+ mkdirSync(dir, { recursive: true });
28411
28571
  }
28412
28572
  dbPath = path;
28413
28573
  configureCustomSqlite(opts?.agentsDir);
@@ -28421,13 +28581,13 @@ function readCurrentSchemaVersion(writeConn) {
28421
28581
  return row && typeof row.version === "number" ? row.version : 0;
28422
28582
  }
28423
28583
  function backupBeforePendingMigrations(writeConn, path) {
28424
- if (existsSync7(path) && hasPendingMigrations(toMigrationDb(writeConn))) {
28584
+ if (existsSync8(path) && hasPendingMigrations(toMigrationDb(writeConn))) {
28425
28585
  return backupBeforeMigration(writeConn, path, readCurrentSchemaVersion(writeConn));
28426
28586
  }
28427
28587
  return null;
28428
28588
  }
28429
28589
  async function backupBeforePendingMigrationsAsync(writeConn, path, deadlineAt) {
28430
- if (existsSync7(path) && hasPendingMigrations(toMigrationDb(writeConn))) {
28590
+ if (existsSync8(path) && hasPendingMigrations(toMigrationDb(writeConn))) {
28431
28591
  return await backupBeforeMigrationAsync(writeConn, path, readCurrentSchemaVersion(writeConn), migrationBackupDeps, deadlineAt);
28432
28592
  }
28433
28593
  return null;
@@ -28509,13 +28669,13 @@ function initDbAccessorReadOnly(dbPathParam, vecExtensionPath, opts) {
28509
28669
  function ensureFtsTable(db, options = {}) {
28510
28670
  const sql = readMemoriesFtsSql(toFtsSchemaQueryDb(db));
28511
28671
  if (sql === null) {
28512
- console.log("[db-accessor] memories_fts missing — recreating FTS5 table");
28672
+ console.error("[db-accessor] memories_fts missing — recreating FTS5 table");
28513
28673
  createMemoriesFts(db);
28514
28674
  if (options.deferBackfill !== true) {
28515
28675
  const backfilled = db.prepare("SELECT COUNT(*) as n FROM memories").get();
28516
28676
  if (backfilled.n > 0) {
28517
28677
  db.exec("INSERT INTO memories_fts(rowid, content) SELECT rowid, content FROM memories");
28518
- console.log(`[db-accessor] Backfilled ${backfilled.n} rows into memories_fts`);
28678
+ console.error(`[db-accessor] Backfilled ${backfilled.n} rows into memories_fts`);
28519
28679
  }
28520
28680
  }
28521
28681
  if (options.deferBackfill !== true)
@@ -28528,7 +28688,7 @@ function ensureFtsTable(db, options = {}) {
28528
28688
  refreshMemoriesFtsState(db);
28529
28689
  return;
28530
28690
  }
28531
- console.log("[db-accessor] memories_fts tokenizer drift detected — recreating FTS5 table");
28691
+ console.error("[db-accessor] memories_fts tokenizer drift detected — recreating FTS5 table");
28532
28692
  if (options.deferBackfill === true)
28533
28693
  recreateMemoriesFtsSchema(db);
28534
28694
  else
@@ -28631,7 +28791,7 @@ function missingVecEmbeddingsRows(db, expectedDimensions, lastId, limit) {
28631
28791
  ORDER BY e.id LIMIT ?`).all(expectedDimensions, lastId, limit);
28632
28792
  }
28633
28793
  function backfillVecEmbeddings(db, expectedDimensions, deadlineAt, options = {}) {
28634
- const log = options.log ?? console.log;
28794
+ const log = options.log ?? console.error;
28635
28795
  const warn = options.warn ?? console.warn;
28636
28796
  ensureVecEmbeddingsQuarantineTable(db);
28637
28797
  const batchSize = Math.max(1, Math.min(options.batchSize ?? VEC_EMBEDDING_BACKFILL_BATCH_SIZE, VEC_EMBEDDING_BACKFILL_BATCH_SIZE));
@@ -28758,7 +28918,7 @@ function continuePendingVecBackfill(db, deadlineAt = Date.now() + VEC_EMBEDDING_
28758
28918
  backfillVecEmbeddings(db, dimensions, deadlineAt);
28759
28919
  }
28760
28920
  function yieldToEventLoop() {
28761
- return new Promise((resolve) => setTimeout(resolve, 0));
28921
+ return new Promise((resolve4) => setTimeout(resolve4, 0));
28762
28922
  }
28763
28923
  function createAccessor(writeConn) {
28764
28924
  let closed = false;
@@ -28867,7 +29027,7 @@ function createAccessor(writeConn) {
28867
29027
  });
28868
29028
  return Promise.reject(new DbReadQueueFullError);
28869
29029
  }
28870
- return new Promise((resolve, reject) => {
29030
+ return new Promise((resolve4, reject) => {
28871
29031
  let settled = false;
28872
29032
  const enqueuedAt = performance.now();
28873
29033
  const waiter = {};
@@ -28905,7 +29065,7 @@ function createAccessor(writeConn) {
28905
29065
  operation,
28906
29066
  timeoutMs,
28907
29067
  signal: options.signal,
28908
- resolve,
29068
+ resolve: resolve4,
28909
29069
  reject,
28910
29070
  onAbort,
28911
29071
  timer
@@ -29018,7 +29178,7 @@ function createAccessor(writeConn) {
29018
29178
  });
29019
29179
  return Promise.reject(new DbWriteQueueFullError);
29020
29180
  }
29021
- return new Promise((resolve, reject) => {
29181
+ return new Promise((resolve4, reject) => {
29022
29182
  const queuedAt = performance.now();
29023
29183
  const job = {};
29024
29184
  const onAbort = () => {
@@ -29054,7 +29214,7 @@ function createAccessor(writeConn) {
29054
29214
  onAbort,
29055
29215
  transactional,
29056
29216
  cancellation: "pending",
29057
- resolve: (value) => resolve(value),
29217
+ resolve: (value) => resolve4(value),
29058
29218
  reject
29059
29219
  });
29060
29220
  writeQueue.push(job);
@@ -29483,12 +29643,12 @@ var init_db_accessor = __esm(() => {
29483
29643
  migrationBackupDeps = {
29484
29644
  copyFileSync,
29485
29645
  readdirSync: readdirSync5,
29486
- statSync: statSync4,
29646
+ statSync: statSync6,
29487
29647
  lstatSync,
29488
29648
  statfsSync: statfsSync3,
29489
29649
  unlinkSync: unlinkSync3,
29490
29650
  now: Date.now,
29491
- log: console.log,
29651
+ log: console.error,
29492
29652
  warn: console.warn
29493
29653
  };
29494
29654
  });
@@ -29933,7 +30093,7 @@ var require_init = __commonJS((exports) => {
29933
30093
  });
29934
30094
 
29935
30095
  // ../../platform/daemon/src/mcp-stdio-runtime.ts
29936
- import { existsSync as existsSync17, statSync as statSync6 } from "node:fs";
30096
+ import { existsSync as existsSync18, statSync as statSync8 } from "node:fs";
29937
30097
  import { isAbsolute } from "node:path";
29938
30098
 
29939
30099
  // ../../node_modules/.bun/@modelcontextprotocol+sdk@1.30.0/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js
@@ -52600,31 +52760,31 @@ init_dist();
52600
52760
  init_db_accessor();
52601
52761
  init_db_accessor_lifecycle();
52602
52762
  import { stat } from "node:fs/promises";
52603
- import { join as join12 } from "node:path";
52763
+ import { join as join13 } from "node:path";
52604
52764
 
52605
52765
  // ../../platform/daemon/src/db-owner-client.ts
52606
52766
  import { randomUUID } from "node:crypto";
52607
52767
  import { spawn } from "node:child_process";
52608
- import { appendFileSync as appendFileSync2, existsSync as existsSync10, readdirSync as readdirSync7, readFileSync as readFileSync9, statSync as statSync5, unlinkSync as unlinkSync5 } from "node:fs";
52609
- import { dirname as dirname9, join as join11 } from "node:path";
52768
+ import { appendFileSync as appendFileSync2, existsSync as existsSync11, readdirSync as readdirSync7, readFileSync as readFileSync10, statSync as statSync7, unlinkSync as unlinkSync5 } from "node:fs";
52769
+ import { dirname as dirname10, join as join12 } from "node:path";
52610
52770
  import { fileURLToPath as fileURLToPath2 } from "node:url";
52611
52771
 
52612
52772
  // ../../platform/daemon/src/native-runtime-assets.ts
52613
52773
  import { createHash as createHash3 } from "node:crypto";
52614
52774
  import {
52615
52775
  chmodSync as chmodSync2,
52616
- existsSync as existsSync9,
52776
+ existsSync as existsSync10,
52617
52777
  mkdirSync as mkdirSync5,
52618
52778
  mkdtempSync,
52619
- readFileSync as readFileSync8,
52779
+ readFileSync as readFileSync9,
52620
52780
  readdirSync as readdirSync6,
52621
- renameSync as renameSync4,
52622
- rmSync,
52781
+ renameSync as renameSync6,
52782
+ rmSync as rmSync3,
52623
52783
  unlinkSync as unlinkSync4,
52624
52784
  writeFileSync
52625
52785
  } from "node:fs";
52626
52786
  import { tmpdir } from "node:os";
52627
- import { dirname as dirname8, join as join9 } from "node:path";
52787
+ import { dirname as dirname9, join as join11 } from "node:path";
52628
52788
  function nativeRuntimeAssets() {
52629
52789
  return globalThis.__SIGNET_NATIVE_RUNTIME_ASSETS__ ?? {};
52630
52790
  }
@@ -52633,10 +52793,10 @@ function resolveEmbeddedWorkerPath(name) {
52633
52793
  if (!worker)
52634
52794
  return null;
52635
52795
  const hash2 = createHash3("sha256").update(worker.contentBase64).digest("hex").slice(0, 16);
52636
- const dir = join9(tmpdir(), "signet-native-workers");
52637
- const path = join9(dir, `${name.replace(/[^a-zA-Z0-9_.-]/g, "_")}-${hash2}.mjs`);
52796
+ const dir = join11(tmpdir(), "signet-native-workers");
52797
+ const path = join11(dir, `${name.replace(/[^a-zA-Z0-9_.-]/g, "_")}-${hash2}.mjs`);
52638
52798
  mkdirSync5(dir, { recursive: true });
52639
- if (!existsSync9(path)) {
52799
+ if (!existsSync10(path)) {
52640
52800
  writeFileSync(path, Buffer.from(worker.contentBase64, "base64"));
52641
52801
  }
52642
52802
  return path;
@@ -52683,8 +52843,8 @@ class DbOwnerCancelledError extends DbOwnerError {
52683
52843
  }
52684
52844
 
52685
52845
  class DbOwnerDiedError extends DbOwnerError {
52686
- constructor(message = "DB owner process died; pending jobs failed closed") {
52687
- super("DB_OWNER_DIED", message);
52846
+ constructor(message = "DB owner process died; pending jobs failed closed", code = "DB_OWNER_DIED", causeFamily, sqliteCode) {
52847
+ super(code, message, causeFamily, sqliteCode);
52688
52848
  this.name = "DbOwnerDiedError";
52689
52849
  }
52690
52850
  }
@@ -52716,9 +52876,9 @@ function sweepStaleCancellationRegistries(directory) {
52716
52876
  for (const entry of entries) {
52717
52877
  if (!entry.startsWith(CANCEL_REGISTRY_PREFIX))
52718
52878
  continue;
52719
- const path = join11(directory, entry);
52879
+ const path = join12(directory, entry);
52720
52880
  try {
52721
- if (statSync5(path).mtimeMs < cutoff)
52881
+ if (statSync7(path).mtimeMs < cutoff)
52722
52882
  unlinkSync5(path);
52723
52883
  } catch {}
52724
52884
  }
@@ -52737,9 +52897,9 @@ function workerArguments(workerPath) {
52737
52897
  if (resolveEmbeddedWorkerPath("db-owner-worker") !== null) {
52738
52898
  return [];
52739
52899
  }
52740
- const directory = dirname9(fileURLToPath2(import.meta.url));
52741
- const bundled = join11(directory, "db-owner-worker.js");
52742
- return [existsSync10(bundled) ? bundled : join11(directory, "db-owner-worker.ts")];
52900
+ const directory = dirname10(fileURLToPath2(import.meta.url));
52901
+ const bundled = join12(directory, "db-owner-worker.js");
52902
+ return [existsSync11(bundled) ? bundled : join12(directory, "db-owner-worker.ts")];
52743
52903
  }
52744
52904
  function ownerIsDead(owner) {
52745
52905
  if (owner.exitCode !== null || owner.signalCode !== null || owner.killed)
@@ -52747,7 +52907,7 @@ function ownerIsDead(owner) {
52747
52907
  if (process.platform !== "linux" || owner.pid === undefined)
52748
52908
  return false;
52749
52909
  try {
52750
- const status = readFileSync9(`/proc/${owner.pid}/status`, "utf8");
52910
+ const status = readFileSync10(`/proc/${owner.pid}/status`, "utf8");
52751
52911
  return /^(?:State:\s+Z|CoreDumping:\s+1)/m.test(status);
52752
52912
  } catch {
52753
52913
  return false;
@@ -52765,6 +52925,8 @@ function oldestAge(first, second) {
52765
52925
  }
52766
52926
  function createSingleDbOwnerClient(options) {
52767
52927
  let child = null;
52928
+ let activeChildClose = null;
52929
+ let retiredChildClose = null;
52768
52930
  let startPromise = null;
52769
52931
  let startupResolve = null;
52770
52932
  let startupReject = null;
@@ -52779,8 +52941,8 @@ function createSingleDbOwnerClient(options) {
52779
52941
  let input = "";
52780
52942
  let stderr = "";
52781
52943
  let writeBlocked = false;
52782
- sweepStaleCancellationRegistries(dirname9(options.dbPath));
52783
- const cancellationRegistryPath = join11(dirname9(options.dbPath), `${CANCEL_REGISTRY_PREFIX}${process.pid}-${randomUUID()}`);
52944
+ sweepStaleCancellationRegistries(dirname10(options.dbPath));
52945
+ const cancellationRegistryPath = join12(dirname10(options.dbPath), `${CANCEL_REGISTRY_PREFIX}${process.pid}-${randomUUID()}`);
52784
52946
  const pending = new Map;
52785
52947
  const abandonedMetrics = new Map;
52786
52948
  function unlinkCancellationRegistry() {
@@ -52826,12 +52988,12 @@ function createSingleDbOwnerClient(options) {
52826
52988
  if (child !== owner || stdin === null || stdin === undefined || ownerIsDead(owner) || stdin.destroyed || stdin.writableEnded) {
52827
52989
  return Promise.reject(new DbOwnerDiedError);
52828
52990
  }
52829
- return new Promise((resolve, reject) => {
52991
+ return new Promise((resolve4, reject) => {
52830
52992
  try {
52831
52993
  stdin.write(`${JSON.stringify(command)}
52832
52994
  `, (error51) => {
52833
52995
  if (error51 === undefined || error51 === null)
52834
- resolve();
52996
+ resolve4();
52835
52997
  else
52836
52998
  reject(error51);
52837
52999
  });
@@ -52866,7 +53028,11 @@ function createSingleDbOwnerClient(options) {
52866
53028
  if (owner !== null && child !== owner)
52867
53029
  return;
52868
53030
  const retired = child;
53031
+ const retiredClose = activeChildClose;
52869
53032
  child = null;
53033
+ activeChildClose = null;
53034
+ if (retiredClose !== null)
53035
+ retiredChildClose = retiredClose;
52870
53036
  pid = null;
52871
53037
  activeJobId = null;
52872
53038
  input = "";
@@ -52913,13 +53079,8 @@ function createSingleDbOwnerClient(options) {
52913
53079
  return;
52914
53080
  }
52915
53081
  if (event.type === "fatal") {
52916
- lastError = event.error.message;
52917
- state = "failed";
52918
- if (initialization === "running")
52919
- initialization = "failed";
52920
- startupReject?.(messageFromError(event.error));
52921
- startupReject = null;
52922
- startupResolve = null;
53082
+ const fatalError = messageFromError(event.error);
53083
+ retireOwner(new DbOwnerDiedError(fatalError.message, fatalError.code, fatalError.causeFamily, fatalError.sqliteCode), owner, "failed", true);
52923
53084
  return;
52924
53085
  }
52925
53086
  const pendingJob = pending.get(event.jobId);
@@ -52960,8 +53121,9 @@ function createSingleDbOwnerClient(options) {
52960
53121
  try {
52961
53122
  handleEvent(owner, JSON.parse(line));
52962
53123
  } catch (error51) {
52963
- lastError = error51 instanceof Error ? error51.message : String(error51);
52964
- state = "failed";
53124
+ const message = error51 instanceof Error ? error51.message : String(error51);
53125
+ retireOwner(new DbOwnerDiedError(`DB owner emitted malformed protocol output: ${message}`), owner, "failed", true);
53126
+ break;
52965
53127
  }
52966
53128
  }
52967
53129
  }
@@ -52999,20 +53161,27 @@ function createSingleDbOwnerClient(options) {
52999
53161
  retireOwner(new DbOwnerDiedError, owner, "dead", true);
53000
53162
  return await start();
53001
53163
  }
53002
- await new Promise((resolve) => setTimeout(resolve, 0));
53164
+ await new Promise((resolve4) => setTimeout(resolve4, 0));
53003
53165
  if (child !== owner || state !== "ready")
53004
53166
  return await start();
53005
53167
  return;
53006
53168
  }
53007
53169
  if (startPromise !== null)
53008
53170
  return await startPromise;
53171
+ const retiredClose = retiredChildClose;
53172
+ if (retiredClose !== null) {
53173
+ await retiredClose;
53174
+ if (retiredChildClose === retiredClose)
53175
+ retiredChildClose = null;
53176
+ return await start();
53177
+ }
53009
53178
  const timeoutMs = resolveStartupTimeoutMs(options);
53010
53179
  state = "starting";
53011
53180
  lastError = null;
53012
53181
  stderr = "";
53013
53182
  generation++;
53014
- startPromise = new Promise((resolve, reject) => {
53015
- startupResolve = resolve;
53183
+ startPromise = new Promise((resolve4, reject) => {
53184
+ startupResolve = resolve4;
53016
53185
  startupReject = reject;
53017
53186
  const workerEnv = {
53018
53187
  ...process.env,
@@ -53028,6 +53197,9 @@ function createSingleDbOwnerClient(options) {
53028
53197
  stdio: ["pipe", "pipe", "pipe"]
53029
53198
  });
53030
53199
  child = owner;
53200
+ activeChildClose = new Promise((resolve6) => {
53201
+ owner.once("close", () => resolve6());
53202
+ });
53031
53203
  const appendStderr = (chunk) => {
53032
53204
  stderr = `${stderr}${chunk}`.slice(-8192);
53033
53205
  };
@@ -53040,10 +53212,8 @@ function createSingleDbOwnerClient(options) {
53040
53212
  owner.once("close", (code, signal) => handleExit(owner, code, signal, stderr.trim() || undefined));
53041
53213
  const timer = setTimeout(() => {
53042
53214
  if (state !== "ready") {
53043
- lastError = diagnostic(`DB owner did not become ready within ${timeoutMs}ms`);
53044
- state = "failed";
53045
- owner.kill("SIGKILL");
53046
- startupReject?.(new DbOwnerError("DB_OWNER_START_TIMEOUT", diagnostic(lastError)));
53215
+ const error51 = new DbOwnerError("DB_OWNER_START_TIMEOUT", diagnostic(`DB owner did not become ready within ${timeoutMs}ms`));
53216
+ retireOwner(error51, owner, "failed", true);
53047
53217
  }
53048
53218
  }, timeoutMs);
53049
53219
  const resolveStartup = startupResolve;
@@ -53145,10 +53315,10 @@ function createSingleDbOwnerClient(options) {
53145
53315
  };
53146
53316
  let pendingJob = null;
53147
53317
  let resolveMetrics = () => {};
53148
- const metrics = new Promise((resolve) => {
53149
- resolveMetrics = resolve;
53318
+ const metrics = new Promise((resolve4) => {
53319
+ resolveMetrics = resolve4;
53150
53320
  });
53151
- const result = new Promise((resolve, reject) => {
53321
+ const result = new Promise((resolve4, reject) => {
53152
53322
  const timer = setTimeout(() => {
53153
53323
  const entry = pending.get(job.id);
53154
53324
  if (entry === undefined || entry.settled)
@@ -53168,7 +53338,7 @@ function createSingleDbOwnerClient(options) {
53168
53338
  write(owner, { type: "cancel", jobId: job.id }).catch(() => {});
53169
53339
  }
53170
53340
  }, submitOptions.deadlineMs);
53171
- pendingJob = { job, resolve, reject, timer, resolveMetrics, settled: false, dispatched: false };
53341
+ pendingJob = { job, resolve: resolve4, reject, timer, resolveMetrics, settled: false, dispatched: false };
53172
53342
  pending.set(job.id, pendingJob);
53173
53343
  if (request.kind === "initialize")
53174
53344
  initialization = "running";
@@ -53214,14 +53384,14 @@ function createSingleDbOwnerClient(options) {
53214
53384
  async function awaitResult(handle, timeoutMs) {
53215
53385
  if (timeoutMs === undefined)
53216
53386
  return await handle.result;
53217
- return await new Promise((resolve, reject) => {
53387
+ return await new Promise((resolve4, reject) => {
53218
53388
  const timer = setTimeout(() => {
53219
53389
  handle.cancel();
53220
53390
  reject(new DbOwnerDeadlineError(handle.job.id));
53221
53391
  }, timeoutMs);
53222
53392
  handle.result.then((value) => {
53223
53393
  clearTimeout(timer);
53224
- resolve(value);
53394
+ resolve4(value);
53225
53395
  }, (error51) => {
53226
53396
  clearTimeout(timer);
53227
53397
  reject(error51);
@@ -53229,21 +53399,25 @@ function createSingleDbOwnerClient(options) {
53229
53399
  });
53230
53400
  }
53231
53401
  async function close() {
53402
+ const owner = child;
53403
+ const ownerClose = activeChildClose;
53232
53404
  closed = true;
53233
- if (child !== null) {
53234
- write(child, { type: "shutdown" }).catch(() => {});
53235
- await new Promise((resolve) => {
53236
- if (child === null) {
53237
- resolve();
53238
- return;
53239
- }
53240
- child.once("close", () => resolve());
53241
- setTimeout(() => {
53242
- child?.kill("SIGKILL");
53243
- resolve();
53244
- }, 250);
53245
- });
53246
- }
53405
+ if (owner !== null) {
53406
+ write(owner, { type: "shutdown" }).catch(() => {});
53407
+ const forceKillTimer = setTimeout(() => {
53408
+ try {
53409
+ owner.kill("SIGKILL");
53410
+ } catch {}
53411
+ }, 250);
53412
+ if (ownerClose !== null)
53413
+ await ownerClose;
53414
+ clearTimeout(forceKillTimer);
53415
+ }
53416
+ const retiredClose = retiredChildClose;
53417
+ if (retiredClose !== null)
53418
+ await retiredClose;
53419
+ if (retiredChildClose === retiredClose)
53420
+ retiredChildClose = null;
53247
53421
  state = "closed";
53248
53422
  rejectAll(new DbOwnerDiedError("DB owner client closed"));
53249
53423
  try {
@@ -53447,6 +53621,8 @@ async function executeInlineOwnerRequest(accessor2, request) {
53447
53621
  case "dreaming_hygiene_attention":
53448
53622
  case "dreaming_surprisal_attention":
53449
53623
  case "dreaming_episodic_backlog":
53624
+ case "dreaming_episodic_backlog_probe":
53625
+ case "dreaming_episodic_backlog_exists":
53450
53626
  case "dreaming_evidence_search":
53451
53627
  case "dreaming_evidence_source":
53452
53628
  case "dreaming_pass_finalize":
@@ -53518,6 +53694,7 @@ function inlineOwner(accessor2) {
53518
53694
  };
53519
53695
  }
53520
53696
  var clients = new Map;
53697
+ var retiredClientClosures = new Map;
53521
53698
  async function dbIdentity(dbPath2) {
53522
53699
  try {
53523
53700
  const metadata = await stat(dbPath2);
@@ -53526,17 +53703,27 @@ async function dbIdentity(dbPath2) {
53526
53703
  return dbPath2;
53527
53704
  }
53528
53705
  }
53529
- async function startDbOwnerWithRole(dbPath2, workerRole) {
53706
+ async function startDbOwnerWithRole(dbPath2, workerRole, options = {}) {
53530
53707
  const identity = await dbIdentity(dbPath2);
53531
53708
  const key = `${workerRole}:${dbPath2}`;
53709
+ const retiredClosure = retiredClientClosures.get(key);
53710
+ if (retiredClosure !== undefined)
53711
+ await retiredClosure;
53532
53712
  const current = clients.get(key);
53533
53713
  if (current !== undefined && (current.identity !== identity || current.owner.health().state === "closed" || current.owner.health().state === "dead" || current.owner.health().state === "failed")) {
53534
53714
  clients.delete(key);
53535
- await current.owner.close();
53715
+ const closing = current.owner.close();
53716
+ retiredClientClosures.set(key, closing);
53717
+ try {
53718
+ await closing;
53719
+ } finally {
53720
+ if (retiredClientClosures.get(key) === closing)
53721
+ retiredClientClosures.delete(key);
53722
+ }
53536
53723
  }
53537
53724
  let entry = clients.get(key);
53538
53725
  if (entry === undefined) {
53539
- entry = { owner: createDbOwnerClient({ dbPath: dbPath2, workerRole }), identity, startPromise: null };
53726
+ entry = { owner: createDbOwnerClient({ dbPath: dbPath2, workerRole, ...options }), identity, startPromise: null };
53540
53727
  clients.set(key, entry);
53541
53728
  }
53542
53729
  if (entry.startPromise !== null)
@@ -53552,7 +53739,7 @@ async function startDbOwnerWithRole(dbPath2, workerRole) {
53552
53739
  currentEntry.startPromise = null;
53553
53740
  }
53554
53741
  }
53555
- async function startDbOwner(dbPath2 = join12(resolveSqliteAgentsDir(), "memory", "memories.db")) {
53742
+ async function startDbOwner(dbPath2 = join13(resolveSqliteAgentsDir(), "memory", "memories.db")) {
53556
53743
  return await startDbOwnerWithRole(dbPath2, "generic");
53557
53744
  }
53558
53745
  async function getCurrentProcessOwner() {
@@ -53620,7 +53807,7 @@ async function submitWithAdmission(owner, request, options) {
53620
53807
  const remainingMs = deadlineAt - Date.now();
53621
53808
  if (remainingMs <= 0)
53622
53809
  throw error51;
53623
- await new Promise((resolve) => setTimeout(resolve, Math.min(25, remainingMs)));
53810
+ await new Promise((resolve4) => setTimeout(resolve4, Math.min(25, remainingMs)));
53624
53811
  }
53625
53812
  }
53626
53813
  }
@@ -54197,7 +54384,7 @@ function findEpisodicSourceAgentIds(db, from) {
54197
54384
  }
54198
54385
  function searchEpisodicSources(db, params) {
54199
54386
  const query = params.query.trim();
54200
- const limit = params.limit === null ? null : Math.max(1, Math.min(Math.floor(params.limit ?? 20), 50));
54387
+ const limit = params.limit === null ? null : Math.max(1, Math.min(Math.floor(params.limit ?? 20), 51));
54201
54388
  const like = `%${query}%`;
54202
54389
  const sinceArgs = params.since !== undefined ? [params.since, EPISODIC_CAPTURED_AT_FLOOR] : [];
54203
54390
  const beforeArgs = params.before !== undefined ? [params.before] : [];
@@ -54303,9 +54490,9 @@ init_db_accessor();
54303
54490
  init_db_accessor();
54304
54491
 
54305
54492
  // ../../platform/daemon/src/pipeline/dreaming-token-cache.ts
54306
- import { existsSync as existsSync11 } from "node:fs";
54307
- import { join as join13 } from "node:path";
54308
- import { dirname as dirname10 } from "node:path";
54493
+ import { existsSync as existsSync12 } from "node:fs";
54494
+ import { join as join14 } from "node:path";
54495
+ import { dirname as dirname11 } from "node:path";
54309
54496
  import { fileURLToPath as fileURLToPath3 } from "node:url";
54310
54497
  import { Worker } from "node:worker_threads";
54311
54498
 
@@ -54348,34 +54535,44 @@ function truncateToTokens(text, limit) {
54348
54535
 
54349
54536
  // ../../platform/daemon/src/pipeline/dreaming-token-cache.ts
54350
54537
  function resolveWorkerPath() {
54351
- const moduleDir = dirname10(fileURLToPath3(import.meta.url));
54352
- const bundled = join13(moduleDir, "dreaming-token-worker.js");
54353
- return existsSync11(bundled) ? bundled : resolveEmbeddedWorkerPath("dreaming-token-worker") ?? join13(moduleDir, "dreaming-token-worker.ts");
54538
+ const moduleDir = dirname11(fileURLToPath3(import.meta.url));
54539
+ const bundled = join14(moduleDir, "dreaming-token-worker.js");
54540
+ return existsSync12(bundled) ? bundled : resolveEmbeddedWorkerPath("dreaming-token-worker") ?? join14(moduleDir, "dreaming-token-worker.ts");
54541
+ }
54542
+ function ensureTokenCount(value, label) {
54543
+ if (!Number.isSafeInteger(value) || value < 0) {
54544
+ throw new RangeError(`${label} must be a finite non-negative safe integer`);
54545
+ }
54546
+ return value;
54547
+ }
54548
+ function addTokenCounts(total, count) {
54549
+ return ensureTokenCount(total + count, "Dreaming token count");
54550
+ }
54551
+ function requestKey(kind, agentId, entries, stopAt) {
54552
+ return JSON.stringify([kind, agentId, entries.map((entry) => [entry.key, entry.revision]), stopAt]);
54354
54553
  }
54355
54554
 
54356
54555
  class DreamingBacklogTokenCache {
54357
54556
  values = new Map;
54358
54557
  entries = new Map;
54359
- entryValues = new Map;
54360
- inflight = new Map;
54558
+ exactInflight = new Map;
54559
+ batchInflight = new Map;
54560
+ tails = new Map;
54361
54561
  workers = new Set;
54362
- async refresh(agentId, entries) {
54363
- const active = this.inflight.get(agentId);
54364
- if (active !== undefined)
54365
- return active;
54366
- const promise3 = this.refreshNow(agentId, entries);
54367
- this.inflight.set(agentId, promise3);
54368
- try {
54369
- return await promise3;
54370
- } finally {
54371
- this.inflight.delete(agentId);
54372
- }
54562
+ async replaceExactSnapshot(agentId, entries) {
54563
+ const key = requestKey("exact", agentId, entries);
54564
+ return await this.enqueue(agentId, key, this.exactInflight, async () => await this.replaceExactSnapshotNow(agentId, entries));
54565
+ }
54566
+ async countEntries(agentId, entries, stopAtTokens) {
54567
+ const stopAt = stopAtTokens === undefined ? undefined : ensureTokenCount(stopAtTokens, "Dreaming token stop limit");
54568
+ const key = requestKey("batch", agentId, entries, stopAt);
54569
+ return await this.enqueue(agentId, key, this.batchInflight, async () => await this.countEntriesNow(agentId, entries, stopAt));
54373
54570
  }
54374
54571
  get(agentId) {
54375
54572
  return this.values.get(agentId) ?? 0;
54376
54573
  }
54377
- record(agentId, count) {
54378
- this.values.set(agentId, count);
54574
+ recordExactTotal(agentId, count) {
54575
+ this.values.set(agentId, ensureTokenCount(count, "Dreaming exact token total"));
54379
54576
  }
54380
54577
  hasValue(agentId) {
54381
54578
  return this.values.has(agentId);
@@ -54384,61 +54581,118 @@ class DreamingBacklogTokenCache {
54384
54581
  for (const worker of this.workers)
54385
54582
  worker.terminate();
54386
54583
  this.workers.clear();
54387
- this.inflight.clear();
54584
+ this.exactInflight.clear();
54585
+ this.batchInflight.clear();
54586
+ this.tails.clear();
54388
54587
  }
54389
- async refreshNow(agentId, entries) {
54588
+ async replaceExactSnapshotNow(agentId, entries) {
54589
+ const result = await this.countEntriesNow(agentId, entries);
54390
54590
  const nextKeys = new Set(entries.map((entry) => entry.key));
54391
- const agentEntries = this.entries.get(agentId) ?? new Map;
54392
- const agentValues = this.entryValues.get(agentId) ?? new Map;
54393
- this.entries.set(agentId, agentEntries);
54394
- this.entryValues.set(agentId, agentValues);
54591
+ const agentEntries = this.entries.get(agentId);
54592
+ if (agentEntries === undefined) {
54593
+ throw new Error(`Missing Dreaming token cache state for ${agentId}`);
54594
+ }
54395
54595
  for (const key of agentEntries.keys()) {
54396
54596
  if (!nextKeys.has(key))
54397
54597
  agentEntries.delete(key);
54398
54598
  }
54399
- const uncached = entries.filter((entry) => {
54400
- const cached2 = agentEntries.get(entry.key);
54401
- return cached2 === undefined || cached2.text !== entry.text;
54402
- });
54403
- if (uncached.length > 0) {
54404
- const counts = await this.count(uncached);
54405
- for (const entry of uncached) {
54406
- const result = counts.find((item) => item.key === entry.key);
54407
- if (result === undefined)
54408
- throw new Error(`Dreaming token worker omitted ${entry.key}`);
54409
- agentEntries.set(entry.key, entry);
54410
- agentValues.set(entry.key, result.count);
54411
- }
54412
- }
54413
- let total = 0;
54414
- for (const entry of entries) {
54415
- const count = agentValues.get(entry.key);
54416
- if (count === undefined)
54417
- throw new Error(`Missing cached Dreaming token count for ${entry.key}`);
54418
- total += count;
54419
- }
54420
- for (const key of agentValues.keys()) {
54421
- if (!nextKeys.has(key))
54422
- agentValues.delete(key);
54423
- }
54424
- this.values.set(agentId, total);
54425
- return total;
54599
+ this.values.set(agentId, result.tokens);
54600
+ return result.tokens;
54426
54601
  }
54427
- async count(entries) {
54602
+ async countEntriesNow(agentId, entries, stopAtTokens) {
54603
+ const agentEntries = this.entries.get(agentId) ?? new Map;
54604
+ this.entries.set(agentId, agentEntries);
54605
+ if (entries.length === 0 || stopAtTokens === 0)
54606
+ return { tokens: 0, entriesCounted: 0 };
54607
+ let tokens = 0;
54608
+ let entriesCounted = 0;
54609
+ let index = 0;
54610
+ while (index < entries.length) {
54611
+ const entry = entries[index];
54612
+ if (entry === undefined)
54613
+ break;
54614
+ const cached2 = agentEntries.get(entry.key);
54615
+ if (cached2 !== undefined && cached2.revision === entry.revision) {
54616
+ tokens = addTokenCounts(tokens, ensureTokenCount(cached2.count, `Dreaming token count for ${entry.key}`));
54617
+ entriesCounted += 1;
54618
+ index += 1;
54619
+ if (stopAtTokens !== undefined && tokens >= stopAtTokens)
54620
+ return { tokens, entriesCounted };
54621
+ continue;
54622
+ }
54623
+ let end = index;
54624
+ while (end < entries.length) {
54625
+ const candidate = entries[end];
54626
+ if (candidate === undefined)
54627
+ break;
54628
+ const candidateCached = agentEntries.get(candidate.key);
54629
+ if (candidateCached !== undefined && candidateCached.revision === candidate.revision)
54630
+ break;
54631
+ end += 1;
54632
+ }
54633
+ const segment = entries.slice(index, end);
54634
+ const counts = await this.count(segment, stopAtTokens === undefined ? undefined : stopAtTokens - tokens);
54635
+ if (counts.length === 0)
54636
+ throw new Error(`Dreaming token worker omitted ${entry.key}`);
54637
+ for (let resultIndex = 0;resultIndex < counts.length; resultIndex += 1) {
54638
+ const candidate = segment[resultIndex];
54639
+ const result = counts[resultIndex];
54640
+ if (candidate === undefined || result === undefined || result.key !== candidate.key) {
54641
+ throw new Error(`Dreaming token worker returned an unexpected entry near ${entry.key}`);
54642
+ }
54643
+ const count = ensureTokenCount(result.count, `Dreaming token count for ${candidate.key}`);
54644
+ agentEntries.set(candidate.key, { revision: candidate.revision, count });
54645
+ tokens = addTokenCounts(tokens, count);
54646
+ entriesCounted += 1;
54647
+ }
54648
+ if (counts.length < segment.length)
54649
+ return { tokens, entriesCounted };
54650
+ index = end;
54651
+ }
54652
+ return { tokens, entriesCounted };
54653
+ }
54654
+ async count(entries, stopAtTokens) {
54428
54655
  const worker = new Worker(resolveWorkerPath(), { workerData: { tokenizerWasmPath } });
54429
54656
  this.workers.add(worker);
54430
54657
  try {
54431
- return await new Promise((resolve, reject) => {
54432
- worker.once("message", (message) => resolve(message.counts));
54658
+ return await new Promise((resolve4, reject) => {
54659
+ worker.once("message", (message) => resolve4(message.counts));
54433
54660
  worker.once("error", reject);
54434
54661
  worker.once("exit", (code) => reject(new Error(`Dreaming token worker exited with code ${code}`)));
54435
- worker.postMessage({ type: "count", requestId: 1, entries });
54662
+ worker.postMessage({
54663
+ type: "count",
54664
+ requestId: 1,
54665
+ entries,
54666
+ ...stopAtTokens === undefined ? {} : { stopAt: stopAtTokens }
54667
+ });
54436
54668
  });
54437
54669
  } finally {
54438
54670
  this.workers.delete(worker);
54439
54671
  worker.terminate().catch(() => {});
54440
54672
  }
54441
54673
  }
54674
+ enqueue(agentId, key, inflight, operation) {
54675
+ const active = inflight.get(key);
54676
+ if (active !== undefined)
54677
+ return active;
54678
+ const prior = this.tails.get(agentId) ?? Promise.resolve();
54679
+ const promise3 = prior.then(operation, operation);
54680
+ inflight.set(key, promise3);
54681
+ const tail = promise3.then(() => {
54682
+ return;
54683
+ }, () => {
54684
+ return;
54685
+ });
54686
+ this.tails.set(agentId, tail);
54687
+ const clear = () => {
54688
+ if (inflight.get(key) === promise3)
54689
+ inflight.delete(key);
54690
+ if (this.tails.get(agentId) === tail)
54691
+ this.tails.delete(agentId);
54692
+ };
54693
+ promise3.then(clear, clear);
54694
+ return promise3;
54695
+ }
54442
54696
  }
54443
54697
  var dreamingBacklogTokenCache = new DreamingBacklogTokenCache;
54444
54698
 
@@ -54957,7 +55211,7 @@ async function getStructuralDensity(_accessor, entityId, agentId) {
54957
55211
  init_dist();
54958
55212
 
54959
55213
  // ../../platform/daemon/src/ontology-evidence.ts
54960
- function isRecord5(value) {
55214
+ function isRecord7(value) {
54961
55215
  return typeof value === "object" && value !== null && !Array.isArray(value);
54962
55216
  }
54963
55217
  function readString(record3, key) {
@@ -55007,7 +55261,7 @@ function readOntologyEvidenceRef(value) {
55007
55261
  const trimmed = value.trim();
55008
55262
  return trimmed.length > 0 ? { sourceKind: null, sourceId: trimmed, sourcePath: null, memoryId: null, quote: null, reference: value } : null;
55009
55263
  }
55010
- if (!isRecord5(value))
55264
+ if (!isRecord7(value))
55011
55265
  return null;
55012
55266
  const transcriptId = readString(value, "transcript_id");
55013
55267
  const sessionKey = readString(value, "session_key");
@@ -56182,12 +56436,12 @@ function now2() {
56182
56436
  function canonical(value) {
56183
56437
  return value.trim().toLowerCase().replace(/\s+/g, " ");
56184
56438
  }
56185
- function isRecord7(value) {
56439
+ function isRecord9(value) {
56186
56440
  return typeof value === "object" && value !== null && !Array.isArray(value);
56187
56441
  }
56188
56442
  function parseJsonRecord(value) {
56189
56443
  const parsed = JSON.parse(value);
56190
- return isRecord7(parsed) ? parsed : {};
56444
+ return isRecord9(parsed) ? parsed : {};
56191
56445
  }
56192
56446
  function parseJsonArray3(value) {
56193
56447
  const parsed = JSON.parse(value);
@@ -56314,7 +56568,7 @@ function isDreamingAttentionEvidenceInTx(db, agentId, value) {
56314
56568
  function validateProposalEvidenceSourcesInTx(db, agentId, evidence) {
56315
56569
  for (const value of evidence) {
56316
56570
  const ref = readOntologyEvidenceRef(value);
56317
- if (ref === null || !isRecord7(ref.reference) || !("source_ref" in ref.reference))
56571
+ if (ref === null || !isRecord9(ref.reference) || !("source_ref" in ref.reference))
56318
56572
  continue;
56319
56573
  if (isDreamingAttentionEvidenceInTx(db, agentId, ref.reference))
56320
56574
  continue;
@@ -57541,7 +57795,7 @@ function wasEntityMergeApplied(db, agentId, sourceId, targetId, sourceSelector)
57541
57795
  if (!Array.isArray(merged))
57542
57796
  continue;
57543
57797
  if (merged.some((item) => {
57544
- if (!isRecord7(item))
57798
+ if (!isRecord9(item))
57545
57799
  return false;
57546
57800
  if (sourceId !== null)
57547
57801
  return readString2(item, "entityId") === sourceId;
@@ -58456,7 +58710,7 @@ async function awaitPressureClear(timeoutMs = 30000) {
58456
58710
  return true;
58457
58711
  const deadline = Date.now() + timeoutMs;
58458
58712
  while (Date.now() < deadline) {
58459
- await new Promise((resolve) => setTimeout(resolve, 500));
58713
+ await new Promise((resolve4) => setTimeout(resolve4, 500));
58460
58714
  tickPressureState();
58461
58715
  if (getSystemPressure() === "normal")
58462
58716
  return true;
@@ -58467,7 +58721,7 @@ async function awaitPressureClear(timeoutMs = 30000) {
58467
58721
  }
58468
58722
 
58469
58723
  // ../../platform/daemon/src/yielding-writes.ts
58470
- var yieldToEventLoop2 = () => new Promise((resolve) => setTimeout(resolve, 0));
58724
+ var yieldToEventLoop2 = () => new Promise((resolve4) => setTimeout(resolve4, 0));
58471
58725
  async function writeBatch(accessor2, processBatch, label, estimatedWorkUnits) {
58472
58726
  if (accessor2.withWriteTxAsync) {
58473
58727
  return accessor2.withWriteTxAsync(processBatch, {
@@ -59449,11 +59703,11 @@ function collectReviewDueClaims(accessor2, now3, options = {}) {
59449
59703
  init_dist();
59450
59704
  init_db_accessor();
59451
59705
  import { createHash as createHash5, randomUUID as randomUUID3 } from "node:crypto";
59452
- import { mkdirSync as mkdirSync6, renameSync as renameSync6, writeFileSync as writeFileSync4, readFileSync as readFileSync10 } from "node:fs";
59453
- import { dirname as dirname11, join as join14 } from "node:path";
59706
+ import { mkdirSync as mkdirSync7, renameSync as renameSync7, writeFileSync as writeFileSync4, readFileSync as readFileSync11 } from "node:fs";
59707
+ import { dirname as dirname12, join as join15 } from "node:path";
59454
59708
  var CURATED_MEMORY_HEAD_MAX_TOKENS = 1000;
59455
59709
  var hash2 = (text2) => createHash5("sha256").update(text2).digest("hex");
59456
- var pathFor = (agentId) => agentId === "default" ? join14(resolveDefaultBasePath(), "MEMORY.md") : join14(resolveDefaultBasePath(), "agents", agentId, "MEMORY.md");
59710
+ var pathFor = (agentId) => agentId === "default" ? join15(resolveDefaultBasePath(), "MEMORY.md") : join15(resolveDefaultBasePath(), "agents", agentId, "MEMORY.md");
59457
59711
  var render = (entries) => entries.map((entry) => `- ${entry.text.trim()}`).join(`
59458
59712
  `);
59459
59713
  async function readCuratedMemoryHead(agentId) {
@@ -59470,17 +59724,17 @@ async function readCuratedMemoryHead(agentId) {
59470
59724
  const content = typeof head?.content === "string" ? head.content : "";
59471
59725
  if (content) {
59472
59726
  const target = pathFor(agentId);
59473
- mkdirSync6(dirname11(target), { recursive: true });
59727
+ mkdirSync7(dirname12(target), { recursive: true });
59474
59728
  let existing = "";
59475
59729
  try {
59476
- existing = readFileSync10(target, "utf8");
59730
+ existing = readFileSync11(target, "utf8");
59477
59731
  } catch {}
59478
59732
  if (existing !== `${content}
59479
59733
  `) {
59480
59734
  const temporary = `${target}.recovery-${String(head?.revision ?? 0)}.tmp`;
59481
59735
  writeFileSync4(temporary, `${content}
59482
59736
  `, "utf8");
59483
- renameSync6(temporary, target);
59737
+ renameSync7(temporary, target);
59484
59738
  }
59485
59739
  if (snapshot.pending?.status === "pending") {
59486
59740
  await getDbAccessor().withWriteTxAsync((writeDb) => {
@@ -59581,12 +59835,12 @@ async function commitCuratedMemoryHead(input) {
59581
59835
  if (!committed.ok || committed.code !== "COMMITTED" || committed.revision === undefined)
59582
59836
  return committed;
59583
59837
  const target = pathFor(input.agentId);
59584
- mkdirSync6(dirname11(target), { recursive: true });
59838
+ mkdirSync7(dirname12(target), { recursive: true });
59585
59839
  const temporary = `${target}.curated-${committed.revision}.tmp`;
59586
59840
  try {
59587
59841
  writeFileSync4(temporary, `${body}
59588
59842
  `, "utf8");
59589
- renameSync6(temporary, target);
59843
+ renameSync7(temporary, target);
59590
59844
  } catch (error51) {
59591
59845
  return {
59592
59846
  ...committed,
@@ -59614,8 +59868,8 @@ async function commitCuratedMemoryHead(input) {
59614
59868
  init_dist();
59615
59869
  init_db_accessor();
59616
59870
  import { createHash as createHash6, randomUUID as randomUUID4 } from "node:crypto";
59617
- import { existsSync as existsSync12, mkdirSync as mkdirSync7, readFileSync as readFileSync11, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "node:fs";
59618
- import { dirname as dirname12, join as join15 } from "node:path";
59871
+ import { existsSync as existsSync13, mkdirSync as mkdirSync8, readFileSync as readFileSync12, rmSync as rmSync5, writeFileSync as writeFileSync6 } from "node:fs";
59872
+ import { dirname as dirname13, join as join16 } from "node:path";
59619
59873
  init_memory_config();
59620
59874
  var MEMORY_HEAD_MAX_TOKENS = 1000;
59621
59875
  function getAgentsDir2() {
@@ -59637,8 +59891,8 @@ function projectMemoryMd(content) {
59637
59891
  }
59638
59892
  function resolveMemoryHeadPath(agentsDir, agentId) {
59639
59893
  if (agentId === "default")
59640
- return join15(agentsDir, "MEMORY.md");
59641
- return join15(agentsDir, "agents", agentId, "MEMORY.md");
59894
+ return join16(agentsDir, "MEMORY.md");
59895
+ return join16(agentsDir, "agents", agentId, "MEMORY.md");
59642
59896
  }
59643
59897
  function acquireHeadLease(agentId, owner, ttlMs) {
59644
59898
  try {
@@ -59685,13 +59939,13 @@ function acquireHeadLease(agentId, owner, ttlMs) {
59685
59939
  function writeProjection(file2, agentId) {
59686
59940
  const agentsDir = getAgentsDir2();
59687
59941
  const path = resolveMemoryHeadPath(agentsDir, agentId);
59688
- const dir = dirname12(path);
59689
- mkdirSync7(dir, { recursive: true });
59690
- if (existsSync12(path)) {
59942
+ const dir = dirname13(path);
59943
+ mkdirSync8(dir, { recursive: true });
59944
+ if (existsSync13(path)) {
59691
59945
  const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
59692
- const backup = join15(dir, "memory", `MEMORY.backup-${stamp}.md`);
59693
- mkdirSync7(dirname12(backup), { recursive: true });
59694
- writeFileSync6(backup, readFileSync11(path, "utf-8"));
59946
+ const backup = join16(dir, "memory", `MEMORY.backup-${stamp}.md`);
59947
+ mkdirSync8(dirname13(backup), { recursive: true });
59948
+ writeFileSync6(backup, readFileSync12(path, "utf-8"));
59695
59949
  }
59696
59950
  writeFileSync6(path, file2);
59697
59951
  }
@@ -59716,7 +59970,7 @@ async function curateMemoryHead(input) {
59716
59970
  const hash3 = hashContent(projected.body);
59717
59971
  const next = lease.row.hash === hash3 ? lease.row.revision : lease.row.revision + 1;
59718
59972
  const path = resolveMemoryHeadPath(getAgentsDir2(), input.agentId);
59719
- const previous = existsSync12(path) ? readFileSync11(path, "utf-8") : undefined;
59973
+ const previous = existsSync13(path) ? readFileSync12(path, "utf-8") : undefined;
59720
59974
  try {
59721
59975
  await getDbAccessor().withWriteTxAsync((db) => {
59722
59976
  db.prepare(`UPDATE memory_md_heads SET content = ?, content_hash = ?, revision = ?, updated_at = ?, lease_token = NULL, lease_owner = NULL, lease_expires_at = NULL WHERE agent_id = ? AND lease_token = ?`).run(projected.body, hash3, next, new Date().toISOString(), input.agentId, lease.row.token);
@@ -59733,8 +59987,8 @@ async function curateMemoryHead(input) {
59733
59987
  } catch (error51) {
59734
59988
  try {
59735
59989
  if (previous === undefined) {
59736
- if (existsSync12(path))
59737
- rmSync3(path);
59990
+ if (existsSync13(path))
59991
+ rmSync5(path);
59738
59992
  } else
59739
59993
  writeFileSync6(path, previous);
59740
59994
  } catch {}
@@ -60348,9 +60602,9 @@ init_dist();
60348
60602
  // ../../platform/daemon/src/graphiq.ts
60349
60603
  init_dist();
60350
60604
  import { spawn as spawn2 } from "node:child_process";
60351
- import { constants, accessSync, existsSync as existsSync13 } from "node:fs";
60605
+ import { constants, accessSync, existsSync as existsSync14 } from "node:fs";
60352
60606
  import { homedir as homedir9 } from "node:os";
60353
- import { delimiter, join as join16 } from "node:path";
60607
+ import { delimiter, join as join17 } from "node:path";
60354
60608
  function getAgentsDir3() {
60355
60609
  return resolveDefaultBasePath();
60356
60610
  }
@@ -60365,8 +60619,8 @@ function getActiveGraphiqDbPath() {
60365
60619
  }
60366
60620
  function resolveGraphiqBinary() {
60367
60621
  const path = process.env.PATH ?? "";
60368
- const candidates = path.split(delimiter).filter((entry) => entry.length > 0).map((entry) => join16(entry, "graphiq"));
60369
- candidates.push(join16(homedir9(), ".local", "bin", "graphiq"));
60622
+ const candidates = path.split(delimiter).filter((entry) => entry.length > 0).map((entry) => join17(entry, "graphiq"));
60623
+ candidates.push(join17(homedir9(), ".local", "bin", "graphiq"));
60370
60624
  for (const candidate of candidates) {
60371
60625
  try {
60372
60626
  accessSync(candidate, constants.X_OK);
@@ -60380,7 +60634,7 @@ async function runGraphiqCli(args, timeoutMs = 15000) {
60380
60634
  if (!active) {
60381
60635
  throw new Error("GraphIQ has no active indexed project. Run `signet index <path>` first.");
60382
60636
  }
60383
- if (!existsSync13(active.dbPath)) {
60637
+ if (!existsSync14(active.dbPath)) {
60384
60638
  throw new Error(`GraphIQ database not found for active project: ${active.dbPath}`);
60385
60639
  }
60386
60640
  const binary = resolveGraphiqBinary();
@@ -60451,7 +60705,7 @@ function runCommand(command, args, timeoutMs, extraEnv) {
60451
60705
 
60452
60706
  // ../../platform/daemon/src/plugins/index.ts
60453
60707
  init_dist();
60454
- import { existsSync as existsSync16, readFileSync as readFileSync14 } from "node:fs";
60708
+ import { existsSync as existsSync17, readFileSync as readFileSync15 } from "node:fs";
60455
60709
 
60456
60710
  // ../../platform/daemon/src/secrets.ts
60457
60711
  init_logger();
@@ -60460,17 +60714,20 @@ init_dist();
60460
60714
  // ../../platform/daemon/src/plugins/audit.ts
60461
60715
  init_dist();
60462
60716
  init_logger();
60463
- import { appendFileSync as appendFileSync3, existsSync as existsSync14, mkdirSync as mkdirSync8, readFileSync as readFileSync12 } from "node:fs";
60464
- import { dirname as dirname13, join as join17 } from "node:path";
60717
+ import { appendFileSync as appendFileSync3, existsSync as existsSync15, mkdirSync as mkdirSync9, readFileSync as readFileSync13 } from "node:fs";
60718
+ import { dirname as dirname14, join as join18 } from "node:path";
60465
60719
  var SENSITIVE_KEY_RE = /(^|[_-])(api-key|apikey|auth-token|authorization|bearer|client-secret|credential|credentials|password|private-key|refresh-token|secret|secret-value|token|value)([_-]|$)/i;
60466
60720
  var SENSITIVE_ASSIGNMENT_RE = /\b((?:access[_-]?token|api[_-]?key|auth(?:orization)?|bearer|client[_-]?secret|credential|password|refresh[_-]?token|secret|token)\s*[:=]\s*)(["']?)([^"'\s,;&]+)/gi;
60467
60721
  var KNOWN_SECRET_VALUE_RE = /\b(AKIA[0-9A-Z]{16}|github_pat_[A-Za-z0-9_]{20,}|gh[pousr]_[A-Za-z0-9_]{20,}|sk-[A-Za-z0-9_-]{12,}|xox[baprs]-[A-Za-z0-9-]{10,})\b/g;
60468
60722
  function getDefaultPluginAuditPath() {
60469
- return join17(resolveDefaultBasePath(), ".daemon", "plugins", "audit-v1.ndjson");
60723
+ return join18(resolveDefaultBasePath(), ".daemon", "plugins", "audit-v1.ndjson");
60470
60724
  }
60471
60725
  function recordPluginAuditEvent(input, auditPath) {
60472
60726
  if (auditPath === null)
60473
60727
  return;
60728
+ const workspace = preflightWorkspace();
60729
+ if (workspace.status === "missing" || workspace.status === "incomplete")
60730
+ return;
60474
60731
  const path = auditPath ?? getDefaultPluginAuditPath();
60475
60732
  const event = {
60476
60733
  id: makeAuditId(),
@@ -60483,7 +60740,7 @@ function recordPluginAuditEvent(input, auditPath) {
60483
60740
  data: sanitizeAuditData(input.data ?? {})
60484
60741
  };
60485
60742
  try {
60486
- mkdirSync8(dirname13(path), { recursive: true });
60743
+ mkdirSync9(dirname14(path), { recursive: true });
60487
60744
  appendFileSync3(path, `${JSON.stringify(event)}
60488
60745
  `, { mode: 384 });
60489
60746
  } catch (err) {
@@ -60516,7 +60773,7 @@ function sanitizeAuditValue(value) {
60516
60773
  return sanitizeAuditString(value);
60517
60774
  if (Array.isArray(value))
60518
60775
  return value.map((entry) => sanitizeAuditValue(entry));
60519
- if (isRecord9(value))
60776
+ if (isRecord10(value))
60520
60777
  return sanitizeAuditData(value);
60521
60778
  return String(value);
60522
60779
  }
@@ -60526,7 +60783,7 @@ function sanitizeAuditString(value) {
60526
60783
  function makeAuditId() {
60527
60784
  return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
60528
60785
  }
60529
- function isRecord9(value) {
60786
+ function isRecord10(value) {
60530
60787
  return typeof value === "object" && value !== null && !Array.isArray(value);
60531
60788
  }
60532
60789
 
@@ -61058,8 +61315,8 @@ var signetGraphiqManifest = {
61058
61315
  // ../../platform/daemon/src/plugins/host.ts
61059
61316
  init_dist();
61060
61317
  init_logger();
61061
- import { existsSync as existsSync15, mkdirSync as mkdirSync9, readFileSync as readFileSync13, writeFileSync as writeFileSync7 } from "node:fs";
61062
- import { dirname as dirname14, join as join18 } from "node:path";
61318
+ import { existsSync as existsSync16, mkdirSync as mkdirSync10, readFileSync as readFileSync14, writeFileSync as writeFileSync7 } from "node:fs";
61319
+ import { dirname as dirname15, join as join19 } from "node:path";
61063
61320
 
61064
61321
  // ../../platform/daemon/src/plugins/manifest.ts
61065
61322
  var PLUGIN_ID_RE = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)+$/;
@@ -61407,11 +61664,11 @@ class PluginHostV1 {
61407
61664
  };
61408
61665
  }
61409
61666
  loadStore() {
61410
- if (!this.storagePath || !existsSync15(this.storagePath)) {
61667
+ if (!this.storagePath || !existsSync16(this.storagePath)) {
61411
61668
  return { version: 1, plugins: {} };
61412
61669
  }
61413
61670
  try {
61414
- const parsed = JSON.parse(readFileSync13(this.storagePath, "utf-8"));
61671
+ const parsed = JSON.parse(readFileSync14(this.storagePath, "utf-8"));
61415
61672
  return parseStore(parsed);
61416
61673
  } catch (err) {
61417
61674
  this.storeWritable = false;
@@ -61435,13 +61692,16 @@ class PluginHostV1 {
61435
61692
  });
61436
61693
  return;
61437
61694
  }
61438
- mkdirSync9(dirname14(this.storagePath), { recursive: true });
61695
+ const workspace = preflightWorkspace();
61696
+ if (workspace.status === "missing" || workspace.status === "incomplete")
61697
+ return;
61698
+ mkdirSync10(dirname15(this.storagePath), { recursive: true });
61439
61699
  writeFileSync7(this.storagePath, `${JSON.stringify(this.store, null, 2)}
61440
61700
  `, { mode: 384 });
61441
61701
  }
61442
61702
  }
61443
61703
  function getDefaultPluginRegistryPath() {
61444
- return join18(resolveDefaultBasePath(), SIGNET_PLUGIN_REGISTRY_DIR, SIGNET_PLUGIN_REGISTRY_FILE);
61704
+ return join19(resolveDefaultBasePath(), SIGNET_PLUGIN_REGISTRY_DIR, SIGNET_PLUGIN_REGISTRY_FILE);
61445
61705
  }
61446
61706
  function resolveState(manifest, enabled, health, validationErrors) {
61447
61707
  if (validationErrors.length > 0) {
@@ -61478,12 +61738,12 @@ function filterSurfacesByCapabilities(surfaces3, grantedCapabilities) {
61478
61738
  };
61479
61739
  }
61480
61740
  function parseStore(value) {
61481
- if (!isRecord10(value) || value.version !== 1 || !isRecord10(value.plugins)) {
61741
+ if (!isRecord11(value) || value.version !== 1 || !isRecord11(value.plugins)) {
61482
61742
  throw new Error("expected plugin registry version 1 with a plugins object");
61483
61743
  }
61484
61744
  const plugins = {};
61485
61745
  for (const [id, raw] of Object.entries(value.plugins)) {
61486
- if (!isRecord10(raw)) {
61746
+ if (!isRecord11(raw)) {
61487
61747
  throw new Error(`expected plugin registry entry ${id} to be an object`);
61488
61748
  }
61489
61749
  plugins[id] = {
@@ -61501,7 +61761,7 @@ function parseStringArray(value) {
61501
61761
  return;
61502
61762
  return value.every((entry) => typeof entry === "string") ? value : undefined;
61503
61763
  }
61504
- function isRecord10(value) {
61764
+ function isRecord11(value) {
61505
61765
  return typeof value === "object" && value !== null && !Array.isArray(value);
61506
61766
  }
61507
61767
  function clipPromptContribution(contribution) {
@@ -61564,9 +61824,9 @@ function auditResultForRecord(record3) {
61564
61824
  // ../../platform/daemon/src/plugins/index.ts
61565
61825
  function resolveGraphiqEnabled() {
61566
61826
  const statePath = getGraphiqStatePath(getAgentsDir3());
61567
- if (existsSync16(statePath)) {
61827
+ if (existsSync17(statePath)) {
61568
61828
  try {
61569
- const parsed = JSON.parse(readFileSync14(statePath, "utf-8"));
61829
+ const parsed = JSON.parse(readFileSync15(statePath, "utf-8"));
61570
61830
  if (typeof parsed === "object" && parsed !== null && typeof parsed.enabled === "boolean") {
61571
61831
  return parsed.enabled;
61572
61832
  }
@@ -63659,7 +63919,7 @@ function isLocalDaemonUrl(url2) {
63659
63919
  }
63660
63920
  function isValidAgentsDir(dir) {
63661
63921
  try {
63662
- return isAbsolute(dir) && existsSync17(dir) && statSync6(dir).isDirectory();
63922
+ return isAbsolute(dir) && existsSync18(dir) && statSync8(dir).isDirectory();
63663
63923
  } catch {
63664
63924
  return false;
63665
63925
  }