@bli-cockpit/telemetry-core 0.1.94 → 0.1.96

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.
@@ -8,5 +8,18 @@
8
8
  * Its own file, and its own `./codex-hooks-trust-guide` export, so a browser
9
9
  * component can import one string without pulling in the whole package.
10
10
  * Repo copy of the guide: `docs/runbooks/codex-hooks-trust.md` (BLI-23315).
11
+ * Since BLI-24349 the guide leads with doctor's one question; `/hooks` is the fallback.
11
12
  */
12
13
  export declare const CODEX_HOOKS_TRUST_GUIDE_URL = "https://tower.buildlaunchiterate.ca/docs/trust-the-bli-memory-hooks-in-codex";
14
+ /** The doctor question, word for word (BLI-24349). Surfaces that tell a person to answer it quote this. */
15
+ export declare const CODEX_HOOKS_TRUST_QUESTION_WORDS = "Auto-trust the BLI Memory hooks in Codex?";
16
+ /** The command that trusts them without the question, for a person who said no earlier. */
17
+ export declare const CODEX_HOOKS_TRUST_COMMAND = "cockpit doctor --trust-codex-hooks";
18
+ /**
19
+ * The one sentence every surface prints for `codex.hooks needs_trust`
20
+ * (BLI-24349): lead with doctor's question, keep `/hooks` as the fallback.
21
+ * `reason` is the receipt's reason label for the piece; `trust_declined` and
22
+ * `managed_hooks_stale` get their own words. Every variant names `/hooks`, so
23
+ * the device doctor's `hook_trust` action keeps matching it.
24
+ */
25
+ export declare function codexHooksTrustAction(reason?: string | null): string;
@@ -8,5 +8,26 @@
8
8
  * Its own file, and its own `./codex-hooks-trust-guide` export, so a browser
9
9
  * component can import one string without pulling in the whole package.
10
10
  * Repo copy of the guide: `docs/runbooks/codex-hooks-trust.md` (BLI-23315).
11
+ * Since BLI-24349 the guide leads with doctor's one question; `/hooks` is the fallback.
11
12
  */
12
13
  export const CODEX_HOOKS_TRUST_GUIDE_URL = "https://tower.buildlaunchiterate.ca/docs/trust-the-bli-memory-hooks-in-codex";
14
+ /** The doctor question, word for word (BLI-24349). Surfaces that tell a person to answer it quote this. */
15
+ export const CODEX_HOOKS_TRUST_QUESTION_WORDS = "Auto-trust the BLI Memory hooks in Codex?";
16
+ /** The command that trusts them without the question, for a person who said no earlier. */
17
+ export const CODEX_HOOKS_TRUST_COMMAND = "cockpit doctor --trust-codex-hooks";
18
+ /**
19
+ * The one sentence every surface prints for `codex.hooks needs_trust`
20
+ * (BLI-24349): lead with doctor's question, keep `/hooks` as the fallback.
21
+ * `reason` is the receipt's reason label for the piece; `trust_declined` and
22
+ * `managed_hooks_stale` get their own words. Every variant names `/hooks`, so
23
+ * the device doctor's `hook_trust` action keeps matching it.
24
+ */
25
+ export function codexHooksTrustAction(reason) {
26
+ if (reason === "trust_declined") {
27
+ return `The person answered no to "${CODEX_HOOKS_TRUST_QUESTION_WORDS}". To trust them, run \`${CODEX_HOOKS_TRUST_COMMAND}\` in a terminal on the machine (or open Codex and run /hooks). Guide: ${CODEX_HOOKS_TRUST_GUIDE_URL}`;
28
+ }
29
+ if (reason === "managed_hooks_stale") {
30
+ return `BLI Memory's Codex hooks changed since they were trusted: run \`cockpit doctor\` in a terminal on the machine and answer Y to "${CODEX_HOOKS_TRUST_QUESTION_WORDS}" (fallback: open Codex and run /hooks). Guide: ${CODEX_HOOKS_TRUST_GUIDE_URL}`;
31
+ }
32
+ return `Run \`cockpit doctor\` in a terminal on the machine and answer Y to "${CODEX_HOOKS_TRUST_QUESTION_WORDS}" (one password or administrator prompt). Fallback: open Codex and run /hooks. Guide: ${CODEX_HOOKS_TRUST_GUIDE_URL}`;
33
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * BLI-23590: a person's collection scope, shared by the server that decides it and the collector that obeys it.
3
+ *
4
+ * Default `all`: every session the collector can see is uploaded, labelled `inside` or `outside` the approved roots
5
+ * (session-first collection, BLI-10734). `roots_only` is the founders' and Ed's setting: a session whose working
6
+ * directory is outside every approved root is not staged, not uploaded and has no session row; the only trace is a
7
+ * count on the heartbeat, with the reason label below.
8
+ *
9
+ * Who may use it is decided on the SERVER (`apps/dashboard/src/lib/settings/collection-scope.ts`), never on the laptop:
10
+ * the install-events reply carries `{ scope, eligible }` for the device's person, and the collector honours a
11
+ * `roots_only` it was not told about only when that reply said `eligible: true`.
12
+ */
13
+ import { z } from "zod";
14
+ export declare const COLLECTION_SCOPES: readonly ["all", "roots_only"];
15
+ export type CollectionScope = (typeof COLLECTION_SCOPES)[number];
16
+ export declare const CollectionScopeSchema: z.ZodEnum<{
17
+ all: "all";
18
+ roots_only: "roots_only";
19
+ }>;
20
+ /** The reason label a withheld session carries on a heartbeat, a log line and the coverage board. */
21
+ export declare const COLLECTION_SCOPE_ROOTS_ONLY_REASON = "collection_scope_roots_only";
22
+ /** What the install-events reply says about this device's person. */
23
+ export declare const CollectionScopeReplySchema: z.ZodObject<{
24
+ scope: z.ZodEnum<{
25
+ all: "all";
26
+ roots_only: "roots_only";
27
+ }>;
28
+ eligible: z.ZodBoolean;
29
+ }, z.core.$strict>;
30
+ export type CollectionScopeReply = z.infer<typeof CollectionScopeReplySchema>;
31
+ /** What a heartbeat reports about the scope the tick ran under. Counts and labels only. */
32
+ export declare const CollectionScopeHeartbeatSchema: z.ZodObject<{
33
+ scope: z.ZodEnum<{
34
+ all: "all";
35
+ roots_only: "roots_only";
36
+ }>;
37
+ withheld_sessions: z.ZodNumber;
38
+ reason: z.ZodString;
39
+ }, z.core.$strict>;
40
+ export type CollectionScopeHeartbeat = z.infer<typeof CollectionScopeHeartbeatSchema>;
@@ -0,0 +1,29 @@
1
+ /**
2
+ * BLI-23590: a person's collection scope, shared by the server that decides it and the collector that obeys it.
3
+ *
4
+ * Default `all`: every session the collector can see is uploaded, labelled `inside` or `outside` the approved roots
5
+ * (session-first collection, BLI-10734). `roots_only` is the founders' and Ed's setting: a session whose working
6
+ * directory is outside every approved root is not staged, not uploaded and has no session row; the only trace is a
7
+ * count on the heartbeat, with the reason label below.
8
+ *
9
+ * Who may use it is decided on the SERVER (`apps/dashboard/src/lib/settings/collection-scope.ts`), never on the laptop:
10
+ * the install-events reply carries `{ scope, eligible }` for the device's person, and the collector honours a
11
+ * `roots_only` it was not told about only when that reply said `eligible: true`.
12
+ */
13
+ import { z } from "zod";
14
+ export const COLLECTION_SCOPES = ["all", "roots_only"];
15
+ export const CollectionScopeSchema = z.enum(COLLECTION_SCOPES);
16
+ /** The reason label a withheld session carries on a heartbeat, a log line and the coverage board. */
17
+ export const COLLECTION_SCOPE_ROOTS_ONLY_REASON = "collection_scope_roots_only";
18
+ /** What the install-events reply says about this device's person. */
19
+ export const CollectionScopeReplySchema = z
20
+ .object({ scope: CollectionScopeSchema, eligible: z.boolean() })
21
+ .strict();
22
+ /** What a heartbeat reports about the scope the tick ran under. Counts and labels only. */
23
+ export const CollectionScopeHeartbeatSchema = z
24
+ .object({
25
+ scope: CollectionScopeSchema,
26
+ withheld_sessions: z.number().int().nonnegative().max(1_000_000),
27
+ reason: z.string().trim().min(1).max(120).regex(/^[a-z0-9_:.-]+$/iu),
28
+ })
29
+ .strict();
@@ -44,6 +44,26 @@ export declare const CollectorHeartbeatSyncStatusSchema: z.ZodEnum<{
44
44
  fail: "fail";
45
45
  not_run: "not_run";
46
46
  }>;
47
+ export declare const CaptureOptOutsSchema: z.ZodObject<{
48
+ standing: z.ZodEnum<{
49
+ unknown: "unknown";
50
+ founder: "founder";
51
+ not_founder: "not_founder";
52
+ }>;
53
+ obeyed: z.ZodArray<z.ZodEnum<{
54
+ memory_capture_off: "memory_capture_off";
55
+ collect_claude_jsonl_false: "collect_claude_jsonl_false";
56
+ collect_codex_jsonl_false: "collect_codex_jsonl_false";
57
+ raw_evidence_upload_disabled: "raw_evidence_upload_disabled";
58
+ }>>;
59
+ ignored: z.ZodArray<z.ZodEnum<{
60
+ memory_capture_off: "memory_capture_off";
61
+ collect_claude_jsonl_false: "collect_claude_jsonl_false";
62
+ collect_codex_jsonl_false: "collect_codex_jsonl_false";
63
+ raw_evidence_upload_disabled: "raw_evidence_upload_disabled";
64
+ }>>;
65
+ }, z.core.$strict>;
66
+ export type CaptureOptOuts = z.infer<typeof CaptureOptOutsSchema>;
47
67
  /**
48
68
  * BLI-23181. What the staging gate measured on this tick's volume, and how much
49
69
  * Tower itself keeps there. Before this the fleet board could say a machine
@@ -356,6 +376,33 @@ export declare const CollectorHeartbeatSchema: z.ZodObject<{
356
376
  }, z.core.$strict>;
357
377
  }, z.core.$strict>;
358
378
  }, z.core.$strict>>;
379
+ collection_scope: z.ZodOptional<z.ZodObject<{
380
+ scope: z.ZodEnum<{
381
+ all: "all";
382
+ roots_only: "roots_only";
383
+ }>;
384
+ withheld_sessions: z.ZodNumber;
385
+ reason: z.ZodString;
386
+ }, z.core.$strict>>;
387
+ capture_opt_outs: z.ZodOptional<z.ZodObject<{
388
+ standing: z.ZodEnum<{
389
+ unknown: "unknown";
390
+ founder: "founder";
391
+ not_founder: "not_founder";
392
+ }>;
393
+ obeyed: z.ZodArray<z.ZodEnum<{
394
+ memory_capture_off: "memory_capture_off";
395
+ collect_claude_jsonl_false: "collect_claude_jsonl_false";
396
+ collect_codex_jsonl_false: "collect_codex_jsonl_false";
397
+ raw_evidence_upload_disabled: "raw_evidence_upload_disabled";
398
+ }>>;
399
+ ignored: z.ZodArray<z.ZodEnum<{
400
+ memory_capture_off: "memory_capture_off";
401
+ collect_claude_jsonl_false: "collect_claude_jsonl_false";
402
+ collect_codex_jsonl_false: "collect_codex_jsonl_false";
403
+ raw_evidence_upload_disabled: "raw_evidence_upload_disabled";
404
+ }>>;
405
+ }, z.core.$strict>>;
359
406
  }, z.core.$strict>;
360
407
  export type CollectorHeartbeat = z.infer<typeof CollectorHeartbeatSchema>;
361
408
  /**
@@ -24,6 +24,7 @@
24
24
  */
25
25
  import { z } from "zod";
26
26
  import { IsoDateTimeSchema, Sha256Schema, VersionStringSchema } from "./common.js";
27
+ import { CollectionScopeHeartbeatSchema } from "./collection-scope.js";
27
28
  import { MemoryInstallReceiptSchema } from "./memory-install-receipt.js";
28
29
  import { SetupReceiptSchema } from "./setup-receipt.js";
29
30
  export const COLLECTOR_HEARTBEAT_SCHEMA_VERSION = "collector-heartbeat.v1";
@@ -52,6 +53,19 @@ export const CollectorHeartbeatSyncStatusSchema = z.enum([
52
53
  "skipped",
53
54
  "not_run",
54
55
  ]);
56
+ const CaptureOptOutLabelSchema = z.enum([
57
+ "memory_capture_off",
58
+ "collect_claude_jsonl_false",
59
+ "collect_codex_jsonl_false",
60
+ "raw_evidence_upload_disabled",
61
+ ]);
62
+ export const CaptureOptOutsSchema = z
63
+ .object({
64
+ standing: z.enum(["founder", "not_founder", "unknown"]),
65
+ obeyed: z.array(CaptureOptOutLabelSchema).max(4),
66
+ ignored: z.array(CaptureOptOutLabelSchema).max(4),
67
+ })
68
+ .strict();
55
69
  /**
56
70
  * BLI-23181. What the staging gate measured on this tick's volume, and how much
57
71
  * Tower itself keeps there. Before this the fleet board could say a machine
@@ -208,6 +222,21 @@ export const CollectorHeartbeatSchema = z
208
222
  * already holds rather than blanking it.
209
223
  */
210
224
  setup_receipt: SetupReceiptSchema.optional(),
225
+ /**
226
+ * BLI-23590. Sent only by a tick that ran under `roots_only`: how many sessions it withheld because their
227
+ * working directory was outside every approved root (a count, nothing else) and the reason label. Absent on every
228
+ * other tick, which reads as "collect everything".
229
+ */
230
+ collection_scope: CollectionScopeHeartbeatSchema.optional(),
231
+ /**
232
+ * BLI-22640 (Jeetesh's review of 2026-10-25). Which of this machine's
233
+ * opt-outs it obeyed and which it ignored, and the founder answer it acted
234
+ * on (`founder-standing-contract.ts`). Only a founder's opt-out is obeyed;
235
+ * Tower compares `obeyed` with its own owners list, so an edited local
236
+ * answer is visible. Labels only. A current CLI always sends it (empty
237
+ * lists when the machine holds no opt-out); absent means an older CLI.
238
+ */
239
+ capture_opt_outs: CaptureOptOutsSchema.optional(),
211
240
  })
212
241
  .strict();
213
242
  /**
@@ -184,9 +184,9 @@ export declare const DecisionOutcomeSchema: z.ZodDiscriminatedUnion<[z.ZodObject
184
184
  }>;
185
185
  granted: z.ZodBoolean;
186
186
  scope: z.ZodEnum<{
187
+ standing: "standing";
187
188
  this_pr: "this_pr";
188
189
  wave: "wave";
189
- standing: "standing";
190
190
  }>;
191
191
  }, z.core.$strict>, z.ZodObject<{
192
192
  kind: z.ZodLiteral<"intervention">;
@@ -336,9 +336,9 @@ export declare const DecisionEventSchema: z.ZodObject<{
336
336
  }>;
337
337
  granted: z.ZodBoolean;
338
338
  scope: z.ZodEnum<{
339
+ standing: "standing";
339
340
  this_pr: "this_pr";
340
341
  wave: "wave";
341
- standing: "standing";
342
342
  }>;
343
343
  }, z.core.$strict>, z.ZodObject<{
344
344
  kind: z.ZodLiteral<"intervention">;
@@ -519,9 +519,9 @@ export declare const DecisionEventEnvelopeSchema: z.ZodObject<{
519
519
  }>;
520
520
  granted: z.ZodBoolean;
521
521
  scope: z.ZodEnum<{
522
+ standing: "standing";
522
523
  this_pr: "this_pr";
523
524
  wave: "wave";
524
- standing: "standing";
525
525
  }>;
526
526
  }, z.core.$strict>, z.ZodObject<{
527
527
  kind: z.ZodLiteral<"intervention">;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * WHO MAY KEEP THEIR WORK OUT OF TOWER (BLI-22640, Jeetesh's review of 2026-10-25).
3
+ *
4
+ * Policy, in plain words: work done on BLI accounts or BLI hardware is BLI's,
5
+ * and all of it goes to Tower. Only the founders (Tower's owners list, the
6
+ * `tower_owners` table: Vee and Jeetesh) may turn BLI Memory off on a machine
7
+ * or keep a machine's sessions from uploading. For anybody else an "off"
8
+ * value is IGNORED and REPORTED, never obeyed, and never deleted either: the
9
+ * person's file stays exactly as they wrote it.
10
+ *
11
+ * The opt-outs this rule covers:
12
+ * - `<state_dir>/memory-capture.json` saying off (`cockpit memory off`,
13
+ * `doctor --no-memory`, "n" to the one-time question);
14
+ * - `collect_claude_jsonl: false`, `collect_codex_jsonl: false` and
15
+ * `raw_evidence_upload: "disabled"` in the collector config, including the
16
+ * copies every config rewrite carries forward (ticket 22341).
17
+ *
18
+ * Who is a founder is TOWER'S answer, never a local list and never a local
19
+ * flag, and it is asked LIVE every time a reader decides what leaves the
20
+ * machine (Jeetesh's rule on the shelves review, 2026-10-26). Two server
21
+ * replies carry it: `GET /api/ambient/founder-standing` and the heartbeat
22
+ * reply's `is_owner`.
23
+ *
24
+ * The saved copy is for DISPLAY ONLY:
25
+ *
26
+ * <state_dir>/founder-standing.json
27
+ * { "founder": false, "checked_at": "<iso>", "source": "heartbeat" }
28
+ *
29
+ * Only a Tower reply writes that file, and nothing that decides what leaves the
30
+ * machine (the hooks, the sync tick, discovery, backfill, the upload envelope,
31
+ * the hook install) reads it: a person can edit a file, so a decision made on
32
+ * it is a decision the person made. The heartbeat carries what this machine
33
+ * obeyed so Tower can compare it with its own owners list.
34
+ *
35
+ * When Tower cannot be asked (not paired, offline, a refusal such as the
36
+ * door's named 503, a reply that does not say) the reader HOLDS
37
+ * (`owner_check_unavailable`): it sends nothing that the opt-out covers and
38
+ * asks again on its next run. A hold is not an answer and is never remembered
39
+ * past the process. It errs toward the founders: a founder's client mail must
40
+ * never leave because a network call failed. A machine with no opt-out has
41
+ * nothing to decide and asks nothing.
42
+ *
43
+ * The collector writes the display file and both it and
44
+ * `@bli-cockpit/memory-mcp`'s hooks ask the door live. The two packages never
45
+ * import each other, so the door's path, the reply reading and the verdict
46
+ * live here, beside `memory-capture-contract.ts`.
47
+ */
48
+ export declare const FOUNDER_STANDING_FILE_NAME = "founder-standing.json";
49
+ /** Tower's door that answers "is this device's person a founder?". */
50
+ export declare const FOUNDER_STANDING_PATH = "/api/ambient/founder-standing";
51
+ /** Which Tower reply the cached answer came from. A label, never a path. */
52
+ export type FounderStandingSource = "standing_door" | "heartbeat";
53
+ export interface FounderStandingRecord {
54
+ founder: boolean;
55
+ checked_at: string;
56
+ source: FounderStandingSource;
57
+ }
58
+ export type FounderStanding = "founder" | "not_founder" | "unknown";
59
+ export interface FounderStandingReading {
60
+ standing: FounderStanding;
61
+ /** Named on every branch. */
62
+ reason: "tower_says_founder" | "tower_says_not_founder" | "standing_never_checked" | "standing_unreadable";
63
+ record: FounderStandingRecord | null;
64
+ }
65
+ /** `raw` is the file's text, or null when the file is not there. */
66
+ export declare function parseFounderStanding(raw: string | null): FounderStandingReading;
67
+ export declare function renderFounderStanding(record: FounderStandingRecord): string;
68
+ /**
69
+ * What a reader does with an opt-out it found, and why. Every reader of every
70
+ * opt-out above asks this one function, so the hooks, the sync tick, doctor
71
+ * and the heartbeat cannot disagree. `standing` must come from a LIVE Tower
72
+ * answer (`LiveFounderAnswer`), never from the saved file.
73
+ *
74
+ * - founder -> obeyed (`opt_out_obeyed_founder`)
75
+ * - not_founder -> ignored (`opt_out_ignored_not_founder`)
76
+ * - unknown -> HELD (`owner_check_unavailable`): withheld like an obeyed
77
+ * opt-out, but named as a hold, never as the person's win.
78
+ */
79
+ export declare const OWNER_CHECK_UNAVAILABLE = "owner_check_unavailable";
80
+ export type OptOutVerdict = {
81
+ obeyed: true;
82
+ held: false;
83
+ reason: "opt_out_obeyed_founder";
84
+ } | {
85
+ obeyed: true;
86
+ held: true;
87
+ reason: typeof OWNER_CHECK_UNAVAILABLE;
88
+ } | {
89
+ obeyed: false;
90
+ held: false;
91
+ reason: "opt_out_ignored_not_founder";
92
+ };
93
+ export declare function optOutVerdict(standing: FounderStanding): OptOutVerdict;
94
+ /** Why Tower could not say. Same names the shelves work uses for the same failures. */
95
+ export type FounderCheckFailure = "not_paired" | "founder_check_unreachable" | "founder_check_refused" | "founder_check_bad_reply";
96
+ /** Tower's live answer, or the reason it could not give one. Never read from a file. */
97
+ export type LiveFounderAnswer = {
98
+ standing: "founder";
99
+ reason: "tower_says_founder";
100
+ } | {
101
+ standing: "not_founder";
102
+ reason: "tower_says_not_founder";
103
+ } | {
104
+ standing: "unknown";
105
+ reason: FounderCheckFailure;
106
+ httpStatus?: number;
107
+ };
108
+ /** No request produced a reply at all (offline, DNS, timeout, reset). */
109
+ export declare function founderAnswerUnreachable(): LiveFounderAnswer;
110
+ /** This machine has no Tower session to ask with. */
111
+ export declare function founderAnswerNotPaired(): LiveFounderAnswer;
112
+ /**
113
+ * Reads one reply from `GET /api/ambient/founder-standing`. Only a 200 whose
114
+ * body carries a boolean `founder` is an answer; the door's 503
115
+ * (`owners_list_unreadable`), any other status and a body that does not say are
116
+ * "Tower could not say", never a "no".
117
+ */
118
+ export declare function founderAnswerFromReply(reply: {
119
+ status: number;
120
+ body: unknown;
121
+ }): LiveFounderAnswer;
122
+ /** The labels a machine's opt-outs are reported under (heartbeat, doctor, logs). */
123
+ export type CaptureOptOutLabel = "memory_capture_off" | "collect_claude_jsonl_false" | "collect_codex_jsonl_false" | "raw_evidence_upload_disabled";
124
+ /** The refusal a non-founder gets from every door that records an "off". */
125
+ export declare const FOUNDERS_ONLY_REFUSAL = "memory_off_founders_only";
126
+ /** The refusal when Tower could not be asked; nothing is recorded. */
127
+ export declare const FOUNDER_CHECK_UNAVAILABLE = "founder_check_unavailable";
@@ -0,0 +1,130 @@
1
+ /**
2
+ * WHO MAY KEEP THEIR WORK OUT OF TOWER (BLI-22640, Jeetesh's review of 2026-10-25).
3
+ *
4
+ * Policy, in plain words: work done on BLI accounts or BLI hardware is BLI's,
5
+ * and all of it goes to Tower. Only the founders (Tower's owners list, the
6
+ * `tower_owners` table: Vee and Jeetesh) may turn BLI Memory off on a machine
7
+ * or keep a machine's sessions from uploading. For anybody else an "off"
8
+ * value is IGNORED and REPORTED, never obeyed, and never deleted either: the
9
+ * person's file stays exactly as they wrote it.
10
+ *
11
+ * The opt-outs this rule covers:
12
+ * - `<state_dir>/memory-capture.json` saying off (`cockpit memory off`,
13
+ * `doctor --no-memory`, "n" to the one-time question);
14
+ * - `collect_claude_jsonl: false`, `collect_codex_jsonl: false` and
15
+ * `raw_evidence_upload: "disabled"` in the collector config, including the
16
+ * copies every config rewrite carries forward (ticket 22341).
17
+ *
18
+ * Who is a founder is TOWER'S answer, never a local list and never a local
19
+ * flag, and it is asked LIVE every time a reader decides what leaves the
20
+ * machine (Jeetesh's rule on the shelves review, 2026-10-26). Two server
21
+ * replies carry it: `GET /api/ambient/founder-standing` and the heartbeat
22
+ * reply's `is_owner`.
23
+ *
24
+ * The saved copy is for DISPLAY ONLY:
25
+ *
26
+ * <state_dir>/founder-standing.json
27
+ * { "founder": false, "checked_at": "<iso>", "source": "heartbeat" }
28
+ *
29
+ * Only a Tower reply writes that file, and nothing that decides what leaves the
30
+ * machine (the hooks, the sync tick, discovery, backfill, the upload envelope,
31
+ * the hook install) reads it: a person can edit a file, so a decision made on
32
+ * it is a decision the person made. The heartbeat carries what this machine
33
+ * obeyed so Tower can compare it with its own owners list.
34
+ *
35
+ * When Tower cannot be asked (not paired, offline, a refusal such as the
36
+ * door's named 503, a reply that does not say) the reader HOLDS
37
+ * (`owner_check_unavailable`): it sends nothing that the opt-out covers and
38
+ * asks again on its next run. A hold is not an answer and is never remembered
39
+ * past the process. It errs toward the founders: a founder's client mail must
40
+ * never leave because a network call failed. A machine with no opt-out has
41
+ * nothing to decide and asks nothing.
42
+ *
43
+ * The collector writes the display file and both it and
44
+ * `@bli-cockpit/memory-mcp`'s hooks ask the door live. The two packages never
45
+ * import each other, so the door's path, the reply reading and the verdict
46
+ * live here, beside `memory-capture-contract.ts`.
47
+ */
48
+ export const FOUNDER_STANDING_FILE_NAME = "founder-standing.json";
49
+ /** Tower's door that answers "is this device's person a founder?". */
50
+ export const FOUNDER_STANDING_PATH = "/api/ambient/founder-standing";
51
+ /** `raw` is the file's text, or null when the file is not there. */
52
+ export function parseFounderStanding(raw) {
53
+ if (raw === null)
54
+ return { standing: "unknown", reason: "standing_never_checked", record: null };
55
+ let parsed;
56
+ try {
57
+ parsed = JSON.parse(raw);
58
+ }
59
+ catch {
60
+ return { standing: "unknown", reason: "standing_unreadable", record: null };
61
+ }
62
+ const value = parsed && typeof parsed === "object" && !Array.isArray(parsed)
63
+ ? parsed
64
+ : null;
65
+ if (typeof value?.["founder"] !== "boolean") {
66
+ return { standing: "unknown", reason: "standing_unreadable", record: null };
67
+ }
68
+ const record = {
69
+ founder: value["founder"],
70
+ checked_at: typeof value["checked_at"] === "string" ? value["checked_at"] : "",
71
+ source: value["source"] === "standing_door" ? "standing_door" : "heartbeat",
72
+ };
73
+ return record.founder
74
+ ? { standing: "founder", reason: "tower_says_founder", record }
75
+ : { standing: "not_founder", reason: "tower_says_not_founder", record };
76
+ }
77
+ export function renderFounderStanding(record) {
78
+ return `${JSON.stringify(record)}\n`;
79
+ }
80
+ /**
81
+ * What a reader does with an opt-out it found, and why. Every reader of every
82
+ * opt-out above asks this one function, so the hooks, the sync tick, doctor
83
+ * and the heartbeat cannot disagree. `standing` must come from a LIVE Tower
84
+ * answer (`LiveFounderAnswer`), never from the saved file.
85
+ *
86
+ * - founder -> obeyed (`opt_out_obeyed_founder`)
87
+ * - not_founder -> ignored (`opt_out_ignored_not_founder`)
88
+ * - unknown -> HELD (`owner_check_unavailable`): withheld like an obeyed
89
+ * opt-out, but named as a hold, never as the person's win.
90
+ */
91
+ export const OWNER_CHECK_UNAVAILABLE = "owner_check_unavailable";
92
+ export function optOutVerdict(standing) {
93
+ if (standing === "founder")
94
+ return { obeyed: true, held: false, reason: "opt_out_obeyed_founder" };
95
+ if (standing === "not_founder")
96
+ return { obeyed: false, held: false, reason: "opt_out_ignored_not_founder" };
97
+ return { obeyed: true, held: true, reason: OWNER_CHECK_UNAVAILABLE };
98
+ }
99
+ /** No request produced a reply at all (offline, DNS, timeout, reset). */
100
+ export function founderAnswerUnreachable() {
101
+ return { standing: "unknown", reason: "founder_check_unreachable" };
102
+ }
103
+ /** This machine has no Tower session to ask with. */
104
+ export function founderAnswerNotPaired() {
105
+ return { standing: "unknown", reason: "not_paired" };
106
+ }
107
+ /**
108
+ * Reads one reply from `GET /api/ambient/founder-standing`. Only a 200 whose
109
+ * body carries a boolean `founder` is an answer; the door's 503
110
+ * (`owners_list_unreadable`), any other status and a body that does not say are
111
+ * "Tower could not say", never a "no".
112
+ */
113
+ export function founderAnswerFromReply(reply) {
114
+ if (reply.status !== 200) {
115
+ return { standing: "unknown", reason: "founder_check_refused", httpStatus: reply.status };
116
+ }
117
+ const founder = reply.body && typeof reply.body === "object"
118
+ ? reply.body["founder"]
119
+ : undefined;
120
+ if (typeof founder !== "boolean") {
121
+ return { standing: "unknown", reason: "founder_check_bad_reply", httpStatus: reply.status };
122
+ }
123
+ return founder
124
+ ? { standing: "founder", reason: "tower_says_founder" }
125
+ : { standing: "not_founder", reason: "tower_says_not_founder" };
126
+ }
127
+ /** The refusal a non-founder gets from every door that records an "off". */
128
+ export const FOUNDERS_ONLY_REFUSAL = "memory_off_founders_only";
129
+ /** The refusal when Tower could not be asked; nothing is recorded. */
130
+ export const FOUNDER_CHECK_UNAVAILABLE = "founder_check_unavailable";
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./agent-artifacts.js";
2
+ export * from "./collection-scope.js";
2
3
  export * from "./collector-heartbeat.js";
3
4
  export * from "./setup-receipt.js";
4
5
  export * from "./agent-setup.js";
@@ -25,6 +26,8 @@ export * from "./local-config.js";
25
26
  export * from "./memory-daemon-endpoint.js";
26
27
  export * from "./memory-hook-stats.js";
27
28
  export * from "./sync-revive-contract.js";
29
+ export * from "./memory-capture-contract.js";
30
+ export * from "./founder-standing-contract.js";
28
31
  export * from "./memory-extract-context.js";
29
32
  export * from "./memory-hook-performance.js";
30
33
  export * from "./codex-hooks-trust-guide.js";
@@ -38,6 +41,7 @@ export * from "./secret-guards.js";
38
41
  export * from "./session-facts.js";
39
42
  export * from "./session-facts-delta.js";
40
43
  export * from "./shelf.js";
44
+ export * from "./safe-log.js";
41
45
  export * from "./session-facts-skills.js";
42
46
  export * from "./session-facts-spawn.js";
43
47
  export * from "./session-facts-active.js";
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./agent-artifacts.js";
2
+ export * from "./collection-scope.js";
2
3
  export * from "./collector-heartbeat.js";
3
4
  export * from "./setup-receipt.js";
4
5
  export * from "./agent-setup.js";
@@ -25,6 +26,8 @@ export * from "./local-config.js";
25
26
  export * from "./memory-daemon-endpoint.js";
26
27
  export * from "./memory-hook-stats.js";
27
28
  export * from "./sync-revive-contract.js";
29
+ export * from "./memory-capture-contract.js";
30
+ export * from "./founder-standing-contract.js";
28
31
  export * from "./memory-extract-context.js";
29
32
  export * from "./memory-hook-performance.js";
30
33
  export * from "./codex-hooks-trust-guide.js";
@@ -38,6 +41,7 @@ export * from "./secret-guards.js";
38
41
  export * from "./session-facts.js";
39
42
  export * from "./session-facts-delta.js";
40
43
  export * from "./shelf.js";
44
+ export * from "./safe-log.js";
41
45
  export * from "./session-facts-skills.js";
42
46
  export * from "./session-facts-spawn.js";
43
47
  export * from "./session-facts-active.js";
@@ -16,6 +16,20 @@ export declare const LocalCollectorConfigSchema: z.ZodObject<{
16
16
  }>>;
17
17
  collect_claude_jsonl: z.ZodDefault<z.ZodBoolean>;
18
18
  collect_codex_jsonl: z.ZodDefault<z.ZodBoolean>;
19
+ collection_scope: z.ZodOptional<z.ZodEnum<{
20
+ all: "all";
21
+ roots_only: "roots_only";
22
+ }>>;
23
+ shelf_default: z.ZodOptional<z.ZodEnum<{
24
+ drawer: "drawer";
25
+ team: "team";
26
+ }>>;
27
+ shelf_metrics_allow: z.ZodOptional<z.ZodArray<z.ZodEnum<{
28
+ model: "model";
29
+ spawn: "spawn";
30
+ day: "day";
31
+ tool: "tool";
32
+ }>>>;
19
33
  session_file_path: z.ZodOptional<z.ZodString>;
20
34
  state_dir_path: z.ZodOptional<z.ZodString>;
21
35
  }, z.core.$strict>;
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { CollectionScopeSchema } from "./collection-scope.js";
2
3
  import { IsoDateTimeSchema, NonEmptyStringSchema, VersionStringSchema, } from "./common.js";
3
4
  export const LocalCollectorConfigSchema = z
4
5
  .object({
@@ -27,6 +28,17 @@ export const LocalCollectorConfigSchema = z
27
28
  // Written to disk only when false, so an older CLI's strict parse never
28
29
  // meets the key on a machine that did not opt out.
29
30
  collect_codex_jsonl: z.boolean().default(true),
31
+ // BLI-23590. A local REQUEST for `roots_only`. It is honoured only when Tower says this person may use it
32
+ // (the install-events reply carries `eligible`), so editing it on an intern's laptop does nothing. On disk
33
+ // only when `roots_only` (`configForDisk`), so an older CLI's strict parse never meets the key otherwise.
34
+ collection_scope: CollectionScopeSchema.optional(),
35
+ // BLI-23478 (three shelves): where a founder's session goes when it is outside every labelled folder.
36
+ // Absent means `team` (today's behaviour). `safe` joins when the safe is live (slice 3). Optional with no
37
+ // default, so the key reaches disk only when someone set it and a machine that never did keeps a config
38
+ // every CLI version can read.
39
+ shelf_default: z.enum(["team", "drawer"]).optional(),
40
+ // BLI-23478: the opt-in categories a founder allows on a bare record (all off when absent).
41
+ shelf_metrics_allow: z.array(z.enum(["day", "tool", "model", "spawn"])).max(4).optional(),
30
42
  session_file_path: NonEmptyStringSchema.optional(),
31
43
  state_dir_path: NonEmptyStringSchema.optional(),
32
44
  })
@@ -0,0 +1,106 @@
1
+ /**
2
+ * THE PER-MACHINE BLI MEMORY OFF-SWITCH (BLI-22640).
3
+ *
4
+ * `cockpit doctor`, `onboard`, `update` and the 15-minute sync tick register
5
+ * BLI Memory's hooks unasked, and the Stop and PreCompact hooks send the turn
6
+ * (and a slice of the transcript) to Tower. A person whose sessions carry
7
+ * client mail or HR matters needs one durable "no" that every one of those
8
+ * paths reads, and that the hooks themselves read before they send anything.
9
+ *
10
+ * The choice is ONE small file in the collector's state directory:
11
+ *
12
+ * <state_dir>/memory-capture.json
13
+ * { "memory_capture": false, "chosen_at": "<iso>", "via": "memory_off" }
14
+ *
15
+ * A file, not a key in `config.json`, for the same two reasons as the
16
+ * autostart and usage-telemetry opt-outs beside it: every config rewrite
17
+ * (doctor, onboard, update, roots add) rebuilds `config.json` from a list of
18
+ * known keys, which is exactly how ticket 22341's opt-out was lost; and the
19
+ * config's schema is strict, so a new key there breaks an older CLI on the
20
+ * same machine. Nothing rewrites this file except the person's own answer.
21
+ *
22
+ * Absent means the person was never asked: the default (on) applies, and an
23
+ * interactive `doctor` / `onboard` asks once. Present but unreadable is read as
24
+ * OFF: somebody wrote a choice there, and guessing "on" over it would send
25
+ * conversation text against a decision we could not read.
26
+ *
27
+ * The collector writes the file; `@bli-cockpit/memory-mcp`'s hooks read it.
28
+ * The two packages never import each other, so the name and the reading live
29
+ * here, the rule `sync-revive-contract.ts` follows.
30
+ *
31
+ * Only a founder's "off" is obeyed (`founder-standing-contract.ts`, Jeetesh's
32
+ * review of 2026-10-25), on Tower's live answer; anybody else's is ignored and
33
+ * reported, and when Tower cannot answer the reader holds.
34
+ */
35
+ import { type CaptureOptOutLabel, type FounderStanding, type OptOutVerdict } from "./founder-standing-contract.js";
36
+ export declare const MEMORY_CAPTURE_CHOICE_FILE_NAME = "memory-capture.json";
37
+ /** Which door recorded the choice. A label, never a path. */
38
+ export type MemoryCaptureVia = "prompt" | "memory_on" | "memory_off" | "memory_install" | "memory_uninstall" | "doctor_flag";
39
+ export interface MemoryCaptureChoice {
40
+ memory_capture: boolean;
41
+ chosen_at: string;
42
+ via: MemoryCaptureVia;
43
+ }
44
+ export type MemoryCaptureReading =
45
+ /** Never asked; the default (on) applies. */
46
+ {
47
+ state: "unchosen";
48
+ } | {
49
+ state: "on";
50
+ choice: MemoryCaptureChoice;
51
+ } | {
52
+ state: "off";
53
+ choice: MemoryCaptureChoice | null;
54
+ reason: "explicit_opt_out" | "choice_unreadable";
55
+ };
56
+ /** `raw` is the file's text, or null when the file is not there. */
57
+ export declare function parseMemoryCaptureChoice(raw: string | null): MemoryCaptureReading;
58
+ export declare function renderMemoryCaptureChoice(choice: MemoryCaptureChoice): string;
59
+ /** Which agent host wrote the session a hook is about. */
60
+ export type MemoryHookHost = "claude_code" | "codex";
61
+ /**
62
+ * What a hook does with this machine's opt-outs before it sends anything.
63
+ *
64
+ * Two independent "no"s, either one enough, and each one obeyed ONLY for a
65
+ * founder (`founder-standing-contract.ts`):
66
+ * - `memory_opt_out`: this machine turned BLI Memory off (the file above).
67
+ * Every hook skips: recall sends the prompt to Tower as a search.
68
+ * - `session_upload_opt_out`: this host's sessions are opted out of upload in
69
+ * the collector config (`collect_claude_jsonl: false`,
70
+ * `collect_codex_jsonl: false`, or `raw_evidence_upload: "disabled"`). Only
71
+ * the SAVE hooks (Stop, PreCompact) skip: they send a slice of that same
72
+ * conversation.
73
+ *
74
+ * For a non-founder neither is obeyed: `refusal` is null and `ignored` names
75
+ * what was found, so the hook says so on its log line. `standing` is Tower's
76
+ * LIVE answer, never the saved file; an unknown one (Tower could not be asked)
77
+ * HOLDS: `refusal` is set, `held` is true and `obeyedReason` is
78
+ * `owner_check_unavailable`.
79
+ *
80
+ * `config` is the parsed `config.json` record, or null when it is missing or
81
+ * unreadable (no source opt-out can be read from it, so none applies).
82
+ */
83
+ export interface MemoryCaptureGate {
84
+ refusal: "memory_opt_out" | "session_upload_opt_out" | null;
85
+ /** Opt-outs found and NOT obeyed because Tower says this person is not a founder. */
86
+ ignored: CaptureOptOutLabel[];
87
+ /** Why the refusal was obeyed; null when nothing was. */
88
+ obeyedReason: OptOutVerdict["reason"] | null;
89
+ /** True when the refusal is a hold: Tower could not say whether this person is a founder. */
90
+ held: boolean;
91
+ }
92
+ export declare function memoryCaptureGate(input: {
93
+ choice: MemoryCaptureReading;
94
+ config: Record<string, unknown> | null;
95
+ host: MemoryHookHost;
96
+ standing: FounderStanding;
97
+ saveHook: boolean;
98
+ }): MemoryCaptureGate;
99
+ /** The config's opt-out for one host's sessions, or null when they upload. */
100
+ export declare function sessionOptOutLabel(config: Record<string, unknown> | null, host: MemoryHookHost): CaptureOptOutLabel | null;
101
+ /**
102
+ * Which host a hook payload's transcript belongs to. Codex keeps its sessions
103
+ * under `.codex/sessions/`; Claude Code under `.claude/projects/`. Anything
104
+ * else reads as Claude Code, the host whose opt-out key the ticket named.
105
+ */
106
+ export declare function memoryHookHost(transcriptPath: string | undefined): MemoryHookHost;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * THE PER-MACHINE BLI MEMORY OFF-SWITCH (BLI-22640).
3
+ *
4
+ * `cockpit doctor`, `onboard`, `update` and the 15-minute sync tick register
5
+ * BLI Memory's hooks unasked, and the Stop and PreCompact hooks send the turn
6
+ * (and a slice of the transcript) to Tower. A person whose sessions carry
7
+ * client mail or HR matters needs one durable "no" that every one of those
8
+ * paths reads, and that the hooks themselves read before they send anything.
9
+ *
10
+ * The choice is ONE small file in the collector's state directory:
11
+ *
12
+ * <state_dir>/memory-capture.json
13
+ * { "memory_capture": false, "chosen_at": "<iso>", "via": "memory_off" }
14
+ *
15
+ * A file, not a key in `config.json`, for the same two reasons as the
16
+ * autostart and usage-telemetry opt-outs beside it: every config rewrite
17
+ * (doctor, onboard, update, roots add) rebuilds `config.json` from a list of
18
+ * known keys, which is exactly how ticket 22341's opt-out was lost; and the
19
+ * config's schema is strict, so a new key there breaks an older CLI on the
20
+ * same machine. Nothing rewrites this file except the person's own answer.
21
+ *
22
+ * Absent means the person was never asked: the default (on) applies, and an
23
+ * interactive `doctor` / `onboard` asks once. Present but unreadable is read as
24
+ * OFF: somebody wrote a choice there, and guessing "on" over it would send
25
+ * conversation text against a decision we could not read.
26
+ *
27
+ * The collector writes the file; `@bli-cockpit/memory-mcp`'s hooks read it.
28
+ * The two packages never import each other, so the name and the reading live
29
+ * here, the rule `sync-revive-contract.ts` follows.
30
+ *
31
+ * Only a founder's "off" is obeyed (`founder-standing-contract.ts`, Jeetesh's
32
+ * review of 2026-10-25), on Tower's live answer; anybody else's is ignored and
33
+ * reported, and when Tower cannot answer the reader holds.
34
+ */
35
+ import { optOutVerdict, } from "./founder-standing-contract.js";
36
+ export const MEMORY_CAPTURE_CHOICE_FILE_NAME = "memory-capture.json";
37
+ /** `raw` is the file's text, or null when the file is not there. */
38
+ export function parseMemoryCaptureChoice(raw) {
39
+ if (raw === null)
40
+ return { state: "unchosen" };
41
+ let parsed;
42
+ try {
43
+ parsed = JSON.parse(raw);
44
+ }
45
+ catch {
46
+ return { state: "off", choice: null, reason: "choice_unreadable" };
47
+ }
48
+ const record = parsed && typeof parsed === "object" && !Array.isArray(parsed)
49
+ ? parsed
50
+ : null;
51
+ const value = record?.["memory_capture"];
52
+ if (typeof value !== "boolean") {
53
+ return { state: "off", choice: null, reason: "choice_unreadable" };
54
+ }
55
+ const choice = {
56
+ memory_capture: value,
57
+ chosen_at: typeof record?.["chosen_at"] === "string" ? record["chosen_at"] : "",
58
+ via: typeof record?.["via"] === "string" ? record["via"] : "memory_off",
59
+ };
60
+ return value
61
+ ? { state: "on", choice }
62
+ : { state: "off", choice, reason: "explicit_opt_out" };
63
+ }
64
+ export function renderMemoryCaptureChoice(choice) {
65
+ return `${JSON.stringify(choice)}\n`;
66
+ }
67
+ export function memoryCaptureGate(input) {
68
+ const memoryOff = input.choice.state === "off";
69
+ const sessionLabel = input.saveHook ? sessionOptOutLabel(input.config, input.host) : null;
70
+ const found = [
71
+ ...(memoryOff ? ["memory_capture_off"] : []),
72
+ ...(sessionLabel ? [sessionLabel] : []),
73
+ ];
74
+ if (found.length === 0)
75
+ return { refusal: null, ignored: [], obeyedReason: null, held: false };
76
+ const verdict = optOutVerdict(input.standing);
77
+ if (!verdict.obeyed)
78
+ return { refusal: null, ignored: found, obeyedReason: null, held: false };
79
+ return {
80
+ refusal: memoryOff ? "memory_opt_out" : "session_upload_opt_out",
81
+ ignored: [],
82
+ obeyedReason: verdict.reason,
83
+ held: verdict.held,
84
+ };
85
+ }
86
+ /** The config's opt-out for one host's sessions, or null when they upload. */
87
+ export function sessionOptOutLabel(config, host) {
88
+ if (!config)
89
+ return null;
90
+ const key = host === "codex" ? "collect_codex_jsonl" : "collect_claude_jsonl";
91
+ if (config[key] === false)
92
+ return host === "codex" ? "collect_codex_jsonl_false" : "collect_claude_jsonl_false";
93
+ return config["raw_evidence_upload"] === "disabled" ? "raw_evidence_upload_disabled" : null;
94
+ }
95
+ /**
96
+ * Which host a hook payload's transcript belongs to. Codex keeps its sessions
97
+ * under `.codex/sessions/`; Claude Code under `.claude/projects/`. Anything
98
+ * else reads as Claude Code, the host whose opt-out key the ticket named.
99
+ */
100
+ export function memoryHookHost(transcriptPath) {
101
+ if (!transcriptPath)
102
+ return "claude_code";
103
+ return /(^|[\\/])\.codex[\\/]/u.test(transcriptPath) ? "codex" : "claude_code";
104
+ }
@@ -1,8 +1,17 @@
1
- export type ExperienceStore = "bli" | "supermemory" | "both";
1
+ /**
2
+ * BLI-24380: BLI Memory is the only memory store. `supermemory` and `both` are
3
+ * retired: a new entry naming them is accepted (never an error) and logged as
4
+ * retired, and receipts queued before the retirement still ship unchanged.
5
+ */
6
+ export type ExperienceStore = "bli";
7
+ export type RetiredExperienceStore = "supermemory" | "both";
8
+ /** What a stored or queued receipt may carry: today's store or a retired one. */
9
+ export type RecordedExperienceStore = ExperienceStore | RetiredExperienceStore;
10
+ export declare const RETIRED_EXPERIENCE_STORES: readonly RetiredExperienceStore[];
2
11
  export type ExperienceVerdict = "win" | "loss" | "noise";
3
12
  export interface MemoryExperience {
4
13
  id: string;
5
- store: ExperienceStore;
14
+ store: RecordedExperienceStore;
6
15
  verdict: ExperienceVerdict;
7
16
  reason: string;
8
17
  created_at: string;
@@ -14,6 +23,24 @@ export type ExperienceSender = (entry: MemoryExperience) => Promise<{
14
23
  ok: boolean;
15
24
  reason?: string;
16
25
  }>;
26
+ export type NormalisedExperienceStore = {
27
+ store: ExperienceStore;
28
+ given: string;
29
+ retired: boolean;
30
+ } | {
31
+ store: null;
32
+ given: "supermemory";
33
+ retired: true;
34
+ reason: "store_retired";
35
+ };
36
+ /**
37
+ * The one rule every new-entry door shares (CLI, MCP). Omitted means `bli`.
38
+ * `both` records as `bli`: BLI Memory was one of the stores that answered.
39
+ * `supermemory` records nothing: that store is gone, so a verdict about it is
40
+ * not a fact about anything Tower runs. Anything else is a caller error.
41
+ */
42
+ export declare function normaliseExperienceStore(given: string | undefined): NormalisedExperienceStore;
43
+ /** Validates a receipt. Retired stores stay valid so an old queued receipt still ships. */
17
44
  export declare function validateExperience(store: string, verdict: string, reason: string): void;
18
45
  export declare function experienceLine(entry: MemoryExperience, agent: string, project: string): string;
19
46
  export declare function appendExperience(input: {
@@ -4,20 +4,42 @@ import { randomUUID } from "node:crypto";
4
4
  import { homedir } from "node:os";
5
5
  import path from "node:path";
6
6
  import { redactSecretLikeContent } from "./secret-guards-masking.js";
7
+ export const RETIRED_EXPERIENCE_STORES = ["supermemory", "both"];
8
+ /**
9
+ * The one rule every new-entry door shares (CLI, MCP). Omitted means `bli`.
10
+ * `both` records as `bli`: BLI Memory was one of the stores that answered.
11
+ * `supermemory` records nothing: that store is gone, so a verdict about it is
12
+ * not a fact about anything Tower runs. Anything else is a caller error.
13
+ */
14
+ export function normaliseExperienceStore(given) {
15
+ const value = given ?? "bli";
16
+ if (value === "bli") {
17
+ return { store: "bli", given: value, retired: false };
18
+ }
19
+ if (value === "both") {
20
+ console.error("[memory experience] store retired", JSON.stringify({ given: value, recorded: "bli" }));
21
+ return { store: "bli", given: value, retired: true };
22
+ }
23
+ if (value === "supermemory") {
24
+ console.error("[memory experience] store retired", JSON.stringify({ given: value, recorded: null, reason: "store_retired" }));
25
+ return { store: null, given: value, retired: true, reason: "store_retired" };
26
+ }
27
+ throw new Error("store must be bli (supermemory and both are retired)");
28
+ }
29
+ /** Validates a receipt. Retired stores stay valid so an old queued receipt still ships. */
7
30
  export function validateExperience(store, verdict, reason) {
8
- if (!["bli", "supermemory", "both"].includes(store))
9
- throw new Error("store must be bli, supermemory or both");
31
+ if (store !== "bli" && !RETIRED_EXPERIENCE_STORES.includes(store))
32
+ throw new Error("store must be bli (supermemory and both are retired)");
10
33
  if (!["win", "loss", "noise"].includes(verdict))
11
34
  throw new Error("verdict must be win, loss or noise");
12
35
  if (!reason.trim() || [...reason].length > 500 || /[\r\n\x00-\x1f\x7f]/u.test(reason)) {
13
36
  throw new Error("reason must be one nonempty line of at most 500 characters; opinions only, no prompts, memory bodies or secrets");
14
37
  }
15
38
  }
16
- const markers = { bli: "[bli]", supermemory: "◪", both: "[bli]+◪" };
17
39
  export function experienceLine(entry, agent, project) {
18
40
  const stamp = new Date(Date.parse(entry.created_at) + 7 * 3600000).toISOString().slice(0, 16).replace("T", " ");
19
41
  const label = (value) => value.replace(/[\r\n·]/gu, " ");
20
- return `- ${stamp} ICT · ${label(agent)} · ${label(project)} · ${entry.store} ${markers[entry.store]} · ${entry.verdict}: ${entry.reason}`;
42
+ return `- ${stamp} ICT · ${label(agent)} · ${label(project)} · ${entry.store} [bli] · ${entry.verdict}: ${entry.reason}`;
21
43
  }
22
44
  function paths(home) {
23
45
  return { log: path.join(home, ".codex", "AGENT-EXPERIENCE.md"), queue: path.join(home, ".codex", "agent-experience-outbox") };
@@ -29,6 +51,9 @@ async function saveReceipt(home, entry) {
29
51
  await rename(temp, target);
30
52
  }
31
53
  export async function appendExperience(input, options) {
54
+ // BLI-24380: a new entry records BLI Memory only; callers normalise first.
55
+ if (input.store !== "bli")
56
+ throw new Error("appendExperience records bli only; run normaliseExperienceStore first");
32
57
  validateExperience(input.store, input.verdict, input.reason);
33
58
  // BLI-12187: the reason is free text an agent wrote and it is uploaded, so the
34
59
  // value is masked before the receipt, the local log or the outbox sees it.
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The one logger for shelf code (BLI-23478, three-shelves design 4.7).
3
+ *
4
+ * Every module that touches drawer or safe plaintext (the drawer spool, the shelf routing in the collector and the
5
+ * hooks) logs ONLY through `safeLog`. Its record admits reason labels, counts, ids, hashes, sizes and durations; an
6
+ * exception is logged by its NAME only. The rule is enforced at run time, not trusted to review: a string value
7
+ * that is not label-shaped (letters, digits and `_ . : @ + -`, at most 120 characters; no spaces and no slashes, so
8
+ * no path) is replaced by `[withheld:not_a_label]`, so a sentence, a path or a snippet can never reach a log line, a
9
+ * receipt or a sync-health detail through this function, whatever a caller passes it.
10
+ *
11
+ * Output goes to stderr, as one line: `[<tag>] <reason> {json}`. stdout is a command's `--json` answer (collector)
12
+ * or the host's context channel (hooks), so it is never used here.
13
+ */
14
+ export type SafeLogValue = string | number | boolean | null;
15
+ export type SafeLogRecord = Record<string, SafeLogValue | undefined>;
16
+ export declare const SAFE_LOG_WITHHELD = "[withheld:not_a_label]";
17
+ export interface SafeLogSink {
18
+ write(line: string): unknown;
19
+ }
20
+ /** Tests: capture every line. Pass null to restore stderr. */
21
+ export declare function setSafeLogSinkForTests(next: SafeLogSink | null): void;
22
+ /** The name of an exception, never its message (a message can carry a path or the content that failed). */
23
+ export declare function errorNameOnly(error: unknown): string;
24
+ /** The record as it will be logged: unknown-shaped keys dropped, non-label strings withheld. */
25
+ export declare function sanitizeSafeLogRecord(record: SafeLogRecord): Record<string, SafeLogValue>;
26
+ /**
27
+ * Log one shelf decision. `tag` names the module (`shelf`, `drawer-spool`), `reason` is the label the line is about.
28
+ * Both must be labels themselves; a tag or reason that is not is withheld like any other value.
29
+ */
30
+ export declare function safeLog(tag: string, reason: string, record?: SafeLogRecord): void;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The one logger for shelf code (BLI-23478, three-shelves design 4.7).
3
+ *
4
+ * Every module that touches drawer or safe plaintext (the drawer spool, the shelf routing in the collector and the
5
+ * hooks) logs ONLY through `safeLog`. Its record admits reason labels, counts, ids, hashes, sizes and durations; an
6
+ * exception is logged by its NAME only. The rule is enforced at run time, not trusted to review: a string value
7
+ * that is not label-shaped (letters, digits and `_ . : @ + -`, at most 120 characters; no spaces and no slashes, so
8
+ * no path) is replaced by `[withheld:not_a_label]`, so a sentence, a path or a snippet can never reach a log line, a
9
+ * receipt or a sync-health detail through this function, whatever a caller passes it.
10
+ *
11
+ * Output goes to stderr, as one line: `[<tag>] <reason> {json}`. stdout is a command's `--json` answer (collector)
12
+ * or the host's context channel (hooks), so it is never used here.
13
+ */
14
+ export const SAFE_LOG_WITHHELD = "[withheld:not_a_label]";
15
+ const LABEL = /^[A-Za-z0-9_.:@+-]{0,120}$/u;
16
+ const KEY = /^[a-z][a-z0-9_]{0,47}$/u;
17
+ let sink = { write: (line) => process.stderr.write(line) };
18
+ /** Tests: capture every line. Pass null to restore stderr. */
19
+ export function setSafeLogSinkForTests(next) {
20
+ sink = next ?? { write: (line) => process.stderr.write(line) };
21
+ }
22
+ /** The name of an exception, never its message (a message can carry a path or the content that failed). */
23
+ export function errorNameOnly(error) {
24
+ if (error instanceof Error) {
25
+ const code = error.code;
26
+ if (typeof code === "string" && LABEL.test(code))
27
+ return `${error.name || "Error"}:${code}`;
28
+ return LABEL.test(error.name) ? error.name || "Error" : "Error";
29
+ }
30
+ return "non_error_thrown";
31
+ }
32
+ function safeValue(value) {
33
+ if (typeof value === "string")
34
+ return LABEL.test(value) ? value : SAFE_LOG_WITHHELD;
35
+ if (typeof value === "number")
36
+ return Number.isFinite(value) ? value : null;
37
+ return value;
38
+ }
39
+ /** The record as it will be logged: unknown-shaped keys dropped, non-label strings withheld. */
40
+ export function sanitizeSafeLogRecord(record) {
41
+ const out = {};
42
+ for (const [key, value] of Object.entries(record)) {
43
+ if (value === undefined || !KEY.test(key))
44
+ continue;
45
+ out[key] = safeValue(value);
46
+ }
47
+ return out;
48
+ }
49
+ /**
50
+ * Log one shelf decision. `tag` names the module (`shelf`, `drawer-spool`), `reason` is the label the line is about.
51
+ * Both must be labels themselves; a tag or reason that is not is withheld like any other value.
52
+ */
53
+ export function safeLog(tag, reason, record = {}) {
54
+ const safeTag = LABEL.test(tag) ? tag : "shelf";
55
+ const safeReason = LABEL.test(reason) ? reason : SAFE_LOG_WITHHELD;
56
+ const fields = { reason: safeReason, ...sanitizeSafeLogRecord(record) };
57
+ try {
58
+ sink.write(`[${safeTag}] ${safeReason} ${JSON.stringify(fields)}\n`);
59
+ }
60
+ catch {
61
+ // A log line that cannot be written must not break the decision it describes.
62
+ }
63
+ }
@@ -112,7 +112,9 @@ export function setupReceiptPieces(receipt, memory) {
112
112
  const reason = memory?.reasons?.[key];
113
113
  return {
114
114
  status: word,
115
- ...(word !== "ok" && reason ? { reason } : {}),
115
+ // BLI-24349: `ok` keeps one reason, `managed_by_system`, so a machine
116
+ // card can say HOW Codex runs the hooks (no trust step needed).
117
+ ...((word !== "ok" || reason === "managed_by_system") && reason ? { reason } : {}),
116
118
  };
117
119
  };
118
120
  return [
package/dist/shelf.d.ts CHANGED
@@ -157,3 +157,68 @@ export declare const ShelfReportsEnvelopeSchema: z.ZodObject<{
157
157
  export type ShelfReportsEnvelope = z.infer<typeof ShelfReportsEnvelopeSchema>;
158
158
  /** `a >= b` for dotted numeric versions (`0.2.250`). Anything unparseable is treated as too old. */
159
159
  export declare function cliVersionAtLeast(version: string | null | undefined, minimum: string): boolean;
160
+ /**
161
+ * The three headers every device-token request from the routing release carries. Only `team` text ever leaves a
162
+ * laptop, so `shelf` is always `team` on the wire; a drawer session or memory is never sent at all.
163
+ */
164
+ export declare function shelfRequestHeaders(options: {
165
+ caller: ShelfCaller;
166
+ cliVersion: string | null | undefined;
167
+ }): Record<string, string>;
168
+ /** The fields of a counted session the bare record is projected from (a subset of `SessionFacts`). */
169
+ export interface ShelfMetricsFacts {
170
+ source: "codex" | "claude_code";
171
+ usage_by_model: Record<string, {
172
+ input_tokens: number;
173
+ output_tokens: number;
174
+ cache_read_input_tokens: number;
175
+ cache_creation_input_tokens: number;
176
+ }>;
177
+ input_tokens: number;
178
+ output_tokens: number;
179
+ cache_read_tokens: number;
180
+ cache_creation_tokens: number;
181
+ total_tokens: number;
182
+ turn_count: number;
183
+ user_prompt_count: number;
184
+ assistant_response_count: number;
185
+ tool_call_count: number;
186
+ first_timestamp: string | null;
187
+ wall_duration_seconds: number | null;
188
+ active_seconds?: number;
189
+ transcript_bytes: number;
190
+ transcript_lines: number;
191
+ transcript_files: number;
192
+ spawn?: {
193
+ kind: "interactive" | "worker" | "subagent";
194
+ };
195
+ }
196
+ /**
197
+ * The bare record for one drawer or safe session (design 3.2): the always-sent numbers, plus only the categories
198
+ * the founder allowed on this laptop. Nothing else of the session can reach it: no id, folder, branch, commit,
199
+ * tool name or text. The result is validated against the strict schema before it is returned, so a projection
200
+ * that ever produced an extra key throws here, on the laptop, rather than being refused by Tower.
201
+ */
202
+ export declare function projectShelfMetrics(facts: ShelfMetricsFacts, allow?: readonly ShelfMetricCategory[]): ShelfSessionMetrics;
203
+ /**
204
+ * What the last heartbeat told this laptop about the lock (design 4.4 "Exemption"), kept in the collector's state
205
+ * dir so the hooks and the Memory MCP server can read it without a network call. Written ONLY by the collector's
206
+ * heartbeat; a missing or unreadable file means "not known to be an owner's laptop", and nothing changes.
207
+ */
208
+ export declare const SHELF_STATE_FILENAME = "shelf-state.json";
209
+ export declare const SHELF_STATE_SCHEMA_VERSION = "shelf-state.v1";
210
+ export declare const ShelfStateFileSchema: z.ZodObject<{
211
+ schema_version: z.ZodLiteral<"shelf-state.v1">;
212
+ checked_at: z.ZodString;
213
+ shelf_enforced: z.ZodBoolean;
214
+ is_owner: z.ZodNullable<z.ZodBoolean>;
215
+ founder_routing_enabled: z.ZodNullable<z.ZodBoolean>;
216
+ min_cli_version: z.ZodNullable<z.ZodString>;
217
+ cli_too_old: z.ZodBoolean;
218
+ }, z.core.$strict>;
219
+ export type ShelfStateFile = z.infer<typeof ShelfStateFileSchema>;
220
+ /** Where the collector keeps a founder's folder labels, beside the approved roots (`<config dir>/root-approvals.json`). */
221
+ export declare const ROOT_APPROVALS_FILENAME = "root-approvals.json";
222
+ /** Labels a folder may carry on the laptop in this release. `safe` is refused until the safe is live (slice 3). */
223
+ export declare const ROOT_LABEL_SHELVES: readonly ["team", "drawer"];
224
+ export type RootLabelShelf = (typeof ROOT_LABEL_SHELVES)[number];
package/dist/shelf.js CHANGED
@@ -109,3 +109,94 @@ export function cliVersionAtLeast(version, minimum) {
109
109
  }
110
110
  return true;
111
111
  }
112
+ // ---------------------------------------------------------------------------
113
+ // BLI-23478 (slice 1b, the laptop half): what the collector and the hooks send.
114
+ // ---------------------------------------------------------------------------
115
+ /**
116
+ * The three headers every device-token request from the routing release carries. Only `team` text ever leaves a
117
+ * laptop, so `shelf` is always `team` on the wire; a drawer session or memory is never sent at all.
118
+ */
119
+ export function shelfRequestHeaders(options) {
120
+ return {
121
+ [SHELF_HEADER]: "team",
122
+ [SHELF_CALLER_HEADER]: options.caller,
123
+ ...(options.cliVersion ? { [SHELF_CLI_VERSION_HEADER]: options.cliVersion } : {}),
124
+ };
125
+ }
126
+ const COUNT_CEILING = 1_000_000_000_000;
127
+ const MODEL_KEY = /^[A-Za-z0-9._:/-]+$/u;
128
+ function count(value) {
129
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
130
+ return 0;
131
+ return Math.min(Math.floor(value), COUNT_CEILING);
132
+ }
133
+ /**
134
+ * The bare record for one drawer or safe session (design 3.2): the always-sent numbers, plus only the categories
135
+ * the founder allowed on this laptop. Nothing else of the session can reach it: no id, folder, branch, commit,
136
+ * tool name or text. The result is validated against the strict schema before it is returned, so a projection
137
+ * that ever produced an extra key throws here, on the laptop, rather than being refused by Tower.
138
+ */
139
+ export function projectShelfMetrics(facts, allow = []) {
140
+ const allowed = new Set(allow);
141
+ const metrics = {
142
+ wall_duration_seconds: count(facts.wall_duration_seconds),
143
+ active_seconds: count(facts.active_seconds),
144
+ turn_count: count(facts.turn_count),
145
+ user_prompt_count: count(facts.user_prompt_count),
146
+ assistant_response_count: count(facts.assistant_response_count),
147
+ tool_call_count: count(facts.tool_call_count),
148
+ input_tokens: count(facts.input_tokens),
149
+ output_tokens: count(facts.output_tokens),
150
+ cache_read_tokens: count(facts.cache_read_tokens),
151
+ cache_creation_tokens: count(facts.cache_creation_tokens),
152
+ total_tokens: count(facts.total_tokens),
153
+ transcript_bytes: count(facts.transcript_bytes),
154
+ transcript_lines: count(facts.transcript_lines),
155
+ transcript_files: count(facts.transcript_files),
156
+ };
157
+ if (allowed.has("day") && facts.first_timestamp) {
158
+ const day = new Date(facts.first_timestamp);
159
+ if (Number.isFinite(day.getTime()))
160
+ metrics.day = day.toISOString().slice(0, 10);
161
+ }
162
+ if (allowed.has("tool"))
163
+ metrics.tool = facts.source === "codex" ? "codex" : "claude";
164
+ if (allowed.has("model")) {
165
+ const byModel = {};
166
+ for (const [model, usage] of Object.entries(facts.usage_by_model)) {
167
+ const key = model.trim().slice(0, 80);
168
+ if (!key || !MODEL_KEY.test(key))
169
+ continue;
170
+ byModel[key] = count((byModel[key] ?? 0) + usage.input_tokens + usage.output_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens);
171
+ }
172
+ if (Object.keys(byModel).length > 0)
173
+ metrics.model_tokens = byModel;
174
+ }
175
+ if (allowed.has("spawn") && facts.spawn) {
176
+ metrics.spawn_kind = facts.spawn.kind === "interactive" ? "human" : facts.spawn.kind === "worker" ? "automated" : "subagent";
177
+ }
178
+ return ShelfSessionMetricsSchema.parse(metrics);
179
+ }
180
+ /**
181
+ * What the last heartbeat told this laptop about the lock (design 4.4 "Exemption"), kept in the collector's state
182
+ * dir so the hooks and the Memory MCP server can read it without a network call. Written ONLY by the collector's
183
+ * heartbeat; a missing or unreadable file means "not known to be an owner's laptop", and nothing changes.
184
+ */
185
+ export const SHELF_STATE_FILENAME = "shelf-state.json";
186
+ export const SHELF_STATE_SCHEMA_VERSION = "shelf-state.v1";
187
+ export const ShelfStateFileSchema = z
188
+ .object({
189
+ schema_version: z.literal(SHELF_STATE_SCHEMA_VERSION),
190
+ checked_at: IsoDateTimeSchema,
191
+ shelf_enforced: z.boolean(),
192
+ /** Null when the server could not read its own state this time. */
193
+ is_owner: z.boolean().nullable(),
194
+ founder_routing_enabled: z.boolean().nullable(),
195
+ min_cli_version: z.string().max(40).nullable(),
196
+ cli_too_old: z.boolean(),
197
+ })
198
+ .strict();
199
+ /** Where the collector keeps a founder's folder labels, beside the approved roots (`<config dir>/root-approvals.json`). */
200
+ export const ROOT_APPROVALS_FILENAME = "root-approvals.json";
201
+ /** Labels a folder may carry on the laptop in this release. `safe` is refused until the safe is live (slice 3). */
202
+ export const ROOT_LABEL_SHELVES = ["team", "drawer"];
@@ -32,6 +32,12 @@ export declare const NO_UPLOAD_ATTEMPT_RECORDED = "no_upload_attempt_recorded";
32
32
  * keep one it had already received.
33
33
  */
34
34
  export declare const STORAGE_REJECTED_OBJECT_TOO_LARGE = "storage_rejected_object_too_large";
35
+ /** BLI-23478: a founder's session kept in the drawer on the laptop (its bare numbers are sent instead). */
36
+ export declare const SHELF_DRAWER = "shelf_drawer";
37
+ /** BLI-23478: a founder's session kept for the safe (not a live shelf yet; treated as the drawer). */
38
+ export declare const SHELF_SAFE = "shelf_safe";
39
+ /** BLI-23478: a pack whose sources resolve to more than one shelf; refused before anything is staged. */
40
+ export declare const MIXED_SHELF_PACK = "mixed_shelf_pack";
35
41
  /** Storage refused the finished object because of its declared media type. */
36
42
  export declare const STORAGE_REJECTED_MEDIA_TYPE = "storage_rejected_media_type";
37
43
  /**
@@ -39,6 +39,12 @@ export const NO_UPLOAD_ATTEMPT_RECORDED = "no_upload_attempt_recorded";
39
39
  * keep one it had already received.
40
40
  */
41
41
  export const STORAGE_REJECTED_OBJECT_TOO_LARGE = "storage_rejected_object_too_large";
42
+ /** BLI-23478: a founder's session kept in the drawer on the laptop (its bare numbers are sent instead). */
43
+ export const SHELF_DRAWER = "shelf_drawer";
44
+ /** BLI-23478: a founder's session kept for the safe (not a live shelf yet; treated as the drawer). */
45
+ export const SHELF_SAFE = "shelf_safe";
46
+ /** BLI-23478: a pack whose sources resolve to more than one shelf; refused before anything is staged. */
47
+ export const MIXED_SHELF_PACK = "mixed_shelf_pack";
42
48
  /** Storage refused the finished object because of its declared media type. */
43
49
  export const STORAGE_REJECTED_MEDIA_TYPE = "storage_rejected_media_type";
44
50
  /**
@@ -260,6 +266,13 @@ const UPLOAD_FAILURE_CLASSES = {
260
266
  secret_redaction_failed: "withheld_by_policy",
261
267
  // The server-side name for the same guard, returned by the commit route.
262
268
  secret_guard_rejected: "withheld_by_policy",
269
+ // BLI-23478 (three shelves): a founder's session that belongs in the drawer or the safe stays on the laptop by
270
+ // the founder's own label; only its bare numbers leave. A retry would be an attempt to upload it anyway.
271
+ [SHELF_DRAWER]: "withheld_by_policy",
272
+ [SHELF_SAFE]: "withheld_by_policy",
273
+ // A pack whose sources do not all resolve to one shelf. Nothing was staged; it stays refused until the labels
274
+ // agree, so repeating the identical call changes nothing.
275
+ [MIXED_SHELF_PACK]: "deterministic",
263
276
  };
264
277
  const HTTP_STATUS_SUFFIX = /_http_\d{3}$/u;
265
278
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bli-cockpit/telemetry-core",
3
- "version": "0.1.94",
3
+ "version": "0.1.96",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",