@tpsdev-ai/flair 0.55.2 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.md +18 -19
  2. package/dist/bridges/builtins/markdown.js +2 -2
  3. package/dist/bridges/discover.js +2 -2
  4. package/dist/bridges/runtime/allow-list.js +2 -2
  5. package/dist/build-info.json +3 -3
  6. package/dist/cli.js +125 -26
  7. package/dist/commands/agent.js +22 -15
  8. package/dist/commands/attention.js +2 -2
  9. package/dist/commands/backup.js +2 -2
  10. package/dist/commands/bridge.js +40 -3
  11. package/dist/commands/doctor.js +91 -28
  12. package/dist/commands/export.js +2 -2
  13. package/dist/commands/federation.js +441 -68
  14. package/dist/commands/hook.js +4 -4
  15. package/dist/commands/init.js +59 -12
  16. package/dist/commands/mcp.js +2 -2
  17. package/dist/commands/migrate-harness-memory.js +8 -8
  18. package/dist/commands/rem.js +2 -2
  19. package/dist/commands/service.js +25 -1
  20. package/dist/commands/session.js +2 -2
  21. package/dist/commands/uninstall.js +2 -2
  22. package/dist/commands/upgrade.js +3 -3
  23. package/dist/doctor-client.js +5 -23
  24. package/dist/engine-version.js +2 -2
  25. package/dist/federation/scheduler.js +5 -5
  26. package/dist/install/clients.js +5 -10
  27. package/dist/keystore.js +10 -2
  28. package/dist/lib/auth-resolve.js +51 -5
  29. package/dist/lib/doctor-config-path.js +2 -2
  30. package/dist/lib/flair-paths.js +29 -0
  31. package/dist/lib/home.js +60 -0
  32. package/dist/lib/instance-identity-row.js +580 -0
  33. package/dist/lib/launchd-repair.js +6 -0
  34. package/dist/lib/mcp-enable.js +4 -4
  35. package/dist/lib/owned-pins.js +1 -13
  36. package/dist/lib/redact-token-id.js +197 -0
  37. package/dist/lib/socket-path-limit.js +120 -0
  38. package/dist/lib/uninstall-purge.js +2 -18
  39. package/dist/lib/upgrade-plain-tree.js +2 -2
  40. package/dist/mcp-client-assertion.js +3 -3
  41. package/dist/rem/runner.js +3 -3
  42. package/dist/rem/scheduler.js +5 -5
  43. package/dist/rem/snapshot.js +2 -2
  44. package/dist/resources/AgentSeed.js +4 -1
  45. package/dist/resources/Asset.js +3 -11
  46. package/dist/resources/Credential.js +4 -10
  47. package/dist/resources/Federation.js +232 -78
  48. package/dist/resources/Integration.js +8 -32
  49. package/dist/resources/Memory.js +58 -16
  50. package/dist/resources/MemoryBootstrap.js +19 -12
  51. package/dist/resources/MemoryCandidate.js +3 -11
  52. package/dist/resources/MemoryDedupStats.js +1 -1
  53. package/dist/resources/MemoryFeed.js +10 -2
  54. package/dist/resources/MemoryGrant.js +19 -40
  55. package/dist/resources/MemoryUsage.js +7 -20
  56. package/dist/resources/OAuth.js +62 -11
  57. package/dist/resources/Presence.js +135 -47
  58. package/dist/resources/Relationship.js +3 -11
  59. package/dist/resources/SemanticSearch.js +25 -13
  60. package/dist/resources/admin-layout.js +7 -2
  61. package/dist/resources/auth-middleware.js +32 -5
  62. package/dist/resources/bm25.js +13 -14
  63. package/dist/resources/federation-cleanup.js +289 -51
  64. package/dist/resources/health.js +48 -8
  65. package/dist/resources/in-process-api.js +2 -1
  66. package/dist/resources/instance-create-lock.js +363 -0
  67. package/dist/resources/instance-identity-rows.js +43 -0
  68. package/dist/resources/instance-identity.js +94 -10
  69. package/dist/resources/mcp-handler.js +9 -1
  70. package/dist/resources/mcp-tool-arguments.js +83 -0
  71. package/dist/resources/mcp-tools.js +4 -5
  72. package/dist/resources/memory-reflect-lib.js +17 -1
  73. package/dist/resources/memory-visibility.js +10 -7
  74. package/dist/resources/rate-limit.js +6 -4
  75. package/dist/resources/record-type-kit.js +47 -23
  76. package/dist/resources/search-readiness.js +7 -1
  77. package/dist/resources/semantic-retrieval-core.js +98 -3
  78. package/dist/resources/table-helpers.js +33 -0
  79. package/dist/resources/tool-descriptors/index.js +2 -2
  80. package/dist/src/keystore.js +10 -2
  81. package/dist/src/lib/home.js +60 -0
  82. package/dist/src/lib/instance-identity-row.js +580 -0
  83. package/dist/src/lib/redact-token-id.js +197 -0
  84. package/dist/src/rem/scheduler.js +5 -5
  85. package/dist/version-check.js +2 -2
  86. package/dist/version-handshake.js +2 -2
  87. package/docs/api-reference.md +32 -7
  88. package/docs/auth.md +19 -7
  89. package/docs/claude-code.md +5 -6
  90. package/docs/deploying-on-fabric.md +8 -4
  91. package/docs/deployment.md +26 -37
  92. package/docs/embedding-in-a-harper-app.md +4 -2
  93. package/docs/entity-vocabulary.md +5 -5
  94. package/docs/federation.md +48 -21
  95. package/docs/hosted-on-fabric.md +7 -4
  96. package/docs/integrations.md +24 -15
  97. package/docs/mcp-clients.md +44 -23
  98. package/docs/n8n.md +8 -8
  99. package/docs/notes/mcp-oauth-model2.md +12 -17
  100. package/docs/openclaw.md +29 -28
  101. package/docs/spoke-bringup.md +44 -22
  102. package/docs/standalone-local.md +12 -16
  103. package/docs/supply-chain-policy.md +21 -8
  104. package/docs/system-requirements.md +1 -1
  105. package/docs/upgrade.md +2 -2
  106. package/package.json +1 -1
@@ -0,0 +1,197 @@
1
+ /**
2
+ * redact-token-id.ts — the ONE pairing-token-id redactor (flair#1902).
3
+ *
4
+ * A pairing-token id IS the credential a spoke redeems, so only its 8-character
5
+ * prefix may ever reach a log line. Three sites grew their own copy of this rule
6
+ * in one day (the cleanup sweep's per-token lines, its table-level lines, and the
7
+ * rollback reporter), so the class is fixed here rather than at each site: one
8
+ * deep redactor every line that can carry a token id passes through.
9
+ *
10
+ * This is HYGIENE, not a security boundary — an operator holds admin credentials
11
+ * and can read the table directly. But a token id printed in full in a log is a
12
+ * credential handed to whoever reads the log, and the same gap reappearing at a
13
+ * new site is the failure this module exists to end.
14
+ *
15
+ * What "deep" means: a string (a message OR a string field at any depth, an array
16
+ * element, or an object KEY) has each secret replaced; numbers, booleans and null
17
+ * pass through untouched; a PLAIN object is rebuilt with redacted keys and values.
18
+ * Object keys are redacted too — a `{ "<token-id>": ... }` map is exactly as much
19
+ * a leak as one in a value. A NON-plain object — a Date, Error, Map, Set or class
20
+ * instance — passes through unchanged: rebuilding it through `Object.entries`
21
+ * would lose its message or entries, and its String form is what a caller should
22
+ * log. A cyclic value terminates: a container already on the path is returned
23
+ * as-is rather than recursed into (a log helper must never crash the sweep).
24
+ *
25
+ * Two properties the naive `split(secret).join(prefix)` gets wrong, and this
26
+ * module gets right:
27
+ *
28
+ * - LENGTH GUARD: a secret shorter than MIN_SECRET_LENGTH characters is
29
+ * replaced by "[redacted]" in full. Cutting an 11-character id to its
30
+ * 8-character prefix leaves most of the id visible, which is not a redaction.
31
+ * Empty secrets are ignored (never a replacement of "" that would splice the
32
+ * replacement between every character).
33
+ * - ONE PASS, LONGEST FIRST: the secrets are matched in a SINGLE pass over the
34
+ * original text, longest secret first. Sequential replaces let a short secret
35
+ * that is a prefix of a longer one match first and strand the longer id's
36
+ * suffix — and let a later secret match inside text a previous replacement
37
+ * just inserted. A single left-to-right scan avoids both, and it deliberately
38
+ * does NOT build a RegExp: a pattern assembled from the secrets would run on
39
+ * caller-supplied text, and a ReDoS there is a worse failure than the leak.
40
+ *
41
+ * `createTokenRedactor(secrets)` compiles the matcher once; the sweep reuses one
42
+ * per tick rather than rebuilding the replacement rules (or copying the id list)
43
+ * for every line it logs.
44
+ */
45
+ /** How many leading characters of a long secret are kept. */
46
+ export const TOKEN_ID_PREFIX_LENGTH = 8;
47
+ /**
48
+ * Below this length, a secret is replaced in full: its "prefix" would be most of
49
+ * it. Pairing-token ids are 32 characters (`randomBytes(24).toString("base64url")`),
50
+ * so this bound is an untested assumption made explicit, not a live path — the
51
+ * guard exists so a short id can never be printed whole by a prefix rule.
52
+ */
53
+ export const MIN_SECRET_LENGTH = 12;
54
+ /** What a secret too short to prefix-cut becomes. */
55
+ export const FULLY_REDACTED = "[redacted]";
56
+ /** The replacement text for one secret. */
57
+ function replacementFor(secret) {
58
+ return secret.length < MIN_SECRET_LENGTH
59
+ ? FULLY_REDACTED
60
+ : `${secret.slice(0, TOKEN_ID_PREFIX_LENGTH)}…`;
61
+ }
62
+ /** Non-empty, de-duplicated secrets paired with their replacement, longest first. */
63
+ function secretReplacements(secrets) {
64
+ const seen = new Set();
65
+ const out = [];
66
+ for (const secret of secrets) {
67
+ if (typeof secret !== "string" || secret.length === 0)
68
+ continue;
69
+ if (seen.has(secret))
70
+ continue;
71
+ seen.add(secret);
72
+ out.push([secret, replacementFor(secret)]);
73
+ }
74
+ // Longest-first: the scan takes the LONGEST secret that starts at a position,
75
+ // so where two secrets overlap the longer one wins and no suffix of it is left
76
+ // stranded by a shorter secret matching first.
77
+ out.sort((a, b) => b[0].length - a[0].length);
78
+ return out;
79
+ }
80
+ /**
81
+ * Compile `secrets` into a redactor. Build it ONCE for a batch of lines and reuse
82
+ * it — the sweep logs many lines per tick, and recompiling per line is the
83
+ * quadratic cost this avoids.
84
+ *
85
+ * The scan walks the ORIGINAL text once: at each position it takes the longest
86
+ * secret that starts there (the list is longest-first), emits that secret's
87
+ * replacement, and advances past it; otherwise it copies one character. Text a
88
+ * replacement inserts is never re-scanned, and no RegExp is built from the
89
+ * secrets (so a token id can never become a pattern).
90
+ */
91
+ export function createTokenRedactor(secrets) {
92
+ const replacements = secretReplacements(secrets);
93
+ const redactMessage = (message) => {
94
+ if (replacements.length === 0 || message.length === 0)
95
+ return message;
96
+ let out = "";
97
+ let i = 0;
98
+ while (i < message.length) {
99
+ let matched;
100
+ for (const pair of replacements) {
101
+ if (message.startsWith(pair[0], i)) {
102
+ matched = pair;
103
+ break;
104
+ }
105
+ }
106
+ if (matched) {
107
+ out += matched[1];
108
+ i += matched[0].length;
109
+ }
110
+ else {
111
+ out += message[i];
112
+ i += 1;
113
+ }
114
+ }
115
+ return out;
116
+ };
117
+ return {
118
+ redactMessage,
119
+ redactValue: (value) => (replacements.length === 0 ? value : walk(value, redactMessage)),
120
+ };
121
+ }
122
+ function walk(value, redact) {
123
+ return walkDeep(value, redact, new Map());
124
+ }
125
+ /**
126
+ * A plain object: its prototype is `Object.prototype` or null. A Date, Error,
127
+ * Map, Set or class instance is NOT a plain object, so it is not rebuilt — it
128
+ * passes through UNREDACTED, and its String form is what a caller should log
129
+ * (every call site stringifies an error before it reaches the redactor).
130
+ */
131
+ function isPlainObject(value) {
132
+ const proto = Object.getPrototypeOf(value);
133
+ return proto === Object.prototype || proto === null;
134
+ }
135
+ /**
136
+ * Rebuild `value` with every string redacted. `copies` maps each container
137
+ * already rebuilt to its REDACTED copy, and the copy is registered before its
138
+ * children are walked: a sub-object reached twice (an alias) is the same
139
+ * redacted copy both times, and a cyclic value terminates by pointing at its own
140
+ * redacted copy. Returning the original for a repeated reference would hand back
141
+ * the unredacted container — the leak flair#1905's review found.
142
+ */
143
+ function walkDeep(value, redact, copies) {
144
+ if (typeof value === "string")
145
+ return redact(value);
146
+ if (Array.isArray(value)) {
147
+ const known = copies.get(value);
148
+ if (known !== undefined)
149
+ return known;
150
+ const out = [];
151
+ copies.set(value, out);
152
+ for (const v of value)
153
+ out.push(walkDeep(v, redact, copies));
154
+ return out;
155
+ }
156
+ if (value && typeof value === "object") {
157
+ if (!isPlainObject(value))
158
+ return value;
159
+ const known = copies.get(value);
160
+ if (known !== undefined)
161
+ return known;
162
+ const out = {};
163
+ copies.set(value, out);
164
+ for (const [key, v] of Object.entries(value)) {
165
+ // Define each rebuilt key as an OWN property. A bracket assignment
166
+ // (`out[redact(key)] = …`) for the key `__proto__` would set the COPY's
167
+ // prototype instead of defining a key, dropping it and giving the copy an
168
+ // attacker-chosen prototype — reachable whenever the input came from
169
+ // JSON.parse or Object.defineProperty (flair#1907).
170
+ Object.defineProperty(out, redact(key), {
171
+ value: walkDeep(v, redact, copies),
172
+ enumerable: true,
173
+ writable: true,
174
+ configurable: true,
175
+ });
176
+ }
177
+ return out;
178
+ }
179
+ // Numbers, booleans, null, undefined, functions, symbols: untouched.
180
+ return value;
181
+ }
182
+ /**
183
+ * A string with every secret replaced by its prefix (or `[redacted]` when the
184
+ * secret is too short to cut). The string-only convenience over the same
185
+ * implementation the deep redactor uses.
186
+ */
187
+ export function redactTokenMessage(message, secrets) {
188
+ return createTokenRedactor(secrets).redactMessage(message);
189
+ }
190
+ /**
191
+ * `value` with every secret replaced in every string at any depth — a message, a
192
+ * string field, an array element, and an object KEY — rebuilt so keys and values
193
+ * are both redacted. Non-string scalars pass through untouched.
194
+ */
195
+ export function redactTokenIds(value, secrets) {
196
+ return createTokenRedactor(secrets).redactValue(value);
197
+ }
@@ -0,0 +1,120 @@
1
+ import { join, resolve } from "node:path";
2
+ /**
3
+ * socket-path-limit.ts — the OS cap on a Unix domain socket's path.
4
+ *
5
+ * A Unix domain socket (the Harper operations API's `operations-server` socket)
6
+ * is bind()ed at a filesystem path, and that path is stored in a
7
+ * `struct sockaddr_un` whose `sun_path` field is a fixed-size buffer. The
8
+ * kernel counts the trailing NUL terminator, so the USABLE path length is one
9
+ * byte shorter than the field size:
10
+ *
11
+ * - macOS (darwin): `sun_path` is 104 bytes -> 103 usable
12
+ * - Linux: `sun_path` is 108 bytes -> 107 usable
13
+ *
14
+ * (darwin and freebsd: <sys/un.h>'s `SUNPATH_MAX`; linux: un(7) / the 108-byte
15
+ * `sa_data` minus the NUL. See also the macOS `listen() EINVAL` behaviour
16
+ * for a path that overflows the buffer.)
17
+ *
18
+ * Harper's operations API socket lives at `<data-dir>/operations-server`, so a
19
+ * long `flair init --data-dir <dir>` can push it past the cap, and `listen`
20
+ * dies with a bare `EINVAL` that names neither the socket nor the limit
21
+ * (flair#916). These pure predicates let callers refuse a too-long data dir
22
+ * BEFORE anything is written to disk, and say exactly what is wrong and how to
23
+ * fix it.
24
+ */
25
+ /**
26
+ * The suffix appended to a data dir to form the operations-socket path,
27
+ * INCLUDING the leading separator. A single 18-byte constant — the part of the
28
+ * socket path that no amount of shortening the data dir can remove.
29
+ */
30
+ export const OPS_SOCKET_SUFFIX = "/operations-server";
31
+ /**
32
+ * The usable (NUL-excluded) maximum length of a Unix socket path, in BYTES,
33
+ * for a platform. macOS (darwin) and FreeBSD both have a 104-byte sun_path,
34
+ * so 103 usable; Linux has a 108-byte sun_path, so 107 usable. Any unknown
35
+ * platform takes the Linux limit of 107.
36
+ * Unknown platforms fall back to 107 because no real platform is looser than
37
+ * Linux's — falling back lower would refuse a path that is actually legal.
38
+ */
39
+ export function socketPathLimit(platform) {
40
+ return platform === "darwin" || platform === "freebsd" ? 103 : 107;
41
+ }
42
+ /**
43
+ * Measure a socket path in BYTES (not characters — a multibyte path counts each
44
+ * byte of its UTF-8 encoding) against its platform's `sun_path`-derived limit.
45
+ * Returns OK when `bytes <= limit`; otherwise a refusal.
46
+ */
47
+ export function checkSocketPathLength(path, platform) {
48
+ const limit = socketPathLimit(platform);
49
+ const bytes = Buffer.byteLength(path, "utf8");
50
+ if (bytes <= limit)
51
+ return { ok: true, bytes, limit };
52
+ return { ok: false, bytes, limit, over: bytes - limit };
53
+ }
54
+ /**
55
+ * Type guard: true when a socket-path check is a refusal (the path overflowed
56
+ * its platform's limit). An explicit type predicate — not control-flow
57
+ * narrowing — so it narrows the refusal branch even under `strict: false`
58
+ * (tsconfig.cli.json turns off strictNullChecks, which disables discriminated
59
+ * union narrowing).
60
+ */
61
+ export function isSocketPathRefusal(check) {
62
+ return !check.ok;
63
+ }
64
+ /**
65
+ * An actionable refusal message for a socket path that exceeds its platform's
66
+ * `sun_path` limit. Names the actual constraint — the socket path itself, its
67
+ * byte length, the platform limit — and the remedy: how many bytes shorter the
68
+ * `--data-dir` must be (the `/operations-server` suffix is fixed, so the data
69
+ * dir is the only part that can move).
70
+ *
71
+ * Pure: it only formats. The caller decides whether to print and exit.
72
+ */
73
+ export function socketPathTooLongMessage(socketPath, dataDir, check) {
74
+ const [head, ...tail] = [
75
+ "Error: the Harper operations socket path is too long for this OS — Harper",
76
+ "would die with a bare `listen EINVAL` instead. Refusing before touching disk.",
77
+ "",
78
+ ` Operations socket: ${JSON.stringify(socketPath)}`,
79
+ ` Path length: ${check.bytes} bytes`,
80
+ ` OS limit: ${check.limit} bytes (Unix-domain-socket sun_path, counting the trailing NUL)`,
81
+ ` Data directory: ${JSON.stringify(dataDir)}`,
82
+ "",
83
+ "The socket is always <data-dir>/operations-server, so that suffix is fixed.",
84
+ "Choose a --data-dir that is at least " +
85
+ `${check.over} byte${check.over === 1 ? "" : "s"} shorter, so the socket path` +
86
+ " fits within " +
87
+ `${check.limit} bytes.`,
88
+ ];
89
+ return head + "\n" + tail.join("\n");
90
+ }
91
+ /**
92
+ * CLI preflight for the operations socket. Builds the socket path from a data
93
+ * directory exactly as Harper binds it (`<data-dir>/operations-server`) and,
94
+ * unless it fits the platform's `sun_path` limit, returns the actionable refusal
95
+ * message. Returns `null` when the path fits.
96
+ *
97
+ * The data dir is resolved to an ABSOLUTE path BEFORE measuring, because Harper
98
+ * binds the socket relative to its own cwd (the flair package directory), not
99
+ * ours — a relative `--data-dir r` would otherwise be measured as the short
100
+ * `r/operations-server` while Harper binds a much longer path. The refusal
101
+ * message prints the RESOLVED path and the resolved data dir.
102
+ *
103
+ * Callers that run it: `flair init` (which accepts `--data-dir`) and
104
+ * `flair start` / `flair restart` (defensive — the default data dir is short).
105
+ * NOT covered here: `flair snapshot create` and the launchd repair path, which
106
+ * hand Harper a socket path without this check; an over-long data dir cannot
107
+ * boot in either case, so it is not a live bug.
108
+ *
109
+ * Pure — it only builds and formats; the caller decides whether to print and
110
+ * exit, so it is unit-testable without `process.exit`.
111
+ */
112
+ export function opsSocketPathRefusal(dataDir, platform) {
113
+ const resolvedDataDir = resolve(dataDir);
114
+ const socketPath = join(resolvedDataDir, OPS_SOCKET_SUFFIX);
115
+ const check = checkSocketPathLength(socketPath, platform);
116
+ if (isSocketPathRefusal(check)) {
117
+ return socketPathTooLongMessage(socketPath, resolvedDataDir, check);
118
+ }
119
+ return null;
120
+ }
@@ -15,8 +15,8 @@
15
15
  * "fully purged" when anything remains.
16
16
  */
17
17
  import { existsSync, rmSync } from "node:fs";
18
- import { homedir } from "node:os";
19
18
  import { join } from "node:path";
19
+ import { resolveHome, withHome } from "./home.js";
20
20
  import { ALL_CLIENTS } from "../install/clients.js";
21
21
  import { uninstallContinuityHooks, uninstallHook, harnessSupportsContinuity, hookBackupPath, hookSettingsPath, SUPPORTED_HARNESSES, } from "../hook-install.js";
22
22
  import { disableScheduler as disableRemScheduler, LAUNCHD_LABEL as REM_LAUNCHD_LABEL, SYSTEMD_SERVICE_UNIT as REM_SYSTEMD_SERVICE, SYSTEMD_TIMER_UNIT as REM_SYSTEMD_TIMER, } from "../rem/scheduler.js";
@@ -24,22 +24,6 @@ import { disableScheduler as disableFederationScheduler, LAUNCHD_LABEL as FED_LA
24
24
  /** The published CLI package. Named here so the leftover line cannot drift
25
25
  * from the remedy command. */
26
26
  export const FLAIR_NPM_PACKAGE = "@tpsdev-ai/flair";
27
- function resolveHome(homeDir) {
28
- return homeDir ?? process.env.HOME ?? process.env.USERPROFILE ?? homedir();
29
- }
30
- function withHome(homeDir, fn) {
31
- const prev = process.env.HOME;
32
- process.env.HOME = homeDir;
33
- try {
34
- return fn();
35
- }
36
- finally {
37
- if (prev === undefined)
38
- delete process.env.HOME;
39
- else
40
- process.env.HOME = prev;
41
- }
42
- }
43
27
  function displayUnderHome(homeDir, absPath) {
44
28
  if (absPath.startsWith(homeDir))
45
29
  return "~" + absPath.slice(homeDir.length);
@@ -127,7 +111,7 @@ function sweepHookBackup(settingsPath, reportedBackup, homeDir, removed, leftove
127
111
  * unless `omitNpmLeftover` is set.
128
112
  */
129
113
  export function purgeFlairInstall(opts = {}) {
130
- const homeDir = resolveHome(opts.homeDir);
114
+ const homeDir = opts.homeDir ?? resolveHome();
131
115
  const skipUnload = !!opts.skipSchedulerUnload;
132
116
  const removed = [];
133
117
  const leftovers = [];
@@ -19,10 +19,10 @@
19
19
  */
20
20
  import { existsSync, mkdirSync, renameSync, rmSync, cpSync, readdirSync, readFileSync, statSync, lstatSync, realpathSync, } from "node:fs";
21
21
  import { basename, dirname, join, resolve } from "node:path";
22
- import { homedir } from "node:os";
23
22
  import { execFileSync } from "node:child_process";
24
23
  import { extract as tarExtract } from "tar";
25
24
  import { canonicalPath, findFlairPackageDir, readFlairPackageAt, sameInstallPath, } from "./upgrade-exec-path.js";
25
+ import { resolveHome } from "./home.js";
26
26
  export const FLAIR_PACKAGE = "@tpsdev-ai/flair";
27
27
  /** Sibling suffix for the staged new tree (same filesystem as the live tree). */
28
28
  export const UPGRADE_NEXT_SUFFIX = "upgrade-next";
@@ -525,7 +525,7 @@ export function unitTextMentionsTree(unitText, treeDir) {
525
525
  return false;
526
526
  }
527
527
  const SYSTEM_UNIT_DIRS = ["/etc/systemd/system"];
528
- export function userSystemdDir(home = homedir()) {
528
+ export function userSystemdDir(home = resolveHome()) {
529
529
  return join(home, ".config", "systemd", "user");
530
530
  }
531
531
  /**
@@ -54,8 +54,8 @@
54
54
  */
55
55
  import { createPrivateKey, createPublicKey, randomUUID, sign } from "node:crypto";
56
56
  import { existsSync, readFileSync } from "node:fs";
57
- import { homedir } from "node:os";
58
57
  import { join } from "node:path";
58
+ import { resolveHome } from "./lib/home.js";
59
59
  // ─── RFC 7523 constants ─────────────────────────────────────────────────────
60
60
  /** RFC 7523 §2.2 value for `client_assertion_type`. */
61
61
  export const CLIENT_ASSERTION_TYPE_JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
@@ -76,8 +76,8 @@ export function resolveAgentKeyPath(agentId, keysDirOverride) {
76
76
  const candidates = [
77
77
  keysDirOverride ? join(keysDirOverride, `${agentId}.key`) : null,
78
78
  process.env.FLAIR_KEY_DIR ? join(process.env.FLAIR_KEY_DIR, `${agentId}.key`) : null,
79
- join(homedir(), ".flair", "keys", `${agentId}.key`),
80
- join(homedir(), ".tps", "secrets", "flair", `${agentId}-priv.key`),
79
+ join(resolveHome(), ".flair", "keys", `${agentId}.key`),
80
+ join(resolveHome(), ".tps", "secrets", "flair", `${agentId}-priv.key`),
81
81
  ].filter((p) => Boolean(p));
82
82
  return candidates.find((p) => existsSync(p)) ?? null;
83
83
  }
@@ -56,11 +56,11 @@
56
56
  */
57
57
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
58
58
  import { dirname, resolve } from "node:path";
59
- import { homedir } from "node:os";
60
59
  import { setImmediate as yieldToEventLoop } from "node:timers/promises";
61
60
  import { createSnapshot } from "./snapshot.js";
62
- export const REM_PAUSE_FLAG = resolve(homedir(), ".flair", "rem.paused");
63
- export const REM_NIGHTLY_LOG = resolve(homedir(), ".flair", "logs", "rem-nightly.jsonl");
61
+ import { resolveHome } from "../lib/home.js";
62
+ export const REM_PAUSE_FLAG = resolve(resolveHome(), ".flair", "rem.paused");
63
+ export const REM_NIGHTLY_LOG = resolve(resolveHome(), ".flair", "logs", "rem-nightly.jsonl");
64
64
  // ─── ADK per-tag distillation (#1205b-1) ─────────────────────────────────────
65
65
  // adk-flair collapses (app_name, user_id) → ONE Flair agentId, distinguishing
66
66
  // users ONLY by a per-user tag `adk:<app>:<user>` (see the adk-flair
@@ -15,25 +15,25 @@
15
15
  */
16
16
  import { existsSync, mkdirSync, chmodSync, rmSync } from "node:fs";
17
17
  import { resolve, dirname } from "node:path";
18
- import { homedir } from "node:os";
19
18
  import { spawn } from "node:child_process";
20
19
  import { fileURLToPath } from "node:url";
21
20
  import { escapeXml } from "../lib/xml-escape.js";
22
21
  import { detectPlatform as detectPlatformFor, spawnReport, readTemplate as readTemplateFrom, renderTemplateWith, writeFileWithDir, interpretActiveResult, describeLoadFailure as describeLoadFailureFor, describeExitCode, resolveNodeBin, resolveFlairBin, formatFlairBinWarning, verifyFirstRun, probeUserLingerEnabled, STATUS_CHECK_TIMEOUT_MS, } from "../lib/scheduler-platform.js";
22
+ import { resolveHome } from "../lib/home.js";
23
23
  // Re-exported so this module's public surface is unchanged by the extraction
24
24
  // into src/lib/scheduler-platform.ts (a second scheduler — `flair federation
25
25
  // sync enable` — needs the identical launchctl/systemctl interpretation, and
26
26
  // flair#850's lesson must have exactly one implementation).
27
27
  export { interpretActiveResult };
28
- export const SHIM_PATH_DEFAULT = resolve(homedir(), ".flair", "bin", "flair-rem-nightly");
28
+ export const SHIM_PATH_DEFAULT = resolve(resolveHome(), ".flair", "bin", "flair-rem-nightly");
29
29
  // Unit names, exported (flair#1278) so `flair doctor`'s scheduled-drivers
30
30
  // section addresses the same job this module installs — same single-source
31
31
  // rule as the federation scheduler's LAUNCHD_LABEL/SYSTEMD_*_UNIT constants.
32
32
  export const LAUNCHD_LABEL = "dev.flair.rem.nightly";
33
33
  export const SYSTEMD_TIMER_UNIT = "flair-rem-nightly.timer";
34
34
  export const SYSTEMD_SERVICE_UNIT = "flair-rem-nightly.service";
35
- export const LAUNCHD_PLIST_PATH = resolve(homedir(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
36
- export const SYSTEMD_USER_DIR = resolve(homedir(), ".config", "systemd", "user");
35
+ export const LAUNCHD_PLIST_PATH = resolve(resolveHome(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
36
+ export const SYSTEMD_USER_DIR = resolve(resolveHome(), ".config", "systemd", "user");
37
37
  export const SYSTEMD_TIMER_PATH = resolve(SYSTEMD_USER_DIR, SYSTEMD_TIMER_UNIT);
38
38
  export const SYSTEMD_SERVICE_PATH = resolve(SYSTEMD_USER_DIR, SYSTEMD_SERVICE_UNIT);
39
39
  function detectPlatform(override) {
@@ -102,7 +102,7 @@ function buildSubstitutions(opts, shimPath, flairBin, nodeBin) {
102
102
  FLAIR_BIN: flairBin,
103
103
  NODE_BIN: nodeBin,
104
104
  SHIM_PATH: shimPath,
105
- HOME: opts.homeOverride ?? homedir(),
105
+ HOME: opts.homeOverride ?? resolveHome(),
106
106
  AGENT_ID: opts.agentId,
107
107
  FLAIR_URL: opts.flairUrl,
108
108
  HOUR: String(opts.hour),
@@ -18,10 +18,10 @@
18
18
  */
19
19
  import { mkdirSync, writeFileSync, statSync, chmodSync, rmSync, existsSync, readdirSync } from "node:fs";
20
20
  import { resolve } from "node:path";
21
- import { homedir } from "node:os";
22
21
  import { create as tarCreate, extract as tarExtract, list as tarList } from "tar";
23
22
  import { validateSnapshotArchive } from "../lib/safe-snapshot-extract.js";
24
- export const SNAPSHOT_ROOT = resolve(homedir(), ".flair", "snapshots");
23
+ import { resolveHome } from "../lib/home.js";
24
+ export const SNAPSHOT_ROOT = resolve(resolveHome(), ".flair", "snapshots");
25
25
  /** Validates the agent id and returns its snapshot directory. */
26
26
  export function remSnapshotDir(agent) {
27
27
  if (!/^[a-zA-Z0-9_-]+$/.test(agent)) {
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  /**
2
3
  * POST /AgentSeed
3
4
  *
@@ -128,7 +129,9 @@ export class AgentSeed extends Resource {
128
129
  const skillDenial = rejectSkillWritePath(def);
129
130
  if (skillDenial)
130
131
  return skillDenial;
131
- const id = `seed-${agentId}-${i}-${Date.now()}`;
132
+ // A full random UUID in the id: this raw-table write is meant to create,
133
+ // never to replace an existing record.
134
+ const id = `seed-${agentId}-${i}-${Date.now()}-${randomUUID()}`;
132
135
  const record = {
133
136
  id,
134
137
  agentId,
@@ -1,11 +1,12 @@
1
1
  import { createBlob, databases } from "harper";
2
2
  import { resolveAgentAuth } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
- import { FORBIDDEN, UNAUTH, makeAuthGate, makeByIdReadGate, makeReadScope, resolveAuthGate, stampAttribution, } from "./record-type-kit.js";
4
+ import { FORBIDDEN, UNAUTH, makeAuthGate, makeByIdReadGate, makeReadScope, makeScopedSearch, resolveAuthGate, stampAttribution, } from "./record-type-kit.js";
5
5
  import { RECORD_TYPES } from "./record-types.js";
6
6
  // Kit parameters read FROM RECORD_TYPES.Asset (single source of truth), same
7
7
  // composition MemoryCandidate.ts uses.
8
8
  const assetReadScope = makeReadScope(RECORD_TYPES.Asset.readScope, RECORD_TYPES.Asset.ownerField);
9
+ const assetScopedSearch = makeScopedSearch(assetReadScope);
9
10
  const assetByIdReadGate = makeByIdReadGate(assetReadScope);
10
11
  const assetAuthGate = makeAuthGate();
11
12
  /**
@@ -58,16 +59,7 @@ export class Asset extends databases.flair.Asset {
58
59
  return gate.response;
59
60
  if (gate.kind === "unfiltered")
60
61
  return super.search(query);
61
- const scope = await assetReadScope(gate.agentId);
62
- const agentCondition = scope.condition;
63
- if (!query?.conditions) {
64
- return super.search({ conditions: [agentCondition], ...(query || {}) });
65
- }
66
- return super.search({
67
- ...query,
68
- conditions: [agentCondition, { conditions: query.conditions, operator: query.operator || "and" }],
69
- operator: "and",
70
- });
62
+ return assetScopedSearch(gate.agentId, query, (q) => super.search(q));
71
63
  }
72
64
  async post(content) {
73
65
  const ctx = this.getContext?.();
@@ -2,7 +2,9 @@ import { databases } from "harper";
2
2
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
4
  import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
5
- import { stampAttribution, UNAUTH } from "./record-type-kit.js";
5
+ import { makeReadScope, makeScopedSearch, stampAttribution, UNAUTH } from "./record-type-kit.js";
6
+ const credentialReadScope = makeReadScope("owner-only", "principalId");
7
+ const credentialScopedSearch = makeScopedSearch(credentialReadScope);
6
8
  /**
7
9
  * Credential resource — authentication surfaces for Principals.
8
10
  *
@@ -84,15 +86,7 @@ export class Credential extends databases.flair.Credential {
84
86
  return super.search(query);
85
87
  }
86
88
  // Non-admin agent: scope to own credentials.
87
- const condition = { attribute: "principalId", comparator: "equals", value: auth.agentId };
88
- if (!query?.conditions) {
89
- return super.search({ conditions: [condition], ...(query || {}) });
90
- }
91
- return super.search({
92
- ...query,
93
- conditions: [condition, { conditions: query.conditions, operator: query.operator || "and" }],
94
- operator: "and",
95
- });
89
+ return credentialScopedSearch(auth.agentId, query, (q) => super.search(q));
96
90
  }
97
91
  async get() {
98
92
  const result = await super.get();