@joe-broadhead/opencode-mem 0.9.2 → 0.9.12

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 (64) hide show
  1. package/CHANGELOG.md +1605 -0
  2. package/README.md +135 -43
  3. package/docs/agent-protocol.md +29 -28
  4. package/docs/permissions.md +148 -0
  5. package/package.json +277 -16
  6. package/skills/mem.pages/SKILL.md +35 -16
  7. package/skills/mem.sharing/SKILL.md +39 -6
  8. package/skills/mem.sources/SKILL.md +41 -10
  9. package/skills/mem.usage/SKILL.md +47 -16
  10. package/src/backend/records.js +413 -50
  11. package/src/backend/v3.js +15 -10
  12. package/src/call-shapes.js +18 -25
  13. package/src/capture-pause.js +136 -0
  14. package/src/capture.js +7 -4
  15. package/src/collector-service.js +212 -35
  16. package/src/collector.js +186 -47
  17. package/src/commands.js +37 -0
  18. package/src/compaction.js +4 -2
  19. package/src/config.js +162 -1
  20. package/src/connect.js +353 -0
  21. package/src/copies.js +28 -3
  22. package/src/credentials.js +35 -7
  23. package/src/curation.js +33 -14
  24. package/src/events.js +144 -36
  25. package/src/forget-purge.js +377 -0
  26. package/src/forgotten.js +356 -0
  27. package/src/hooks.js +9 -4
  28. package/src/index.js +25 -6
  29. package/src/permissions.js +116 -38
  30. package/src/protocol.js +21 -11
  31. package/src/records.js +4 -1
  32. package/src/runtime.js +207 -16
  33. package/src/shapes.js +63 -0
  34. package/src/sources.js +183 -12
  35. package/src/spaces.js +58 -1
  36. package/src/spool.js +442 -64
  37. package/src/stated.js +334 -0
  38. package/src/storable.js +477 -0
  39. package/src/tools/aliases.js +36 -147
  40. package/src/tools/commitments.js +69 -12
  41. package/src/tools/held-write.js +9 -1
  42. package/src/tools/index.js +29 -44
  43. package/src/tools/ingest.js +33 -128
  44. package/src/tools/memory.js +594 -901
  45. package/src/tools/page-sections.js +147 -0
  46. package/src/tools/page.js +314 -82
  47. package/src/tools/recall-browse.js +173 -0
  48. package/src/tools/recall.js +79 -19
  49. package/src/tools/share.js +494 -131
  50. package/src/tools/shared.js +97 -19
  51. package/src/tools/spaces.js +215 -104
  52. package/src/tools/status.js +31 -3
  53. package/src/tools/wiki.js +5 -13
  54. package/src/util.js +10 -20
  55. package/src/views/contracts.js +137 -6
  56. package/src/views/overdue.js +125 -0
  57. package/src/views/profile.js +154 -0
  58. package/src/views/records-reads.js +132 -33
  59. package/src/views/rpc.js +63 -12
  60. package/src/views/shape.js +49 -0
  61. package/views/commitments.html +31 -4
  62. package/views/home.html +22 -3
  63. package/views/memory.html +126 -24
  64. package/src/erase.js +0 -36
package/src/runtime.js CHANGED
@@ -9,6 +9,9 @@ import { UNLINKED_SENTENCE, asSession, credentialLine, unavailableReason } from
9
9
  import { createControlClient } from "./spaces.js"
10
10
  import { createSkillContexts } from "./skill-contexts.js"
11
11
  import { createSpool } from "./spool.js"
12
+ import { createForgetPurge } from "./forget-purge.js"
13
+ import { createCapturePause } from "./capture-pause.js"
14
+ import { createStatedText } from "./stated.js"
12
15
  import { errorMessage, oneLine, rememberBounded, shortHash } from "./util.js"
13
16
 
14
17
  /** A session bind uses a shorter bound so prompt construction never waits long. */
@@ -57,6 +60,8 @@ export function createRuntime(input) {
57
60
  const credentials = input.credentials ?? null
58
61
  /** Wall clock for cache expiry and spool scheduling; injectable for tests. Deadlines use real time. */
59
62
  const now = typeof input.now === "function" ? input.now : Date.now
63
+ /** The per-session capture pause (/mem-pause, /mem-resume): no turn, summary or checkpoint while set. */
64
+ const capturePause = createCapturePause({ stateDir: config.stateDir, log, now: () => new Date(now()) })
60
65
  /** `${sessionID}::${agent}` -> the pinned block and its refresh state. */
61
66
  const pins = new Map()
62
67
  /** `${sessionID}::${agent}` -> { context, expires }: the session context, cached for the TTL. */
@@ -87,6 +92,8 @@ export function createRuntime(input) {
87
92
  const clock = createClock(config)
88
93
  /** Today's date in the agent's zone: part of the pinned block's cache key. */
89
94
  const today = () => dayIn(clock.now(), clock.zone)
95
+ /** The person's recent messages per session, for the writes that keep only what they said (src/stated.js). */
96
+ const stated = createStatedText({ now: clock.now })
90
97
  const gatewayMode = input.gateway ?? Boolean(config.controlURL)
91
98
  const control =
92
99
  input.control ??
@@ -131,7 +138,11 @@ export function createRuntime(input) {
131
138
  */
132
139
  async function availability() {
133
140
  const reason = unavailable()
134
- if (reason || !control || !credentials?.check) return reason
141
+ if (reason) {
142
+ // A /connect sign-in made since the last look (src/connect.js): ask OpenCode once.
143
+ return control && (await credentials?.probeSignIn?.()) ? unavailable() : reason
144
+ }
145
+ if (!control || !credentials?.check) return reason
135
146
  await credentials.check()
136
147
  return unavailable()
137
148
  }
@@ -141,8 +152,14 @@ export function createRuntime(input) {
141
152
  * container, user, and agent; without one the fixed local scope applies.
142
153
  */
143
154
  function scopeFor(context, overrides = {}) {
155
+ // A data-plane call with a space and a session lets the gateway's context
156
+ // lookup bind the session to that space (control before 0.9.7). The
157
+ // session goes only with the space the session is bound to; a space a call
158
+ // names, or the personal space read for a shared-bound session, goes alone.
159
+ const foreign = Boolean(context?.space_id) && context.session_space_id !== context.space_id
144
160
  return resolveScope(config, {
145
161
  ...overrides,
162
+ ...(foreign ? { sessionID: undefined } : {}),
146
163
  spaceID: context?.space_id,
147
164
  containerID: context?.container_id,
148
165
  user: overrides.user || context?.user_id,
@@ -164,7 +181,7 @@ export function createRuntime(input) {
164
181
 
165
182
  /**
166
183
  * The task a session declared most recently through mem_recall, mem_remember,
167
- * or mem_forget. Captured turns and the compaction checkpoint of that session
184
+ * or revise forget. Captured turns and the compaction checkpoint of that session
168
185
  * carry it as `x-tdai-task-id`. Returns the stored key, or "" when the value
169
186
  * clears the task or has no usable characters.
170
187
  */
@@ -190,17 +207,21 @@ export function createRuntime(input) {
190
207
  if (!control) return null
191
208
  const space = String(overrides.space ?? "").trim()
192
209
  const agent = overrides.agent && overrides.agent !== "auto" ? String(overrides.agent) : undefined
210
+ // Only an explicit bind (mem_spaces current with bind) changes the
211
+ // session's binding. A space named for one call is resolved without the
212
+ // session: control before 0.9.7 binds any session sent with a space.
213
+ const bind = overrides.bind === true && Boolean(overrides.sessionID)
193
214
  const context = await control.resolveContext({
194
215
  userId: overrides.userId || config.user,
195
216
  spaceId: space || undefined,
196
- sessionId: overrides.sessionID,
217
+ sessionId: space && !bind ? undefined : overrides.sessionID,
197
218
  agent,
219
+ ...(bind ? { bind: true } : {}),
198
220
  })
199
- // An explicit space together with a session binds the session to that
200
- // space. When that changes the session's space, the cached session context
221
+ // A bind that changes the session's space makes the cached session context
201
222
  // and the pinned block belong to the previous binding: the next model call
202
223
  // starts a new epoch. Re-binding to the same space changes nothing.
203
- if (space && overrides.sessionID && cachedSpaceOf(overrides.sessionID) !== context?.space_id) {
224
+ if (bind && cachedSpaceOf(overrides.sessionID) !== context?.space_id) {
204
225
  invalidate(overrides.sessionID)
205
226
  }
206
227
  return context
@@ -241,6 +262,55 @@ export function createRuntime(input) {
241
262
  return context
242
263
  }
243
264
 
265
+ /**
266
+ * Run a data-plane call that must carry a session with a space that may not
267
+ * be the session's own (deleting turns needs the session they were written
268
+ * under). Control before 0.9.7 binds a session sent with a space, so for a
269
+ * session this process has resolved, the binding is read before the call
270
+ * and put back with an explicit bind if the call moved it. Other sessions,
271
+ * and a control that only binds on request, take the call as it is.
272
+ *
273
+ * @template T
274
+ * @param {{ space_id?: string, session_id?: string, agent_id?: string } | null | undefined} scope
275
+ * @param {() => Promise<T>} run
276
+ * @param {string[]} [notes] receives a sentence when the binding could not be
277
+ * put back, so the caller's answer can tell the person
278
+ * @returns {Promise<T>}
279
+ */
280
+ async function keepBinding(scope, run, notes = []) {
281
+ const sessionID = scope?.session_id
282
+ const space = scope?.space_id
283
+ if (!control || !sessionID || !space || cachedSpaceOf(sessionID) === undefined) return run()
284
+ // No agent hint: the session keeps the agent it runs as.
285
+ const agent = undefined
286
+ let prior = ""
287
+ try {
288
+ prior = (await resolveContext({ sessionID, agent }))?.session_space_id || ""
289
+ } catch {
290
+ prior = ""
291
+ }
292
+ if (!prior || prior === space) return run()
293
+ try {
294
+ return await run()
295
+ } finally {
296
+ let after = ""
297
+ try {
298
+ after = (await resolveContext({ sessionID, agent }))?.session_space_id || ""
299
+ if (after !== prior) {
300
+ await resolveContext({ space: prior, sessionID, agent, bind: true })
301
+ log.info("restored a session binding an older control moved", { sessionID })
302
+ }
303
+ } catch (error) {
304
+ log.warn("could not restore the session binding after a delete", { sessionID, error: errorMessage(error) })
305
+ const now = after && after !== prior ? after : space
306
+ notes.push(
307
+ `The session may now be bound to ${oneLine(now, 80)}, not ${oneLine(prior, 80)}: an older Memory control binds a session sent with a space, and putting the binding back failed (${oneLine(errorMessage(error), 160)}). ` +
308
+ `Rebind with mem_spaces({"action": "current", "bind": {"space": "personal"}}) or mem_spaces({"action": "current", "bind": {"space": "${oneLine(prior, 80)}"}}); check it with mem_spaces({"action": "current"}).`,
309
+ )
310
+ }
311
+ }
312
+ }
313
+
244
314
  /** The space of any context cached for a session, whatever the agent. */
245
315
  function cachedSpaceOf(sessionID) {
246
316
  const prefix = `${sessionID}::`
@@ -250,6 +320,24 @@ export function createRuntime(input) {
250
320
  return undefined
251
321
  }
252
322
 
323
+ /**
324
+ * The space a captured turn will most likely land in, as far as this
325
+ * machine knows without a request ("" when not known). Recorded with a
326
+ * spooled turn so a pending forget holds back that space's turns only
327
+ * (src/forget-purge.js); never used to place the turn.
328
+ */
329
+ function spaceHint(sessionID, visibility = config.captureVisibility) {
330
+ if (!control) return scope({ sessionID }).space_id ?? ""
331
+ if (visibility === "team") {
332
+ for (const [key, cached] of sessionContexts) {
333
+ if (key.startsWith(`${sessionID}::`) && cached.context?.space_kind === "shared") return cached.context.space_id ?? ""
334
+ }
335
+ return ""
336
+ }
337
+ for (const cached of sessionContexts.values()) if (cached.context?.personal_space_id) return cached.context.personal_space_id
338
+ return ""
339
+ }
340
+
253
341
  /** The session context cached by the last fresh resolution, if still within the TTL. */
254
342
  function cachedSessionContext(sessionID, agent) {
255
343
  if (!sessionID) return null
@@ -324,12 +412,15 @@ export function createRuntime(input) {
324
412
  * fallback to the data plane: that would put the container choice back in
325
413
  * the plugin.
326
414
  *
327
- * @param {{ sessionID: string, agent?: string, visibility?: string, task?: string, payload: object }} input
415
+ * `key` is the turn's idempotency key (`turnKey`): the gateway answers a
416
+ * repeat from its receipt instead of storing the turn twice.
417
+ *
418
+ * @param {{ sessionID: string, agent?: string, visibility?: string, task?: string, payload: object, key?: string }} input
328
419
  */
329
- async function captureTurn({ sessionID, agent, visibility, task, payload }) {
420
+ async function captureTurn({ sessionID, agent, visibility, task, payload, key }) {
330
421
  const requested = visibility === "team" ? "team" : "private"
331
422
  const hint = agent && agent !== "auto" ? String(agent) : undefined
332
- const send = (as) => backend.captureTurn({ sessionID, agent: hint, visibility: as, task, payload })
423
+ const send = (as) => backend.captureTurn({ sessionID, agent: hint, visibility: as, task, payload, ...(key ? { key } : {}) })
333
424
  try {
334
425
  return await send(requested)
335
426
  } catch (error) {
@@ -716,7 +807,7 @@ export function createRuntime(input) {
716
807
  *
717
808
  * @param {{ sessionID?: string, agent?: string, messages?: any[], timeoutMs?: number, model?: any, directory?: string }} input
718
809
  * @returns {Promise<{ ok: boolean, chars: number, sessionID: string, reason?: string }>}
719
- * `reason` says why nothing was written: no-session, disabled, unavailable, subagent,
810
+ * `reason` says why nothing was written: no-session, disabled, paused, unavailable, subagent,
720
811
  * context-unresolved, no-context, empty, duplicate, or write-failed.
721
812
  */
722
813
  function writeCompactionCheckpoint(input = {}) {
@@ -731,6 +822,9 @@ export function createRuntime(input) {
731
822
  const skipped = (reason) => ({ ok: false, chars: 0, sessionID, reason })
732
823
  if (!sessionID) return skipped("no-session")
733
824
  if (config.compactionCheckpoint === false) return skipped("disabled")
825
+ // The person paused capture in this session (/mem-pause): the checkpoint
826
+ // summarises the whole transcript, so it stays off even after a resume.
827
+ if (capturePause.everPaused(sessionID)) return skipped("paused")
734
828
  // As the session compacting: its token, or nothing when its speaker has
735
829
  // no Jelly account linked on this host.
736
830
  if (await availability()) return skipped("unavailable")
@@ -767,7 +861,7 @@ export function createRuntime(input) {
767
861
  }
768
862
 
769
863
  const label = context ? contextScopeLabel(context, scoped) : scopeLabel(scoped)
770
- const checkpoint = buildCheckpoint({
864
+ const built = buildCheckpoint({
771
865
  sessionID,
772
866
  agent: input.agent,
773
867
  messages,
@@ -775,10 +869,16 @@ export function createRuntime(input) {
775
869
  now: new Date(),
776
870
  directory: typeof input.directory === "string" ? input.directory : undefined,
777
871
  })
778
- if (!checkpoint) {
872
+ if (!built) {
779
873
  log.debug("compaction checkpoint skipped: nothing to checkpoint", { sessionID })
780
874
  return skipped("empty")
781
875
  }
876
+ // The transcript may still hold text the person asked to forget (the
877
+ // asking turn restates it): each run of it is masked before upload
878
+ // (src/forget-purge.js).
879
+ const masked = forgetPurge.mask(built.text)
880
+ if (masked.hits.length > 0) log.info("compaction checkpoint: forgotten text masked", { sessionID, purge: masked.hits })
881
+ const checkpoint = masked.hits.length > 0 ? { ...built, text: masked.value } : built
782
882
 
783
883
  // The timestamp changes on every fire; exclude it so a repeated compaction
784
884
  // event for the same transcript is recognized as a duplicate.
@@ -841,17 +941,82 @@ export function createRuntime(input) {
841
941
  await credentials.check()
842
942
  return credentials.subject()
843
943
  },
944
+ // An entry that holds text the person forgot after it was queued is
945
+ // deleted, never replayed (src/forget-purge.js).
946
+ sendable: (entry) => forgetPurge.sendable(entry),
844
947
  })
845
948
 
949
+ /** Forget, end to end on the client: purge the spool, mask captures (src/forget-purge.js). */
950
+ const forgetPurge = createForgetPurge({
951
+ config,
952
+ log,
953
+ records: recordsClient,
954
+ spool,
955
+ now,
956
+ scope: () => scope({}),
957
+ hasEntries: () => {
958
+ const stats = spool.spoolStats()
959
+ return stats.pending + stats.inflight + stats.quarantined > 0
960
+ },
961
+ })
962
+
963
+ /**
964
+ * Replay the spool, after the forget purge: new purge entries are fetched
965
+ * (startup, a drain, /mem-sync) and matching entries deleted first. While a
966
+ * forget is pending and its entries cannot be read, nothing is replayed.
967
+ */
968
+ async function flushSpool(options = {}) {
969
+ let gate = { ok: true }
970
+ try {
971
+ gate = await forgetPurge.beforeFlush({ force: options?.force === true })
972
+ } catch (error) {
973
+ log.warn("forget purge before replay failed", errorMessage(error))
974
+ }
975
+ if (!gate.ok) return { flushed: 0, failed: 0, quarantined: 0, deferred: spool.spoolStats().pending, held: "forget-pending" }
976
+ return spool.flushSpool(options)
977
+ }
978
+
846
979
  /** A new user message in a session: its Jelly token is asked for again (src/credentials.js `userTurn`). */
847
980
  function userTurn(sessionID, messageID) {
848
981
  credentials?.userTurn?.(sessionID, messageID)
849
982
  }
850
983
 
984
+ /** Keep a user message as the person's words in this session (the `prompt` hook and the admission events). */
985
+ function notePrompt(sessionID, text) {
986
+ stated.note(sessionID, text)
987
+ }
988
+
989
+ /**
990
+ * The person's recent messages for a tool call in `sessionID`, oldest first.
991
+ * A known subagent's prompt is its parent agent's brief, so the root
992
+ * session's messages are read instead. An empty list: none was seen.
993
+ */
994
+ function personSaid(sessionID) {
995
+ return stated.of(rootSession(sessionID))
996
+ }
997
+
998
+ /** The due dates the commitments check dropped in this session's root, with the words they were tied to. */
999
+ function personDrops(sessionID) {
1000
+ return stated.drops(rootSession(sessionID))
1001
+ }
1002
+
1003
+ /** A session's root: itself, or the first ancestor with no recorded parent. */
1004
+ function rootSession(sessionID) {
1005
+ let id = sessionID ? String(sessionID) : ""
1006
+ for (let hops = 0; id && hops < 8; hops += 1) {
1007
+ const parent = parentOf(id)
1008
+ if (!parent) break
1009
+ id = parent
1010
+ }
1011
+ return id
1012
+ }
1013
+
851
1014
  /** Drop what is kept for a session OpenCode deleted: its credential, pinned block and context. */
852
1015
  function forgetSession(sessionID) {
853
1016
  if (!sessionID) return
854
1017
  credentials?.forget?.(sessionID)
1018
+ stated.drop(sessionID)
1019
+ capturePause.drop(sessionID)
855
1020
  invalidate(sessionID)
856
1021
  }
857
1022
  let lastDrain = 0
@@ -867,11 +1032,22 @@ export function createRuntime(input) {
867
1032
  if (started - lastDrain < SPOOL_DRAIN_INTERVAL_MS) return
868
1033
  lastDrain = started
869
1034
  if (spool.spoolStats().pending === 0) return
870
- void spool.flushSpool().catch((error) => log.warn("background spool flush failed", errorMessage(error)))
1035
+ void flushSpool().catch((error) => log.warn("background spool flush failed", errorMessage(error)))
1036
+ }
1037
+
1038
+ /** What capture does for a session: off, paused since when, or on with its visibility. */
1039
+ function describeCapture(sessionID) {
1040
+ if (!config.capture) return "off"
1041
+ const since = sessionID ? capturePause.pausedSince(sessionID) : ""
1042
+ if (since) return `paused for this session since ${since} (/mem-resume turns it back on)`
1043
+ if (sessionID && capturePause.everPaused(sessionID)) return `${config.captureVisibility}; no checkpoint or compaction summary for this session, which was paused`
1044
+ return config.captureVisibility
871
1045
  }
872
1046
 
873
1047
  async function status(overrides = {}) {
874
- const { context, ...rest } = overrides
1048
+ // `captureSession`: the session whose capture state to show, also when the
1049
+ // counts are for another space (mem_spaces health with a space).
1050
+ const { context, captureSession, ...rest } = overrides
875
1051
  const scoped = scope({ ...rest, context, visibility: rest.visibility ?? config.captureVisibility })
876
1052
  const shared = sharedScope({ context })
877
1053
  // Counts describe the whole scope, not the current session.
@@ -897,7 +1073,8 @@ export function createRuntime(input) {
897
1073
  spaceName: context?.space_name ?? null,
898
1074
  spaceKind: context?.space_kind ?? null,
899
1075
  collection: context?.collection_id ?? null,
900
- capture: config.captureVisibility,
1076
+ capture: describeCapture(captureSession ?? rest.sessionID),
1077
+ capturePaused: (captureSession ?? rest.sessionID) ? capturePause.pausedSince(captureSession ?? rest.sessionID) : "",
901
1078
  layers: {
902
1079
  l0: conversations?.total ?? null,
903
1080
  l1: atoms?.total ?? null,
@@ -927,21 +1104,31 @@ export function createRuntime(input) {
927
1104
  unavailable,
928
1105
  availability,
929
1106
  userTurn,
1107
+ notePrompt,
1108
+ personSaid,
1109
+ personDrops,
930
1110
  forgetSession,
931
1111
  scope,
932
1112
  scopeFor,
933
1113
  sharedScope,
934
1114
  resolveContext,
935
1115
  isSessionBound,
1116
+ keepBinding,
936
1117
  sessionContext,
937
1118
  captureContext,
938
1119
  gatewayCapture,
939
1120
  captureTurn,
1121
+ spaceHint,
940
1122
  noteSession,
941
1123
  noteAgent,
942
1124
  agentFor: lastAgent,
943
1125
  parentOf,
944
1126
  skipsSubagent,
1127
+ pauseCapture: (sessionID) => capturePause.pause(sessionID),
1128
+ resumeCapture: (sessionID) => capturePause.resume(sessionID),
1129
+ capturePausedSince: (sessionID) => capturePause.pausedSince(sessionID),
1130
+ captureEverPaused: (sessionID) => capturePause.everPaused(sessionID),
1131
+ describeCapture,
945
1132
  setSessionTask,
946
1133
  taskFor,
947
1134
  skillContexts,
@@ -965,8 +1152,12 @@ export function createRuntime(input) {
965
1152
  recentCheckpoint: spool.recentCheckpoint,
966
1153
  pruneClaims: spool.pruneClaims,
967
1154
  enqueueSpool: spool.enqueueSpool,
968
- flushSpool: spool.flushSpool,
1155
+ flushSpool,
969
1156
  spoolStats: spool.spoolStats,
1157
+ // The forget purge's hook (slice 6b): delete spooled entries a predicate matches.
1158
+ purgeSpool: spool.purgeMatching,
1159
+ forgetPurge,
1160
+ maskForgotten: forgetPurge.mask,
970
1161
  drainSpool,
971
1162
  status,
972
1163
  }
package/src/shapes.js ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The unsafe shapes of a text: instruction, permission, share
3
+ * (memory-funnel-v1.md §7, §10). One module, two copies kept identical by
4
+ * scripts/check-copies.mjs: records/src/shapes.js for the routines and the
5
+ * store, src/shapes.js for the plugin's pinned block. The patterns are
6
+ * anchored on the phrasing of an injected command, not on single words, so an
7
+ * ordinary "I'll share the deck on Monday" survives.
8
+ */
9
+
10
+ const INSTRUCTION = [
11
+ /\b(?:ignore|disregard|forget|override) (?:(?:all|any|the|your|of|my) )*(?:(?:previous|prior|above|earlier|other|existing) )?(?:instructions|rules|directions|guidelines|prompts?)\b/i,
12
+ /\b(?:you are|you're) now\b/i,
13
+ /\breveal (?:the |your )?(?:secret|token|password|api key|credentials|system prompt)\b/i,
14
+ /\b(?:print|show|repeat|override|replace|ignore|disregard) (?:the |your )?system prompt\b/i,
15
+ /\b(?:new|updated) system prompt\b/i,
16
+ /\b(?:do not|don't|never) (?:tell|mention|inform|alert) the (?:user|person|owner)\b/i,
17
+ /\b(?:when|if|once|after) you (?:read|see|recall|retrieve|load|process|summari[sz]e) (?:this|these)\b/i,
18
+ /\b(?:note|message|instructions?) (?:to|for) (?:the |any )?(?:ai|assistant|agent|llm|model|bot)s?\b/i,
19
+ /\b(?:ai|llm|assistant|agent|model)s?(?: (?:reading|processing|summari[sz]ing))? (?:this|these)[^.]{0,40}\b(?:must|should|shall|will)\b/i,
20
+ /\bfrom now on\b[^.]{0,60}\b(?:you|always|never|the assistant)\b/i,
21
+ /\b(?:add|store|save|remember|record|write|create) (?:a |an |the )?(?:new )?(?:memory|preference|rule|constraint|instruction|decision)s? (?:that|saying|stating)\b/i,
22
+ /\b(?:system|assistant)\s*:\s*\S/i,
23
+ /<\s*\/?\s*(?:system|instructions?|assistant|im_start|im_end)\b/i,
24
+ /\b(?:run|execute|eval) (?:the following|this) (?:command|code|script)\b/i,
25
+ ]
26
+
27
+ const PERMISSION = [
28
+ /\b(?:grant|give|assign|add)\b[^.]{0,40}\b(?:access|permissions?|admin|owner(?:ship)?|editor|write rights?)\b/i,
29
+ /\b(?:make|set|promote)\b[^.]{0,30}\b(?:an? )?(?:admin|owner|editor)\b/i,
30
+ /\ballow\b[^.]{0,40}\bto (?:read|write|access|edit|delete|see)\b/i,
31
+ /\b(?:auto-?approve|approve (?:all|every|everything|any))\b/i,
32
+ /\b(?:disable|turn off|bypass|skip)\b[^.]{0,20}\b(?:review|safety|filters?|guards?|checks?|approval|2fa|mfa)\b/i,
33
+ /\b(?:transfer|hand over)\b[^.]{0,30}\b(?:ownership|the (?:space|vault|account))\b/i,
34
+ // Standing approvals (FABLE records #4): "always approve shares from …",
35
+ // "accept invites … without asking".
36
+ /\b(?:always|automatically|auto-)\s*(?:approve|accept|grant|trust|allow)\b/i,
37
+ /\b(?:approve|accept|allow|grant|share|forward|send)\b[^.]{0,60}\bwithout (?:asking|confirm(?:ing|ation)|review(?:ing)?|approval|checking|permission)\b/i,
38
+ /\bapprove\b[^.]{0,40}\b(?:shares?|share requests?|access requests?|invites?|invitations?|permissions?|grants?)\b/i,
39
+ /\b(?:ignore|disregard|bypass|override)\b[^.]{0,30}\b(?:rules?|polic(?:y|ies)|protocol|permissions?)\b/i,
40
+ ]
41
+
42
+ const SHARE = [
43
+ /\b(?:share|send|forward|export|upload|post|leak|email|copy|dump)\b[^.]{0,40}\b(?:all|every|entire|whole|everything|your)\b[^.]{0,30}\b(?:memor(?:y|ies)|notes|records|journals?|vault|pages|data|contacts|inbox|mail|files|credentials|passwords?|secrets?|tokens?|keys)\b/i,
44
+ /\b(?:share|send|forward|export|copy)\b[^.]{0,30}\b(?:memor(?:y|ies)|vault|journals?|records)\b[^.]{0,40}\b(?:to|with)\b/i,
45
+ /\bmake\b[^.]{0,40}\bpublic\b/i,
46
+ /\b(?:publish|expose)\b[^.]{0,30}\b(?:memor(?:y|ies)|notes|vault|journals?|pages)\b/i,
47
+ /\bshare everything\b/i,
48
+ /\b(?:all|every|everything)\b[^.]{0,30}\b(?:memor(?:y|ies)|notes|records|journals?|vault|pages|data)\b[^.]{0,20}\b(?:shared|sent|forwarded|exported|published|public(?:ly)?)\b/i,
49
+ /\bshared? (?:it |them |this |these |everything )?(?:publicly|with (?:everyone|anyone|the public))\b/i,
50
+ ]
51
+
52
+ /**
53
+ * Which unsafe shapes a text has.
54
+ * @param {string} text
55
+ * @returns {{instruction: boolean, permission: boolean, share: boolean, any: boolean}}
56
+ */
57
+ export function shapes(text) {
58
+ const value = String(text ?? "")
59
+ const instruction = INSTRUCTION.some((p) => p.test(value))
60
+ const permission = PERMISSION.some((p) => p.test(value))
61
+ const share = SHARE.some((p) => p.test(value))
62
+ return { instruction, permission, share, any: instruction || permission || share }
63
+ }