counterparts 0.3.12 → 0.3.13

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 (116) hide show
  1. package/CHANGELOG.md +184 -0
  2. package/docs/module-map.md +1 -1
  3. package/package.json +1 -1
  4. package/src/adapters/claude-code/CONTRACT.md +36 -10
  5. package/src/adapters/claude-code/INTERFACE-GAPS.md +116 -16
  6. package/src/adapters/claude-code/NOTES.md +131 -0
  7. package/src/adapters/claude-code/bin/hook.ts +35 -2
  8. package/src/adapters/claude-code/doctor.ts +155 -21
  9. package/src/adapters/claude-code/hooks.ts +49 -7
  10. package/src/adapters/claude-code/index.ts +11 -0
  11. package/src/adapters/claude-code/night-run.ts +133 -12
  12. package/src/adapters/claude-code/transcript.ts +268 -1
  13. package/src/adapters/cli/CONTRACT.md +5 -0
  14. package/src/adapters/cli/INTERFACE-GAPS.md +8 -4
  15. package/src/adapters/cli/NOTES.md +111 -0
  16. package/src/adapters/cli/commands.ts +65 -14
  17. package/src/adapters/cli/dream-core.ts +57 -42
  18. package/src/adapters/cli/export.ts +320 -21
  19. package/src/adapters/cli/index.ts +1 -0
  20. package/src/adapters/cli/install.ts +39 -7
  21. package/src/adapters/cli/mechanisms.ts +7 -1
  22. package/src/adapters/cli/uninstall.ts +13 -5
  23. package/src/adapters/cli/wire.ts +189 -63
  24. package/src/adapters/dashboard/INTERFACE-GAPS.md +10 -1
  25. package/src/adapters/dashboard/NOTES.md +79 -0
  26. package/src/adapters/dashboard/registries.ts +10 -2
  27. package/src/adapters/dashboard/web/README.md +19 -14
  28. package/src/adapters/dashboard/web/actions.ts +23 -1
  29. package/src/adapters/dashboard/web/flow.ts +4 -1
  30. package/src/adapters/dashboard/web/lanes.ts +3 -0
  31. package/src/adapters/dashboard/web/narrate.ts +30 -2
  32. package/src/adapters/dashboard/web/pages/flow/sections/fired.js +1 -0
  33. package/src/adapters/dashboard/web/pages/memories/memories.css +17 -4
  34. package/src/adapters/dashboard/web/pages/memories/row.js +37 -21
  35. package/src/adapters/dashboard/web/pages/memories/sections/search.js +279 -60
  36. package/src/adapters/dashboard/web/pages/memories/state.js +2 -1
  37. package/src/adapters/dashboard/web/server.ts +0 -5
  38. package/src/adapters/dashboard/web/shared/memory-marks.css +7 -0
  39. package/src/adapters/dashboard/web/shared/memory-marks.js +33 -0
  40. package/src/adapters/dashboard/web/shared/memory-modal.js +5 -3
  41. package/src/adapters/dashboard/web/views/health.ts +1 -1
  42. package/src/adapters/dashboard/web/views/search.ts +4 -45
  43. package/src/adapters/dashboard/web/views.ts +2 -2
  44. package/src/adapters/fired.ts +410 -25
  45. package/src/adapters/host-wiring.ts +300 -0
  46. package/src/adapters/lifecycle.ts +14 -0
  47. package/src/adapters/log/index.ts +2 -0
  48. package/src/adapters/mcp/CONTRACT.md +33 -3
  49. package/src/adapters/mcp/INTERFACE-GAPS.md +24 -2
  50. package/src/adapters/mcp/NOTES.md +136 -0
  51. package/src/adapters/mcp/bin/serve.ts +30 -0
  52. package/src/adapters/mcp/facts.ts +13 -1
  53. package/src/adapters/mcp/meaning.ts +208 -13
  54. package/src/adapters/mcp/server.ts +87 -15
  55. package/src/adapters/mcp/stdio.ts +3 -1
  56. package/src/adapters/mcp/stood-down.ts +51 -0
  57. package/src/adapters/mcp/tools.ts +27 -7
  58. package/src/adapters/plugin-run.sh +133 -0
  59. package/src/adapters/plugin.ts +329 -0
  60. package/src/core/associate/CONTRACT.md +2 -1
  61. package/src/core/associate/INTERFACE-GAPS.md +6 -1
  62. package/src/core/associate/NOTES.md +45 -0
  63. package/src/core/briefing.ts +12 -3
  64. package/src/core/contradictions.ts +184 -0
  65. package/src/core/counterpart.ts +451 -18
  66. package/src/core/dream/CONTRACT.md +5 -2
  67. package/src/core/dream/INTERFACE-GAPS.md +29 -6
  68. package/src/core/dream/NOTES.md +21 -0
  69. package/src/core/dream/index.ts +33 -1
  70. package/src/core/dream/reflect.ts +20 -5
  71. package/src/core/encode/INTERFACE-GAPS.md +3 -1
  72. package/src/core/fit/INTERFACE-GAPS.md +8 -2
  73. package/src/core/fit/NOTES.md +5 -2
  74. package/src/core/fit/index.ts +4 -1
  75. package/src/core/handoff/CONTRACT.md +37 -2
  76. package/src/core/handoff/INTERFACE-GAPS.md +10 -0
  77. package/src/core/handoff/NOTES.md +66 -0
  78. package/src/core/handoff/index.ts +214 -12
  79. package/src/core/mint.ts +8 -2
  80. package/src/core/physics/CONTRACT.md +11 -1
  81. package/src/core/physics/NOTES.md +30 -0
  82. package/src/core/physics/index.ts +26 -4
  83. package/src/core/prospective/CONTRACT.md +45 -6
  84. package/src/core/prospective/INTERFACE-GAPS.md +4 -0
  85. package/src/core/prospective/NOTES.md +138 -0
  86. package/src/core/prospective/derive.ts +33 -5
  87. package/src/core/prospective/index.ts +90 -5
  88. package/src/core/prospective/windows.ts +72 -1
  89. package/src/core/recall/CONTRACT.md +6 -2
  90. package/src/core/recall/INTERFACE-GAPS.md +28 -4
  91. package/src/core/recall/NOTES.md +57 -1
  92. package/src/core/recall/probe.ts +58 -0
  93. package/src/core/recall/session.ts +27 -3
  94. package/src/core/recall/time-ask.ts +116 -18
  95. package/src/core/remember/CONTRACT.md +4 -1
  96. package/src/core/remember/INTERFACE-GAPS.md +9 -1
  97. package/src/core/remember/proposals.ts +38 -5
  98. package/src/core/revision.ts +5 -0
  99. package/src/core/schemas/CONTRACT.md +13 -1
  100. package/src/core/schemas/INTERFACE-GAPS.md +20 -2
  101. package/src/core/schemas/NOTES.md +127 -0
  102. package/src/core/schemas/types.ts +2 -0
  103. package/src/core/self/CONTRACT.md +15 -4
  104. package/src/core/self/INTERFACE-GAPS.md +7 -2
  105. package/src/core/self/NOTES.md +49 -0
  106. package/src/core/self/briefing.ts +12 -2
  107. package/src/core/self/index.ts +82 -8
  108. package/src/core/self/page.ts +88 -0
  109. package/src/core/sleep/INTERFACE-GAPS.md +22 -3
  110. package/src/core/sleep/NOTES.md +11 -0
  111. package/src/core/sleep/prune.ts +6 -2
  112. package/src/core/store/NOTES.md +14 -0
  113. package/src/core/store/index.ts +107 -0
  114. package/src/core/time.ts +152 -0
  115. package/tools/install-loop/run.sh +48 -12
  116. package/src/adapters/dashboard/web/pages/memories/fold.js +0 -53
@@ -58,6 +58,7 @@
58
58
  import { CORE_EMOTIONS } from "../../core/feelings-wheel.js";
59
59
  import { RECALL_MAX_IDS } from "./deliberate.js";
60
60
  import { FACTS_MEANING_CAP, FACTS_PAGE_SIZE } from "./facts.js";
61
+ import { RECURRENCES } from "../../core/time.js";
61
62
 
62
63
  /**
63
64
  * A MEMORY'S TITLE, ASKED FOR AS ONE LINE (2026-09-28, build B). Indexes — the
@@ -316,7 +317,19 @@ const TRAITS_PROPERTY = {
316
317
  const EVENT_DATE_PROPERTY = {
317
318
  type: ["string", "null"],
318
319
  description:
319
- 'Optional: the calendar date this memory is ABOUT, when that is a future date — so it comes back around then (when it already happened, that is occurredOn). Write it yourself, in one of four shapes: a day "2026-10-15", a month "2026-10", a range of two days "2026-10-20..2026-10-31" (that is how to say "late October"), or a year "2026" (a year alone never comes back on its own). Say "before the 15th" as the day or a range ending on it. Leave it out when nothing is dated; a date written only in the text is never read. An unreadable date is refused, and nothing is stored. Revising a dated memory by its id with `updates`: its date and remind carry over unless you send new ones; send null to drop the date (done, cancelled).',
320
+ 'Optional: the calendar date this memory is ABOUT, when that is a future date — so it comes back around then (when it already happened, that is occurredOn). Write it yourself, in one of four shapes: a day "2026-10-15", a month "2026-10", a range of two days "2026-10-20..2026-10-31" (that is how to say "late October"), or a year "2026" (a year alone never comes back on its own). Say "before the 15th" as the day or a range ending on it. Leave it out when nothing is dated; a date written only in the text is never read. An unreadable date is refused, and nothing is stored. Revising a dated memory by its id with `updates`: its date, remind and recurring carry over unless you send new ones; send null to drop the date (done, cancelled).',
321
+ } as const;
322
+
323
+ /**
324
+ * `recurring` beside `eventDate` (2026-10-09, the owner's design, held
325
+ * lightly): how often a DAY comes round, anchored on it, in `meta.recurring`.
326
+ * One sentence on the field, which the host serves whole.
327
+ */
328
+ const RECURRING_PROPERTY = {
329
+ type: ["string", "null"],
330
+ enum: [...RECURRENCES, null],
331
+ description:
332
+ 'Optional, with a day eventDate: "daily", "weekly", "monthly" or "yearly" — it then comes back every time, counted from that day (a birthday: its date, "yearly"); null on a revision stops it repeating.',
320
333
  } as const;
321
334
 
322
335
  /**
@@ -370,9 +383,9 @@ const DATE_PRIVILEGES: readonly Privilege[] = [
370
383
  },
371
384
  {
372
385
  claim:
373
- 'A "plain" reminder is said at most once per beat — on its day, or on the first and the last day of a month or range — and never under observer stance; a "quiet" one is only ever a cue, capped at the footnote tier and spent at most twice per window.',
386
+ 'A "plain" reminder is said at most once per beat — on its day, or on the first and the last day of a month or range — and never under observer stance; a "quiet" one is only ever a cue, capped at the footnote tier and spent at most twice per window. A recurring date counts each time it comes round as its own, and each time it is said or surfaced counts once as a use of the memory; while it repeats, the nightly prune keeps it, and it comes round on its date even when it has faded.',
374
387
  mechanizedBy:
375
- "src/core/prospective/index.ts#Prospective.plainDue + claimPlain (dedupKey latch) + fire (FIRES_PER_WINDOW) -> src/core/counterpart.ts#recallForTurn",
388
+ "src/core/prospective/index.ts#Prospective.plainDue + claimPlain (dedupKey latch) + fire (FIRES_PER_WINDOW) -> src/core/counterpart.ts#recallForTurn; src/core/prospective/windows.ts#recurringWindowAt (one window key per occurrence); Prospective.occurrenceUndelivered -> src/core/counterpart.ts#creditOccurrence (store.reinforce, surfaced) + src/core/physics/index.ts#pruneVerdict (recurring); src/core/prospective/derive.ts#derive (a live repeat is not refused faded)",
376
389
  },
377
390
  {
378
391
  claim:
@@ -395,7 +408,7 @@ const HOW_PROPERTY = {
395
408
  type: "string",
396
409
  enum: ["changed", "corrected", "open"],
397
410
  description:
398
- "With `updates`: how this settles the memory it revises. `changed` (the default): both were true at their time — the old one fades once and is shown as earlier. `corrected`: the old one was wrong — it leaves recall, still readable by its id. `open`: a real disagreement — both stay, each shown with the other. For changed or corrected, say the journey in your own words (\"I used to think X, now Y\").",
411
+ "With `updates`: how this settles the memory it revises. `changed` (the default): both were true at their time — the old one fades once and is shown as earlier. `corrected`: the old one was wrong — it leaves recall, still readable by its id. `open`: a real disagreement — both stay, each shown with the other. For changed or corrected, say the journey in your own words (\"I used to think X, now Y\"). If the memory you name looks unrelated to what you wrote, nothing is settled and you are shown it: settle it yourself if you meant it.",
399
412
  } as const;
400
413
 
401
414
  /** Settling two memories that already exist, on `note` (2026-09-29). */
@@ -421,6 +434,11 @@ const SETTLE_PRIVILEGES: readonly Privilege[] = [
421
434
  "`how` beside `updates` settles the memory it revises — changed (it fades once and is shown as earlier), corrected (archived: out of recall, readable by its id, never deleted), or open (both kept, shown together) — and every settle is recorded (who, how, why, when) and can be undone. A belief, a core memory, a current-state fact and a protected memory keep their own revision path, and the result says so.",
422
435
  mechanizedBy: "src/core/revision.ts#applyRevision -> src/core/contradictions.ts#settleOnWrite",
423
436
  },
437
+ {
438
+ claim:
439
+ "A changed or corrected at a memory that looks unrelated to the new one — not close in meaning, or with no embedder, no content word in common — is held: the new memory is stored unlinked, the old one is left as it was, its title and text come back with the ask to settle it yourself if you meant it, and the hold is recorded. Closing an open thread, moving or dropping a date, and changing a status go straight through.",
440
+ mechanizedBy: "src/core/counterpart.ts#guardUpdate -> src/core/contradictions.ts#updateRelatedness",
441
+ },
424
442
  {
425
443
  claim:
426
444
  "A stored memory comes back with its nearest few existing memories, when any are close, so you can settle one there and then.",
@@ -548,6 +566,7 @@ const NOTE: ToolSpec = {
548
566
  title: { type: "string", description: TITLE_TEXT },
549
567
  eventDate: EVENT_DATE_PROPERTY,
550
568
  remind: REMIND_PROPERTY,
569
+ recurring: RECURRING_PROPERTY,
551
570
  occurredOn: OCCURRED_ON_PROPERTY,
552
571
  saidBy: SAID_BY_PROPERTY,
553
572
  status: STATUS_PROPERTY,
@@ -602,7 +621,7 @@ const RECALL: ToolSpec = {
602
621
  },
603
622
  {
604
623
  claim:
605
- "A time in the question filters: \"last week\", \"in September\", \"early October\", \"3 days ago\", a date, \"since 09-20\", \"this morning\" — only memories inside the window come back, by when the thing happened or, with no event date, when it was learned, and the header counts the matches outside it. A week or a month stretches two days each side; a date stays exact. \"Around the cut-over\" resolves the event to the date of the memory that best names it, shown in the header as \"cut-over → 09-21\"; \"the last session\" or \"where did we leave off\" means the session the session-start \"Last here\" line named, and its own rows come first.",
624
+ "A time in the question filters: \"last week\", \"in September\", \"early October\", \"3 days ago\", \"last Saturday\", a date, \"since 09-20\", \"before 09-20\", \"this morning\" — only memories inside the window come back, by when the thing happened or, with no event date, when it was learned, and the header counts the matches outside it. A week or a month stretches two days each side; a date stays exact; \"before\" a date is every day before it, \"after\" every day after, \"until\" or \"by\" every day through it. \"Around the cut-over\" resolves the event to the date of the memory that best names it, shown in the header as \"cut-over → 09-21\"; \"the last session\" or \"where did we leave off\" means the session the session-start \"Last here\" line named, and its own rows come first.",
606
625
  mechanizedBy: "src/core/recall/time-ask.ts#readTimeAsk + src/adapters/mcp/facts.ts#factsRecall (inWindow, lastSession)",
607
626
  },
608
627
  {
@@ -616,9 +635,9 @@ const RECALL: ToolSpec = {
616
635
  },
617
636
  {
618
637
  claim:
619
- "Meaning mode answers with the arc of what the question names — a person, a project, \"us\", or a feeling: the chapters that hold it, in time order, each with a line of what happened, its moments by id and the feelings in it with whose they are, side by side; then earlier readings (dreams, reflections) and what is still open. It arranges; you say what it adds up to. In a question about feeling, \"I\" and \"me\" mean YOU, the counterpart, and \"you\" means the owner: to ask about the owner's feelings, say \"the owner\" or the owner's name — do not pass the owner's own words through unchanged.",
638
+ "Meaning mode answers with the arc of what the question names — a person, a project, \"us\", or a feeling: the chapters that hold it, in time order, each with a line of what happened, its moments by id and the feelings in it with whose they are, side by side; then earlier readings (dreams, reflections) and what is still open. It arranges; you say what it adds up to. When it names several, the arc follows the one the question asks about (\"what has X been to Y\" is X's; named alike, the first, and it says so), and the rest are listed to ask for by name. In a question about feeling, \"I\" and \"me\" mean YOU, the counterpart, and \"you\" means the owner: to ask about the owner's feelings, say \"the owner\" or the owner's name — do not pass the owner's own words through unchanged.",
620
639
  mechanizedBy:
621
- "src/adapters/mcp/meaning.ts#meaningRecall + src/adapters/mcp/meaning.ts#renderMeaning + src/core/recall/feeling-ask.ts#whoseAsked (asker: self, src/adapters/mcp/server.ts#askQuestion)",
640
+ "src/adapters/mcp/meaning.ts#meaningRecall + src/adapters/mcp/meaning.ts#subjectOf + src/adapters/mcp/meaning.ts#renderMeaning + src/core/recall/feeling-ask.ts#whoseAsked (asker: self, src/adapters/mcp/server.ts#askQuestion)",
622
641
  },
623
642
  {
624
643
  claim:
@@ -905,6 +924,7 @@ const SESSION_END: ToolSpec = {
905
924
  how: HOW_PROPERTY,
906
925
  eventDate: EVENT_DATE_PROPERTY,
907
926
  remind: REMIND_PROPERTY,
927
+ recurring: RECURRING_PROPERTY,
908
928
  occurredOn: OCCURRED_ON_PROPERTY,
909
929
  saidBy: SAID_BY_PROPERTY,
910
930
  status: STATUS_PROPERTY,
@@ -0,0 +1,133 @@
1
+ #!/bin/sh
2
+ # The Claude Code plugin's launcher (prototype, 2026-10-09).
3
+ #
4
+ # sh plugin-run.sh hook - the five hooks (hooks/hooks.json)
5
+ # sh plugin-run.sh mcp - the memory server (.claude-plugin/plugin.json)
6
+ # sh plugin-run.sh cli … - the console, for a plugin user with no
7
+ # `counterparts` on PATH (commands/doctor.md)
8
+ #
9
+ # Claude Code runs this with `sh` and the absolute path, so it needs no exec
10
+ # bit and no runtime of its own. Its one job is the one the npm install does
11
+ # at `install` time and a plugin cannot: FIND A RUNTIME. The install writes the
12
+ # absolute path of the runtime it ran under into the host's configuration
13
+ # (cli/install.ts, scar 2.18: a host's PATH is not the login shell's); a
14
+ # plugin's command is fixed in a file we ship, so the search happens here, at
15
+ # every launch, in this order:
16
+ #
17
+ # 1. COUNTERPARTS_RUNTIME, when set: that executable and nothing else.
18
+ # 2. Bun 1.3+: on PATH, then $BUN_INSTALL/bin, ~/.bun/bin, Homebrew.
19
+ # 3. Node 22.15+: on PATH, then Homebrew, /usr/local, Volta, nvm, fnm, asdf,
20
+ # mise. A Node older than 22.15 is skipped, not run (it cannot load the
21
+ # TypeScript sources: adapters/runtime.ts#NODE_FLOOR).
22
+ #
23
+ # Bun first, because that is what the npm bins do (cli/bin/counterparts.mjs).
24
+ # The entry it runs is the same one those bins run (hook.mjs, serve.mjs,
25
+ # counterparts.mjs), so the runtime choice is the only difference.
26
+ #
27
+ # With no runtime: a hook says so ONCE, at SessionStart, as a systemMessage the
28
+ # person sees (and a line of context, so the model can say it too), and exits 0;
29
+ # every other event exits 0 in silence. The server exits 127 with the reason on
30
+ # stderr, which /mcp shows. Claude Code's own native binary does not double as
31
+ # a JavaScript runtime (BUN_BE_BUN=1 is ignored; measured on 2.1.295).
32
+ #
33
+ # Only shell built-ins and parameter expansion below, plus the runtimes'
34
+ # own --version: a PATH with nothing on it still reaches the message.
35
+
36
+ mode="${1:-}"
37
+ [ $# -gt 0 ] && shift
38
+
39
+ here="${0%/*}"
40
+ [ "$here" = "$0" ] && here="."
41
+
42
+ case "$mode" in
43
+ hook) entry="$here/claude-code/bin/hook.mjs" ;;
44
+ mcp) entry="$here/mcp/bin/serve.mjs" ;;
45
+ cli) entry="$here/cli/bin/counterparts.mjs" ;;
46
+ *)
47
+ echo "counterparts plugin-run: usage: sh plugin-run.sh hook|mcp|cli [args]" >&2
48
+ exit 2
49
+ ;;
50
+ esac
51
+
52
+ runtime=""
53
+
54
+ # version_at_least <version> <major> <minor> (a leading "v" is ignored)
55
+ version_at_least() {
56
+ v="${1#v}"
57
+ major="${v%%.*}"
58
+ rest="${v#*.}"
59
+ minor="${rest%%.*}"
60
+ minor="${minor%%-*}"
61
+ case "$major" in "" | *[!0-9]*) return 1 ;; esac
62
+ case "$minor" in "" | *[!0-9]*) return 1 ;; esac
63
+ [ "$major" -gt "$2" ] && return 0
64
+ [ "$major" -eq "$2" ] && [ "$minor" -ge "$3" ] && return 0
65
+ return 1
66
+ }
67
+
68
+ try_bun() {
69
+ [ -n "$1" ] && [ -x "$1" ] || return 1
70
+ v="$("$1" --version 2>/dev/null)" || return 1
71
+ version_at_least "$v" 1 3 || return 1
72
+ runtime="$1"
73
+ }
74
+
75
+ try_node() {
76
+ [ -n "$1" ] && [ -x "$1" ] || return 1
77
+ v="$("$1" --version 2>/dev/null)" || return 1
78
+ version_at_least "$v" 22 15 || return 1
79
+ runtime="$1"
80
+ }
81
+
82
+ try_node_glob() { # a glob of node binaries: the first that is new enough
83
+ for candidate in "$@"; do
84
+ try_node "$candidate" && return 0
85
+ done
86
+ return 1
87
+ }
88
+
89
+ if [ -n "${COUNTERPARTS_RUNTIME:-}" ]; then
90
+ case "${COUNTERPARTS_RUNTIME##*/}" in
91
+ node*) try_node "$COUNTERPARTS_RUNTIME" ;;
92
+ *) try_bun "$COUNTERPARTS_RUNTIME" ;;
93
+ esac
94
+ else
95
+ try_bun "$(command -v bun 2>/dev/null)" ||
96
+ try_bun "${BUN_INSTALL:-$HOME/.bun}/bin/bun" ||
97
+ try_bun "$HOME/.bun/bin/bun" ||
98
+ try_bun /opt/homebrew/bin/bun ||
99
+ try_bun /usr/local/bin/bun ||
100
+ try_node "$(command -v node 2>/dev/null)" ||
101
+ try_node /opt/homebrew/bin/node ||
102
+ try_node /usr/local/bin/node ||
103
+ try_node /usr/bin/node ||
104
+ try_node "$HOME/.volta/bin/node" ||
105
+ try_node_glob "$HOME"/.nvm/versions/node/v*/bin/node ||
106
+ try_node_glob "$HOME"/.local/share/fnm/node-versions/*/installation/bin/node ||
107
+ try_node_glob "$HOME/Library/Application Support/fnm/node-versions"/*/installation/bin/node ||
108
+ try_node_glob "$HOME"/.asdf/installs/nodejs/*/bin/node ||
109
+ try_node_glob "$HOME"/.local/share/mise/installs/node/*/bin/node
110
+ fi
111
+
112
+ if [ -n "$runtime" ]; then
113
+ exec "$runtime" "$entry" "$@"
114
+ fi
115
+
116
+ said="Counterparts (memory) is not running: it needs Bun 1.3+ or Node.js 22.15+ and found neither on PATH or in the usual places. Install one (https://bun.sh or https://nodejs.org), then restart Claude Code."
117
+
118
+ if [ "$mode" = "hook" ]; then
119
+ payload=""
120
+ while IFS= read -r line || [ -n "$line" ]; do
121
+ payload="$payload$line"
122
+ done
123
+ case "$payload" in
124
+ *'"hook_event_name":"SessionStart"'* | *'"hook_event_name": "SessionStart"'*)
125
+ printf '{"systemMessage":"%s","hookSpecificOutput":{"hookEventName":"SessionStart","additionalContext":"%s"}}\n' \
126
+ "$said" "Counterparts memory is not running in this session (no Bun 1.3+ or Node.js 22.15+ found). If the person asks about memory, tell them that."
127
+ ;;
128
+ esac
129
+ exit 0
130
+ fi
131
+
132
+ echo "$said" >&2
133
+ exit 127
@@ -0,0 +1,329 @@
1
+ /**
2
+ * THE CLAUDE CODE PLUGIN'S SEAM — prototype, 2026-10-09.
3
+ *
4
+ * Counterparts can reach Claude Code two ways now. The npm way: `npm i -g
5
+ * counterparts`, then `counterparts install`, which writes the store and its
6
+ * configuration and wires the host by editing `~/.claude/settings.json` and
7
+ * running `claude mcp add`. The plugin way: Claude Code fetches this
8
+ * repository as a plugin (`.claude-plugin/plugin.json` at its root), runs the
9
+ * five hooks `hooks/hooks.json` names and the MCP server `plugin.json` names,
10
+ * and nothing in the person's settings is edited by us at all.
11
+ *
12
+ * Both launch the SAME entry points (`claude-code/bin/hook.ts`,
13
+ * `mcp/bin/serve.ts`) through `plugin-run.sh`. This file is the few things
14
+ * that differ when the launcher is the plugin's:
15
+ *
16
+ * 1. **Knowing it.** `CLAUDE_PLUGIN_ROOT` is set by Claude Code on the
17
+ * plugin's own hook and server processes, and it is THIS package's root
18
+ * exactly when the plugin is this copy of Counterparts. Equality, not
19
+ * presence: the variable is inherited by children, and a settings-wired
20
+ * hook of a different install must never mistake itself for the plugin.
21
+ * 2. **Not firing twice.** A person with the npm wiring AND the plugin gets
22
+ * every hook twice (Claude Code merges hooks from settings and plugins
23
+ * and runs them all) and two memory servers (plugin servers are deduped
24
+ * only by identical command). The npm installs already out there cannot
25
+ * learn about the plugin, so the rule has to live on THIS side: **the
26
+ * plugin stands down wherever the npm wiring is live** — hooks for
27
+ * hooks, the server for the server — and says once, at session start,
28
+ * how to move (`counterparts disconnect`). Same store either way, so
29
+ * moving loses nothing.
30
+ * 3. **First run without a terminal.** The npm way creates the store and
31
+ * `~/.counterparts/claude-code.json` at `install`. A plugin has no
32
+ * install step we run, so the first hook or server to start runs that
33
+ * same `install` (non-interactive, `--no-connect`: it writes OUR two
34
+ * things and touches no host file), under a lock so the hook and the
35
+ * server racing at session start produce one install, not two. The
36
+ * layout is therefore exactly the npm one, which is what makes moving
37
+ * between the two a non-event.
38
+ */
39
+ import { spawnSync } from "node:child_process";
40
+ import { createHash } from "node:crypto";
41
+ import { existsSync, mkdirSync, readdirSync, realpathSync, rmdirSync, statSync } from "node:fs";
42
+ import { tmpdir } from "node:os";
43
+ import { basename, dirname, join, resolve } from "node:path";
44
+ import { fileURLToPath } from "node:url";
45
+
46
+ import { implicitConfigRefusal } from "./config-path.js";
47
+ import type { ConfigChoice } from "./config-path.js";
48
+ import type { NpmWiring } from "./host-wiring.js";
49
+ import { CLI_SCRIPT, scriptArgs } from "./runtime.js";
50
+
51
+ /** Set by Claude Code on a plugin's hook, MCP and LSP processes. */
52
+ export const PLUGIN_ROOT_ENV = "CLAUDE_PLUGIN_ROOT";
53
+ /**
54
+ * The plugin's persistent directory — and the memory is deliberately NOT in
55
+ * it. Claude Code deletes `~/.claude/plugins/data/<id>/` when the plugin is
56
+ * uninstalled from its last scope (unless `--keep-data`), and a memory that an
57
+ * uninstall erases is not one anybody agreed to. The store stays where the
58
+ * npm install puts it, `~/.counterparts/store`, which is also what lets a
59
+ * person move between the two installs without moving anything.
60
+ */
61
+ export const PLUGIN_DATA_ENV = "CLAUDE_PLUGIN_DATA";
62
+
63
+ /** This package's root — the directory holding `package.json` and, in this
64
+ * repository, `.claude-plugin/`. */
65
+ export const PACKAGE_ROOT = fileURLToPath(new URL("../../", import.meta.url));
66
+
67
+ function realOrResolved(path: string): string {
68
+ try {
69
+ return realpathSync(path);
70
+ } catch {
71
+ return resolve(path);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Is this process the plugin's? True when Claude Code's `CLAUDE_PLUGIN_ROOT`
77
+ * names this very package. Both sides are realpath'd: macOS spells one
78
+ * directory `/var/…` and `/private/var/…`, and a plugin added from a symlinked
79
+ * checkout is the same plugin.
80
+ */
81
+ export function runningAsPlugin(
82
+ env: Record<string, string | undefined>,
83
+ packageRoot: string = PACKAGE_ROOT,
84
+ ): boolean {
85
+ const named = (env[PLUGIN_ROOT_ENV] ?? "").trim();
86
+ if (named.length === 0) return false;
87
+ return realOrResolved(named) === realOrResolved(packageRoot);
88
+ }
89
+
90
+ /** `~/…` for a path under the home directory, for a line a person reads. */
91
+ function tildeOf(path: string, home: string): string {
92
+ const h = resolve(home);
93
+ const p = resolve(path);
94
+ return p === h ? "~" : p.startsWith(`${h}/`) ? `~${p.slice(h.length)}` : p;
95
+ }
96
+
97
+ /** What the plugin's hook does about the npm wiring, and what it says. */
98
+ export interface PluginGate {
99
+ readonly standDown: boolean;
100
+ /** One line for the owner at session start, or null. */
101
+ readonly line: string | null;
102
+ }
103
+
104
+ /**
105
+ * THE HOOKS' RULE: live npm hooks win. A DEAD npm entry (its runtime or script
106
+ * gone — an uninstalled package, a deleted checkout) runs nothing, so the
107
+ * plugin carries on and says the stale lines are there.
108
+ */
109
+ export function hookGate(wiring: NpmWiring, home: string): PluginGate {
110
+ const live = wiring.hooks.find((h) => h.live);
111
+ if (live !== undefined) {
112
+ return {
113
+ standDown: true,
114
+ line:
115
+ `Counterparts is installed twice: the npm install's hooks in ${tildeOf(live.file, home)} and this plugin. ` +
116
+ "The plugin is standing down so nothing is captured twice. To keep only the plugin, run " +
117
+ "`counterparts disconnect` and restart Claude Code; the memory is the same either way.",
118
+ };
119
+ }
120
+ const dead = wiring.hooks[0];
121
+ if (dead !== undefined) {
122
+ return {
123
+ standDown: false,
124
+ line:
125
+ `Counterparts: ${tildeOf(dead.file, home)} still names an old Counterparts hook that no longer runs. ` +
126
+ "The plugin is keeping your memory; remove those entries to quiet them.",
127
+ };
128
+ }
129
+ return { standDown: false, line: null };
130
+ }
131
+
132
+ /**
133
+ * THE SERVER'S RULE: a live `counterparts` registration in the user or local
134
+ * scope wins. The words become the stood-down server's `instructions`, which
135
+ * is the only thing a model sees of a server with no tools.
136
+ */
137
+ export function mcpGate(wiring: NpmWiring, home: string): { readonly standDown: boolean; readonly instructions: string | null } {
138
+ const live = wiring.mcp.find((m) => m.live);
139
+ if (live === undefined) return { standDown: false, instructions: null };
140
+ return {
141
+ standDown: true,
142
+ instructions:
143
+ `This plugin's Counterparts server is standing down: the npm install already registers a ` +
144
+ `"counterparts" memory server (${live.scope} scope, ${tildeOf(live.file, home)}), and two servers ` +
145
+ "over one memory would offer every tool twice. Use that server's tools. To use the plugin's " +
146
+ "instead, run `counterparts disconnect` and restart Claude Code.",
147
+ };
148
+ }
149
+
150
+ // ── first run ───────────────────────────────────────────────────────────────
151
+
152
+ /**
153
+ * `joined`: absent when this process looked, made by a CONCURRENT first run
154
+ * (the hook and the server start together) while this one waited. It is still
155
+ * this session's first run, so it carries the same line as `created`.
156
+ */
157
+ export type FirstRunState = "existed" | "created" | "joined" | "skipped" | "failed";
158
+
159
+ export interface FirstRun {
160
+ readonly state: FirstRunState;
161
+ /** One line for the owner at session start, or null when there is nothing
162
+ * to say (an existing install, a skipped one). */
163
+ readonly line: string | null;
164
+ /** Why it failed or was skipped, for stderr. */
165
+ readonly detail?: string;
166
+ }
167
+
168
+ /** How long a waiting process gives the one holding the lock. An install is a
169
+ * directory, an empty database and a small JSON file: well under a second on
170
+ * the machines measured, so twenty is generous and still inside Claude
171
+ * Code's thirty-second MCP start-up window. */
172
+ export const FIRST_RUN_WAIT_MS = 20_000;
173
+ /** A lock older than this is a process that died holding it. */
174
+ export const FIRST_RUN_STALE_MS = 120_000;
175
+ /** The install's own ceiling, as a child process. */
176
+ export const FIRST_RUN_TIMEOUT_MS = 60_000;
177
+
178
+ /**
179
+ * Where the lock lives: the system temp directory, keyed by the configuration
180
+ * path — never inside `~/.counterparts`, where a leftover lock directory would
181
+ * be one more entry for `doctor` and `start-fresh` to have an opinion about.
182
+ */
183
+ export function firstRunLockPath(configPath: string, tmp: string = tmpdir()): string {
184
+ const key = createHash("sha256").update(resolve(configPath)).digest("hex").slice(0, 16);
185
+ return join(tmp, `counterparts-first-run-${key}.lock`);
186
+ }
187
+
188
+ /**
189
+ * A MEMORY SET ASIDE BESIDE THE ONE ABOUT TO BE MADE (review of #328).
190
+ * `counterparts uninstall --park` leaves `<base>.parked-<date>[-N]` next to
191
+ * where the configuration lives (`cli/install.ts#parkedNameParts`, which also
192
+ * checks the date is a real day; the shape is enough here). A non-interactive
193
+ * install walks past one and makes a blank store beside it, and says so on
194
+ * stdout (review M4: "a second store the person does not know about") — but
195
+ * the first run drops that stdout, so the line it hands the wake has to say it
196
+ * instead. Named only: nothing here opens, moves or counts it.
197
+ */
198
+ export function parkedBeside(base: string): string[] {
199
+ const dir = dirname(resolve(base));
200
+ const prefix = `${basename(resolve(base))}.parked-`;
201
+ try {
202
+ return readdirSync(dir)
203
+ .filter((n) => n.startsWith(prefix) && /^\d{4}-\d{2}-\d{2}(-\d+)?$/.test(n.slice(prefix.length)))
204
+ .sort()
205
+ .map((n) => join(dir, n));
206
+ } catch {
207
+ return [];
208
+ }
209
+ }
210
+
211
+ function sleepSync(ms: number): void {
212
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
213
+ }
214
+
215
+ export interface FirstRunInput {
216
+ readonly choice: ConfigChoice;
217
+ readonly env: Record<string, string | undefined>;
218
+ readonly home: string;
219
+ /** The runtime that runs the console: this process's own, by default. */
220
+ readonly runtime?: string;
221
+ readonly cliScript?: string;
222
+ readonly lockPath?: string;
223
+ readonly waitMs?: number;
224
+ readonly staleMs?: number;
225
+ readonly now?: () => number;
226
+ }
227
+
228
+ /**
229
+ * Make sure the store and the default configuration exist, the way
230
+ * `counterparts install` makes them — by running it.
231
+ *
232
+ * SKIPPED, and nothing written, when a configuration was NAMED (`--config`,
233
+ * `COUNTERPARTS_CONFIG`: somebody chose a file, and a missing one is that
234
+ * entry point's refusal to make) or when the explicit-dir guard is armed (it
235
+ * refuses the implicit default by design; `config-path.ts#implicitConfigRefusal`).
236
+ *
237
+ * The console is SPAWNED rather than imported: adapters do not import each
238
+ * other, and the console is the one place that knows how an install is made
239
+ * ("invent no second install path"). Its output is captured and dropped — a
240
+ * hook's stdout is the model's context, and a server's is the JSON-RPC wire.
241
+ */
242
+ export function ensureFirstRun(input: FirstRunInput): FirstRun {
243
+ const { choice, env } = input;
244
+ if (choice.source !== "default") return { state: "skipped", line: null, detail: `configuration named by ${choice.source}` };
245
+ if (existsSync(choice.path)) return { state: "existed", line: null };
246
+ const guard = implicitConfigRefusal(choice, env);
247
+ if (guard !== null) return { state: "skipped", line: null, detail: guard };
248
+
249
+ const now = input.now ?? ((): number => Date.now());
250
+ const lock = input.lockPath ?? firstRunLockPath(choice.path);
251
+ const waitMs = input.waitMs ?? FIRST_RUN_WAIT_MS;
252
+ const staleMs = input.staleMs ?? FIRST_RUN_STALE_MS;
253
+ const base = dirname(choice.path);
254
+ const parked = parkedBeside(base);
255
+ const created: FirstRun = {
256
+ state: "created",
257
+ line:
258
+ `Counterparts: first run — a new memory was set up at ${tildeOf(base, input.home)}. ` +
259
+ "It stays on this computer." +
260
+ (parked.length === 0
261
+ ? ""
262
+ : ` A memory set aside earlier is still at ${parked.map((p) => tildeOf(p, input.home)).join(", ")}, untouched; ` +
263
+ "the new one does not include it."),
264
+ };
265
+
266
+ const take = (): boolean => {
267
+ try {
268
+ mkdirSync(lock);
269
+ return true;
270
+ } catch (err) {
271
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
272
+ return false;
273
+ }
274
+ };
275
+
276
+ let held = take();
277
+ if (!held) {
278
+ // Somebody else is installing. Wait for the configuration to appear; a
279
+ // lock older than `staleMs` is a dead process's, and is taken over once.
280
+ const until = now() + waitMs;
281
+ while (!held) {
282
+ if (existsSync(choice.path)) return { ...created, state: "joined" };
283
+ let age = 0;
284
+ try {
285
+ age = now() - statSync(lock).mtimeMs;
286
+ } catch {
287
+ age = 0;
288
+ }
289
+ if (age > staleMs) {
290
+ try {
291
+ rmdirSync(lock);
292
+ } catch {
293
+ // Gone already, or not ours to remove; `take` below decides.
294
+ }
295
+ }
296
+ held = take();
297
+ if (held) break;
298
+ if (now() >= until) {
299
+ return { state: "failed", line: null, detail: `timed out after ${String(waitMs)} ms waiting for another first run (${lock})` };
300
+ }
301
+ sleepSync(100);
302
+ }
303
+ }
304
+ try {
305
+ // The one who waited may find it done the moment it gets the lock.
306
+ if (existsSync(choice.path)) return { ...created, state: "joined" };
307
+ const runtime = input.runtime ?? process.execPath;
308
+ const script = input.cliScript ?? CLI_SCRIPT;
309
+ const res = spawnSync(runtime, [...scriptArgs(script, runtime), "install", "--no-connect"], {
310
+ env: env as NodeJS.ProcessEnv,
311
+ encoding: "utf8",
312
+ timeout: FIRST_RUN_TIMEOUT_MS,
313
+ stdio: ["ignore", "pipe", "pipe"],
314
+ });
315
+ if (res.status === 0 && existsSync(choice.path)) return created;
316
+ const why = (String(res.stderr ?? "").trim().split("\n").pop() ?? "") || (res.error?.message ?? `exit ${String(res.status)}`);
317
+ return {
318
+ state: "failed",
319
+ line: `Counterparts could not set up its memory on first run (${why.slice(0, 200)}). Memory is off for this session.`,
320
+ detail: why,
321
+ };
322
+ } finally {
323
+ try {
324
+ rmdirSync(lock);
325
+ } catch {
326
+ // Already gone: nothing to release.
327
+ }
328
+ }
329
+ }
@@ -125,7 +125,8 @@ for `recall/`; telemetry by reference.
125
125
  writers) · **E7** (observers train nothing) · **E8** (base-level decay on lived days) ·
126
126
  **§2.1** (multi-writer structured state needs a transaction) · **§2.2** (a removed id must
127
127
  stop conducting; supersede retargets edges too — v1's `gist.merge` set `merged_into` and
128
- nothing re-pointed the edges, so successors started cold) · **§2.4** (no success telemetry
128
+ nothing re-pointed the edges, so successors started cold. So do a dream merge and, since
129
+ 2026-10-09, a regrown chapter copy, NOTES §15) · **§2.4** (no success telemetry
129
130
  for a publish that did not land) · **§2.8** (credit weights ship measured or disabled) ·
130
131
  **§2.17** (edges have an exit path — eviction — and its count is reported).
131
132
 
@@ -123,6 +123,10 @@ counts and ids sitting in `sessions/association/claims/`.
123
123
  ## 4. Nobody calls `retargetOnSupersede` — supersede does not know about edges
124
124
 
125
125
  **Closed 2026-09-24** — `counterpart.ts` injects `retargetOnSupersede` into both `supersede` callers (`Schemas.open`'s `retarget`, and `applyRevision` in `core/revision.ts`).
126
+ The same callback reaches a dream merge (`Dreams`' `retarget`, 2026-09-26) and, since
127
+ 2026-10-09, a regrown chapter copy (`Self`'s `retarget`; the copies archived before then
128
+ are carried once at open, NOTES §15). A bare `Store.supersede` or `Store.archive` still
129
+ carries nothing.
126
130
 
127
131
  **Owner:** `store/` and whoever owns revision (scar §2.2: "supersede retargets edges
128
132
  too — v1's `gist.merge` set `merged_into` and nothing re-pointed the edges, so
@@ -241,7 +245,8 @@ be its own design.
241
245
 
242
246
  ## 12. A dream's lookups never reach the credit pass (noted 2026-09-28)
243
247
 
244
- **Owner:** the Claude Code adapter (`transcript.ts`, `hooks.ts#creditAtBoundary`).
248
+ **Owner:** the Claude Code adapter (`transcript.ts`, `hooks.ts#creditAtBoundary` — in
249
+ `adapters/lifecycle.ts` since #292, 2026-09-30).
245
250
  **Have:** index co-credit works where the lookups are in the session's own transcript:
246
251
  the hook flattens every `recall ids:[…]` batch in a reply's slice into the credit pass's
247
252
  expansions (tested, `association-build2.test.ts` › "5."). **Gap:** the nightly run —
@@ -411,3 +411,48 @@ referenced × surfaced pair conducts on its first meeting — "shown beside" lin
411
411
  accumulate across boundaries; the credit pass passes no surfaced member in any case, and
412
412
  one loud slot a turn means surfaced × surfaced cannot occur in one reply. The fixture
413
413
  contract §4 asks for is `association-build2.test.ts` › "6.".
414
+
415
+ ## 15. Regrown chapter copies carry their links (2026-10-09)
416
+
417
+ The association diagnosis of 10-02 (measured on a copy of the owner's store) found 324
418
+ of 1,200 edge rows with an archived endpoint: 260 on chapter copies archived
419
+ `episode-regrown`, 54 on dream-merge originals, 10 on corrected memories. Read against the
420
+ code:
421
+
422
+ - **Regrown copies were the gap.** `Self#ingestEpisode` mints a new copy when its chapter
423
+ grows and archives the old one, and nothing handed the old copy's links on. Now `Self`
424
+ takes a `retarget` callback (SEAMS E, the way `schemas/` and `dream/` do; `self/` may
425
+ not import this module) and calls it per archived copy, after the archive, so one stale
426
+ copy's tie to another is not carried. The composition root wires it to
427
+ `retargetOnSupersede`, the merge rule unchanged: the old copy's live outgoing weights as
428
+ they stand on the day, `max` with what the new copy has, both directions, capped. A
429
+ throw costs the links, never the copy (`self.episode.relink.failed`).
430
+ - **Dream merges and corrections were not.** Both already go through
431
+ `retargetOnSupersede` (`dream/index.ts`, `revision.ts`). Their 64 rows are the
432
+ originals' own, left in place by design (this module has no delete); the merged or
433
+ corrected memory holds the carried copies.
434
+ - **The links already stranded are carried once.** `Counterpart#relinkRegrownCopies` runs
435
+ at open, latched in meta (`REGROWN_RELINK_META`) like the v12 subject backfill: it reads
436
+ the edge table (not the store), finds each source archived `episode-regrown`, and hands
437
+ its links to the chapter's live copy (`origin_ref`), or counts it `noLiveCopy` when the
438
+ chapter has none. A link that has faded below the floor since carries nothing. Writer
439
+ only; fail-open, tried again next open; idempotent if cut short. A carry whose write
440
+ failed (the edge module answers `failed` rather than throwing) leaves the pass
441
+ unlatched, so a store that keeps failing re-reads its edge table at every open until
442
+ one pass lands, as the v12 backfill would.
443
+ - *Review of #329.* A copy a removal has taken dark (its edge rows still waiting for the
444
+ chase) carries nothing and is counted `removed`: its links must not outlive the chase on
445
+ the live copy. The live copies come from one `store.copiesOf` read, not a
446
+ `list({ originRef })` per chapter (`origin_ref` has no index). Measured on synthetic
447
+ stores at open: about 800 memories and 1,800 edge rows (130 pairs stranded), the pass
448
+ went from 120–340 ms to about 50 ms; about 15,000 memories and 12,000 edge rows, from
449
+ 2.8–3.4 s to about 0.3 s. Most of what is left is one `linkMany` per copy. Every later
450
+ open pays one meta read.
451
+ - *Known limits, the merge rule's own:* only the old copy's outgoing rows are read, so a
452
+ row written one way into it would not carry (co-use, contiguity and a dream's links all
453
+ write both ways today), and contiguity's forward-over-back difference becomes the
454
+ stronger outgoing weight both ways. The carry writes through `linkMany`, not the flush,
455
+ so the per-node cap applies at the next flush that touches the copy, not at the carry.
456
+ The archived copy's rows stay until they decay to the floor and a flush sweeps them, so
457
+ a re-run of the 10-02 count will still find them for a while; count what the live copy
458
+ holds, not what the archived one still has.