opencode-self-improvement 0.14.12 → 0.14.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,7 +34,7 @@ After that, memory is just conversation: ask the agent to remember something and
34
34
 
35
35
  - **`memory_*` tools** — `memory_init`, `memory_remember`, `memory_recall`, `memory_update`, `memory_forget`, `memory_list`, `memory_undo`, `memory_status`, `memory_evidence`, `memory_export`, `memory_import`, `memory_decay`, `memory_consolidate`, `memory_merge_review`.
36
36
  - **`/repo-init`** — per-repo setup: code graph index plus build/test commands, keyed to the git head.
37
- - **Write gates** — code references are verified against your actual repo, near-duplicates are collapsed, contradictions with superseded memories are rejected. Blocked writes are logged with a reason in `memory_evidence`.
37
+ - **Write gates** — code references are verified against your actual repo, near-duplicates are collapsed, contradictions with superseded memories are rejected. Blocked writes are logged with a reason in `memory_evidence`, which reads one real calendar day inside `evidence/` at a time — its `date` is a date, never a path.
38
38
  - **Memory-aware compaction** — durable memories are handed to the compaction summarizer, so a long session keeps its facts.
39
39
  - **Auto-capture (opt-in)** — on the idle and compaction triggers, one cheap model pass per trigger proposes candidates, which face the same write gates; a 5-minute cooldown per session and trigger bounds the spend ([per-trigger numbers](bench/capture-trigger-results.md)). Off by default.
40
40
  - **Repo scoping** — rows belong to the repo that wrote them; project A's facts never surface in project B.
@@ -95,7 +95,7 @@ Nothing is deleted: `memory_update` supersedes the previous row, `memory_forget`
95
95
 
96
96
  Rows are stamped with your git origin (an id that survives re-clones and moves between machines) or, without an origin, a hash of the normalized directory path. `repoPath` keeps the human-readable path, so rows written before hashing keep matching.
97
97
 
98
- Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything". Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global, and the viewer (an admin surface over every repo) edits and restores a row with its own repo stamp — the viewer's missing session scope never decides a row's visibility. Upgrading changes nothing.
98
+ Injection, recall, the frontier block, compaction, `memory_forget` and decay only see the current repo plus global rows, resolved from the calling session's identity at flow entry. A session that reaches a plugin instance is bound to that instance's own workspace on first contact — in a process hosting several workspaces, one session never borrows the repository some other workspace's setup left behind. A session whose repository cannot be resolved at all sees global rows only; "unknown" is never "everything". Writes follow that rule in the stricter direction: a named session with no resolved repository has **no write target**, so `memory_remember`, `memory_update`, `memory_import` and auto-capture refuse it (evidence `write_refused`) and store nothing — the alternatives were stamping your private content into whichever workspace's `setup()` ran last, or publishing it to every project as an unstamped row. A caller that names no session at all (the viewer process, a restore, a script) keeps the process scope, and an explicit `global: true` is a deliberate owner. Evidence lines carry the same stamp, so `memory_evidence` answers from the caller's repo plus global lines; a line a named session wrote while its repository was unresolvable is private to that session, and only an explicitly global (or predating-stamps) line reads as global. Preferences that should follow you everywhere go in with `memory_remember global: true`. Rows written before scoping existed are global, and the viewer (an admin surface over every repo) edits and restores a row with its own repo stamp — the viewer's missing session scope never decides a row's visibility. `memory_merge_review` applies the same rule to its inputs: a session may merge exactly the rows it may read — global rows plus its own repo's, from either seat — and a row id it merely knows is not authority to retire another repo's memory. Upgrading changes nothing.
99
99
 
100
100
  ## Token cost and caching
101
101
 
@@ -185,7 +185,7 @@ On the eval dataset the pass takes 200 rows to 52 with **R@3 52 → 53 and R@1 5
185
185
 
186
186
  ## Secret redaction
187
187
 
188
- One best-effort credential rule set (`src/secrets.ts`) runs over the auto-capture prompt before it leaves the plugin, at the write gate before content is hashed or analysed, again in the final write choke point used by gated writes and the viewer's edit and restore paths, and at the durable audit boundaries — every evidence line, every supersede field written into a retired row, and every deletion-audit reason — so a recognized credential cannot persist in `evidence/` or `deletions.logfmt` or a tombstoned row regardless of which path carried it.
188
+ One best-effort credential rule set (`src/secrets.ts`) runs over the auto-capture prompt before it leaves the plugin — redacting the complete transcript before the character budget crops it, so a credential cut in half by the window still matches its pattern — at the write gate before content is hashed or analysed, again in the final write choke point used by gated writes and the viewer's edit and restore paths, and at the durable audit boundaries — every evidence line, every supersede field written into a retired row, and every deletion-audit reason — so a recognized credential cannot persist in `evidence/` or `deletions.logfmt` or a tombstoned row regardless of which path carried it.
189
189
 
190
190
  Covered: OpenAI `sk-`, GitHub `ghp_` / `gho_` / `github_pat_`, Slack `xoxb-` / `xoxp-`, AWS `AKIA`, Google `AIza`, bearer tokens containing digits, PEM private-key blocks, and high-entropy values assigned to names ending in `_KEY`, `_TOKEN`, `_SECRET` or `_PASSWORD` (plus `password`).
191
191
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.14.12",
3
+ "version": "0.14.14",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
package/src/evidence.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  // Evidence log writer. One logfmt line per event, appended in hook order to
2
2
  // ~/.config/opencode/memory/evidence/<date>.logfmt. Evidence is DATA: never
3
3
  // injected into chat, and stored outside every repo.
4
- import { join } from "node:path";
4
+ import { existsSync, realpathSync } from "node:fs";
5
+ import { dirname, join, resolve } from "node:path";
5
6
  import { createHash } from "node:crypto";
6
7
  import { dateStr, evidenceDir } from "./config.ts";
7
8
  import { appendLog, formatLine } from "./logfmt.ts";
@@ -11,6 +12,36 @@ import { redactSecrets } from "./secrets.ts";
11
12
 
12
13
  export type EvidenceEvent = string;
13
14
 
15
+ // The ONLY path memory_evidence may read (#130): a real calendar date in
16
+ // YYYY-MM-DD form, resolved INSIDE the evidence directory. The schema layer
17
+ // already refuses non-date strings at the boundary; this is the second door —
18
+ // impossible dates (2026-02-30, which Date would silently roll over) and
19
+ // symlinked day files must not hand out files outside the evidence dir.
20
+ // Returns null when the read must be refused; the forced .logfmt suffix is
21
+ // the primitive's residual bound either way.
22
+ export function evidenceFileFor(date?: string): string | null {
23
+ const d = date ?? dateStr();
24
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(d);
25
+ if (!m) return null;
26
+ const [y, mo, day] = [Number(m[1]), Number(m[2]), Number(m[3])];
27
+ const probe = new Date(Date.UTC(y, mo - 1, day));
28
+ if (probe.getUTCFullYear() !== y || probe.getUTCMonth() !== mo - 1 || probe.getUTCDate() !== day) {
29
+ return null;
30
+ }
31
+ const dir = resolve(evidenceDir());
32
+ const file = resolve(dir, `${d}.logfmt`);
33
+ if (dirname(file) !== dir) return null; // containment, defense in depth
34
+ if (existsSync(file)) {
35
+ // A day file symlinked out of the store still has to land inside it.
36
+ try {
37
+ if (realpathSync(file) !== join(realpathSync(dir), `${d}.logfmt`)) return null;
38
+ } catch {
39
+ return null; // an unreadable link is not a file we will follow
40
+ }
41
+ }
42
+ return file;
43
+ }
44
+
14
45
  // Credential scrub at the evidence WRITE boundary. Evidence fields routinely
15
46
  // carry caller-authored prose (gate reasons, block reasons, review notes) and
16
47
  // tool-derived summaries; a recognized credential must not persist in the
package/src/index.ts CHANGED
@@ -12,7 +12,7 @@
12
12
  // helper modules.
13
13
  import type { Cleanup, Plugin } from "@opencode/plugin/promise/plugin";
14
14
  import { basename, join } from "node:path";
15
- import { evidenceDir, frontierBudget, injectBudget, memoryRoot, dateStr } from "./config.ts";
15
+ import { frontierBudget, injectBudget, memoryRoot } from "./config.ts";
16
16
  import { STATUSES, TYPES } from "./types.ts";
17
17
  import {
18
18
  clearSuperseded,
@@ -27,6 +27,7 @@ import {
27
27
  readerFromSid,
28
28
  resolveMemoryTarget,
29
29
  snapshotFiles,
30
+ unresolvedWriteMessage,
30
31
  visibleTo,
31
32
  type Memory,
32
33
  } from "./memory.ts";
@@ -36,7 +37,7 @@ import { pruneMemory } from "./prune.ts";
36
37
  import { exportMemories, findStaleOpen, importMemories } from "./portable.ts";
37
38
  import { listSnapshots, restoreSnapshot } from "./undo.ts";
38
39
  import { SESSION_CAP, SessionLru } from "./sessions.ts";
39
- import { record, recordCaptureLag } from "./evidence.ts";
40
+ import { evidenceFileFor, record, recordCaptureLag } from "./evidence.ts";
40
41
  import { proposeConsolidations, renderProposals } from "./consolidate.ts";
41
42
  import { readReads } from "./hits.ts";
42
43
  import {
@@ -81,7 +82,7 @@ import {
81
82
  onCompacting,
82
83
  } from "./triggers.ts";
83
84
  import { getCurrent, setCurrent } from "./state.ts";
84
- import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional } from "./repokey.ts";
85
+ import { resolveRepo, setRepoScope, rememberSessionDir, sessionDir, sessionDirFirm, bindSessionProvisional, writeTarget } from "./repokey.ts";
85
86
  import { parseLine, readLines } from "./logfmt.ts";
86
87
  import { buildCapturePrompt, flattenTranscript, lagSince, parseCandidates, parseModelRef } from "./capture.ts";
87
88
  import { redactSecrets } from "./secrets.ts";
@@ -343,6 +344,24 @@ const impl = {
343
344
  };
344
345
  };
345
346
 
347
+ // A durable write needs an OWNER (#152). Reads already fail closed for a
348
+ // session whose repository never resolved — it sees global rows and nothing
349
+ // else — so such a session may not write either: the alternatives were the
350
+ // last setup's repository or an unstamped (hence global) row. This answers
351
+ // at the entry, where the model can be told what to do, and records the
352
+ // refusal so "why is nothing stored" is answerable from memory_evidence.
353
+ // appendMemory throws the same rule at the choke point; the two share one
354
+ // message so they cannot drift.
355
+ const ownerlessWriter = (sid: string | undefined): string | null => {
356
+ const target = writeTarget(sid);
357
+ return target.ok ? null : target.sid;
358
+ };
359
+
360
+ const refuseOwnerlessWrite = async (sid: string, op: string): Promise<{ content: string }> => {
361
+ await record("write_refused", { op }, true, sid);
362
+ return { content: unresolvedWriteMessage(sid) };
363
+ };
364
+
346
365
  // Identity of a tool call, captured SYNCHRONOUSLY at the tool's entry —
347
366
  // the first await of the call comes after this. The V2 host hands every
348
367
  // execute a per-call ToolContext carrying sessionID; the harness and any
@@ -457,6 +476,12 @@ const impl = {
457
476
  repo: args.global ? "global" : undefined,
458
477
  };
459
478
  await bindSessionIdentity(sid);
479
+ // An explicit global write needs no repository owner; anything else
480
+ // does (#152).
481
+ if (!args.global) {
482
+ const ownerless = ownerlessWriter(sid);
483
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "remember");
484
+ }
460
485
  const outcome = await runWriteGate(candidate, gateContext(sid));
461
486
  if (outcome.action === "promoted") return { content: `Remembered: ${args.type} in ${args.scope}` };
462
487
  if (outcome.action === "collapsed") return { content: `Duplicate ignored: ${args.type}/${args.scope}` };
@@ -503,6 +528,8 @@ const impl = {
503
528
  async execute(args, context): Promise<{ content: string }> {
504
529
  const { sid } = toolIds(context);
505
530
  await bindSessionIdentity(sid);
531
+ const ownerless = ownerlessWriter(sid);
532
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "init");
506
533
  const summary = await runInit({
507
534
  liveRoot: gateContext(sid).liveRoot,
508
535
  force: args.force,
@@ -563,6 +590,8 @@ const impl = {
563
590
  async execute(args, context): Promise<{ content: string }> {
564
591
  const { sid } = toolIds(context);
565
592
  await bindSessionIdentity(sid);
593
+ const ownerless = ownerlessWriter(sid);
594
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "update");
566
595
  const reader = readerFromSid(sid);
567
596
  // The whole update — resolve, gate, supersede — runs under one
568
597
  // UPDATE-ORDER lock. Without it, two concurrent updates that both
@@ -717,7 +746,16 @@ const impl = {
717
746
  async execute(args, context): Promise<{ content: string }> {
718
747
  const { sid } = toolIds(context);
719
748
  const reader = readerFromSid(sid);
720
- const file = join(evidenceDir(), `${args.date || dateStr()}.logfmt`);
749
+ // #130: the ONE path the schema-validated date can resolve to —
750
+ // a real calendar day inside the evidence dir, never a traversal
751
+ // into the raw store or the filesystem beyond it.
752
+ const file = evidenceFileFor(args.date);
753
+ if (!file) {
754
+ return {
755
+ content:
756
+ "memory_evidence blocked: date must be a real YYYY-MM-DD calendar date — nothing was read.",
757
+ };
758
+ }
721
759
  let lines = await readLines(file);
722
760
  // Data partitions too (#131's ownership rule, applied to evidence):
723
761
  // a line stamped to another repository is not this session's data,
@@ -740,54 +778,126 @@ const impl = {
740
778
  editor.add(validated(MergeReviewArgs, {
741
779
  name: "memory_merge_review",
742
780
  description:
743
- "Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. Fails closed (no partial apply) when the reason or the survivor id is missing, the survivor id names no row in the store, or the loser is already superseded or is the survivor itself.",
781
+ "Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. A session may merge exactly the rows it may read: global rows are mergeable from anywhere, but a row belonging to another repository is refused in either seat. Fails closed (no partial apply) when the reason or the survivor id is missing, the survivor id names no row in the store, the loser is already superseded or is the survivor itself, or either seat names a foreign repository's row.",
744
782
  options: direct,
745
- async execute(args): Promise<{ content: string }> {
783
+ async execute(args, context): Promise<{ content: string }> {
784
+ const { sid } = toolIds(context);
746
785
  if (!args.loser || !args.survivor || !args.reason) {
747
786
  return { content: "merge_review blocked: loser, survivor, and reason are all required (fail-closed)." };
748
787
  }
749
- // Probed: marking with a survivor id that names no row retired the
750
- // loser toward a pointer to nothing (the scope ended with zero
751
- // active rows) while the response declared it canonical. Validate
752
- // BEFORE touching the loser — a resolution must never retire real
753
- // data for a phantom. (Same-row input would mark and then revive
754
- // the same row: a silent no-op that reports full success.)
755
788
  if (args.loser === args.survivor) {
789
+ // (Same-row input would mark and then revive the same row: a
790
+ // silent no-op that reports full success.)
756
791
  return { content: "merge_review blocked: loser and survivor are the same row — nothing to resolve. No evidence written." };
757
792
  }
758
- if (!(await loadAll()).some((m) => m.ts === args.survivor)) {
759
- return { content: `merge_review blocked: survivor ${args.survivor} does not exist in the store — nothing to resolve. No evidence written.` };
760
- }
761
- const ok = await markSuperseded(args.loser, {
762
- superseded_by: args.survivor,
763
- reason: args.reason,
764
- symbol: args.loser,
765
- from: args.loser,
766
- to: args.survivor,
767
- });
768
- if (!ok) {
769
- return { content: "merge_review: loser not found or already superseded — nothing to resolve. No evidence written." };
793
+ // A row id is a pointer, not authority (#131): resolving and
794
+ // authorizing BOTH seats happens against the caller's Reader —
795
+ // captured at entry, never re-read after an await (#127) — and the
796
+ // whole resolve/check/mutate runs under the same update-order lock
797
+ // memory_update serializes on (#125), so the authorization is
798
+ // revalidated under the mutation lock instead of against a snapshot
799
+ // a concurrent update could have replaced. Acquisition order is
800
+ // always update-order then store-file locks, never the reverse, so
801
+ // this cannot deadlock against a plain writer; on timeout it fails
802
+ // closed with nothing written.
803
+ const reader = readerFromSid(sid);
804
+ // Where a throw lands decides what is true to say: before the
805
+ // mutation nothing was written (the documented fail-closed
806
+ // contract); AFTER markSuperseded the loser IS retired on disk and
807
+ // claiming "nothing was done" is a lie (review probe 5).
808
+ let mutated = false;
809
+ try {
810
+ return await withStoreLock(
811
+ join(memoryRoot(), "update-order"),
812
+ async () => {
813
+ const all = await loadAll();
814
+ const survivorRow = all.find((m) => m.ts === args.survivor);
815
+ // Probed: marking with a survivor id that names no row retired
816
+ // the loser toward a pointer to nothing (the scope ended with
817
+ // zero active rows) while the response declared it canonical.
818
+ // Validate BEFORE touching the loser — a resolution must never
819
+ // retire real data for a phantom.
820
+ if (!survivorRow) {
821
+ return { content: `merge_review blocked: survivor ${args.survivor} does not exist in the store — nothing to resolve. No evidence written.` };
822
+ }
823
+ const loserRow = all.find((m) => m.ts === args.loser);
824
+ // Visibility is the authorization contract (#131): a session
825
+ // may merge exactly the rows it may read. Global and legacy
826
+ // unstamped rows are visible everywhere and therefore
827
+ // mergeable from anywhere — stated here, not granted
828
+ // implicitly by store-wide reach. A foreign row in EITHER
829
+ // seat — including an attempt to revive another repository's
830
+ // superseded survivor — is refused before any mutation.
831
+ if (loserRow && !isVisibleTo(loserRow, reader)) {
832
+ return { content: "merge_review blocked: the loser belongs to another repository — this session may not retire it. Nothing was done. No evidence written." };
833
+ }
834
+ if (!isVisibleTo(survivorRow, reader)) {
835
+ return { content: "merge_review blocked: the survivor belongs to another repository — this session may not promote or revive it. Nothing was done. No evidence written." };
836
+ }
837
+ const ok = await markSuperseded(args.loser, {
838
+ superseded_by: args.survivor,
839
+ reason: args.reason,
840
+ symbol: args.loser,
841
+ from: args.loser,
842
+ to: args.survivor,
843
+ });
844
+ if (!ok) {
845
+ return { content: "merge_review: loser not found or already superseded — nothing to resolve. No evidence written." };
846
+ }
847
+ mutated = true;
848
+ // The survivor may itself have been superseded earlier (e.g. by
849
+ // a row this very call just made the loser). Declaring it
850
+ // canonical has to make it recallable, so clear its own marker.
851
+ const revived = await clearSuperseded(args.survivor);
852
+ // The response has always claimed "Evidence recorded" — now it
853
+ // is true, and it names the session the merge ran FOR (#121's
854
+ // residue on this line). The host tool_result hook covers
855
+ // grep/read/edit/shell only, so a merge used to leave zero
856
+ // trace: which reviewer decision, on which reason, reviving
857
+ // what — unauditable.
858
+ await record(
859
+ "merge_resolved",
860
+ {
861
+ loser: args.loser,
862
+ survivor: args.survivor,
863
+ revived,
864
+ reason: args.reason,
865
+ },
866
+ true,
867
+ sid,
868
+ );
869
+ return {
870
+ content:
871
+ `Resolved merge: ${args.survivor} is canonical; ${args.loser} superseded (recoverable via memory_undo). ` +
872
+ (revived ? `Survivor's own supersession cleared, it is active again. ` : "") +
873
+ `Evidence recorded for reason='${args.reason}'.`,
874
+ };
875
+ },
876
+ {
877
+ onTimeout: "fail",
878
+ onEvent: (event, waitedMs) => {
879
+ void record("store_lock", { event, waited_ms: waitedMs, op: "merge" });
880
+ },
881
+ },
882
+ );
883
+ } catch (err) {
884
+ // Before mutation this is the fail-closed lock contract: nothing
885
+ // written. After markSuperseded succeeded the loser IS retired —
886
+ // the honest report names the completed mutation and the failed
887
+ // follow-up (evidence/revive), not a blanket "nothing was done".
888
+ if (!mutated) {
889
+ return {
890
+ content: "merge_review blocked: the store was busy past the lock budget — nothing was done. Retry.",
891
+ };
892
+ }
893
+ const why = err instanceof Error ? err.message : String(err);
894
+ return {
895
+ content:
896
+ `merge_review PARTIAL: ${args.loser} IS retired on disk (superseded_by ${args.survivor}; ` +
897
+ `recoverable via memory_undo) but a post-mutation step failed: ${why}. ` +
898
+ `The evidence line may be missing; re-running reports the loser already superseded.`,
899
+ };
770
900
  }
771
- // The survivor may itself have been superseded earlier (e.g. by a row
772
- // this very call just made the loser). Declaring it canonical has to
773
- // make it recallable, so clear its own marker too.
774
- const revived = await clearSuperseded(args.survivor);
775
- // The response has always claimed "Evidence recorded" — now it is
776
- // true. The host tool_result hook covers grep/read/edit/shell only,
777
- // so a merge used to leave zero trace: which reviewer decision, on
778
- // which reason, reviving what — unauditable.
779
- await record("merge_resolved", {
780
- loser: args.loser,
781
- survivor: args.survivor,
782
- revived,
783
- reason: args.reason,
784
- });
785
- return {
786
- content:
787
- `Resolved merge: ${args.survivor} is canonical; ${args.loser} superseded (recoverable via memory_undo). ` +
788
- (revived ? `Survivor's own supersession cleared, it is active again. ` : "") +
789
- `Evidence recorded for reason='${args.reason}'.`,
790
- };
791
901
  },
792
902
  }));
793
903
 
@@ -815,6 +925,12 @@ const impl = {
815
925
  options: direct,
816
926
  async execute(args, context): Promise<{ content: string }> {
817
927
  const { sid } = toolIds(context);
928
+ // Resolve before touching the file: every imported row is re-stamped
929
+ // with the IMPORTING session's repository, so an unresolved caller
930
+ // would move a whole export into whoever set up last (#152).
931
+ await bindSessionIdentity(sid);
932
+ const ownerless = ownerlessWriter(sid);
933
+ if (ownerless) return await refuseOwnerlessWrite(ownerless, "import");
818
934
  try {
819
935
  const t = await importMemories(
820
936
  args.file,
@@ -1359,6 +1475,14 @@ const impl = {
1359
1475
  // no-op there). SYNC only: a lookup call here would break the
1360
1476
  // zero-token promise of the capture tests.
1361
1477
  bindSessionProvisional(sid, instanceDir);
1478
+ // #152: an instance with no workspace cannot say which repository the
1479
+ // mined rows belong to, and rows with no owner are exactly what the
1480
+ // store refuses. Skip BEFORE the model call — no tokens spent on a
1481
+ // capture that cannot be stored — and leave the reason in evidence.
1482
+ if (!writeTarget(sid).ok) {
1483
+ await record("auto_capture_refused", { session: sid, trigger }, true, sid);
1484
+ return;
1485
+ }
1362
1486
  let transcript = seeded;
1363
1487
  let msgs = seededMsgs;
1364
1488
  if (transcript.length < 200) {
@@ -1373,7 +1497,12 @@ const impl = {
1373
1497
  const lagMs = lagSince(msgs);
1374
1498
  const out = await generateApi.text({
1375
1499
  model: modelRef,
1376
- prompt: buildCapturePrompt(transcript.slice(-8000), captureMax),
1500
+ // Redact the COMPLETE transcript, THEN apply the character budget
1501
+ // (#132). Cropping first can start the window INSIDE a credential:
1502
+ // a PEM body whose BEGIN marker fell off, or a token whose prefix
1503
+ // fell off, matches no pattern — buildCapturePrompt's own scrub
1504
+ // (kept, defense in depth) cannot recognize a fragment.
1505
+ prompt: buildCapturePrompt(redactSecrets(transcript).slice(-8000), captureMax),
1377
1506
  });
1378
1507
  const text = typeof out === "string" ? out : out?.text ?? "";
1379
1508
  const candidates = parseCandidates(text, captureMax);
package/src/memory.ts CHANGED
@@ -6,7 +6,7 @@ import { existsSync } from "node:fs";
6
6
  import { open } from "node:fs/promises";
7
7
  import { join, basename } from "node:path";
8
8
  import { dateStr, memoryRoot, deletionsFile, snapshotDir, HITS_FILENAME } from "./config.ts";
9
- import { repoScopeFor, sessionScope, type RepoScope } from "./repokey.ts";
9
+ import { repoScopeFor, sessionScope, writeTarget, type RepoScope } from "./repokey.ts";
10
10
  import { getCurrent } from "./state.ts";
11
11
  import {
12
12
  appendLog,
@@ -219,6 +219,30 @@ async function existingTs(file: string): Promise<Set<string>> {
219
219
  return set;
220
220
  }
221
221
 
222
+ // #152: the store's answer to a write whose owner it cannot determine. Thrown
223
+ // from the one place that knows what an owner is (the stamp resolution below),
224
+ // so no caller — gate, import, capture, or a future one — can quietly persist
225
+ // an ownerless row. `unresolvedWriteMessage` is the same text the model-facing
226
+ // tools return, kept here so the two can never drift.
227
+ export function unresolvedWriteMessage(sid: string): string {
228
+ return (
229
+ `Write refused: session ${sid} has no resolvable repository, so nothing was stored. ` +
230
+ `A memory with no owner must not be stamped into another repository or published as a ` +
231
+ `global row. Retry from a session in the project you mean, or pass global:true for a ` +
232
+ `deliberate cross-project memory.`
233
+ );
234
+ }
235
+
236
+ export class UnresolvedWriterError extends Error {
237
+ /** The named-but-unresolved session whose write was refused. */
238
+ sid: string;
239
+ constructor(sid: string) {
240
+ super(unresolvedWriteMessage(sid));
241
+ this.name = "UnresolvedWriterError";
242
+ this.sid = sid;
243
+ }
244
+ }
245
+
222
246
  // Append a durable memory. GATE-4 promotions and the viewer's edit/restore-entry
223
247
  // paths all call this single write choke point.
224
248
  export async function appendMemory(input: AppendMemoryInput): Promise<string> {
@@ -270,10 +294,20 @@ export async function appendMemory(input: AppendMemoryInput): Promise<string> {
270
294
  // the last setCurrent before persistence may belong to another session
271
295
  // entirely (#116). Unnamed writers (tools, viewer, restore) keep the
272
296
  // ambient binding.
273
- const cur = repoScopeFor(input.sessionID ?? getCurrent().sid);
274
- if (cur) {
275
- repo = cur.key;
276
- repoPath = cur.path;
297
+ //
298
+ // A NAMED session that never resolved a repository is not an unnamed one
299
+ // (#152): falling back to the module scope stamped its rows into whatever
300
+ // workspace set up last, and with no module scope at all it stamped nothing
301
+ // — which every reader calls global. Both outcomes publish private content
302
+ // somewhere its owner can no longer see it, so the store refuses the write
303
+ // instead of guessing an owner. Tools answer with this message before the
304
+ // gate runs; throwing here is what covers every caller, including ones that
305
+ // reach the store without a tool.
306
+ const target = writeTarget(input.sessionID ?? getCurrent().sid);
307
+ if (!target.ok) throw new UnresolvedWriterError(target.sid);
308
+ if (target.scope) {
309
+ repo = target.scope.key;
310
+ repoPath = target.scope.path;
277
311
  }
278
312
  }
279
313
  // Day file chosen before the lock (it IS the lock key). A ts bumped across
package/src/portable.ts CHANGED
@@ -8,8 +8,15 @@ import { mkdir, open } from "node:fs/promises";
8
8
  import { dirname, join } from "node:path";
9
9
  import { allowOutsideStorePaths, exportsDir, memoryRoot } from "./config.ts";
10
10
  import { resolveContained } from "./containment.ts";
11
- import { isActive, isVisibleTo, loadAll, readerFromSid, type Memory } from "./memory.ts";
12
- import { repoScopeFor } from "./repokey.ts";
11
+ import {
12
+ isActive,
13
+ isVisibleTo,
14
+ loadAll,
15
+ readerFromSid,
16
+ UnresolvedWriterError,
17
+ type Memory,
18
+ } from "./memory.ts";
19
+ import { writeTarget } from "./repokey.ts";
13
20
  import { getCurrent } from "./state.ts";
14
21
  import { TYPES } from "./types.ts";
15
22
  import type { WriteCandidate } from "./gates.ts";
@@ -262,7 +269,14 @@ export async function importMemories(
262
269
  const file = Bun.file(target);
263
270
  if (!(await file.exists())) throw new Error(`import file not found: ${target}`);
264
271
  const tally: ImportTally = { promoted: 0, collapsed: 0, blocked: 0, skipped: 0, downgraded: 0 };
265
- const currentScope = repoScopeFor(sessionID ?? getCurrent().sid);
272
+ // #152: the importing session's repository is resolved BEFORE the first row,
273
+ // through the writer rule rather than the ambient one. An unresolved named
274
+ // session has no write target, and half a file re-stamped into whatever
275
+ // workspace happened to set up last is worse than none — so this throws
276
+ // before a single row is gated, not partway through the tally.
277
+ const writeAt = writeTarget(sessionID ?? getCurrent().sid);
278
+ if (!writeAt.ok) throw new UnresolvedWriterError(writeAt.sid);
279
+ const currentScope = writeAt.scope;
266
280
  let allowFrontier = false;
267
281
  let first = true;
268
282
  for (const line of (await file.text()).split("\n")) {
package/src/repokey.ts CHANGED
@@ -154,10 +154,37 @@ export function repoScopeFor(sid?: string): RepoScope | null {
154
154
  // (#127), never inherit a module scope that belongs to another workspace (or
155
155
  // is null, which the ambient reader has always read as "everything").
156
156
  export function sessionScope(sid?: unknown): RepoScope | undefined {
157
- if (typeof sid !== "string" || sid === "" || sid === "?") return undefined;
157
+ if (!isNamedSid(sid)) return undefined;
158
158
  return bySession.get(sid)?.scope;
159
159
  }
160
160
 
161
+ /** Did the host actually name a session? ("?" and absent mean nobody.) */
162
+ export function isNamedSid(sid: unknown): sid is string {
163
+ return typeof sid === "string" && sid !== "" && sid !== "?";
164
+ }
165
+
166
+ // The repository a DURABLE WRITE belongs to (#152) — the write-side twin of
167
+ // sessionScope, and deliberately not `repoScopeFor`: that helper's last resort
168
+ // is the module scope, which is the identity of whoever called setup() LAST.
169
+ // Reading with the wrong owner can only ever show too little (an unbound
170
+ // session reads global rows and nothing else), but writing with the wrong owner
171
+ // MOVES private content into a repository that cannot recall where it came
172
+ // from — and a null module scope turns the same write into an unstamped, hence
173
+ // global, row that every other project then reads. So an identity the host
174
+ // named but never resolved has NO write target: `ok:false`, which callers must
175
+ // refuse rather than downgrade. A caller that names nobody (viewer process,
176
+ // restore, scripts, unit tests) keeps the historical module-scope answer,
177
+ // including "no scope at all" — that is the deliberate admin path.
178
+ export type WriteTarget =
179
+ | { ok: true; scope: RepoScope | null }
180
+ | { ok: false; sid: string };
181
+
182
+ export function writeTarget(sid?: unknown): WriteTarget {
183
+ if (!isNamedSid(sid)) return { ok: true, scope: current };
184
+ const scope = sessionScope(sid);
185
+ return scope ? { ok: true, scope } : { ok: false, sid };
186
+ }
187
+
161
188
  export function resetSessionScopes(): void {
162
189
  bySession.clear();
163
190
  byDir.clear();
package/src/schema.ts CHANGED
@@ -121,7 +121,10 @@ export const UndoArgs = z.object({
121
121
  });
122
122
 
123
123
  export const EvidenceArgs = z.object({
124
- date: z.string().optional(),
124
+ date: z
125
+ .string()
126
+ .regex(/^\d{4}-\d{2}-\d{2}$/, "must be a YYYY-MM-DD calendar date (paths are refused)")
127
+ .optional(),
125
128
  ev: z.string().optional(),
126
129
  limit: z.coerce.number().optional(),
127
130
  });