counterparts 0.3.49 → 0.3.52

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 (95) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +18 -10
  3. package/docs/QUICKSTART.md +46 -12
  4. package/docs/manual.md +2 -1
  5. package/docs/module-map.md +3 -0
  6. package/package.json +3 -2
  7. package/src/adapters/claude-code/NOTES.md +43 -0
  8. package/src/adapters/claude-code/child.ts +23 -2
  9. package/src/adapters/claude-code/doctor-growth.ts +269 -0
  10. package/src/adapters/claude-code/doctor-host.ts +19 -1
  11. package/src/adapters/claude-code/doctor-recall-steps.ts +84 -0
  12. package/src/adapters/claude-code/doctor.ts +26 -3
  13. package/src/adapters/claude-code/hooks.ts +7 -1
  14. package/src/adapters/cli/INTERFACE-GAPS.md +18 -0
  15. package/src/adapters/cli/NOTES.md +24 -0
  16. package/src/adapters/cli/commands-dashboard.ts +9 -1
  17. package/src/adapters/cli/commands-project.ts +2 -1
  18. package/src/adapters/cli/commands-readings.ts +19 -8
  19. package/src/adapters/cli/commands-verify.ts +1 -1
  20. package/src/adapters/cli/commands.ts +4 -2
  21. package/src/adapters/cli/export.ts +2 -1
  22. package/src/adapters/cli/install.ts +14 -6
  23. package/src/adapters/cli/mechanisms.ts +1 -1
  24. package/src/adapters/cli/wire.ts +22 -6
  25. package/src/adapters/dashboard/activity.ts +6 -3
  26. package/src/adapters/dashboard/registries.ts +11 -0
  27. package/src/adapters/dashboard/web/flow.ts +3 -0
  28. package/src/adapters/dashboard/web/lanes.ts +4 -0
  29. package/src/adapters/dashboard/web/narrate.ts +23 -0
  30. package/src/adapters/dashboard/web/views/activity.ts +4 -2
  31. package/src/adapters/dashboard/web/views/flow-view.ts +6 -0
  32. package/src/adapters/dashboard/web/views/memory.ts +13 -0
  33. package/src/adapters/dashboard/web/views/shared.ts +2 -1
  34. package/src/adapters/fired.ts +113 -11
  35. package/src/adapters/host-wiring.ts +3 -1
  36. package/src/adapters/lifecycle.ts +36 -9
  37. package/src/adapters/mcp/CONTRACT.md +22 -1
  38. package/src/adapters/mcp/server-args.ts +51 -0
  39. package/src/adapters/mcp/server-session-end.ts +8 -2
  40. package/src/adapters/mcp/server-words.ts +14 -1
  41. package/src/adapters/mcp/server.ts +117 -7
  42. package/src/adapters/mcp/tools.ts +4 -3
  43. package/src/adapters/plugin.ts +1 -0
  44. package/src/adapters/presence.ts +74 -0
  45. package/src/adapters/runtime.ts +258 -8
  46. package/src/adapters/scopes.ts +3 -2
  47. package/src/adapters/spawn.ts +3 -0
  48. package/src/adapters/update-check.ts +1 -1
  49. package/src/adapters/windows-shims.mjs +102 -0
  50. package/src/core/close-hint.ts +297 -0
  51. package/src/core/counterpart-boundary.ts +15 -0
  52. package/src/core/counterpart-deposit.ts +24 -3
  53. package/src/core/counterpart-events.ts +14 -0
  54. package/src/core/counterpart-types.ts +6 -0
  55. package/src/core/counterpart-wake-shape.ts +88 -19
  56. package/src/core/counterpart.ts +143 -7
  57. package/src/core/dream/index.ts +1 -1
  58. package/src/core/dream/reflect.ts +54 -34
  59. package/src/core/encode/NOTES.md +55 -0
  60. package/src/core/encode/secrets.ts +477 -3
  61. package/src/core/event-rollup.ts +175 -0
  62. package/src/core/handoff/CONTRACT.md +7 -0
  63. package/src/core/interference.ts +496 -0
  64. package/src/core/open-close.ts +583 -0
  65. package/src/core/prospective/CONTRACT.md +24 -0
  66. package/src/core/prospective/derive.ts +22 -1
  67. package/src/core/prospective/index.ts +115 -1
  68. package/src/core/recall/CONTRACT.md +9 -2
  69. package/src/core/recall/NOTES.md +99 -0
  70. package/src/core/recall/activate.ts +83 -6
  71. package/src/core/recall/index.ts +75 -5
  72. package/src/core/recall/probe.ts +134 -0
  73. package/src/core/recall/steps.ts +84 -0
  74. package/src/core/recall/tunables.ts +11 -0
  75. package/src/core/reconsolidation.ts +14 -4
  76. package/src/core/remember/CONTRACT.md +2 -1
  77. package/src/core/remember/NOTES.md +15 -0
  78. package/src/core/remember/spans.ts +44 -6
  79. package/src/core/self/NOTES.md +21 -0
  80. package/src/core/self/work.ts +9 -5
  81. package/src/core/sleep/CONTRACT.md +36 -2
  82. package/src/core/sleep/NOTES.md +35 -0
  83. package/src/core/sleep/close.ts +77 -0
  84. package/src/core/sleep/cycle.ts +44 -0
  85. package/src/core/sleep/index.ts +4 -0
  86. package/src/core/sleep/interfere.ts +73 -0
  87. package/src/core/sleep/log.ts +27 -2
  88. package/src/core/sleep/tunables.ts +19 -0
  89. package/src/core/sleep/types.ts +20 -0
  90. package/src/core/store/index.ts +157 -10
  91. package/src/core/store/operational.ts +22 -0
  92. package/src/core/store/owner-op-seam.ts +16 -0
  93. package/src/core/store/reads-history.ts +173 -7
  94. package/src/core/store/reads-memories.ts +253 -4
  95. package/src/core/store/shapes.ts +8 -0
@@ -53,6 +53,15 @@ export interface SecretPattern {
53
53
  * match its own family already made, never skip a family.
54
54
  */
55
55
  skip?: (value: string, match: string, name: string) => boolean;
56
+ /**
57
+ * For a family whose VALUE a regular expression cannot bound (SX1, a password
58
+ * in a sentence): `re` finds only the anchor, and this reads the text after it,
59
+ * returning the `[start, end)` to redact, or null for nothing. When present,
60
+ * `value` and `skip` are not used.
61
+ */
62
+ extent?: (m: RegExpExecArray, text: string) => [number, number] | null;
63
+ /** With `extent`: only a captured value this accepts is carried to its other copies. */
64
+ propagateIf?: (value: string) => boolean;
56
65
  /** Why this family exists — lineage where there is any. */
57
66
  why: string;
58
67
  }
@@ -124,7 +133,7 @@ const CODE_REFERENCE =
124
133
  /^[A-Za-z_$][A-Za-z_$]*(?:(?:(?:\.|::|->)[A-Za-z_$][A-Za-z0-9_$]*|\[[^\]\n]{0,60}\]|\([^)\n]{0,80}\))+[[(]?|[[(])[,;]?$/;
125
134
  const TYPE_NAME =
126
135
  /^(?:str|int|bytes|bool|float|dict|list|tuple|set|object|Any|None|SecretStr|SecretBytes|string|number|boolean|[A-Z][a-z]+(?:[A-Z][a-z0-9]*)+)[,;]?$/;
127
- const PASSWORD_NAME = /(?:password|passwd|pwd|passphrase|pass)$/i;
136
+ const PASSWORD_NAME = /(?:password|passwd|passcode|pwd|pw|passphrase|pass)$/i;
128
137
  // A bare identifier assigned to a credential-looking name (`pad_token` set to `eos_token`):
129
138
  // letters only, joined by underscores or camelCase humps, no digit. A real secret
130
139
  // has digits or no word structure; `hunter2x` and `abcdefghijkl` stay values.
@@ -184,6 +193,374 @@ const PASSWORD_VALUE = "(\"[^\"\\n]{4,}\"|'[^'\\n]{4,}'|[^\\s\"'\\n]{4,})";
184
193
  /** Any other credential: six or more, and a `,` or `;` ends it. */
185
194
  const CREDENTIAL_VALUE = "(\"[^\"\\n]{4,}\"|'[^'\\n]{4,}'|[^\\s\"'\\n,;]{6,})";
186
195
 
196
+ /**
197
+ * A PASSWORD NAMED IN A SENTENCE (SX1, 2026-11-09). "my password is <value>",
198
+ * "the wifi password's <value>", "pw for the router is <value>", "passcode <digits>":
199
+ * none has a `:` or `=` straight after the name, so the catch-all above never saw
200
+ * them, and a reviewer's sentence was kept word for word in the memory and the raw
201
+ * buffer. This family takes the VALUE only and keeps the sentence ("my wifi
202
+ * password is [REDACTED:password]"), so the memory still says a password exists.
203
+ *
204
+ * Two halves. A regular expression finds the ANCHOR: a name, an optional short
205
+ * clause ("for the router", "I gave you"), and a connector. Then `proseValue`
206
+ * reads the text after it, in code, and decides how much of it is the value —
207
+ * one token, a quoted run, a run of capitalised words, or a passphrase to the end
208
+ * of its clause — or that it is a word of the sentence and nothing is taken.
209
+ * A regex cannot say "a lowercase word followed by more words is the sentence"
210
+ * clearly; code can. The fix round of #788 (an adversarial review: 26 of 53
211
+ * phrasings leaked, 28 of 97 ordinary sentences were cut) is why.
212
+ *
213
+ * The costs are not symmetric: a missed password is stored (on a server, for a
214
+ * hosted person); a false positive costs one word of a sentence ABOUT passwords.
215
+ * Where the choice is between the two, this takes the word.
216
+ *
217
+ * Every group is bounded, and nothing crosses a line except a value that starts
218
+ * on the next line and looks like a secret (two O(n²) incidents above).
219
+ */
220
+ const PROSE_NAME =
221
+ "(password|passwd|pasword|passwrod|passowrd|passcode|" +
222
+ // seed and recovery phrases: the highest-value secret a crypto user says
223
+ "(?:seed|recovery|mnemonic|backup|secret)[ -](?:phrase|words)|mnemonic|" +
224
+ "pass[ -]?phrase|pass[ -]code|pin(?:[ -](?:code|number))?|pw|" +
225
+ // `pwd` only in a possessive or a "the pwd for X" frame: alone it is the working directory.
226
+ // Every lookbehind here sits AFTER its word and is bounded: one before a word ran at every
227
+ // position of a long run of spaces (43 s at 200 KB, caught by the scaling check).
228
+ "pwd(?<=(?:my|our|your|his|her|their|the)[ \\t]+(?:[\\p{L}\\p{N}'’-]{1,20}[ \\t]+)?pwd)|" +
229
+ // `pass:` only where a field starts (a line, or after `,` `;` `/` `|` `(`): "first pass: 74%" is prose.
230
+ "pass(?<=(?:^|[\\n,;/|(])[ \\t]{0,8}pass)(?=[ \\t]*:)|" +
231
+ "(?:door|gate|garage|alarm|lock|safe|entry|access|building|keypad|locker)[ -]code|" +
232
+ "(?:locker|lock|safe|bike)[ -]comb(?:o|ination)|wi-?fi[ -]key|" +
233
+ "contraseña|contrasena|mot de passe|mdp|passwort|kennwort|senha)";
234
+ const PROSE_BEFORE = "(?<![\\p{L}\\p{N}_])";
235
+ const PROSE_AFTER = "(?![\\p{L}\\p{N}_])";
236
+ /** is / was, in five languages (and a typo), as a whole word. */
237
+ const PROSE_VERB = "(?:is|iz|was|es|est|ist|war|é|era)(?![\\p{L}\\p{N}])";
238
+ /** A word of the clause before the connector: never the connector itself. */
239
+ const PROSE_WORD = `(?!${PROSE_VERB})[^\\s.,;:!?"'\`“”‘’|[\\]]{1,40}`;
240
+ /** "for the wifi", "to my laptop", "for wifi at moms house": a preposition and up to four words, on one line. */
241
+ const PROSE_FOR = `[ \\t]+(?:for|to|on|of|at|in|with|from)[ \\t]+(?:${PROSE_WORD}[ \\t]+){0,3}${PROSE_WORD}`;
242
+ /** "I use", "we set", "I gave you" (and then, optionally, "for gmail"). */
243
+ const PROSE_WHO =
244
+ "[ \\t]+(?:i|we|you|they|he|she)[ \\t]+" +
245
+ "(?:use|used|set|picked|chose|have|had|got|gave|sent|told|shared|made|created|mentioned|wrote)" +
246
+ `(?:[ \\t]+(?:you|me|him|her|them|us))?(?:${PROSE_FOR})?`;
247
+ /** An aside between the name and its verb: ", if you need it," / "(case sensitive)". Starts with a letter, so ", 5512," is a value. */
248
+ const PROSE_ASIDE = "[ \\t]*(?:,[ \\t]*\\p{L}[^,\\n]{0,40},|\\([ \\t]*\\p{L}[^)\\n]{0,40}\\))";
249
+ const PROSE_ADVERB =
250
+ "(?:[ \\t]+(?:now|currently|still|just|actually|simply|literally|basically|probably|always|like|kinda|honestly)){0,3}";
251
+ /** The connector, captured whole (group 2) so `proseValue` can tell which one it was. */
252
+ const PROSE_CONNECTOR =
253
+ "(" +
254
+ // is / was, in five languages (and a typo), then "now", "set to", "the word"
255
+ "[ \\t]+" +
256
+ PROSE_VERB +
257
+ "(?:[ \\t]*:)?" +
258
+ PROSE_ADVERB +
259
+ "(?:[ \\t]+(?:set|changed|updated|reset)[ \\t]+to)?(?:[ \\t]+the[ \\t]+(?:word|phrase|string|number))?" +
260
+ // the contraction: "the wifi password's <value>"
261
+ "|[ \\t]*['’]s" +
262
+ // a colon after a short clause: "password for the router: <value>"
263
+ "|[ \\t]*:" +
264
+ // an arrow, a spaced dash, a table cell, a comma, a question mark ("password? it's <value>")
265
+ "|[ \\t]*(?:->|=>|→)|[ \\t]+[-–—]|[ \\t]*\\||[ \\t]*,|[ \\t]*\\?(?:[ \\t]+it(?:['’]s|[ \\t]+is))?" +
266
+ // "changed my password to <value>": `to`, only after a word that changes it
267
+ "|(?<=\\b(?:change|changed|changing|set|reset|update|updated|switched)\\b[^\\n.]{0,40})[ \\t]+to" +
268
+ // no verb at all: "pw <value>", "PIN <digits>", or the value alone on the next line
269
+ "|(?=[ \\t\\r\\n]))" +
270
+ // then the gap before the value: on this line, or ONE line break
271
+ "([ \\t]*(?:\\r?\\n[ \\t]*)?)";
272
+
273
+ /** Ordinary grammar words: never a value. Four letters or more. */
274
+ const PROSE_GRAMMAR = new Set(
275
+ (
276
+ "that this these those what which where when there here your their mine yours ours theirs " +
277
+ "into onto from with without under inside behind about like than then also just only even " +
278
+ "still again already never always often usually really quite very pretty kind sort none " +
279
+ "some each every both either neither enough more most less least much many being been " +
280
+ "something nothing anything everything someone somewhere elsewhere another other whatever " +
281
+ "because cause unless until since while after before above below later gone back same kinda " +
282
+ "four five seven eight nine three eleven twelve twenty thirty forty fifty sixty hundred " +
283
+ "mein meine minha"
284
+ ).split(/\s+/),
285
+ );
286
+ /** Function words: a run of words holding one is a sentence, not a passphrase ("mandatory for every export"). */
287
+ const PROSE_FUNCTION = new Set(
288
+ (
289
+ "a an the i me my you your we our us it its he she him her his they them their to of in on at for from " +
290
+ "with by if or and but so as than then when while because is are was were be been am do does did not no " +
291
+ "can will would should could this that these those there here what which who whom where why how per via"
292
+ ).split(/\s+/),
293
+ );
294
+ /** What a password IS, in a sentence about one. Kept short on purpose: the shape rules below do most of it. */
295
+ const PROSE_STOP = new Set(
296
+ (
297
+ "required mandatory optional needed necessary wrong incorrect correct right invalid valid " +
298
+ "empty blank missing null expired stale weak strong secure insecure safe unsafe good fine " +
299
+ "okay great bad simple easy hard long short complex random unique default temporary weird " +
300
+ "known unknown visible case sensitive loose stuck ready available unavailable plaintext cleartext " +
301
+ "lowercase uppercase length strength hash complexity requirement requirements rule rules policy " +
302
+ "format field expiry expiration manager hint prompt entropy history characters chars value salt " +
303
+ "secret private public personal different new old current problem issue thing part step reset " +
304
+ "change login sign see " +
305
+ "falsch richtig leer erforderlich incorrecta incorrecto correcta correcto vacía vacia " +
306
+ "obligatoria requerida faux fausse vide obligatoire errada vazia obrigatória"
307
+ ).split(/\s+/),
308
+ );
309
+ /** Irregular past participles: "the password is sent / written / kept / read …". */
310
+ const PROSE_PARTICIPLE = new Set(
311
+ (
312
+ "sent written kept shown stolen given read known hidden taken made held told found lost broken " +
313
+ "chosen forgotten done seen bought paid built spent shot left meant drawn grown thrown worn torn " +
314
+ "sworn bound wound hung stuck struck spun split shut spread cast"
315
+ ).split(/\s+/),
316
+ );
317
+ /** The same, with a prefix: "overwritten", "rewritten", "unbroken". */
318
+ const PROSE_PARTICIPLE_END = /^\p{L}{2,6}(?:written|stolen|given|shown|taken|chosen|broken|forgotten|hidden|known|made|done|sent|kept)$/iu;
319
+ /** An adjective, adverb or participle by its ending ("complicated", "expiring", "numeric", "sensitive"). */
320
+ const PROSE_SUFFIX = /^\p{L}+(?:ly|ed|ing|able|ible|less|ful|ous|ive|ic)$/iu;
321
+ /** Algorithms and encodings: "the password is argon2id / SHA256 / UTF-8 / base64 / utf8mb4". */
322
+ const PROSE_ALGO =
323
+ /^(?:md5|sha-?(?:1|2|3|224|256|384|512)|bcrypt|scrypt|argon2(?:id|i|d)?|pbkdf2|utf-?(?:8|16|32)(?:mb[34])?|ascii|base(?:32|64)|aes-?\d*|rsa|hmac|2fa|mfa|otp|totp|hotp)$/i;
324
+ /** Password managers and sign-in products: a name, never a value ("1Password is my password manager"). */
325
+ const PROSE_PRODUCT =
326
+ /^(?:1password|lastpass|keepass(?:xc)?|bitwarden|dashlane|nordpass|keeper|protonpass|enpass|roboform|okta|authy|vaultwarden)$/i;
327
+ /** A measurement, a fraction or a version: "1200ms", "74%", "12/15", "v2.1". */
328
+ const PROSE_MEASURE = /^(?:[+-]?\d+(?:[.,]\d+)?(?:ms|s|secs?|m|mins?|h|hrs?|d|kb|mb|gb|tb|k|x|px|%)|\d+\/\d+|v\d+(?:\.\d+)+)$/i;
329
+ /** Words a value may be followed by and still end its clause: "my password is <value> lol". */
330
+ const PROSE_FILLER = new Set("lol haha lmao btw tho though now ok okay right i iirc fyi please thanks".split(" "));
331
+
332
+ /** A participle, adjective or description: by list, by ending, or as the last part of a hyphenated word. */
333
+ function describes(word: string): boolean {
334
+ const w = word.toLowerCase();
335
+ if (PROSE_STOP.has(w) || PROSE_PARTICIPLE.has(w) || PROSE_PARTICIPLE_END.test(w) || PROSE_SUFFIX.test(w) || PROSE_ALGO.test(w)) return true;
336
+ // "case-sensitive", "base64-encoded", "2FA-protected": the last part says what it is.
337
+ const last = /-(\p{L}+)$/u.exec(w)?.[1];
338
+ return last !== undefined && w.length > last.length + 1 && (PROSE_STOP.has(last) || PROSE_PARTICIPLE.has(last) || PROSE_SUFFIX.test(last));
339
+ }
340
+
341
+ /**
342
+ * IS THIS TOKEN A WORD OF THE SENTENCE RATHER THAN A PASSWORD? A null word, a
343
+ * grammar word, a description (`describes`), an algorithm, a product, a
344
+ * measurement or version, a path or a URL, a placeholder (`$VAR`, `<password>`,
345
+ * `{pw}`, `%s`), or no letter or digit at all (`****`). The trade: a password
346
+ * that is itself one of those words ("my password is fabulous") is kept.
347
+ */
348
+ function isProseWord(word: string): boolean {
349
+ const core = word.replace(/^[([{'"“‘]+|[)\]}!'"”’]+$/g, "");
350
+ if (core.length < 4) return true;
351
+ if (PLAIN_WORDS.test(core) || PROSE_GRAMMAR.has(core.toLowerCase())) return true;
352
+ if (describes(core) || PROSE_PRODUCT.test(core) || PROSE_MEASURE.test(core)) return true;
353
+ if (/^(?:~|\.{1,2})?[/]/.test(core) || core.includes("://")) return true;
354
+ if (/^[$<{%]/.test(core)) return true;
355
+ return !/[\p{L}\p{N}]/u.test(core);
356
+ }
357
+
358
+ /** Looks like a secret on its own: a digit, or a symbol among letters ("Ocelot!99", "Kx7#mPq2"). A path's `/` and `.` are not symbols here. */
359
+ function secretShaped(word: string): boolean {
360
+ const t = word.replace(/^[*_([{'"“‘`]+/u, "").replace(/[.,;:?!*_)\]}'"”’`|]+$/u, "");
361
+ return /\d/.test(t) || (/\p{L}/u.test(t) && /[^\p{L}\p{N}\-_.'’/\\]/u.test(t));
362
+ }
363
+
364
+ /** Code, not a value: brackets, an assignment, a call, a dotted reference (`flags["x"]`, `f.color`, `passRecord(input)`). */
365
+ function codeShaped(word: string): boolean {
366
+ return /[[\](){}<>=;]/.test(word) || (/^[A-Za-z_$][\w$]*\.[A-Za-z_$][\w$.]*$/.test(word) && !/\.\d+$/.test(word)) || CODE_REFERENCE.test(word);
367
+ }
368
+
369
+ /**
370
+ * "I changed my netflix password to <value> yesterday": the anchor read " to <value> …" as a
371
+ * "for the router" clause and the value as its last word, so nothing was taken. When that
372
+ * reading finds no value, try the other one: `to` straight after the name, after a word that
373
+ * changes it, is the connector.
374
+ */
375
+ function changedTo(text: string, nameEnd: number, name: string): [number, number] | null {
376
+ const to = /^[ \t]+to[ \t]+/.exec(text.slice(nameEnd, nameEnd + 16));
377
+ const before = text.slice(Math.max(0, nameEnd - name.length - 48), nameEnd - name.length);
378
+ if (to === null || !/\b(?:change|changed|changing|set|reset|update|updated|switched)\b[^\n.]*$/i.test(before)) return null;
379
+ return proseValue(text, nameEnd + to[0].length, name, to[0].replace(/[ \t]+$/, ""), " ");
380
+ }
381
+
382
+ /** Markup and sentence punctuation around a word: `**none.**`, `(hunter2)`, `hunter2!!`. */
383
+ const TOKEN_LEAD = /^[*_([{'"“‘`]+/u;
384
+ const TOKEN_TRAIL = /[.,;:?!*_)\]}'"”’`|]+$/u;
385
+ const clean = (word: string): string => word.replace(TOKEN_LEAD, "").replace(TOKEN_TRAIL, "");
386
+
387
+ /**
388
+ * DOES THIS RUN OF WORDS READ AS A PASSPHRASE? Two to eight words with no function
389
+ * word in them ("correct horse battery staple", "blue skies over denver"), and at
390
+ * least three (or all, for two) that are not words describing a password. A
391
+ * describing clause ("mandatory for every export", "kinda long i made it from a
392
+ * song") is the sentence.
393
+ */
394
+ function phraseRun(tokens: readonly string[]): boolean {
395
+ if (tokens.length < 2 || tokens.length > 8) return false;
396
+ if (PROSE_GRAMMAR.has(clean(tokens[0] ?? "").toLowerCase())) return false;
397
+ let content = 0;
398
+ for (const t of tokens) {
399
+ const w = clean(t).toLowerCase();
400
+ if (w.length === 0 || PROSE_FUNCTION.has(w) || PROSE_MEASURE.test(w) || codeShaped(w)) return false;
401
+ if (!PROSE_GRAMMAR.has(w) && !describes(w) && !PLAIN_WORDS.test(w)) content += 1;
402
+ }
403
+ return content >= Math.min(3, tokens.length);
404
+ }
405
+
406
+ const QUOTE_CLOSE: Record<string, string> = { '"': '"', "“": "”", "‘": "’", "'": "'", "`": "`" };
407
+ /** Where a clause ends: sentence punctuation before a space, a spaced dash, a conjunction, a bracket, a cell. */
408
+ const CLAUSE_END = /[.,;!?:](?=[\s"'”’)*_]|$)|[ \t]+(?:[-–—]|and|but|so|or|then|because)(?=[ \t])|[)\]|]/u;
409
+ /** The longest value read after a connector. */
410
+ const PROSE_REACH = 160;
411
+ const PROSE_QUOTE_REACH = 64;
412
+ /** At most this many symbol-only tokens (an emoji, a `**`) are stepped over before a value. */
413
+ const PROSE_SKIP_SYMBOLS = 2;
414
+ /** A seed phrase runs to its clause's end, up to this many words. */
415
+ const PROSE_SEED_WORDS = 24;
416
+
417
+ /**
418
+ * HOW MUCH AFTER THE CONNECTOR IS THE VALUE? `[start, end)` in `text`, or null:
419
+ * nothing is a password here and nothing is redacted or counted.
420
+ */
421
+ function proseValue(text: string, start: number, name: string, connector: string, gap: string): [number, number] | null {
422
+ const kind = connector.trim().toLowerCase();
423
+ const lower = name.toLowerCase();
424
+ const crossLine = gap.includes("\n");
425
+ const bare = kind === "";
426
+ if (bare && lower === "pwd") return null;
427
+ const wordConnector = bare || /^(?:is|iz|was|es|est|ist|war|é|era|['’]s)\b|^to$/u.test(kind) || /^[-–—]$/.test(kind);
428
+ if (wordConnector && !/[ \t]$/.test(connector + gap) && !crossLine) return null;
429
+ if (text.startsWith(REDACTION_MARK, start)) return null;
430
+ // Bounded BEFORE the newline search (an unbounded search per anchor is quadratic on a long
431
+ // line), and cut at `\r\n` as at `\n`: a Windows `\r` left on the last word hid it from every list.
432
+ const reach = text.slice(start, start + PROSE_REACH);
433
+ const nl = reach.search(/\r?\n|\r/);
434
+ const line = nl < 0 ? reach : reach.slice(0, nl);
435
+ // A PIN, a door code or a lock combination is digits. Not a passcode, which may be letters.
436
+ const combo = /comb(?:o|ination)$/.test(lower) || (/code$/.test(lower) && !/^pass/.test(lower));
437
+ const digitsOnly = /^pin/.test(lower) || combo;
438
+ const seed = /^(?:seed|recovery|mnemonic|backup|secret)[ -]|^mnemonic$/.test(lower);
439
+ // After a value on the NEXT line, a bare name, a dash, an arrow, a cell, a comma, a question
440
+ // or `pass:`, only a value that looks like a secret on its own.
441
+ const weak = crossLine || bare || /^(?:[-–—]|->|=>|→|\||,)$/.test(kind) || kind.startsWith("?") || lower === "pass";
442
+
443
+ // A QUOTED value: the quote has to close on this line, within reach, or nothing is taken.
444
+ const close = QUOTE_CLOSE[line[0] ?? ""];
445
+ if (close !== undefined) {
446
+ if (crossLine) return null;
447
+ const closeRe = close === "'" ? /'(?![\p{L}\p{N}])/u : new RegExp(close === "`" ? "`" : close);
448
+ const at = line.slice(1, PROSE_QUOTE_REACH + 1).search(closeRe);
449
+ if (at < 0) return null;
450
+ const inner = line.slice(1, at + 1).trim();
451
+ if (inner.length < 4 || inner.startsWith(REDACTION_MARK) || codeShaped(inner)) return null;
452
+ if (digitsOnly ? !/^\d{4,12}[#*]?$/.test(inner) : weak && !secretShaped(inner)) return null;
453
+ if (!/\s/.test(inner) && isProseWord(inner)) return null;
454
+ return [start, start + at + 2];
455
+ }
456
+
457
+ const endAt = line.search(CLAUSE_END);
458
+ const whole = (endAt < 0 ? line : line.slice(0, endAt)).replace(/[ \t]+$/, "");
459
+ // Step over an emoji or a bare `**` before the value: "my password is 🔐 <value>".
460
+ let skipped = 0;
461
+ let from = 0;
462
+ for (let i = 0; i < PROSE_SKIP_SYMBOLS; i += 1) {
463
+ const m = /^[ \t]*(\S+)[ \t]+/u.exec(whole.slice(from));
464
+ if (m === null || !/^(?:[*_~>#•·-]+|[\p{Extended_Pictographic}\u{FE0F}\u{200D}]+)$/u.test(m[1] ?? "")) break;
465
+ from += m[0].length;
466
+ skipped += 1;
467
+ }
468
+ const clause = whole.slice(from);
469
+ const vstart = start + from;
470
+ const tokens = clause.split(/[ \t]+/).filter((t) => t.length > 0);
471
+ const raw = tokens[0];
472
+ if (raw === undefined) return null;
473
+ const lead = TOKEN_LEAD.exec(raw)?.[0].length ?? 0;
474
+ const first = raw.slice(lead).replace(TOKEN_TRAIL, "");
475
+ if (first.length < 4 || first.startsWith(REDACTION_MARK) || codeShaped(first)) return null;
476
+ const one: [number, number] = [vstart + lead, vstart + lead + first.length];
477
+ const next = clean(tokens[1] ?? "");
478
+
479
+ // A value on the next line is one token alone there ("the pin\n1234 Main St" is an address).
480
+ if (crossLine && (tokens.length !== 1 || skipped > 0)) return null;
481
+ if (digitsOnly) {
482
+ const digits = /^\d{4,12}[#*]?$/.test(first) && !(/^pin/.test(lower) && /[#*]$/.test(first));
483
+ if (!digits && !(combo && /^\d{1,4}(?:[-–]\d{1,4}){2,5}$/.test(first))) return null;
484
+ // A year with a noun after it is not a PIN: "PIN 2024 rollout".
485
+ if (/^(?:19|20)\d\d$/.test(first) && /^\p{Ll}+$/u.test(next) && !/^(?:for|to|on|at|in|is|was|and|or)$/.test(next)) return null;
486
+ return one;
487
+ }
488
+ if (bare && !/\d/.test(first)) return null;
489
+ if (weak && !secretShaped(first)) return null;
490
+
491
+ // A seed phrase: its words, to the end of the clause, whatever they are.
492
+ if (seed && tokens.length >= 3 && tokens.length <= PROSE_SEED_WORDS && tokens.every((t) => /^\p{Ll}+$/u.test(clean(t)))) {
493
+ return [vstart + lead, vstart + clause.replace(TOKEN_TRAIL, "").length];
494
+ }
495
+ // A passphrase, or a short clause after a colon, is the clause whole when it reads as one.
496
+ if ((/phrase$|words$/.test(lower) || kind.endsWith(":")) && phraseRun(tokens)) {
497
+ return [vstart + lead, vstart + clause.replace(TOKEN_TRAIL, "").length];
498
+ }
499
+ // "is the word <value>": whatever comes next is the value, even an ordinary word, but not "that".
500
+ if (/the[ \t]+(?:word|phrase|string|number)$/u.test(kind)) {
501
+ return PROSE_FUNCTION.has(first.toLowerCase()) || PROSE_GRAMMAR.has(first.toLowerCase()) ? null : one;
502
+ }
503
+ if (isProseWord(first)) return null;
504
+ // A run of Capitalised words: "Blue Skies Over Denver"; not when a description follows ("Okta managed").
505
+ if (/^\p{Lu}/u.test(first) && tokens.length > 1 && /^\p{Lu}[\p{L}\p{N}]*$/u.test(next)) {
506
+ let n = 1;
507
+ while (n < tokens.length && /^\p{Lu}[\p{L}\p{N}!#$%&*@]*$/u.test(tokens[n] ?? "")) n += 1;
508
+ if (n < tokens.length && describes(clean(tokens[n] ?? ""))) return null;
509
+ const run = new RegExp(`^(?:\\S+[ \\t]+){${String(n - 1)}}\\S+`).exec(clause)?.[0] ?? raw;
510
+ return [vstart + lead, vstart + run.replace(TOKEN_TRAIL, "").length];
511
+ }
512
+ // A word with no digit, and a description or more of the clause after it, is the sentence
513
+ // ("is sent over TLS", "is Okta managed").
514
+ if (/^\p{L}+$/u.test(first) && tokens.length > 1) {
515
+ if (describes(next)) return null;
516
+ if (/^\p{Ll}+$/u.test(first) && !PROSE_FILLER.has(next.toLowerCase())) return null;
517
+ }
518
+ return one;
519
+ }
520
+
521
+ /** A password name. */
522
+ const NAME_WORD = "(?:password|passwd|pasword|passcode|passphrase|pin|pw|pwd)";
523
+ const NAME_NEARBY = new RegExp(`(?<![\\p{L}\\p{N}_])${NAME_WORD}(?![\\p{L}\\p{N}_])`, "iu");
524
+ /** "…, the password I mean", "— the wifi password": the name after a determiner, right after the value. */
525
+ const NAME_AFTER = new RegExp(
526
+ `^[ \\t]*[,—–-]?[ \\t]*(?:the|my|our|your)[ \\t]+(?:[\\p{L}\\p{N}-]{1,20}[ \\t]+){0,2}${NAME_WORD}(?![\\p{L}\\p{N}_])`,
527
+ "iu",
528
+ );
529
+ /**
530
+ * "it's <value>" belongs to a password named IN ITS CLAUSE: earlier in it ("password?
531
+ * it's <value>", "my password was <value> and now it's <value>"; a `?` or `:` does not
532
+ * end the clause, a `.` `,` `;` `!` or line break does), or right after the value ("<value>,
533
+ * the password I mean"). An 80-character window either side cut ordinary chat.
534
+ */
535
+ function nameInClause(text: string, from: number, to: number): boolean {
536
+ const before = text.slice(Math.max(0, from - 80), from);
537
+ const cut = Math.max(...[".", ",", ";", "!", "\n"].map((c) => before.lastIndexOf(c)));
538
+ if (NAME_NEARBY.test(cut < 0 ? before : before.slice(cut + 1))) return true;
539
+ const after = text.slice(to, to + 48);
540
+ return NAME_AFTER.test(after.split(/\r?\n/)[0] ?? "");
541
+ }
542
+
543
+ /** A password name anywhere on this line, within reach before or after `at`. */
544
+ function nameNear(text: string, from: number, to: number): boolean {
545
+ // A window of 80 either side, cut at the line breaks inside it (bounded, so linear).
546
+ const lo = Math.max(0, from - 80);
547
+ const before = text.slice(lo, from);
548
+ const after = text.slice(to, to + 80);
549
+ const b = before.lastIndexOf("\n");
550
+ const a = after.indexOf("\n");
551
+ const window = (b < 0 ? before : before.slice(b + 1)) + text.slice(from, to) + (a < 0 ? after : after.slice(0, a));
552
+ return NAME_NEARBY.test(window);
553
+ }
554
+
555
+ /** One secret-shaped token at `start`, on this line, or null. */
556
+ function shapedToken(text: string, start: number): [number, number] | null {
557
+ if (text.startsWith(REDACTION_MARK, start)) return null;
558
+ const m = /^[^\s"'`“”]{4,64}/u.exec(text.slice(start, start + 65));
559
+ if (m === null) return null;
560
+ const candidate = m[0].replace(/[.,;:?)\]}]+$/, "");
561
+ return candidate.length >= 4 && secretShaped(candidate) && !isProseWord(candidate) && !codeShaped(candidate) ? [start, start + candidate.length] : null;
562
+ }
563
+
187
564
  // The same lever exists one class later in `url-path-token`: an unbounded
188
565
  // host/path run (`[^\s"'<>]*`) retried across a comma-joined URL list was
189
566
  // quadratic too (179ms at 64KB, 2.8s at 256KB — PR-8 review). Bounded to 512:
@@ -384,7 +761,7 @@ export const SECRET_FAMILIES: readonly SecretPattern[] = [
384
761
  // one (re-review R4: `DB_PASSWORD=abc,defghij`, `DB_PASSWORD=Ab3$x`).
385
762
  // `pgpassword` is Postgres's own variable, glued with no separator.
386
763
  re: new RegExp(
387
- "(?<![A-Za-z0-9])(pgpassword|password|passwd|pwd|passphrase|(?<=[A-Za-z0-9][_-])pass)\\b" +
764
+ "(?<![A-Za-z0-9])(pgpassword|password|passwd|passcode|pwd|pw|passphrase|(?<=[A-Za-z0-9][_-])pass)\\b" +
388
765
  ASSIGNED_SEPARATOR +
389
766
  NOT_A_PLACEHOLDER +
390
767
  PASSWORD_VALUE,
@@ -442,7 +819,7 @@ export const SECRET_FAMILIES: readonly SecretPattern[] = [
442
819
  // 4. A PIN, as a whole name or `user_pin` / `PIN_CODE` / `pinCode` (`pin_memory=True` and `spin` never match) and only
443
820
  // with a numeric value of four to twelve digits, quoted or not.
444
821
  re: new RegExp(
445
- "(?:(?<![A-Za-z0-9])|(?<=[_-]))(pin(?:[_-]?code)?)\\b" +
822
+ "(?:(?<![A-Za-z0-9])|(?<=[_-]))(pin(?:[_-]?code)?|passcode)\\b" +
446
823
  ASSIGNED_SEPARATOR +
447
824
  NOT_A_PLACEHOLDER +
448
825
  "(\"\\d{4,12}\"|'\\d{4,12}'|\\d{4,12})(?![\\w.])",
@@ -465,6 +842,71 @@ export const SECRET_FAMILIES: readonly SecretPattern[] = [
465
842
  skip: isSetting,
466
843
  why: "A bare AUTH / BEARER environment variable.",
467
844
  },
845
+ // A PASSWORD NAMED IN A SENTENCE (SX1). Last, so the catch-all keeps every
846
+ // `name:` / `name=` form with its code guards, and a value it already took is a
847
+ // placeholder here. Each pattern finds an ANCHOR; `extent` reads the value. Only
848
+ // a secret-shaped value is carried to its other copies: a plain word ("my password is" a weekday)
849
+ // must not take every copy of that word in the text with it.
850
+ {
851
+ family: "password",
852
+ // 1. The name, an optional clause or aside, a connector: "my password is <value>",
853
+ // "the wifi password's <value>", "pw for the router: <value>", "PIN <digits>".
854
+ re: new RegExp(
855
+ PROSE_BEFORE + PROSE_NAME + PROSE_AFTER + `(?:${PROSE_FOR}|${PROSE_WHO}|${PROSE_ASIDE})?` + PROSE_CONNECTOR,
856
+ "giu",
857
+ ),
858
+ value: 0,
859
+ extent: (m, text) =>
860
+ proseValue(text, m.index + m[0].length, m[1] ?? "", m[2] ?? "", m[3] ?? "") ?? changedTo(text, m.index + (m[1] ?? "").length, m[1] ?? ""),
861
+ propagate: true,
862
+ propagateIf: secretShaped,
863
+ why: "A password, passcode, passphrase, seed phrase, PIN or door code named in a sentence.",
864
+ },
865
+ {
866
+ family: "password",
867
+ // 2. "it's <value>" / "that was <value>" / "my home one is <value>", with a password
868
+ // named in the same clause before it, or right after the value ("<value>, the
869
+ // password I mean"). Only a value that looks like a secret on its own.
870
+ re: /(?<![\p{L}\p{N}_])(?:it|that|one)(?:['’]s|[ \t]+(?:is|was))[ \t]+/giu,
871
+ value: 0,
872
+ extent: (m, text) => {
873
+ const r = shapedToken(text, m.index + m[0].length);
874
+ return r !== null && nameInClause(text, m.index, r[1]) ? r : null;
875
+ },
876
+ propagate: true,
877
+ propagateIf: secretShaped,
878
+ why: "A password said as 'it's …' in the clause that names it.",
879
+ },
880
+ {
881
+ family: "password",
882
+ // 3. "set it to <value> when you reset the admin password". A bare number is a
883
+ // setting (a timeout "set to" a number, beside a password setting) unless the name is a PIN or code.
884
+ re: /(?<![\p{L}\p{N}_])(?:set|change|changed|reset|update|updated)[ \t]+(?:it|this|that)[ \t]+to[ \t]+/giu,
885
+ value: 0,
886
+ extent: (m, text) => {
887
+ const r = shapedToken(text, m.index + m[0].length);
888
+ if (r === null || !nameNear(text, m.index, r[1])) return null;
889
+ if (/^\d+$/.test(text.slice(r[0], r[1]))) {
890
+ const line = text.slice(m.index, Math.min(text.length, r[1] + 80)).split(/\r?\n/)[0] ?? "";
891
+ if (!/(?<![\p{L}\p{N}_])(?:pin|passcode|code)(?![\p{L}\p{N}_])/iu.test(line)) return null;
892
+ }
893
+ return r;
894
+ },
895
+ propagate: true,
896
+ propagateIf: secretShaped,
897
+ why: "A password set 'to …' with its name on the same line.",
898
+ },
899
+ {
900
+ family: "password",
901
+ // 4. The value first: "<value> is my password for everything". Not a product
902
+ // ("1Password is my password manager"): `isProseWord` knows those.
903
+ re: /(?<![^\s"'(])[^\s"'`“”]{4,64}(?=[ \t]+(?:is|was)[ \t]+(?:my|our|the|your|his|her|their)[ \t]+(?:[\p{L}-]{1,20}[ \t]+){0,2}(?:password|passcode|passphrase|pin|pw)(?![\p{L}\p{N}_]))/giu,
904
+ value: 0,
905
+ extent: (m, text) => shapedToken(text, m.index),
906
+ propagate: true,
907
+ propagateIf: secretShaped,
908
+ why: "A password said before its name.",
909
+ },
468
910
  ];
469
911
 
470
912
  export interface SecretsScan {
@@ -486,6 +928,7 @@ function redactOne(
486
928
  // A fresh regex per call: a module-level /g regex carries `lastIndex` state,
487
929
  // and a shared mutable cursor across callers is a bug waiting for a Tuesday.
488
930
  const re = new RegExp(p.re.source, p.re.flags);
931
+ if (p.extent !== undefined) return redactByExtent(text, re, p, hit, captured);
489
932
  return text.replace(re, (...args: unknown[]): string => {
490
933
  const match = String(args[0] ?? "");
491
934
  const mark = `[REDACTED:${p.family}]`;
@@ -508,6 +951,37 @@ function redactOne(
508
951
  });
509
952
  }
510
953
 
954
+ /**
955
+ * The anchor-and-extent form: every anchor `re` finds, `p.extent` says what after
956
+ * it is the value. Ranges never overlap and never move backwards, and the scan
957
+ * resumes after a taken value, so the pass stays linear.
958
+ */
959
+ function redactByExtent(
960
+ text: string,
961
+ re: RegExp,
962
+ p: SecretPattern,
963
+ hit: () => void,
964
+ captured?: (value: string) => void,
965
+ ): string {
966
+ const mark = `[REDACTED:${p.family}]`;
967
+ let out = "";
968
+ let from = 0;
969
+ for (let m = re.exec(text); m !== null; m = re.exec(text)) {
970
+ if (m[0].length === 0) re.lastIndex += 1;
971
+ const range = p.extent?.(m, text) ?? null;
972
+ if (range === null) continue;
973
+ const [start, end] = range;
974
+ if (start < from || end <= start || end > text.length) continue;
975
+ hit();
976
+ const value = text.slice(start, end);
977
+ if (p.propagateIf === undefined || p.propagateIf(value)) captured?.(value);
978
+ out += text.slice(from, start) + mark;
979
+ from = end;
980
+ if (re.lastIndex < end) re.lastIndex = end;
981
+ }
982
+ return from === 0 ? text : out + text.slice(from);
983
+ }
984
+
511
985
  function unquote(value: string): string {
512
986
  return /^(["']).*\1$/s.test(value) ? value.slice(1, -1) : value.replace(/[,;]+$/, "");
513
987
  }