total-recall-brain 3.40.5 → 3.40.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "total-recall-brain",
3
- "version": "3.40.5",
3
+ "version": "3.40.6",
4
4
  "description": "The Vibe Coding Brain & Autonomous Software Factory: memory, rules, secrets, and 33 visual plugins automatically managed across all your devices.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli/init.mjs CHANGED
@@ -198,6 +198,59 @@ function printHelp() {
198
198
  `);
199
199
  }
200
200
 
201
+ // ─── Bootstrap token store resolution ───────────────────────────────────────
202
+
203
+ /**
204
+ * The brain directory whose key store the server answering `brainUrl` reads.
205
+ *
206
+ * A server process derives its store from `AGENT_DIR` alone (`core/config.mjs`
207
+ * → `brainDir`), and the launchd service starts it with the GLOBAL agent dir.
208
+ * So a token written into a project brain's `brain.json` is only usable when
209
+ * it was minted into that global store. Minting into the project's own store
210
+ * produced a token no running server would accept, while init still reported
211
+ * success — the failure surfaced later as `startup check` reporting
212
+ * `brain failed` (`instructions-http-401`) for every project.
213
+ *
214
+ * Loopback URLs therefore resolve to the store the local server reads. A
215
+ * remote brain's store is not reachable from here, so the target brain keeps
216
+ * its own store.
217
+ *
218
+ * Two constraints pull against each other and both must hold:
219
+ * 1. `AGENT_DIR` (and the `_TR_TEST_AGENT_DIR` fixture override) honours an
220
+ * explicitly selected root, so the serving store must not be derived by
221
+ * blindly re-reading it — when it is pinned at the project the two stores
222
+ * collapse and the bug returns untouched.
223
+ * 2. An explicit root owns its whole layout: init must never create
224
+ * `$HOME/.agent` behind a caller that named a different root (a test, or
225
+ * an isolated install). So `globalBrainDir` is used only when it is
226
+ * genuinely distinct AND already exists; otherwise the target store is
227
+ * kept rather than a new one being created.
228
+ */
229
+ export function resolveServingBrainDir({ brainDir, isProject, brainUrl, globalBrainDir = null }) {
230
+ if (!isProject) return brainDir;
231
+ let loopback = false;
232
+ try {
233
+ const host = new URL(brainUrl).hostname;
234
+ loopback = ['localhost', '127.0.0.1', '[::1]', '::1'].includes(host);
235
+ } catch { /* unparseable URL: treat as remote and keep the target store */ }
236
+ if (!loopback) return brainDir;
237
+ // `globalBrainDir` is the caller's explicit answer and is preferred. Only
238
+ // when it names nothing usable do we consider the home-relative global
239
+ // brain — and never when an explicit root owns the layout, because that
240
+ // root's server is the one being served and $HOME belongs to someone else.
241
+ const explicitRoot = Boolean(process.env.AGENT_DIR || process.env._TR_TEST_AGENT_DIR);
242
+ const candidates = [globalBrainDir];
243
+ if (!explicitRoot) candidates.push(path.join(os.homedir(), '.agent', 'skills', 'total-recall'));
244
+ for (const candidate of candidates) {
245
+ if (!candidate || candidate === brainDir) continue;
246
+ // Only adopt a store that is already established; adopting a missing one
247
+ // would make init responsible for creating it, which constraint 2 forbids.
248
+ if (fs.existsSync(path.join(candidate, 'config', 'keys.jsonl'))
249
+ || fs.existsSync(path.join(candidate, 'config', '.ssss'))) return candidate;
250
+ }
251
+ return brainDir;
252
+ }
253
+
201
254
  // ─── Main ───────────────────────────────────────────────────────────────────
202
255
 
203
256
  export default async function init(args) {
@@ -207,6 +260,10 @@ export default async function init(args) {
207
260
  const cwd = process.cwd();
208
261
  const globalAgentDir = getGlobalAgentDir();
209
262
  const globalBrainDir = path.join(globalAgentDir, 'skills', 'total-recall');
263
+ // The HOME-relative global brain, which is what a background server reads.
264
+ // `globalAgentDir` above honours AGENT_DIR and can therefore point at the
265
+ // project being initialised; the serving store must not be derived from it.
266
+ const servingGlobalBrainDir = path.join(os.homedir(), '.agent', 'skills', 'total-recall');
210
267
 
211
268
  // Determine target based on --project flag
212
269
  const isProject = opts.project;
@@ -705,12 +762,26 @@ export default async function init(args) {
705
762
 
706
763
  if (needsBootstrap) {
707
764
  try {
708
- const { issueKey } = await import('../server/keys.mjs');
709
- const keyData = issueKey('Default Local Developer Key', { scopes: ['*'] });
765
+ const { keyStoreFor } = await import('../server/keys.mjs');
710
766
  brainCfg.url = brainCfg.url || 'http://localhost:3000';
767
+ // Mint the bootstrap token into the store the SERVER reads, which is
768
+ // the store under `AGENT_DIR` — not necessarily the brain this init run
769
+ // targets. A project brain's token is validated by whatever server
770
+ // process answers `brainCfg.url`, and that process resolves its store
771
+ // from `AGENT_DIR` (launchd starts it with the global one). Issuing
772
+ // into the project's own store wrote a token no running server could
773
+ // match: init reported "pre-authorized" and every request answered 401,
774
+ // so `startup check` said `brain failed` on project after project.
775
+ // When the target IS the store the server reads this is a no-op branch.
776
+ const servingBrainDir = resolveServingBrainDir({ brainDir, isProject, brainUrl: brainCfg.url, globalBrainDir: servingGlobalBrainDir });
777
+ const { issueKey } = keyStoreFor(servingBrainDir);
778
+ const keyData = issueKey('Default Local Developer Key', { scopes: ['*'] });
711
779
  brainCfg.token = brainCfg.token || keyData.token;
712
780
  writeFileSecure(brainJsonPath, JSON.stringify(brainCfg, null, 2), { mode: 0o600 });
713
781
  logOk(`Bootstrap configuration successfully generated and pre-authorized at ${brainCfg.url}`);
782
+ if (isProject && servingBrainDir !== brainDir) {
783
+ logOk(`Bootstrap token issued to the serving brain store at ${servingBrainDir}`);
784
+ }
714
785
  if (brainCfg.project_id) {
715
786
  logOk(`Assigned project UUID ${brainCfg.project_id} to project brain`);
716
787
  }
@@ -2,4 +2,30 @@
2
2
  import { brainDir } from '../core/config.mjs';
3
3
  import { loadPluginModule } from '../core/plugin-runtime.mjs';
4
4
  const { createKeyStore } = await loadPluginModule('auth', 'access-keys');
5
+
6
+ /**
7
+ * The default store is the one under `AGENT_DIR`. That is the store a server
8
+ * process reads, because `core/config.mjs` derives `brainDir` from
9
+ * `AGENT_DIR` alone. Anything that mints a token a *server* must accept has to
10
+ * use this store — see `keyStoreFor`.
11
+ */
5
12
  export const { ALL_SCOPES, KNOWN_SCOPES, normalizeScopes, isExpiredKey, keyHasScope, keyHasAnyScope, loadKeys, issueKey, revokeKey, recordKeyUsage, isValidToken, findValidKeyByToken, loadRoles, setRole, listKeyUsage, recordKeyOutcome } = createKeyStore({ brainDir });
13
+
14
+ /**
15
+ * A key store bound to an explicit brain directory.
16
+ *
17
+ * `init` writes a bootstrap PAT into a brain's `config/brain.json`, and the
18
+ * server that answers that brain's URL validates it against whatever store its
19
+ * own `AGENT_DIR` produced. When the two differ, `init` used to mint the token
20
+ * into a store no running server reads: it printed "pre-authorized", and every
21
+ * request with that token then answered 401. Callers that need a token the
22
+ * server will accept resolve the serving brain first and pass it here.
23
+ *
24
+ * @param {string} targetBrainDir absolute brain directory (…/skills/total-recall)
25
+ */
26
+ export function keyStoreFor(targetBrainDir) {
27
+ if (typeof targetBrainDir !== 'string' || !targetBrainDir) {
28
+ throw new Error('Explicit auth key store brain directory required');
29
+ }
30
+ return createKeyStore({ brainDir: targetBrainDir });
31
+ }