hippo-memory 3.3.3 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/README.md +4 -4
  2. package/dist/api/callers.d.ts +4 -1
  3. package/dist/api/context/context-plan.js +3 -0
  4. package/dist/api/context/context-pools.js +4 -1
  5. package/dist/api/context/user-rule.js +2 -1
  6. package/dist/api/dashboard/detail.js +2 -1
  7. package/dist/api/dashboard/live.d.ts +0 -4
  8. package/dist/api/dashboard/live.js +0 -8
  9. package/dist/api/memories/conflicts.d.ts +2 -1
  10. package/dist/api/memories/conflicts.js +3 -8
  11. package/dist/api/memories/promote.js +6 -2
  12. package/dist/api/objects/object-kinds.d.ts +1 -4
  13. package/dist/api/objects/object-kinds.js +1 -5
  14. package/dist/api/recall/compose.js +2 -1
  15. package/dist/api/recall/rank-stages.js +2 -1
  16. package/dist/api/recall/rows.js +2 -1
  17. package/dist/api/session-end.d.ts +3 -2
  18. package/dist/api/session-end.js +8 -4
  19. package/dist/api/sharing.d.ts +4 -3
  20. package/dist/api/sharing.js +2 -2
  21. package/dist/api/sleep/auto-sleep.d.ts +3 -2
  22. package/dist/api/sleep/auto-sleep.js +16 -3
  23. package/dist/api/sleep/one-sleep.d.ts +23 -0
  24. package/dist/api/sleep/one-sleep.js +53 -0
  25. package/dist/api/sleep/sleep-run.js +2 -1
  26. package/dist/api/sleep/sleep.d.ts +5 -0
  27. package/dist/api/sleep/sleep.js +2 -1
  28. package/dist/api/summary-parents.js +2 -1
  29. package/dist/base/config/config-keys.js +1 -0
  30. package/dist/base/config/config.d.ts +2 -0
  31. package/dist/base/config/config.js +1 -0
  32. package/dist/base/embeddings/local.d.ts +1 -1
  33. package/dist/base/embeddings/local.js +2 -3
  34. package/dist/base/memory/ambient.js +2 -1
  35. package/dist/base/memory/entry.d.ts +4 -1
  36. package/dist/base/memory/entry.js +7 -1
  37. package/dist/base/memory/half-life-plan.js +6 -4
  38. package/dist/base/memory/keep-rules.js +2 -1
  39. package/dist/base/memory/liveness.d.ts +7 -0
  40. package/dist/base/memory/liveness.js +6 -0
  41. package/dist/base/memory/markdown.js +15 -5
  42. package/dist/base/memory/memory-audit.js +2 -1
  43. package/dist/base/memory/memory-facts.d.ts +0 -2
  44. package/dist/base/memory/memory-facts.js +0 -2
  45. package/dist/base/memory/merged-row.js +3 -2
  46. package/dist/base/memory/rule-replaces.js +2 -1
  47. package/dist/base/memory/stale-mark.d.ts +9 -0
  48. package/dist/base/memory/stale-mark.js +18 -0
  49. package/dist/base/ports/store/capture.d.ts +2 -0
  50. package/dist/base/ports/store/conflicts.d.ts +5 -1
  51. package/dist/base/ports/store/conflicts.js +2 -0
  52. package/dist/base/ports/store/consolidation.d.ts +66 -2
  53. package/dist/base/ports/store/consolidation.js +5 -0
  54. package/dist/base/ports/store/context-reads.d.ts +2 -0
  55. package/dist/base/ports/store/objects.d.ts +15 -4
  56. package/dist/base/ports/store/sessions.d.ts +8 -2
  57. package/dist/base/ports/store/sessions.js +6 -0
  58. package/dist/base/ports/store/store-effects.d.ts +5 -0
  59. package/dist/base/ports/store.d.ts +1 -1
  60. package/dist/base/scope/live-memory.d.ts +7 -0
  61. package/dist/base/scope/live-memory.js +10 -0
  62. package/dist/base/scope/read-admission.d.ts +2 -0
  63. package/dist/base/scope/read-admission.js +9 -2
  64. package/dist/base/util/version.d.ts +1 -1
  65. package/dist/base/util/version.js +1 -1
  66. package/dist/db/continuity-tables.d.ts +4 -1
  67. package/dist/db/continuity-tables.js +21 -12
  68. package/dist/db/migrate.js +2 -2
  69. package/dist/db/migrations/index.d.ts +1 -1
  70. package/dist/db/migrations/index.js +5 -1
  71. package/dist/db/migrations/v61.js +3 -3
  72. package/dist/db/migrations/v62.d.ts +3 -0
  73. package/dist/db/migrations/v62.js +43 -0
  74. package/dist/db/migrations/v63.d.ts +3 -0
  75. package/dist/db/migrations/v63.js +9 -0
  76. package/dist/db/required-objects.js +2 -1
  77. package/dist/db/sql-predicates.d.ts +22 -2
  78. package/dist/db/sql-predicates.js +27 -2
  79. package/dist/domain/agent-memories/apply.js +2 -1
  80. package/dist/domain/agent-memories/container-view.js +2 -1
  81. package/dist/domain/consolidate/conflicts.js +2 -1
  82. package/dist/domain/consolidate/dag-summary.d.ts +2 -0
  83. package/dist/domain/consolidate/dag.d.ts +3 -0
  84. package/dist/domain/consolidate/dag.js +53 -8
  85. package/dist/domain/consolidate/dedupe.js +2 -1
  86. package/dist/domain/consolidate/events.d.ts +2 -0
  87. package/dist/domain/consolidate/llm-passes.js +94 -20
  88. package/dist/domain/consolidate/merge.js +11 -10
  89. package/dist/domain/consolidate/retry-holds.d.ts +14 -0
  90. package/dist/domain/consolidate/retry-holds.js +26 -0
  91. package/dist/domain/consolidate/run.d.ts +8 -0
  92. package/dist/domain/consolidate/run.js +2 -0
  93. package/dist/domain/consolidate/tombstones.d.ts +3 -4
  94. package/dist/domain/consolidate/tombstones.js +3 -3
  95. package/dist/domain/graph/recall.js +3 -2
  96. package/dist/domain/learn/churn-stale.js +2 -1
  97. package/dist/domain/learn/extract.d.ts +10 -0
  98. package/dist/domain/learn/extract.js +10 -5
  99. package/dist/domain/learn/invalidation.d.ts +1 -1
  100. package/dist/domain/learn/invalidation.js +4 -11
  101. package/dist/domain/objects/decisions.d.ts +4 -7
  102. package/dist/domain/objects/decisions.js +1 -14
  103. package/dist/domain/objects/descriptor.d.ts +2 -0
  104. package/dist/domain/objects/lifecycle.js +8 -2
  105. package/dist/domain/search/as-of.js +3 -2
  106. package/dist/domain/sharing/share.d.ts +16 -4
  107. package/dist/domain/sharing/share.js +33 -17
  108. package/dist/entry/store-kit.js +2 -1
  109. package/dist/infra/local-embedder.js +14 -2
  110. package/dist/infra/spool-claims.d.ts +2 -2
  111. package/dist/infra/spool-claims.js +4 -3
  112. package/dist/infra/spool-import.js +1 -1
  113. package/dist/infra/spool-record.d.ts +3 -1
  114. package/dist/store/sqlite/capture/compaction-hooks.js +14 -6
  115. package/dist/store/sqlite/capture/compaction-rows.js +9 -2
  116. package/dist/store/sqlite/capture/spool-request-id.d.ts +3 -0
  117. package/dist/store/sqlite/capture/spool-request-id.js +12 -0
  118. package/dist/store/sqlite/connectors/quarantine.js +13 -4
  119. package/dist/store/sqlite/consolidation/consolidation-summaries.d.ts +4 -5
  120. package/dist/store/sqlite/consolidation/consolidation-summaries.js +46 -26
  121. package/dist/store/sqlite/consolidation/consolidation.js +7 -0
  122. package/dist/store/sqlite/consolidation/empty-extractions.d.ts +14 -0
  123. package/dist/store/sqlite/consolidation/empty-extractions.js +57 -0
  124. package/dist/store/sqlite/consolidation/rebuild-holds.d.ts +21 -0
  125. package/dist/store/sqlite/consolidation/rebuild-holds.js +68 -0
  126. package/dist/store/sqlite/consolidation/sleep-lock.d.ts +4 -0
  127. package/dist/store/sqlite/consolidation/sleep-lock.js +69 -0
  128. package/dist/store/sqlite/entries/entry-filter.js +3 -3
  129. package/dist/store/sqlite/entries/entry-reads.js +2 -1
  130. package/dist/store/sqlite/entries/entry-row.js +5 -1
  131. package/dist/store/sqlite/entries/entry-writes.js +9 -15
  132. package/dist/store/sqlite/entries/raw-archive.d.ts +2 -1
  133. package/dist/store/sqlite/entries/raw-archive.js +12 -3
  134. package/dist/store/sqlite/maintenance/agent-import-steps.js +7 -2
  135. package/dist/store/sqlite/maintenance/project-tags.js +4 -3
  136. package/dist/store/sqlite/recall/candidates.js +12 -11
  137. package/dist/store/sqlite/recall/search-rows.d.ts +3 -0
  138. package/dist/store/sqlite/recall/search-rows.js +26 -9
  139. package/dist/store/sqlite/records/object-rows.d.ts +2 -0
  140. package/dist/store/sqlite/records/object-rows.js +5 -1
  141. package/dist/store/sqlite/records/object-writes.d.ts +3 -0
  142. package/dist/store/sqlite/records/object-writes.js +43 -1
  143. package/dist/store/sqlite/reports/dashboard-lists.js +3 -2
  144. package/dist/store/sqlite/reports/dashboard-reads.js +5 -3
  145. package/dist/store/sqlite/reports/dashboard-sql.d.ts +0 -3
  146. package/dist/store/sqlite/reports/dashboard-sql.js +2 -9
  147. package/dist/store/sqlite/reports/reports.js +2 -1
  148. package/dist/store/sqlite/review/conflicts.js +10 -5
  149. package/dist/store/sqlite/runtime/rule-sql.d.ts +1 -0
  150. package/dist/store/sqlite/runtime/rule-sql.js +4 -1
  151. package/dist/store/sqlite/runtime/status-transitions.d.ts +98 -0
  152. package/dist/store/sqlite/runtime/status-transitions.js +105 -0
  153. package/dist/store/sqlite/sessions/goals.js +11 -12
  154. package/dist/store/sqlite/sessions/sessions.d.ts +1 -1
  155. package/dist/store/sqlite/sessions/sessions.js +20 -8
  156. package/dist/surface/capture/session-worker.d.ts +3 -2
  157. package/dist/surface/capture/session-worker.js +36 -10
  158. package/dist/surface/cli/api-context.js +2 -1
  159. package/dist/surface/cli/client.d.ts +6 -5
  160. package/dist/surface/cli/client.js +50 -19
  161. package/dist/surface/cli/conflicts.js +12 -1
  162. package/dist/surface/cli/continuity.js +4 -0
  163. package/dist/surface/cli/decisions.js +16 -17
  164. package/dist/surface/cli/hooks/session-end-worker.js +3 -2
  165. package/dist/surface/cli/install-steps.js +99 -13
  166. package/dist/surface/cli/memory-writes.js +3 -2
  167. package/dist/surface/cli/print.js +2 -1
  168. package/dist/surface/cli/sleep-render.js +7 -0
  169. package/dist/surface/cli/sleep.d.ts +3 -2
  170. package/dist/surface/cli/sleep.js +10 -4
  171. package/dist/surface/cli/transfer.js +6 -3
  172. package/dist/surface/cli/verbs/objects.js +2 -2
  173. package/dist/surface/dashboard/dashboard-actions.js +1 -1
  174. package/dist/surface/hooks-install/codex-wrapper.js +52 -11
  175. package/dist/surface/hooks-install/rules/hook-blocks.js +9 -2
  176. package/dist/surface/mcp/admin-tools.js +5 -2
  177. package/dist/surface/render/sleep-events.js +2 -0
  178. package/dist/surface/server/routes/decisions.js +2 -2
  179. package/dist/surface/server/sleep-child.js +5 -4
  180. package/dist/surface/server/sleep-offload.js +36 -25
  181. package/dist-ui/assets/index-Cst0ubfs.js +1 -0
  182. package/dist-ui/index.html +1 -1
  183. package/extensions/openclaw-plugin/openclaw.plugin.json +1 -1
  184. package/extensions/openclaw-plugin/package.json +1 -1
  185. package/openclaw.plugin.json +1 -1
  186. package/package.json +1 -1
  187. package/dist-ui/assets/index-Q9SY-1Bj.js +0 -1
@@ -63,13 +63,13 @@ function takeQueued(queued) {
63
63
  catch (err) {
64
64
  // ENOENT means nothing is queued; any other refusal leaves the request queued for the next
65
65
  // round, but is told.
66
- if (errorCode(err) !== 'ENOENT') {
67
- logger.warn(`session worker: cannot take the queued request ${queued}: ${errorMessage(err)}`, errorFields(err));
68
- }
69
- return null;
66
+ if (errorCode(err) === 'ENOENT')
67
+ return { kind: 'empty' };
68
+ logger.warn(`session worker: cannot take the queued request ${queued}: ${errorMessage(err)}`, errorFields(err));
69
+ return { kind: 'failed', err };
70
70
  }
71
71
  try {
72
- return fs.readFileSync(taken, 'utf8') === 'full' ? 'full' : 'turn';
72
+ return { kind: 'took', mode: fs.readFileSync(taken, 'utf8') === 'full' ? 'full' : 'turn' };
73
73
  }
74
74
  finally {
75
75
  fs.rmSync(taken, { force: true });
@@ -77,35 +77,61 @@ function takeQueued(queued) {
77
77
  }
78
78
  // Rounds in which takeQueued took nothing: such a request stays queued for the next worker instead of spinning here.
79
79
  const MAX_ROUNDS = 5;
80
+ function queuedKind(queued) {
81
+ try {
82
+ return fs.readFileSync(queued, 'utf8') === 'full' ? 'full' : 'turn';
83
+ }
84
+ catch (err) {
85
+ logger.debug(`session worker: cannot read ${queued}: ${errorMessage(err)}`, errorFields(err));
86
+ return 'unreadable';
87
+ }
88
+ }
89
+ function reportGaveUp(queued, lastFailed, gaveUp) {
90
+ const lastTake = lastFailed === null
91
+ ? 'none: the request was queued again each round'
92
+ : errorMessage(lastFailed.err);
93
+ const line = `session worker: gave up after ${MAX_ROUNDS} rounds with the ${queuedKind(queued)} request ` +
94
+ `still queued in ${queued}; ` +
95
+ `last take error: ${lastTake}`;
96
+ logger.warn(line, lastFailed === null ? undefined : errorFields(lastFailed.err));
97
+ gaveUp?.(line);
98
+ }
80
99
  /** Runs `work` unless a live worker holds this session, which then runs the request after its
81
- * own so the last reply is never dropped. */
82
- export async function runSessionWorker(sessionId, mode, work) {
100
+ * own so the last reply is never dropped. A detached worker's stderr goes nowhere, so `gaveUp`
101
+ * is where it leaves the line saying it stopped with the request still queued. */
102
+ export async function runSessionWorker(sessionId, mode, work, gaveUp) {
83
103
  const files = sessionStateFiles(sessionId);
84
104
  if (files === null)
85
105
  return work(mode);
86
106
  if (!queueRun(files, mode))
87
107
  return;
88
108
  let idleRounds = 0;
109
+ let lastFailed = null;
89
110
  for (let take = takeFileLock(files.lock); take.kind !== 'held'; take = takeFileLock(files.lock)) {
90
111
  if (take.kind === 'unusable') {
91
112
  warnUnusableLockOnce(files.lock, take.cause);
92
113
  return work(mode);
93
114
  }
94
115
  let ran = false;
116
+ let next = { kind: 'empty' };
95
117
  try {
96
- for (let next = takeQueued(files.queued); next !== null; next = takeQueued(files.queued)) {
118
+ for (next = takeQueued(files.queued); next.kind === 'took'; next = takeQueued(files.queued)) {
97
119
  ran = true;
98
- await work(next);
120
+ await work(next.mode);
99
121
  }
100
122
  }
101
123
  finally {
102
124
  take.lock.release();
103
125
  }
126
+ if (next.kind === 'failed')
127
+ lastFailed = next;
104
128
  // A taker that found the lock held left its request queued, so look again after every release.
105
129
  if (!fs.existsSync(files.queued))
106
130
  return;
107
- if (!ran && ++idleRounds >= MAX_ROUNDS)
131
+ if (!ran && ++idleRounds >= MAX_ROUNDS) {
132
+ reportGaveUp(files.queued, lastFailed, gaveUp);
108
133
  return;
134
+ }
109
135
  }
110
136
  }
111
137
  function turnKey(turn) {
@@ -4,6 +4,7 @@ import { contextReach, } from '../../api/types.js';
4
4
  import { ledgerReachOf } from '../../api/ledger-db.js';
5
5
  import { configReader } from '../../host/config-file.js';
6
6
  import { autoSleepConsolidate } from '../../api/sleep/auto-sleep.js';
7
+ import { sleepWasRefused } from '../../api/sleep/one-sleep.js';
7
8
  import { rerankerWithClef } from '../../api/recall/rows.js';
8
9
  import { hippoHomeDir } from '../../host/agent-homes.js';
9
10
  import { allMcpTools } from '../mcp/request.js';
@@ -166,7 +167,7 @@ function rootAutoSleep(root, hostTenantId) {
166
167
  config: cliConfig(root),
167
168
  tenantId: hostTenantId,
168
169
  infra: cliInfra(),
169
- }), 'cli', cliRuntime()).then(() => undefined);
170
+ }), 'cli', cliRuntime()).then((outcome) => (sleepWasRefused(outcome) ? outcome : undefined));
170
171
  }
171
172
  /** Stdio is the operator's own process: host admin, the folder's hippo.db, and an auto-sleep
172
173
  * that runs in process. One host per stdio loop, so its callers live as long as the loop, which
@@ -18,7 +18,7 @@ export declare class HttpResponseError extends Error {
18
18
  * pidfile's port. */
19
19
  export declare class MalformedReplyError extends Error {
20
20
  readonly route: string;
21
- constructor(route: string, detail: string);
21
+ constructor(route: string, detail: string, cause?: unknown);
22
22
  }
23
23
  /** The server gates every write, so a reply may be a skip; `force: true` stores it anyway. */
24
24
  export declare function postRemember(serverUrl: string, apiKey: string | undefined, opts: RememberOptions & {
@@ -51,10 +51,11 @@ export interface NearestIdsBody {
51
51
  /** The ids the server finds nearest `body.vector`, nearest first, in one try that gives up after
52
52
  * `timeoutMs`. */
53
53
  export declare function nearestIds(serverUrl: string, apiKey: string | undefined, body: NearestIdsBody, timeoutMs: number): Promise<string[]>;
54
- /**
55
- * 'never-sent': connection never opened, safe to replay locally. 'delivery-unknown': the request
56
- * was on the wire and may have committed, so never replay a write. 'none': not a transport
57
- * failure. */
54
+ /** 'never-sent': the connection never opened, so a write replays locally. 'none': the server answered
55
+ * with an error, or the request could not be built. 'delivery-unknown': the default for every error
56
+ * not listed, as the request may have committed, so a write is never replayed. */
58
57
  export type TransportFailure = 'none' | 'never-sent' | 'delivery-unknown';
59
58
  export declare function classifyTransportFailure(err: Error): TransportFailure;
59
+ /** What the user reads when a write may have landed and is not replayed. */
60
+ export declare function deliveryUnknownReason(err: Error, url: string): string;
60
61
  //# sourceMappingURL=client.d.ts.map
@@ -76,18 +76,31 @@ async function throwForStatus(res) {
76
76
  * pidfile's port. */
77
77
  export class MalformedReplyError extends Error {
78
78
  route;
79
- constructor(route, detail) {
80
- super(`the hippo server's reply to ${route} was not the expected JSON object (${detail})`);
79
+ constructor(route, detail, cause) {
80
+ super(`the hippo server's reply to ${route} was not the expected JSON object (${detail})`, cause === undefined ? undefined : { cause });
81
81
  this.route = route;
82
82
  this.name = 'MalformedReplyError';
83
83
  }
84
84
  }
85
+ /** A 2xx body under the cap: the plain Errors `readCappedJson` throws become a MalformedReplyError,
86
+ * and a transport error keeps its class. */
87
+ async function readReplyBody(res, route) {
88
+ try {
89
+ return await readCappedJson(res, MAX_REPLY_BYTES);
90
+ }
91
+ catch (err) {
92
+ if (err instanceof Error && err.constructor === Error) {
93
+ throw new MalformedReplyError(route, err.message, err);
94
+ }
95
+ throw err;
96
+ }
97
+ }
85
98
  /**
86
99
  * A 2xx reply's body, read under the cap; it must be a JSON object, and `guard` narrows it further
87
100
  * where the shape is known.
88
101
  */
89
102
  async function readReply(res, route, guard) {
90
- const body = await readCappedJson(res, MAX_REPLY_BYTES);
103
+ const body = await readReplyBody(res, route);
91
104
  if (!isJsonObject(body)) {
92
105
  throw new MalformedReplyError(route, body === null ? 'null' : Array.isArray(body) ? 'array' : 'a scalar');
93
106
  }
@@ -155,29 +168,47 @@ function transportCode(err) {
155
168
  const cause = err.cause;
156
169
  return isObjectLike(cause) && 'code' in cause ? String(cause.code) : '';
157
170
  }
171
+ const SOCKET_CODES = new Set([
172
+ 'ECONNRESET',
173
+ 'ECONNABORTED',
174
+ 'EPIPE',
175
+ 'UND_ERR_SOCKET',
176
+ ]);
177
+ /** A request that was on the wire when it failed: a dead socket, a fetch TypeError (no code means no
178
+ * known syscall) or a server gone quiet. */
179
+ function diedOnTheWire(err) {
180
+ return (SOCKET_CODES.has(transportCode(err)) || err instanceof TypeError || err.name === 'TimeoutError');
181
+ }
158
182
  export function classifyTransportFailure(err) {
159
- // The server answered, so the transport worked, whatever the message says.
160
- if (err instanceof HttpResponseError)
183
+ // The server answered, or encodeURIComponent threw before any request existed.
184
+ if (err instanceof HttpResponseError || err instanceof URIError)
161
185
  return 'none';
162
186
  const code = transportCode(err);
163
187
  // Connect-phase failures: no request bytes ever left the client, so a stale pidfile can be healed
164
188
  // and the call replayed on the direct path.
165
189
  if (code === 'ECONNREFUSED' || code === 'ENOTFOUND' || code === 'EAI_AGAIN')
166
190
  return 'never-sent';
167
- // The socket died mid-exchange.
168
- if (code === 'ECONNRESET' ||
169
- code === 'ECONNABORTED' ||
170
- code === 'EPIPE' ||
171
- code === 'UND_ERR_SOCKET') {
172
- return 'delivery-unknown';
191
+ // Any other error may have committed: only the two classes above are known not to have.
192
+ return 'delivery-unknown';
193
+ }
194
+ const WRITE_MAY_HAVE_LANDED = 'so the write may already have been applied. Not retrying locally.';
195
+ /** The syscall code or the class name of an error hippo does not know, never its message, which a
196
+ * foreign library may fill with the request's headers. */
197
+ function unrecognisedDetail(err) {
198
+ const code = transportCode(err);
199
+ const name = err.constructor.name;
200
+ const detail = /^[A-Z0-9_]+$/.test(code) ? code : name === 'Error' ? '' : name;
201
+ return detail === '' ? '' : ` (${detail})`;
202
+ }
203
+ /** What the user reads when a write may have landed and is not replayed. */
204
+ export function deliveryUnknownReason(err, url) {
205
+ if (err instanceof MalformedReplyError) {
206
+ return `${url} answered, but its reply could not be read, ${WRITE_MAY_HAVE_LANDED}`;
207
+ }
208
+ if (diedOnTheWire(err)) {
209
+ return `the connection to ${url} dropped or timed out mid-request, ${WRITE_MAY_HAVE_LANDED}`;
173
210
  }
174
- // Fetch rejects every network failure as a TypeError, with a cause only when the syscall is
175
- // known, so no code means the conservative answer.
176
- if (err instanceof TypeError)
177
- return 'delivery-unknown';
178
- // The request was sent and the server went quiet, so it may have committed.
179
- if (err.name === 'TimeoutError')
180
- return 'delivery-unknown';
181
- return 'none';
211
+ const unrecognised = `failed in a way hippo does not recognise${unrecognisedDetail(err)}`;
212
+ return `the request to ${url} ${unrecognised}, ${WRITE_MAY_HAVE_LANDED}`;
182
213
  }
183
214
  //# sourceMappingURL=client.js.map
@@ -9,10 +9,21 @@ import { requireInit } from './shared.js';
9
9
  import { fmt } from './print.js';
10
10
  import { printJsonList } from './json-list.js';
11
11
  import { fail } from './exit.js';
12
+ import { CONFLICT_STATUSES } from '../../base/ports/store/conflicts.js';
12
13
  const CONFLICT_PREVIEW_CHARS = 120;
14
+ /** `--status` as a conflict status or '*', or exit 1 with the message that lists every allowed value. */
15
+ function conflictStatusFilter(status) {
16
+ if (status === '*')
17
+ return status;
18
+ const found = CONFLICT_STATUSES.find((s) => s === status);
19
+ if (found === undefined) {
20
+ fail(`Invalid --status: "${status}". Must be one of: ${[...CONFLICT_STATUSES, '*'].join(' | ')}.`);
21
+ }
22
+ return found;
23
+ }
13
24
  export async function handleConflicts({ hippoRoot, tenantId, flags, }) {
14
25
  requireInit(hippoRoot);
15
- const status = stringFlagOrExit(flags, 'status') ?? 'open';
26
+ const status = conflictStatusFilter(stringFlagOrExit(flags, 'status') ?? 'open');
16
27
  const ctx = cliApiContext(hippoRoot, tenantId);
17
28
  const read = (page) => api.conflictList(ctx, status, { everyTenant: true }, page);
18
29
  if (boolFlag(flags, 'json')) {
@@ -1,6 +1,7 @@
1
1
  // Where-you-left-off verbs that read or save the live state: snapshot, current and working memory.
2
2
  import { CONTINUITY_EVENT_LIMIT, continuityLatest } from '../../api/continuity/continuity.js';
3
3
  import { cliApiContext, cliStore } from './api-context.js';
4
+ import { SNAPSHOT_CLOSE_STATUSES, isSnapshotCloseStatus, } from '../../base/ports/store/sessions.js';
4
5
  import { snapshotJson } from '../../api/continuity/continuity-json.js';
5
6
  import { requireInit } from './shared.js';
6
7
  import { printActiveTaskSnapshot } from './print.js';
@@ -34,6 +35,9 @@ async function snapshotSave(hippoRoot, tenantId, flags) {
34
35
  }
35
36
  async function snapshotClear(hippoRoot, tenantId, flags) {
36
37
  const status = stringFlagOrExit(flags, 'status') ?? 'cleared';
38
+ if (!isSnapshotCloseStatus(status)) {
39
+ fail(`Invalid --status: "${status}". Must be one of: ${SNAPSHOT_CLOSE_STATUSES.join(' | ')}.`);
40
+ }
37
41
  const cleared = await cliStore(hippoRoot).sessions.clear(tenantId, 'snapshot', { status });
38
42
  if (cleared === 0) {
39
43
  console.log('No active task snapshot to clear.');
@@ -1,17 +1,17 @@
1
1
  // First-class object verbs for decisions: record one (optionally superseding an older one's
2
2
  // memory), list, get, close.
3
3
  import { memoryGet } from '../../api/memories/memories.js';
4
- import { decisionIdByMemory, decisionMemoryWeaken } from '../../api/objects/object-kinds.js';
4
+ import { decisionIdByMemory } from '../../api/objects/object-kinds.js';
5
5
  import { objectClose, objectCreate, objectGet, objectList, objectStates, } from '../../api/objects/objects.js';
6
6
  import { printError } from './output.js';
7
7
  import { flagValueless, nonEmptyStringFlag, stringFlag, } from './flag-values.js';
8
8
  import { requireInit } from './shared.js';
9
9
  import { cliApiContext } from './api-context.js';
10
10
  import { closeObjectVerb, foundOrExit, idArgOrExit, listObjectsVerb, printLifecycleTail, } from './object-verbs.js';
11
- import { errorMessage } from '../../base/util/log.js';
12
11
  import { fail } from './exit.js';
13
12
  import { shellFolder } from './versioned-verbs.js';
14
13
  const DECISION = { cmd: 'decide', noun: 'Decision', idLabel: 'decision' };
14
+ const NOT_RECORDED = 'The decision was NOT recorded. Nothing changed, so it is safe to run the command again.';
15
15
  function printDecisionRow(d) {
16
16
  const supPart = d.supersededBy !== null ? ` superseded_by=#${d.supersededBy}` : '';
17
17
  console.log(`#${d.id} [${d.status}]${supPart} memory=${d.memoryId ?? '-'}`);
@@ -63,22 +63,20 @@ async function decideCreate(ctx, decisionText, flags) {
63
63
  fail('--supersedes requires a memory id, e.g. hippo decide "<text>" --supersedes mem_abc123.');
64
64
  }
65
65
  const supersedesMemId = stringFlag(flags, 'supersedes') ?? null;
66
- // Commit the table create+supersede first (inside the save's SAVEPOINT) and weaken the old memory
67
- // last, best-effort, so a memory-write failure cannot leave the memory stale while the table
68
- // shows the supersession.
66
+ // The save weakens the old memory in the same write. A decision row backing the memory is
67
+ // weakened through its supersede link; a plain memory is named so the save weakens it too.
69
68
  let supersedesDecisionId;
70
- let oldEntry = null;
69
+ let weakensMemoryId;
71
70
  if (supersedesMemId) {
72
- oldEntry = await memoryGet(ctx, supersedesMemId);
73
- if (!oldEntry) {
71
+ if (!(await memoryGet(ctx, supersedesMemId))) {
74
72
  fail(`Memory ${supersedesMemId} not found.`);
75
73
  }
76
74
  supersedesDecisionId = (await decisionIdByMemory(ctx, supersedesMemId)) ?? undefined;
75
+ if (supersedesDecisionId === undefined)
76
+ weakensMemoryId = supersedesMemId;
77
77
  }
78
- const write = { decisionText, context, supersedesDecisionId };
79
- const created = await objectCreate(ctx, 'decision', write, shellFolder());
80
- if (oldEntry)
81
- await weakenOrWarn(ctx, oldEntry, supersedesMemId);
78
+ const write = { decisionText, context, supersedesDecisionId, weakensMemoryId };
79
+ const created = await recordDecision(ctx, write, Boolean(supersedesMemId));
82
80
  console.log(`Decision recorded: #${created.id}`);
83
81
  if (created.memoryId)
84
82
  console.log(` memory: ${created.memoryId}`);
@@ -91,14 +89,15 @@ function exitWithDecideUsage() {
91
89
  printError(' hippo decide get <id>');
92
90
  fail(' hippo decide close <id>');
93
91
  }
94
- async function weakenOrWarn(ctx, oldEntry, supersedesMemId) {
95
- // Best-effort and last: the decision already committed. Failing here would make a retry find no
96
- // active decision for the old memory and create a duplicate active successor, so warn instead.
92
+ async function recordDecision(ctx, write, supersedes) {
97
93
  try {
98
- await decisionMemoryWeaken(ctx, oldEntry);
94
+ return await objectCreate(ctx, 'decision', write, shellFolder());
99
95
  }
100
96
  catch (e) {
101
- printError(` warning: decision recorded and superseded, but failed to weaken the prior memory ${supersedesMemId}: ${errorMessage(e)}`);
97
+ // True only while the save is whole or nothing: a throw after its commit would break this claim.
98
+ if (supersedes)
99
+ printError(NOT_RECORDED);
100
+ throw e;
102
101
  }
103
102
  }
104
103
  function printSupersedes(supersedesMemId, supersedesDecisionId) {
@@ -11,7 +11,7 @@ import { workingFolder } from '../shared.js';
11
11
  import { boolFlag, stringFlag } from '../flag-values.js';
12
12
  import { appendSessionEndCloseLog, captureTarget, flushingOnExit, logSessionEndImport, reportSessionEndFailure, } from '../hook-runtime.js';
13
13
  export async function handleSessionEndWorker({ hippoRoot, tenantId, flags, }) {
14
- await runSessionWorker(stringFlag(flags, 'session-id') ?? null, boolFlag(flags, 'turn') ? 'turn' : 'full', (mode) => sessionEndWork(hippoRoot, tenantId, flags, mode));
14
+ await runSessionWorker(stringFlag(flags, 'session-id') ?? null, boolFlag(flags, 'turn') ? 'turn' : 'full', (mode) => sessionEndWork(hippoRoot, tenantId, flags, mode), (line, opts) => appendSessionEndCloseLog(stringFlag(flags, 'log-file') ?? null, line, opts));
15
15
  }
16
16
  async function sessionEndWork(hippoRoot, tenantId, flags, mode) {
17
17
  const logFile = stringFlag(flags, 'log-file') ?? null;
@@ -55,11 +55,12 @@ function runSessionEndWork({ hippoRoot, tenantId, flags, mode, held, }) {
55
55
  * regardless. */
56
56
  async function sleepFolderStore(hippoRoot, tenantId, flags, closeLogFile) {
57
57
  try {
58
- await (await import('../sleep.js')).sleepStore({ hippoRoot, tenantId, args: [], flags });
58
+ return await (await import('../sleep.js')).sleepStore({ hippoRoot, tenantId, args: [], flags });
59
59
  }
60
60
  catch (err) {
61
61
  // sleepStore writes its own failure line only once its log tee is open.
62
62
  reportSessionEndFailure(closeLogFile, 'session-end: sleep', err);
63
+ return false;
63
64
  }
64
65
  }
65
66
  /** True when capture ran to the end, so a turn close may move its cursor past these turns. */
@@ -93,9 +93,13 @@ function scheduleOnWindows(taskName, cmd, run) {
93
93
  }
94
94
  }
95
95
  catch (err) {
96
- // A non-zero exit means the task does not exist yet, so it is created below.
97
- if (schedulerTimedOut(err))
98
- warnSchedulerTimedOut('schtasks /query');
96
+ if (schedulerTimedOut(err)) {
97
+ // An unanswered query may hide an existing task, so nothing is created over it.
98
+ console.log(` schtasks /query did not answer within ${SCHEDULER_CALL_TIMEOUT_MS / 1000} s and was stopped, so Task ` +
99
+ `Scheduler was not changed; run hippo init again, or check for the task ${taskName}.`);
100
+ return;
101
+ }
102
+ // Any other non-zero exit means the task does not exist yet, so it is created below.
99
103
  }
100
104
  try {
101
105
  run('schtasks', buildSchtasksCreateArgs(taskName, cmd), SCHEDULER_CALL);
@@ -129,28 +133,110 @@ function readCrontab(run) {
129
133
  throw err;
130
134
  }
131
135
  }
136
+ const dailyCronLine = (cmd, marker) => `15 6 * * * ${cmd} ${marker}`;
137
+ // The five schedule fields or an @macro, with any leading blanks.
138
+ const CRON_SCHEDULE = /^\s*(?:@\S+|\S+(?:\s+\S+){4})(?=\s|$)/;
139
+ /** Best effort shell scan: false when `text` ends inside a quote, where a marker is another job's data. */
140
+ function outsideQuotes(text) {
141
+ let open = '';
142
+ for (let i = 0; i < text.length; i++) {
143
+ const c = text[i];
144
+ if (open === `'`)
145
+ open = c === `'` ? '' : open;
146
+ else if (c === '\\')
147
+ i++;
148
+ else if (open === '"')
149
+ open = c === '"' ? '' : open;
150
+ else if (c === `'` || c === '"')
151
+ open = c;
152
+ }
153
+ return open === '';
154
+ }
155
+ /** Where `marker` stands in `line` as a whole token outside quotes, or -1; `<marker>-old` is another name. */
156
+ function markerAt(line, marker) {
157
+ const blankOrEdge = (i) => i < 0 || i >= line.length || /\s/.test(line[i]);
158
+ const isOurs = (at) => blankOrEdge(at - 1) && blankOrEdge(at + marker.length) && outsideQuotes(line.slice(0, at));
159
+ for (let at = line.indexOf(marker); at >= 0; at = line.indexOf(marker, at + 1)) {
160
+ if (isOurs(at))
161
+ return at;
162
+ }
163
+ return -1;
164
+ }
165
+ /** `line` with its command replaced by `cmd`, schedule and marker kept; null when it has no schedule. */
166
+ function withCommand(line, at, cmd) {
167
+ const schedule = CRON_SCHEDULE.exec(line)?.[0];
168
+ if (schedule === undefined || at < schedule.length)
169
+ return null;
170
+ return line.slice(schedule.length, at).trim() === cmd
171
+ ? line
172
+ : `${schedule} ${cmd} ${line.slice(at)}`;
173
+ }
174
+ function appendEntry(existing, marker, cmd) {
175
+ // A user with no crontab yet gets the line alone, with no blank line above it.
176
+ const kept = existing.trimEnd();
177
+ return {
178
+ kind: 'write',
179
+ text: `${kept === '' ? '' : `${kept}\n`}${dailyCronLine(cmd, marker)}\n`,
180
+ said: [' Scheduled machine-level daily runner (6:15am) via crontab'],
181
+ };
182
+ }
183
+ /**
184
+ * What to do with the user's crontab so it holds exactly one active line for the daily runner.
185
+ * Every other line is kept as it was, line endings included.
186
+ */
187
+ function reconcileCrontab(existing, marker, cmd) {
188
+ const lines = existing.split('\n');
189
+ const isEntry = (line) => !/^\s*#/.test(line) && markerAt(line, marker) >= 0;
190
+ const [first, ...extra] = lines.flatMap((line, i) => (isEntry(line) ? [i] : []));
191
+ if (first === undefined)
192
+ return appendEntry(existing, marker, cmd);
193
+ const old = lines[first];
194
+ const fresh = withCommand(old, markerAt(old, marker), cmd);
195
+ if (fresh === null)
196
+ return { kind: 'unreadable', line: old.trim() };
197
+ if (fresh === old && extra.length === 0)
198
+ return { kind: 'keep' };
199
+ const said = [
200
+ ...(fresh === old
201
+ ? []
202
+ : [
203
+ ' Updated the daily runner entry in your crontab (the command changed).',
204
+ ` was: ${old.trimEnd()}`,
205
+ ` now: ${fresh.trimEnd()}`,
206
+ ]),
207
+ ...extra.flatMap((i) => [
208
+ ' Removed a duplicate daily runner entry from your crontab:',
209
+ ` ${lines[i].trimEnd()}`,
210
+ ]),
211
+ ];
212
+ const text = lines
213
+ .map((line, i) => (i === first ? fresh : line))
214
+ .filter((_, i) => !extra.includes(i))
215
+ .join('\n');
216
+ return { kind: 'write', text: text.endsWith('\n') ? text : `${text}\n`, said };
217
+ }
132
218
  function scheduleOnCrontab(taskName, cmd, run) {
133
219
  const marker = `# hippo:${taskName}`;
134
220
  try {
135
- const existing = readCrontab(run);
136
- if (existing.includes(marker)) {
221
+ const plan = reconcileCrontab(readCrontab(run), marker, cmd);
222
+ if (plan.kind === 'keep')
137
223
  return; // already scheduled
224
+ if (plan.kind === 'unreadable') {
225
+ log.warn(`install: the daily runner line in your crontab is not a cron schedule hippo can read, so it was left as it ` +
226
+ `is: ${plan.line}`);
227
+ return;
138
228
  }
139
- const cronLine = `15 6 * * * ${cmd} ${marker}`;
140
- // A user with no crontab yet gets the line alone, with no blank line above it.
141
- const kept = existing.trimEnd();
142
- const newCrontab = `${kept === '' ? '' : `${kept}\n`}${cronLine}\n`;
143
- run('crontab', ['-'], { ...SCHEDULER_CALL, input: newCrontab });
144
- console.log(` Scheduled machine-level daily runner (6:15am) via crontab`);
229
+ run('crontab', ['-'], { ...SCHEDULER_CALL, input: plan.text });
230
+ for (const line of plan.said)
231
+ console.log(line);
145
232
  }
146
233
  catch (err) {
147
234
  if (schedulerTimedOut(err))
148
235
  warnSchedulerTimedOut('crontab');
149
236
  log.warn(`install: crontab could not be read or written, so the daily runner is not scheduled: ${errorMessage(err)}`, errorFields(err));
150
237
  // No permission or no crontab program: print the line for the user to add by hand.
151
- const cronLine = `15 6 * * * ${cmd}`;
152
238
  console.log(` To schedule the machine-level daily runner, add to crontab (crontab -e):`);
153
- console.log(` ${cronLine}`);
239
+ console.log(` ${dailyCronLine(cmd, marker)}`);
154
240
  }
155
241
  }
156
242
  //# sourceMappingURL=install-steps.js.map
@@ -159,8 +159,9 @@ async function sendOrFallBack(hippoRoot, server, call) {
159
159
  if (failure === 'none')
160
160
  return call.refused(err);
161
161
  if (failure === 'delivery-unknown') {
162
- fail(`hippo: the connection to ${server.url} dropped or timed out mid-request, so the write may already have been ` +
163
- 'applied. Not retrying locally. Check with `hippo recall` before running this again.');
162
+ log.debug('a served write may have landed, so it is not replayed on the store', errorFields(err));
163
+ const reason = client.deliveryUnknownReason(err, server.url);
164
+ fail(`hippo: ${reason} Check with \`hippo recall\` before running this again.`);
164
165
  }
165
166
  failIfServerRequired('the server pidfile was stale (connection refused)');
166
167
  log.warn('stale server pidfile detected, falling back to direct mode', errorFields(err));
@@ -4,6 +4,7 @@ import { recallJsonRow } from '../../api/recall/rows.js';
4
4
  import { summaryLine } from '../../base/memory/agent-memory-report.js';
5
5
  import { handoffSectionText, snapshotSectionText, snapshotText, sessionTrailText, handoffText, } from '../../api/context/context-render.js';
6
6
  import { printError } from './output.js';
7
+ import { isSuperseded } from '../../base/memory/liveness.js';
7
8
  export function fmt(n, digits = 2) {
8
9
  return n.toFixed(digits);
9
10
  }
@@ -16,7 +17,7 @@ export function recallEntryText({ r, query, showWhy, isGlobal, now, }) {
16
17
  const graphMark = r.graphVia ? ` [graph: ${r.graphVia.hops}hop ${r.graphVia.relType}]` : '';
17
18
  const lines = [
18
19
  `--- ${e.id} [${e.layer}] ` +
19
- `${confLabel}${isGlobal ? ' [global]' : ''}${e.supersededBy ? ' [superseded]' : ''}${graphMark} ` +
20
+ `${confLabel}${isGlobal ? ' [global]' : ''}${isSuperseded(e) ? ' [superseded]' : ''}${graphMark} ` +
20
21
  `score=${fmt(r.score, 3)} strength=${fmt(e.strength)}`,
21
22
  ` [${'█'.repeat(bars)}${'░'.repeat(10 - bars)}] tags: ${e.tags.join(', ') || 'none'} | retrieved: ` +
22
23
  `${e.retrievalCount}x`,
@@ -3,11 +3,18 @@
3
3
  import { renderAmbientSummary } from '../../base/memory/ambient.js';
4
4
  import { plural } from '../../base/util/format.js';
5
5
  import { sleepEventLines } from '../render/sleep-events.js';
6
+ import { sleepWasRefused } from '../../api/sleep/one-sleep.js';
6
7
  /**
7
8
  * The lines `hippo sleep` prints for an api.sleep result; pure, so the snapshot tests read them
8
9
  * without a console spy.
9
10
  */
10
11
  export function sleepResultLines(result) {
12
+ if (sleepWasRefused(result)) {
13
+ return [
14
+ `A sleep is already running on this store (since ${result.alreadyRunning.since}), ` +
15
+ 'so this one skipped consolidation.',
16
+ ];
17
+ }
11
18
  return [
12
19
  ...sleepCountLines(result),
13
20
  ...(result.dryRun ? ['\n(dry run - nothing written)'] : []),
@@ -1,6 +1,7 @@
1
1
  import { type CommandContext } from './flag-values.js';
2
2
  /** Runs `hippo sleep`; `--global` sleeps the global store instead of the folder's. */
3
3
  export declare function handleSleep({ hippoRoot, tenantId, args, flags, }: CommandContext): Promise<void>;
4
- /** Sleeps one store; with `--log-file` it also tees its output to that file. */
5
- export declare function sleepStore({ hippoRoot, tenantId, flags }: CommandContext): Promise<void>;
4
+ /** Sleeps one store; with `--log-file` it also tees its output to that file. True when another
5
+ * sleep held the store's claim, so this one consolidated nothing. */
6
+ export declare function sleepStore({ hippoRoot, tenantId, flags }: CommandContext): Promise<boolean>;
6
7
  //# sourceMappingURL=sleep.d.ts.map
@@ -11,6 +11,7 @@ import * as api from '../../api/index.js';
11
11
  import { cliConfig, cliApiContext, cliStore, cliSyncOptions } from './api-context.js';
12
12
  import { saveVectorGraphFile } from '../open-store.js';
13
13
  import { sleepResultLines } from './sleep-render.js';
14
+ import { sleepWasRefused } from '../../api/sleep/one-sleep.js';
14
15
  import { errorFields, errorMessage, log } from '../../base/util/log.js';
15
16
  import { teeStdStreams } from '../../host/stream-tee.js';
16
17
  import { boolFlag, stringFlag } from './flag-values.js';
@@ -26,7 +27,8 @@ export async function handleSleep({ hippoRoot, tenantId, args, flags, }) {
26
27
  const root = boolFlag(flags, 'global') ? hippoHomeDir() : hippoRoot;
27
28
  await sleepStore({ hippoRoot: root, tenantId, args, flags });
28
29
  }
29
- /** Sleeps one store; with `--log-file` it also tees its output to that file. */
30
+ /** Sleeps one store; with `--log-file` it also tees its output to that file. True when another
31
+ * sleep held the store's claim, so this one consolidated nothing. */
30
32
  export async function sleepStore({ hippoRoot, tenantId, flags }) {
31
33
  // Tee stdout/stderr to a log file when --log-file is set; the SessionEnd hook uses it so the
32
34
  // SessionStart hook can re-display the output.
@@ -43,9 +45,10 @@ export async function sleepStore({ hippoRoot, tenantId, flags }) {
43
45
  }
44
46
  }
45
47
  try {
46
- await runSleepCommand(hippoRoot, tenantId, flags);
47
- if (logFile)
48
+ const refused = await runSleepCommand(hippoRoot, tenantId, flags);
49
+ if (logFile && !refused)
48
50
  console.log('[hippo] sleep complete');
51
+ return refused;
49
52
  }
50
53
  catch (err) {
51
54
  if (logFile)
@@ -115,6 +118,7 @@ async function learnBeforeSleep(hippoRoot, tenantId, flags) {
115
118
  printAgentImport(await importForStore(hippoRoot, cliSyncOptions(tenantId, currentMachine())), '');
116
119
  }
117
120
  }
121
+ /** True when another sleep held the store's claim, so this one consolidated nothing. */
118
122
  async function runSleepCommand(hippoRoot, tenantId, flags) {
119
123
  requireInit(hippoRoot);
120
124
  await learnBeforeSleep(hippoRoot, tenantId, flags);
@@ -137,11 +141,13 @@ async function runSleepCommand(hippoRoot, tenantId, flags) {
137
141
  noShare: boolFlag(flags, 'no-share'),
138
142
  });
139
143
  renderSleepResult(result);
144
+ const refused = sleepWasRefused(result);
140
145
  // A store with no `hippo serve` gets its saved vector graph from its sleeps.
141
- if (!result.dryRun) {
146
+ if (!result.dryRun && !refused) {
142
147
  await saveVectorGraphFile(hippoRoot, {
143
148
  maxVectors: ctx.config.vectorGraph.maxVectors,
144
149
  });
145
150
  }
151
+ return refused;
146
152
  }
147
153
  //# sourceMappingURL=sleep.js.map
@@ -50,9 +50,12 @@ export async function handleShare({ hippoRoot, tenantId, args, flags, }) {
50
50
  const force = boolFlag(flags, 'force');
51
51
  const ctx = cliApiContext(hippoRoot, tenantId);
52
52
  const result = await api.shareToGlobal(ctx, shareId, { force });
53
- if (result) {
54
- console.log(`Shared [${result.id}] to global store.`);
55
- console.log(` Source: ${result.source}`);
53
+ if (result.kind === 'shared') {
54
+ console.log(`Shared [${result.entry.id}] to global store.`);
55
+ console.log(` Source: ${result.entry.source}`);
56
+ }
57
+ else if (result.kind === 'already-shared') {
58
+ console.log(`Already shared: the global store holds this text as [${result.existingId}].`);
56
59
  }
57
60
  else {
58
61
  const entry = await memoryGet(ctx, shareId);