@sparkelf/dsh-knowledge-base 0.6.8 → 0.6.10

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/lib/index.js CHANGED
@@ -18028,6 +18028,66 @@ async function handleMemoryRoute(input) {
18028
18028
  }
18029
18029
  }
18030
18030
  //#endregion
18031
+ //#region src/memoryHeal.ts
18032
+ /**
18033
+ * Storage-error alerting for personal memory: notify the guardian session.
18034
+ *
18035
+ * Memory CRUD reads and writes under the knowledge storage root. When that root
18036
+ * becomes inaccessible — a removed local directory, an unmounted remote share —
18037
+ * operations fail with a filesystem error. The repair is deliberately NOT done
18038
+ * programmatically here: the memory guardian is an agent, so the right response is
18039
+ * to hand it a message describing the failure and let it diagnose and repair with
18040
+ * its own tools (remount the share, recreate the directory, verify access).
18041
+ *
18042
+ * This module only decides when a failure is a storage-root problem and raises the
18043
+ * alert. The original error is always rethrown so the caller sees the failure; the
18044
+ * guardian repairs asynchronously and a later operation succeeds.
18045
+ *
18046
+ * @module @sparkelf/dsh-knowledge-base/memory-heal
18047
+ */
18048
+ /** Filesystem codes that indicate the storage root itself is unreachable. */
18049
+ const STORAGE_ROOT_CODES = /* @__PURE__ */ new Set([
18050
+ "ENOENT",
18051
+ "ENOTDIR",
18052
+ "EACCES",
18053
+ "EPERM",
18054
+ "ESTALE",
18055
+ "EIO",
18056
+ "ENXIO",
18057
+ "EROFS"
18058
+ ]);
18059
+ /**
18060
+ * Whether an error looks like storage-root unreachability rather than a logic error.
18061
+ * @param error - the thrown value from a memory operation.
18062
+ * @returns true when the error carries a filesystem code the guardian could repair.
18063
+ */
18064
+ function isStorageRootError(error) {
18065
+ if (typeof error !== "object" || error === null) return false;
18066
+ const code = error.code;
18067
+ return typeof code === "string" && STORAGE_ROOT_CODES.has(code);
18068
+ }
18069
+ /**
18070
+ * Run a memory operation; on a storage-root failure, alert the guardian once.
18071
+ *
18072
+ * The alert is fire-and-forget and must never mask the original error: the caller
18073
+ * still sees the failure, while the guardian session receives a message asking it
18074
+ * to diagnose and repair the storage. A non-storage error is rethrown untouched.
18075
+ *
18076
+ * @param operation - the memory CRUD action to run.
18077
+ * @param alert - notifies the guardian session about the storage failure.
18078
+ * @returns the operation result.
18079
+ */
18080
+ async function alertGuardianOnStorageError(operation, alert) {
18081
+ try {
18082
+ return await operation();
18083
+ } catch (error) {
18084
+ if (isStorageRootError(error)) try {
18085
+ alert(error);
18086
+ } catch {}
18087
+ throw error;
18088
+ }
18089
+ }
18090
+ //#endregion
18031
18091
  //#region src/memoryPromotionRoutes.ts
18032
18092
  const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
18033
18093
  const ok = (body) => ({
@@ -18462,6 +18522,27 @@ var GuardianSessionStore = class {
18462
18522
  }
18463
18523
  return false;
18464
18524
  }
18525
+ /**
18526
+ * Every user's durable guardian session id, for the system-patrol seam.
18527
+ * A missing users root yields no guardians; an unreadable state file is skipped.
18528
+ * @returns the guardian session ids in directory order.
18529
+ */
18530
+ async listSessionIds() {
18531
+ let entries;
18532
+ try {
18533
+ entries = await readdir(this.usersRoot, { withFileTypes: true });
18534
+ } catch (error) {
18535
+ if (isErrno(error, "ENOENT")) return [];
18536
+ throw error;
18537
+ }
18538
+ const ids = [];
18539
+ for (const entry of entries) {
18540
+ if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
18541
+ const state = await this.read(entry.name).catch(() => void 0);
18542
+ if (state !== void 0) ids.push(state.sessionId);
18543
+ }
18544
+ return ids;
18545
+ }
18465
18546
  };
18466
18547
  /**
18467
18548
  * Resolve the user's guardian, creating it lazily when needed.
@@ -26855,7 +26936,7 @@ function apply(ctx, deploymentConfig) {
26855
26936
  const body = await readJsonBody(req);
26856
26937
  const personalScope = personalScopeRootFor(caller.userId);
26857
26938
  const defaultEnabled = config.memoryDefaultEnabledPermission.trim() !== "" && (caller.permissions ?? []).includes(config.memoryDefaultEnabledPermission);
26858
- const result = await handleMemoryRoute({
26939
+ const result = await alertGuardianOnStorageError(() => handleMemoryRoute({
26859
26940
  method,
26860
26941
  body,
26861
26942
  caller: {
@@ -26866,7 +26947,7 @@ function apply(ctx, deploymentConfig) {
26866
26947
  settings: new MemorySettingsStore(memoryUsersRoot),
26867
26948
  defaultEnabled,
26868
26949
  graphWriter: new MemoryGraphWriter({ scopeRoot: personalScope })
26869
- });
26950
+ }), (error) => alertGuardianStorageError(caller.userId, error));
26870
26951
  return writeJson(res, result.status, result.body);
26871
26952
  }
26872
26953
  case "memory.promote":
@@ -28268,6 +28349,20 @@ function apply(ctx, deploymentConfig) {
28268
28349
  return join(localConfig(config).actualRoot, "personal", userId);
28269
28350
  };
28270
28351
  /**
28352
+ * Hand a memory storage failure to the guardian session. The guardian is an agent,
28353
+ * so it diagnoses and repairs the storage (remount a share, recreate a directory,
28354
+ * verify access) with its own tools rather than a programmatic patch here. The
28355
+ * caller still sees the original error; the repair happens asynchronously and a
28356
+ * later operation succeeds.
28357
+ */
28358
+ const alertGuardianStorageError = (userId, error) => {
28359
+ const message = error instanceof Error ? error.message : String(error);
28360
+ sendToGuardian(guardianSessionHost, userId, {
28361
+ reason: "manual",
28362
+ note: `记忆存储访问报错(${message})。请诊断并修复存储(如重新挂载盘、重建目录),修复后验证记忆可读写。`
28363
+ }).catch(() => {});
28364
+ };
28365
+ /**
28271
28366
  * Load the department/global shared-memory graphs the caller may read.
28272
28367
  *
28273
28368
  * A promotion writes `<scope>/记忆共享/<id>.md` and
@@ -28350,30 +28445,59 @@ function apply(ctx, deploymentConfig) {
28350
28445
  })]),
28351
28446
  source: Object.freeze({ kind: "user" })
28352
28447
  });
28448
+ const guardianWorkspaceRegistry = ctx.workspaceRegistry;
28449
+ const guardianCwd = guardianWorkspaceRegistry?.list()[0]?.path ?? process.cwd();
28450
+ const guardianPersistence = ctx.sessionPersistence;
28451
+ const attachGuardianToWorkspace = async (agent) => {
28452
+ if (guardianWorkspaceRegistry === void 0) return;
28453
+ const sessionId = agent.session?.id ?? agent.id;
28454
+ try {
28455
+ await (await guardianWorkspaceRegistry.resolveByPath(guardianCwd))?.attachSession(sessionId);
28456
+ } catch (error) {
28457
+ ctx.logger.warn(`knowledge-base: guardian ${sessionId} did not join workspace at ${guardianCwd}: ${String(error)}`);
28458
+ }
28459
+ };
28353
28460
  const guardianSessionHost = {
28354
28461
  usersRoot: memoryUsersRoot,
28355
- cwd: process.cwd(),
28462
+ cwd: guardianCwd,
28356
28463
  timeoutMs: DEFAULT_GUARDIAN_TIMEOUT_MS,
28357
28464
  getAgent: (sessionId) => guardianRegistry?.get(sessionId),
28358
- createAgent: async ({ sessionId, cwd, title }) => {
28465
+ createAgent: async ({ sessionId, title }) => {
28359
28466
  if (guardianLoop === void 0) throw new Error("the DSH agent loop is not available");
28360
28467
  const handle = await guardianLoop.createAgent(ctx, {
28361
28468
  sessionId,
28362
- meta: { cwd },
28469
+ meta: { cwd: guardianCwd },
28363
28470
  ...guardianAgentOptions === void 0 ? {} : { agentOptions: guardianAgentOptions }
28364
28471
  });
28365
28472
  try {
28366
28473
  const session = handle.agent.session;
28367
28474
  if (session !== void 0) guardianTitles?.rename(session, title);
28368
28475
  } catch {}
28476
+ await attachGuardianToWorkspace(handle.agent);
28369
28477
  return handle.agent;
28370
28478
  },
28371
28479
  resumeAgent: async ({ sessionId }) => {
28372
28480
  if (guardianLoop === void 0) throw new Error("the DSH agent loop is not available");
28373
- return (await guardianLoop.resume(ctx, {
28481
+ if (guardianPersistence !== void 0) {
28482
+ let persistedCwd;
28483
+ try {
28484
+ const handle = await guardianPersistence.open(sessionId, "read");
28485
+ try {
28486
+ persistedCwd = handle.header.cwd;
28487
+ } finally {
28488
+ await handle.close();
28489
+ }
28490
+ } catch {
28491
+ persistedCwd = void 0;
28492
+ }
28493
+ if (persistedCwd !== void 0 && persistedCwd !== guardianCwd) throw new Error(`guardian ${sessionId} cwd ${persistedCwd} differs from workspace ${guardianCwd}; recreating`);
28494
+ }
28495
+ const handle = await guardianLoop.resume(ctx, {
28374
28496
  resumeSessionId: sessionId,
28375
28497
  ...guardianAgentOptions === void 0 ? {} : { agentOptions: guardianAgentOptions }
28376
- })).agent;
28498
+ });
28499
+ await attachGuardianToWorkspace(handle.agent);
28500
+ return handle.agent;
28377
28501
  },
28378
28502
  deliverText: (agent, text) => {
28379
28503
  const runtime = agent;
@@ -28386,6 +28510,15 @@ function apply(ctx, deploymentConfig) {
28386
28510
  }
28387
28511
  };
28388
28512
  const guardianSessions = new GuardianSessionStore(memoryUsersRoot);
28513
+ ctx.provide("memoryGuardianSessions", { listSessionIds: () => guardianSessions.listSessionIds() });
28514
+ if (!isTeamDeployment(config)) (async () => {
28515
+ try {
28516
+ if (!await memorySettings.isEnabled("local")) return;
28517
+ await resolveOrCreateGuardian(guardianSessionHost, LOCAL_USER_ID);
28518
+ } catch (error) {
28519
+ host.logger?.warn?.(`knowledge-base: eager guardian creation failed: ${String(error)}`);
28520
+ }
28521
+ })();
28389
28522
  const memoryGuardianToolHost = {
28390
28523
  resolveCaller: async () => {
28391
28524
  return { userId: (await fetchCaller(host, config)).userId };
@@ -142,6 +142,12 @@ export declare class GuardianSessionStore {
142
142
  * are, so the common turn-event path stays cheap.
143
143
  */
144
144
  isGuardianSession(sessionId: string): Promise<boolean>;
145
+ /**
146
+ * Every user's durable guardian session id, for the system-patrol seam.
147
+ * A missing users root yields no guardians; an unreadable state file is skipped.
148
+ * @returns the guardian session ids in directory order.
149
+ */
150
+ listSessionIds(): Promise<string[]>;
145
151
  }
146
152
  /**
147
153
  * Resolve the user's guardian, creating it lazily when needed.
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Storage-error alerting for personal memory: notify the guardian session.
3
+ *
4
+ * Memory CRUD reads and writes under the knowledge storage root. When that root
5
+ * becomes inaccessible — a removed local directory, an unmounted remote share —
6
+ * operations fail with a filesystem error. The repair is deliberately NOT done
7
+ * programmatically here: the memory guardian is an agent, so the right response is
8
+ * to hand it a message describing the failure and let it diagnose and repair with
9
+ * its own tools (remount the share, recreate the directory, verify access).
10
+ *
11
+ * This module only decides when a failure is a storage-root problem and raises the
12
+ * alert. The original error is always rethrown so the caller sees the failure; the
13
+ * guardian repairs asynchronously and a later operation succeeds.
14
+ *
15
+ * @module @sparkelf/dsh-knowledge-base/memory-heal
16
+ */
17
+ /**
18
+ * Whether an error looks like storage-root unreachability rather than a logic error.
19
+ * @param error - the thrown value from a memory operation.
20
+ * @returns true when the error carries a filesystem code the guardian could repair.
21
+ */
22
+ export declare function isStorageRootError(error: unknown): boolean;
23
+ /**
24
+ * Run a memory operation; on a storage-root failure, alert the guardian once.
25
+ *
26
+ * The alert is fire-and-forget and must never mask the original error: the caller
27
+ * still sees the failure, while the guardian session receives a message asking it
28
+ * to diagnose and repair the storage. A non-storage error is rethrown untouched.
29
+ *
30
+ * @param operation - the memory CRUD action to run.
31
+ * @param alert - notifies the guardian session about the storage failure.
32
+ * @returns the operation result.
33
+ */
34
+ export declare function alertGuardianOnStorageError<T>(operation: () => Promise<T>, alert: (error: unknown) => void): Promise<T>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sparkelf/dsh-knowledge-base",
3
- "version": "0.6.8",
3
+ "version": "0.6.10",
4
4
  "description": "DataOps-backed knowledge base for DeepSeek Harness: a left-sidebar destination, Settings configuration, and index tooling over a mounted NAS view.",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -7,8 +7,23 @@
7
7
  - **空闲**:某个会话静默了一段时间,可能积累了值得记住的内容。
8
8
  - **压缩**:某个会话开始压缩。原始消息仍然存在,压缩摘要会标出被遮蔽的范围;判断依据以原始轨迹为准。
9
9
  - **dream**:每日一次的整理与评估。每天确认这个每日任务只存在一份,按标题去重。
10
+ - **存储报错**:记忆增删改查遇到存储访问错误(如未挂载盘、目录缺失、权限拒绝)。消息里带错误信息,按「存储报错自愈」处理。
10
11
 
11
- 三类消息按到达顺序串行处理。上一轮没有收尾时,不要开始下一轮;宁可晚一点整理,也不要把同一天的记忆写乱。
12
+ 四类消息按到达顺序串行处理。上一轮没有收尾时,不要开始下一轮;宁可晚一点整理,也不要把同一天的记忆写乱。存储报错优先处理——存储不可用时整理也写不进去。
13
+
14
+ ## 存储报错自愈
15
+
16
+ 收到存储报错消息时,先修复存储,再谈整理。你是 agent,用工具自己诊断和修复,不要等程序兜底:
17
+
18
+ 1. **定位根因**:读错误信息,确认记忆根目录(`<存储根>/personal/<用户>/记忆`)是否可访问。常见是盘没挂载、目录被删、权限拒绝。
19
+ 2. **按因修复**:
20
+ - 未挂载盘:查挂载状态(`mountpoint`/`findmnt`),按部署的挂载方式重新挂载;挂不上就如实报告,不要假装已修。
21
+ - 目录缺失:重建缺失的目录。
22
+ - 权限拒绝:核对属主与权限,能修则修,不能修就报告。
23
+ 3. **验证**:修复后实际读一次、写一次记忆确认可用,别只看命令退出码。
24
+ 4. **收尾**:修好了就继续正常处理积压的记忆消息;修不好就把根因和已尝试的办法写清楚,留给主人决策,不要静默跳过。
25
+
26
+ 修复只动存储本身,不改记忆内容;不要借机删改记忆来“绕过”报错。
12
27
 
13
28
  ## 一轮怎么处理
14
29