@cachly-dev/mcp-server 0.10.117 → 0.10.118

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 (38) hide show
  1. package/README.md +2 -2
  2. package/dist/src/ambient-cli.d.ts +85 -0
  3. package/dist/src/ambient-cli.js +199 -0
  4. package/dist/src/ambient-cli.js.map +1 -0
  5. package/dist/src/ambient-hooks.d.ts +128 -0
  6. package/dist/src/ambient-hooks.js +269 -0
  7. package/dist/src/ambient-hooks.js.map +1 -0
  8. package/dist/src/ambient-ledger.d.ts +19 -0
  9. package/dist/src/ambient-ledger.js +95 -0
  10. package/dist/src/ambient-ledger.js.map +1 -0
  11. package/dist/src/ambient-recall.d.ts +59 -0
  12. package/dist/src/ambient-recall.js +96 -0
  13. package/dist/src/ambient-recall.js.map +1 -0
  14. package/dist/src/doctor.d.ts +47 -0
  15. package/dist/src/doctor.js +247 -0
  16. package/dist/src/doctor.js.map +1 -0
  17. package/dist/src/first-contact.d.ts +56 -0
  18. package/dist/src/first-contact.js +108 -0
  19. package/dist/src/first-contact.js.map +1 -0
  20. package/dist/src/handlers/brain.d.ts +1 -0
  21. package/dist/src/handlers/brain.js +37 -7
  22. package/dist/src/handlers/brain.js.map +1 -1
  23. package/dist/src/handlers/fedbrain.js +48 -16
  24. package/dist/src/handlers/fedbrain.js.map +1 -1
  25. package/dist/src/handlers/syndicate.js +91 -1
  26. package/dist/src/handlers/syndicate.js.map +1 -1
  27. package/dist/src/handlers/team.d.ts +10 -0
  28. package/dist/src/handlers/team.js +45 -1
  29. package/dist/src/handlers/team.js.map +1 -1
  30. package/dist/src/index.d.ts +8 -5
  31. package/dist/src/index.js +211 -14
  32. package/dist/src/index.js.map +1 -1
  33. package/dist/src/tools.d.ts +5 -0
  34. package/dist/src/tools.js +12 -1
  35. package/dist/src/tools.js.map +1 -1
  36. package/glama.json +1 -1
  37. package/package.json +2 -2
  38. package/server.json +4 -4
@@ -0,0 +1,247 @@
1
+ // `cachly doctor` — one-command setup diagnosis.
2
+ //
3
+ // The activation funnel dies silently: a missing JWT, an unreachable API, a
4
+ // half-installed hook set or a stale v1 shell hook all look identical from the
5
+ // editor ("the brain just doesn't answer"). doctor makes every link of the
6
+ // chain visible in one run: environment → credential → API → instance → hooks
7
+ // → ledger. Pure check functions with injected effects so the whole module is
8
+ // unit-testable; the CLI shell in index.ts only wires and prints.
9
+ import { existsSync, readFileSync } from 'node:fs';
10
+ import { resolve } from 'node:path';
11
+ import { AMBIENT_HOOK_VERSION } from './ambient-hooks.js';
12
+ import { netBalance, shouldBackoff } from './ambient-recall.js';
13
+ const MIN_NODE_MAJOR = 18;
14
+ /** Node runtime new enough for fetch/AbortSignal (>= 18). */
15
+ export function checkNodeVersion(version = process.version) {
16
+ const major = Number(version.replace(/^v/, '').split('.')[0]);
17
+ if (Number.isFinite(major) && major >= MIN_NODE_MAJOR) {
18
+ return { name: 'Node.js', status: 'ok', detail: `${version}` };
19
+ }
20
+ return {
21
+ name: 'Node.js',
22
+ status: 'fail',
23
+ detail: `${version} — too old`,
24
+ hint: `cachly needs Node ${MIN_NODE_MAJOR}+ (built-in fetch). Install a current LTS from nodejs.org.`,
25
+ };
26
+ }
27
+ /** Credential present and roughly the right shape (cky_… API key or JWT). */
28
+ export function checkCredential(jwt) {
29
+ if (!jwt) {
30
+ return {
31
+ name: 'Credential',
32
+ status: 'fail',
33
+ detail: 'CACHLY_JWT is not set',
34
+ hint: 'Run `npx @cachly-dev/mcp-server@latest autopilot` (browser sign-in) or export CACHLY_JWT=<cky_…>.',
35
+ };
36
+ }
37
+ const looksApiKey = jwt.startsWith('cky_');
38
+ const looksJwt = jwt.split('.').length === 3;
39
+ if (!looksApiKey && !looksJwt) {
40
+ return {
41
+ name: 'Credential',
42
+ status: 'warn',
43
+ detail: 'CACHLY_JWT is set but looks neither like a cky_… key nor a JWT',
44
+ hint: 'Re-copy the key from the dashboard (API Keys) — it may be truncated.',
45
+ };
46
+ }
47
+ return { name: 'Credential', status: 'ok', detail: looksApiKey ? 'API key (cky_…)' : 'JWT' };
48
+ }
49
+ /** API reachable at all (public /health — no auth involved). */
50
+ export async function checkApiReachable(apiUrl, fetchFn = fetch) {
51
+ try {
52
+ const res = await fetchFn(`${apiUrl}/health`, { signal: AbortSignal.timeout(5000) });
53
+ if (res.ok)
54
+ return { name: 'API', status: 'ok', detail: `${apiUrl} reachable` };
55
+ return {
56
+ name: 'API',
57
+ status: 'fail',
58
+ detail: `${apiUrl}/health returned HTTP ${res.status}`,
59
+ hint: 'The API answered but is unhealthy — check https://cachly.dev/status or your CACHLY_API_URL.',
60
+ };
61
+ }
62
+ catch {
63
+ return {
64
+ name: 'API',
65
+ status: 'fail',
66
+ detail: `${apiUrl} not reachable`,
67
+ hint: 'Check your network/proxy. Self-hosted: is CACHLY_API_URL correct and the API running?',
68
+ };
69
+ }
70
+ }
71
+ /** Credential actually accepted by the API (authenticated list call). */
72
+ export async function checkAuthAccepted(apiUrl, jwt, fetchFn = fetch) {
73
+ if (!jwt) {
74
+ return { name: 'Auth', status: 'fail', detail: 'skipped — no credential', hint: 'Fix the Credential check first.' };
75
+ }
76
+ try {
77
+ const res = await fetchFn(`${apiUrl}/api/v1/instances`, {
78
+ headers: { Authorization: `Bearer ${jwt}` },
79
+ signal: AbortSignal.timeout(5000),
80
+ });
81
+ if (res.ok)
82
+ return { name: 'Auth', status: 'ok', detail: 'credential accepted' };
83
+ if (res.status === 401 || res.status === 403) {
84
+ return {
85
+ name: 'Auth',
86
+ status: 'fail',
87
+ detail: `API rejected the credential (HTTP ${res.status})`,
88
+ hint: 'The key is expired or revoked. Create a new one in the dashboard, or re-run autopilot.',
89
+ };
90
+ }
91
+ return { name: 'Auth', status: 'warn', detail: `unexpected HTTP ${res.status} from /api/v1/instances` };
92
+ }
93
+ catch {
94
+ return { name: 'Auth', status: 'warn', detail: 'could not verify (network error)' };
95
+ }
96
+ }
97
+ /** Brain instance configured (env or auto-provisioned default). */
98
+ export function checkInstance(instanceId) {
99
+ if (!instanceId) {
100
+ return {
101
+ name: 'Instance',
102
+ status: 'warn',
103
+ detail: 'no CACHLY_BRAIN_INSTANCE_ID set and no default instance resolved',
104
+ hint: 'Run `npx @cachly-dev/mcp-server@latest init` in your project, or export CACHLY_BRAIN_INSTANCE_ID.',
105
+ };
106
+ }
107
+ const uuidish = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(instanceId);
108
+ return uuidish
109
+ ? { name: 'Instance', status: 'ok', detail: instanceId.slice(0, 8) + '…' }
110
+ : {
111
+ name: 'Instance',
112
+ status: 'warn',
113
+ detail: `"${instanceId.slice(0, 24)}" does not look like an instance UUID`,
114
+ hint: 'Copy the instance ID from the dashboard (Instances → your brain).',
115
+ };
116
+ }
117
+ /** Read-only look at .claude/ in projectDir — never throws. */
118
+ export function inspectAmbientHooks(projectDir) {
119
+ const out = { settingsExists: false, wiredEvents: [], scriptFiles: [] };
120
+ try {
121
+ const settingsPath = resolve(projectDir, '.claude/settings.json');
122
+ out.settingsExists = existsSync(settingsPath);
123
+ if (out.settingsExists) {
124
+ const parsed = JSON.parse(readFileSync(settingsPath, 'utf-8'));
125
+ for (const [event, groups] of Object.entries(parsed.hooks ?? {})) {
126
+ // Normalise Windows backslash paths so the marker match and the path
127
+ // extraction below work on every platform (node fs accepts / on Windows).
128
+ const norm = (c) => (c ?? '').replace(/\\/g, '/');
129
+ const ours = (groups ?? []).some((g) => (g.hooks ?? []).some((h) => norm(h.command).includes('.claude/hooks/cachly-ambient-')));
130
+ if (ours) {
131
+ out.wiredEvents.push(event);
132
+ for (const g of groups ?? []) {
133
+ for (const h of g.hooks ?? []) {
134
+ const cmd = norm(h.command);
135
+ const m = cmd.match(/["']?([^"']*\.claude\/hooks\/cachly-ambient-[^"']+)["']?/);
136
+ if (!m)
137
+ continue;
138
+ const scriptPath = m[1].replace('$CLAUDE_PROJECT_DIR', projectDir);
139
+ const exists = existsSync(scriptPath);
140
+ let version = 'unknown';
141
+ if (exists) {
142
+ try {
143
+ const body = readFileSync(scriptPath, 'utf-8');
144
+ version = body.includes(AMBIENT_HOOK_VERSION) ? 'current' : 'stale';
145
+ }
146
+ catch { /* keep unknown */ }
147
+ }
148
+ out.scriptFiles.push({ path: scriptPath, exists, version });
149
+ }
150
+ }
151
+ }
152
+ }
153
+ }
154
+ }
155
+ catch { /* corrupt settings → report as not wired */ }
156
+ return out;
157
+ }
158
+ const AMBIENT_EVENTS = ['SessionStart', 'UserPromptSubmit', 'PreToolUse', 'Stop'];
159
+ /** Ambient hooks wired, scripts present, version current. */
160
+ export function checkHooks(inspection) {
161
+ if (!inspection.settingsExists || inspection.wiredEvents.length === 0) {
162
+ return {
163
+ name: 'Hooks',
164
+ status: 'warn',
165
+ detail: 'Ambient Recall hooks are not installed in this project',
166
+ hint: 'Run `npx @cachly-dev/mcp-server@latest init` here — memory then injects itself (no hooks = pull-only).',
167
+ };
168
+ }
169
+ const missingEvents = AMBIENT_EVENTS.filter((e) => !inspection.wiredEvents.includes(e));
170
+ const missingFiles = inspection.scriptFiles.filter((f) => !f.exists);
171
+ const stale = inspection.scriptFiles.filter((f) => f.exists && f.version === 'stale');
172
+ if (missingFiles.length > 0) {
173
+ return {
174
+ name: 'Hooks',
175
+ status: 'fail',
176
+ detail: `settings.json wires hooks whose script files are missing (${missingFiles.length})`,
177
+ hint: 'Re-run `npx @cachly-dev/mcp-server@latest init` to rewrite the scripts.',
178
+ };
179
+ }
180
+ if (stale.length > 0) {
181
+ return {
182
+ name: 'Hooks',
183
+ status: 'warn',
184
+ detail: `installed hooks are an older version (current: ${AMBIENT_HOOK_VERSION}); v1/v2 shell hooks never ran on native Windows`,
185
+ hint: 'Re-run `npx @cachly-dev/mcp-server@latest init` to upgrade in place.',
186
+ };
187
+ }
188
+ if (missingEvents.length > 0) {
189
+ return {
190
+ name: 'Hooks',
191
+ status: 'warn',
192
+ detail: `partial install — missing events: ${missingEvents.join(', ')}`,
193
+ hint: 'Re-run `npx @cachly-dev/mcp-server@latest init` to add the missing hooks.',
194
+ };
195
+ }
196
+ return { name: 'Hooks', status: 'ok', detail: `all 4 events wired, scripts ${AMBIENT_HOOK_VERSION}` };
197
+ }
198
+ /** Net-token ledger readable + backoff state. */
199
+ export function checkLedger(entries, ledgerPath) {
200
+ const bal = netBalance(entries);
201
+ const backing = shouldBackoff(entries);
202
+ if (entries.length === 0) {
203
+ return {
204
+ name: 'Ledger',
205
+ status: 'ok',
206
+ detail: `empty (${ledgerPath}) — fills up once ambient hooks inject`,
207
+ };
208
+ }
209
+ if (backing) {
210
+ return {
211
+ name: 'Ledger',
212
+ status: 'warn',
213
+ detail: `${entries.length} entries, net ${bal.net} tokens — auto-backoff ACTIVE, injection paused`,
214
+ hint: 'The agent has not reported prevented tokens lately. This self-heals; `ambient-stats` shows details.',
215
+ };
216
+ }
217
+ return {
218
+ name: 'Ledger',
219
+ status: 'ok',
220
+ detail: `${entries.length} entries, net ${bal.net >= 0 ? '+' : ''}${bal.net} tokens`,
221
+ };
222
+ }
223
+ const ICON = { ok: '✅', warn: '⚠️ ', fail: '❌' };
224
+ /** Render the report; deterministic, no colors (CI-friendly). */
225
+ export function renderDoctorReport(checks) {
226
+ const lines = ['', '🩺 cachly doctor', ''];
227
+ for (const c of checks) {
228
+ lines.push(` ${ICON[c.status]} ${c.name.padEnd(11)} ${c.detail}`);
229
+ if (c.hint && c.status !== 'ok')
230
+ lines.push(` ↳ ${c.hint}`);
231
+ }
232
+ const fails = checks.filter((c) => c.status === 'fail').length;
233
+ const warns = checks.filter((c) => c.status === 'warn').length;
234
+ lines.push('');
235
+ lines.push(fails > 0
236
+ ? ` ${fails} problem${fails > 1 ? 's' : ''} to fix${warns ? `, ${warns} warning${warns > 1 ? 's' : ''}` : ''}.`
237
+ : warns > 0
238
+ ? ` No blockers — ${warns} warning${warns > 1 ? 's' : ''}.`
239
+ : ' Everything looks healthy. Your brain is wired.');
240
+ lines.push('');
241
+ return lines.join('\n');
242
+ }
243
+ /** Exit code contract: 1 only on hard failures (warnings stay 0 for CI use). */
244
+ export function doctorExitCode(checks) {
245
+ return checks.some((c) => c.status === 'fail') ? 1 : 0;
246
+ }
247
+ //# sourceMappingURL=doctor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"doctor.js","sourceRoot":"","sources":["../../src/doctor.ts"],"names":[],"mappings":"AAAA,iDAAiD;AACjD,EAAE;AACF,4EAA4E;AAC5E,+EAA+E;AAC/E,2EAA2E;AAC3E,8EAA8E;AAC9E,8EAA8E;AAC9E,kEAAkE;AAElE,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,UAAU,EAAE,aAAa,EAAmB,MAAM,qBAAqB,CAAC;AAcjF,MAAM,cAAc,GAAG,EAAE,CAAC;AAE1B,6DAA6D;AAC7D,MAAM,UAAU,gBAAgB,CAAC,UAAkB,OAAO,CAAC,OAAO;IAChE,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9D,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,cAAc,EAAE,CAAC;QACtD,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,EAAE,EAAE,CAAC;IACjE,CAAC;IACD,OAAO;QACL,IAAI,EAAE,SAAS;QACf,MAAM,EAAE,MAAM;QACd,MAAM,EAAE,GAAG,OAAO,YAAY;QAC9B,IAAI,EAAE,qBAAqB,cAAc,4DAA4D;KACtG,CAAC;AACJ,CAAC;AAED,6EAA6E;AAC7E,MAAM,UA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AAK,MAAM,CAAC,CAAC,MAAM,CAAC;IAC/D,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACf,KAAK,CAAC,IAAI,CACR,KAAK,GAAG,CAAC;QACP,CAAC,CAAC,MAAM,KAAK,WAAW,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,UAAU,KAAK,CAAC,CAAC,CAAC,KAAK,KAAK,WAAW,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,GAAG;QACjH,CAAC,CAAC,KAAK,GAAG,CAAC;YACT,CAAC,CAAC,oBAAoB,KAAK,WAAW,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG;YAC7D,CAAC,CAAC,mDAAmD,CAC1D,CAAC;IACF,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACf,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,cAAc,CAAC,MAAqB;IAClD,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACzD,CAAC"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * First-contact response builder for `brain_from_git` (roadmap P1-5:
3
+ * "Onboarding-Magie messen & polieren").
4
+ *
5
+ * The very first `brain_from_git` run is a new user's first contact with the
6
+ * Brain, and it decides whether they ever reach the "aha". The response must,
7
+ * in one message:
8
+ * (a) summarize what was just learned (counts by category + severity),
9
+ * (b) prove recall already works — show the top hit of a real search that
10
+ * ran against a topic seeded seconds ago,
11
+ * (c) hand the user 2-3 copy-pasteable next queries, and
12
+ * (d) degrade gracefully for empty/small repos (clear guidance, not empty stats).
13
+ *
14
+ * Pure string building — no I/O, no schema/tool changes — so the onboarding
15
+ * bench and its CI test can assert the exact first-contact response shape.
16
+ */
17
+ export interface FirstContactProof {
18
+ /** The query that was run internally against the freshly seeded lessons. */
19
+ query: string;
20
+ /** Topic of the top hit. */
21
+ topic: string;
22
+ /** Short snippet of the top hit's lesson. */
23
+ snippet: string;
24
+ }
25
+ export interface FirstContactReportInput {
26
+ repoDir: string;
27
+ revRange: string;
28
+ processed: number;
29
+ ingested: number;
30
+ skipped: number;
31
+ /** Wall-clock time the seeding run took. */
32
+ durationMs: number;
33
+ isIncremental: boolean;
34
+ lastSha?: string;
35
+ instanceId: string;
36
+ /** category → count, sorted descending by the caller. */
37
+ categories: Array<[string, number]>;
38
+ /** severity → count (optional), sorted descending by the caller. */
39
+ severities?: Array<[string, number]>;
40
+ /** Proof-of-value: top hit of an internal search against a just-seeded topic. */
41
+ proof?: FirstContactProof | null;
42
+ /** Copy-pasteable follow-up queries (see suggestRecallQueries). */
43
+ suggestedQueries: string[];
44
+ /** Optional context for the empty case (e.g. "No commits found on branch X"). */
45
+ emptyReason?: string;
46
+ }
47
+ /** Below this many ingested lessons we treat the repo as "small" and add growth guidance. */
48
+ export declare const SMALL_SEED_THRESHOLD = 5;
49
+ export declare function formatSeedDuration(ms: number): string;
50
+ /**
51
+ * Turn seeded topics (`category:some-domain`) into up to `max` copy-pasteable
52
+ * `smart_recall` calls a brand-new user can paste as their literal next message.
53
+ * Deduplicates by domain so three "fix:*" topics don't yield three identical queries.
54
+ */
55
+ export declare function suggestRecallQueries(topics: string[], instanceId: string, max?: number): string[];
56
+ export declare function buildFirstContactReport(r: FirstContactReportInput): string;
@@ -0,0 +1,108 @@
1
+ /**
2
+ * First-contact response builder for `brain_from_git` (roadmap P1-5:
3
+ * "Onboarding-Magie messen & polieren").
4
+ *
5
+ * The very first `brain_from_git` run is a new user's first contact with the
6
+ * Brain, and it decides whether they ever reach the "aha". The response must,
7
+ * in one message:
8
+ * (a) summarize what was just learned (counts by category + severity),
9
+ * (b) prove recall already works — show the top hit of a real search that
10
+ * ran against a topic seeded seconds ago,
11
+ * (c) hand the user 2-3 copy-pasteable next queries, and
12
+ * (d) degrade gracefully for empty/small repos (clear guidance, not empty stats).
13
+ *
14
+ * Pure string building — no I/O, no schema/tool changes — so the onboarding
15
+ * bench and its CI test can assert the exact first-contact response shape.
16
+ */
17
+ /** Below this many ingested lessons we treat the repo as "small" and add growth guidance. */
18
+ export const SMALL_SEED_THRESHOLD = 5;
19
+ export function formatSeedDuration(ms) {
20
+ if (ms < 1000)
21
+ return `${Math.max(ms, 1)}ms`;
22
+ if (ms < 60_000)
23
+ return `${(ms / 1000).toFixed(1)}s`;
24
+ return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;
25
+ }
26
+ /**
27
+ * Turn seeded topics (`category:some-domain`) into up to `max` copy-pasteable
28
+ * `smart_recall` calls a brand-new user can paste as their literal next message.
29
+ * Deduplicates by domain so three "fix:*" topics don't yield three identical queries.
30
+ */
31
+ export function suggestRecallQueries(topics, instanceId, max = 3) {
32
+ const seen = new Set();
33
+ const out = [];
34
+ for (const topic of topics) {
35
+ const domain = (topic.includes(':') ? topic.slice(topic.indexOf(':') + 1) : topic)
36
+ .replace(/[-_]+/g, ' ')
37
+ .trim();
38
+ if (!domain || seen.has(domain))
39
+ continue;
40
+ seen.add(domain);
41
+ out.push(`smart_recall(instance_id="${instanceId}", query="${domain}")`);
42
+ if (out.length >= max)
43
+ break;
44
+ }
45
+ return out;
46
+ }
47
+ /** Steps that take an empty/tiny Brain to a first recall hit in under a minute. */
48
+ function growthSteps(instanceId) {
49
+ return [
50
+ ` 1. \`brain_seed_starter(instance_id="${instanceId}")\` — load 16 curated engineering lessons instantly`,
51
+ ` 2. \`smart_recall(instance_id="${instanceId}", query="docker build slow")\` — see your first recall hit`,
52
+ ` 3. \`learn_from_attempts(...)\` after your next fix — the Brain grows with every lesson from here on`,
53
+ ];
54
+ }
55
+ export function buildFirstContactReport(r) {
56
+ const lines = [];
57
+ lines.push(`🔁 **brain_from_git: ${r.repoDir}**`);
58
+ if (r.isIncremental && r.lastSha) {
59
+ lines.push(`🔄 Incremental mode — only new commits since \`${r.lastSha.slice(0, 8)}\` were processed`);
60
+ }
61
+ lines.push('');
62
+ lines.push(`📂 Branch: \`${r.revRange}\` | Processed: **${r.processed}** commits | ` +
63
+ `Ingested: **${r.ingested}** lessons | Skipped: ${r.skipped} | ` +
64
+ `⏱️ Seeding took ${formatSeedDuration(r.durationMs)}`);
65
+ lines.push('');
66
+ // ── Empty repo / nothing ingested — guidance instead of empty stats ─────────
67
+ if (r.ingested === 0) {
68
+ if (r.emptyReason)
69
+ lines.push(`⚠️ ${r.emptyReason}`);
70
+ lines.push(`🌱 **Nothing to learn from this git history yet** — normal for fresh, shallow, or squash-only repos.`);
71
+ lines.push(`Get to your first recall in under a minute:`);
72
+ lines.push(...growthSteps(r.instanceId));
73
+ return lines.join('\n');
74
+ }
75
+ // ── (a) Seeded summary — what the Brain just learned ────────────────────────
76
+ lines.push(`**What your Brain just learned (by category):**`);
77
+ lines.push(r.categories.map(([k, v]) => ` • **${k}** (${v})`).join('\n'));
78
+ if (r.severities && r.severities.length > 0) {
79
+ lines.push(`**By severity:** ${r.severities.map(([k, v]) => `${k} ${v}`).join(' · ')}`);
80
+ }
81
+ // ── (b) Proof of value — a real recall against a just-seeded topic ──────────
82
+ if (r.proof) {
83
+ lines.push('');
84
+ lines.push(`🎯 **Proof — your first recall already works.** We just searched your fresh Brain for:`);
85
+ lines.push(` "${r.proof.query}"`);
86
+ lines.push(` → Top hit: **${r.proof.topic}** — ${r.proof.snippet}`);
87
+ }
88
+ // ── (c) Suggested next queries — copy-pasteable ──────────────────────────────
89
+ if (r.suggestedQueries.length > 0) {
90
+ lines.push('');
91
+ lines.push(`**Try these next (copy-paste):**`);
92
+ for (const q of r.suggestedQueries)
93
+ lines.push(` • \`${q}\``);
94
+ }
95
+ // ── (d) Small-repo guidance ──────────────────────────────────────────────────
96
+ if (r.ingested < SMALL_SEED_THRESHOLD) {
97
+ lines.push('');
98
+ lines.push(`🌱 **Small git history — only ${r.ingested} lesson${r.ingested === 1 ? '' : 's'} so far.** Top it up:`);
99
+ lines.push(...growthSteps(r.instanceId));
100
+ }
101
+ lines.push('');
102
+ lines.push(`💡 New lessons are stored with confidence 0.55 (auto-inferred).`);
103
+ lines.push(`💡 As you confirm them via \`learn_from_attempts\`, confidence rises automatically.`);
104
+ lines.push(`🔍 Explore: \`brain_search(query="fix")\` | \`ckg_inspect(concept="deploy")\``);
105
+ lines.push(`💾 Next run will automatically continue from the latest commit (incremental mode).`);
106
+ return lines.join('\n');
107
+ }
108
+ //# sourceMappingURL=first-contact.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"first-contact.js","sourceRoot":"","sources":["../../src/first-contact.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAkCH,6FAA6F;AAC7F,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAEtC,MAAM,UAAU,kBAAkB,CAAC,EAAU;IAC3C,IAAI,EAAE,GAAG,IAAI;QAAE,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC;IAC7C,IAAI,EAAE,GAAG,MAAM;QAAE,OAAO,GAAG,CAAC,EAAE,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC;IACrD,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,EAAE,GAAG,MAAM,CAAC,KAAK,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC;AAC5E,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,oBAAoB,CAAC,MAAgB,EAAE,UAAkB,EAAE,GAAG,GAAG,CAAC;IAChF,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CA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,KAAK,CAAC,IAAI,CAAC,iFAAiF,CAAC,CAAC;IAC9F,KAAK,CAAC,IAAI,CAAC,oFAAoF,CAAC,CAAC;IACjG,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC"}
@@ -13,6 +13,7 @@ export interface Instance {
13
13
  memory_mb: number;
14
14
  encryption_at_rest: boolean;
15
15
  created_at: string;
16
+ org_id?: string;
16
17
  }
17
18
  type GetConnection = (instanceId: string) => Promise<Redis>;
18
19
  type ApiFetch = <T>(path: string, options?: RequestInit) => Promise<T>;
@@ -2,7 +2,7 @@ import { execSync } from 'node:child_process';
2
2
  import { calculateConfidence, confidenceBadge, STRUCTURED_TEMPLATES, CONFIDENCE_WARN_VALUE, CONFIDENCE_STALE_VALUE, CONFIDENCE_WARN_DAYS } from '../confidence.js';
3
3
  import { ckgSlug, extractProblemConcept, ckgUpsertNode, ckgUpdateEdge, ckgUpsertPersonNode, ckgUpsertFileNode, ckgRecordCollaboration, ckgUpsertServiceNode } from '../ckg.js';
4
4
  import { safeJsonParse, scanKeys } from '../utils.js';
5
- import { getRole, ROLE_BADGE, getScopes, lessonVisibleToScope } from './team.js';
5
+ import { getRole, ROLE_BADGE, getScopes, lessonVisibleToScope, reviewModeEnabled, storeLessonProposal } from './team.js';
6
6
  import { keywordSearch, tokenize, splitMultiQuery, levenshtein, indexVocab as _indexVocab } from '../search.js';
7
7
  import { rerankByQuality } from '../rerank.js';
8
8
  import { computeEmbedding, hasEmbedProvider } from '../embeddings.js';
@@ -402,6 +402,21 @@ export async function handleBrainTool(name, args, getConnection, apiFetch) {
402
402
  const { instance_id, topic, outcome, what_worked, what_failed = '', context: ctx = '', severity = 'major', file_paths = [], commands = [], tags = [], depends_on = [], author = '', visibility = 'team', service = '', service_kind = 'service', group = '', } = args;
403
403
  const redis = await getConnection(instance_id);
404
404
  const ts = new Date().toISOString();
405
+ // ── Lessons-Review workflow (P1-1) ─────────────────────────────────────
406
+ // When the org enabled pending-mode on this (shared) brain, team-visible
407
+ // lessons become proposals awaiting owner/admin approval instead of
408
+ // landing in the recall keyspace. Private notes stay direct — they never
409
+ // surface in team recall anyway. Flag absent = direct write, as before.
410
+ if (visibility !== 'private' && await reviewModeEnabled(redis, instance_id)) {
411
+ return storeLessonProposal(redis, topic, {
412
+ topic, outcome, what_worked, what_failed, context: ctx, severity,
413
+ file_paths, commands, tags, depends_on,
414
+ ...(author ? { author } : {}),
415
+ ...(service ? { service } : {}),
416
+ ...(group ? { group: String(group).toLowerCase().trim() } : {}),
417
+ visibility, recall_count: 0, ts, confidence: 1.0, version: 3,
418
+ });
419
+ }
405
420
  // ── Structured template hints ──────────────────────────────────────────
406
421
  const category = topic.split(':')[0];
407
422
  const template = STRUCTURED_TEMPLATES[category];
@@ -416,12 +431,14 @@ export async function handleBrainTool(name, args, getConnection, apiFetch) {
416
431
  // ── Deduplication + audit trail ────────────────────────────────────────
417
432
  let isUpdate = false;
418
433
  let recallCount = 0;
434
+ let lastRecalledAt;
419
435
  let auditTrail = [];
420
436
  const existingRaw = await redis.get(`cachly:lesson:best:${topic}`);
421
437
  if (existingRaw) {
422
438
  try {
423
439
  const prev = JSON.parse(existingRaw);
424
440
  recallCount = prev.recall_count ?? 0;
441
+ lastRecalledAt = prev.last_recalled_at; // learn never stamps it — only recall does
425
442
  auditTrail = prev.audit_trail ?? [];
426
443
  auditTrail.push({ ts, action: 'updated', prev_outcome: prev.outcome });
427
444
  if (auditTrail.length > 20)
@@ -521,6 +538,7 @@ export async function handleBrainTool(name, args, getConnection, apiFetch) {
521
538
  ...(group ? { group: String(group).toLowerCase().trim() } : {}),
522
539
  visibility,
523
540
  recall_count: recallCount,
541
+ ...(lastRecalledAt ? { last_recalled_at: lastRecalledAt } : {}),
524
542
  ts,
525
543
  verified_at: outcome === 'success' || outcome === 'partial' ? ts : undefined,
526
544
  confidence: 1.0,
@@ -788,11 +806,14 @@ export async function handleBrainTool(name, args, getConnection, apiFetch) {
788
806
  const ref = lesson.verified_at ?? lesson.ts;
789
807
  const ageDays = (Date.now() - new Date(ref).getTime()) / 86400000;
790
808
  const badge = confidenceBadge(confidence, ageDays);
791
- // Recall resets verified_at (confidence clock restart)
809
+ // Recall resets verified_at (confidence clock restart) and stamps
810
+ // last_recalled_at so the recall-quality dashboard can measure recency.
811
+ const recalledAt = new Date().toISOString();
792
812
  const updatedLesson = {
793
813
  ...lesson,
794
814
  recall_count: (lesson.recall_count ?? 0) + 1,
795
- verified_at: new Date().toISOString(),
815
+ verified_at: recalledAt,
816
+ last_recalled_at: recalledAt,
796
817
  confidence: 1.0,
797
818
  };
798
819
  await redis.set(`cachly:lesson:best:${topic}`, JSON.stringify(updatedLesson));
@@ -837,7 +858,9 @@ export async function handleBrainTool(name, args, getConnection, apiFetch) {
837
858
  trustBadge,
838
859
  `${badge} **Best solution for \`${topic}\`** ${sevEmoji}${lesson.severity ? ` (${lesson.severity})` : ''} · recalled ${updatedLesson.recall_count}×`,
839
860
  ``,
840
- `**What worked:** ${lesson.what_worked}`,
861
+ // what_worked may be empty for unresolved failure lessons (the API
862
+ // accepts empty what_worked when outcome=failure) — skip the line.
863
+ lesson.what_worked ? `**What worked:** ${lesson.what_worked}` : '',
841
864
  lesson.what_failed ? `**What failed (avoid this):** ${lesson.what_failed}` : '',
842
865
  lesson.context ? `**Context:** ${lesson.context}` : '',
843
866
  (lesson.file_paths ?? []).length > 0 ? `**Files:** ${(lesson.file_paths ?? []).map((f) => `\`${f}\``).join(', ')}` : '',
@@ -906,6 +929,7 @@ export async function handleBrainTool(name, args, getConnection, apiFetch) {
906
929
  // Exclude archived lessons — they are kept for audit but must not surface in recall.
907
930
  const lessonMatches = kwMatches.filter(m => m.key.startsWith('cachly:lesson:best:'));
908
931
  let crossAuthorThisCall = 0;
932
+ let successRecallsThisCall = 0;
909
933
  for (const m of lessonMatches.slice(0, 5)) {
910
934
  const existing = await redis.get(m.key).catch(() => null);
911
935
  if (existing) {
@@ -914,7 +938,8 @@ export async function handleBrainTool(name, args, getConnection, apiFetch) {
914
938
  if (lesson?.state === 'archived')
915
939
  continue;
916
940
  if (lesson) {
917
- const updated = { ...lesson, recall_count: (lesson.recall_count ?? 0) + 1, verified_at: new Date().toISOString() };
941
+ const recalledAt = new Date().toISOString();
942
+ const updated = { ...lesson, recall_count: (lesson.recall_count ?? 0) + 1, verified_at: recalledAt, last_recalled_at: recalledAt };
918
943
  redis.set(m.key, JSON.stringify(updated)).catch(() => { });
919
944
  const sev = lesson.severity;
920
945
  const savedMins = sev === 'critical' ? 240 : sev === 'major' ? 60 : 30;
@@ -934,6 +959,8 @@ export async function handleBrainTool(name, args, getConnection, apiFetch) {
934
959
  ckgUpdateEdge(redis, reqPersonId, 'collaborates', authPersonId, true).catch(() => { });
935
960
  ckgUpdateEdge(redis, authPersonId, 'collaborates', reqPersonId, true).catch(() => { });
936
961
  }
962
+ if (lesson.outcome === 'success')
963
+ successRecallsThisCall++;
937
964
  // Surface banner for proven successes (recall_count >= 1 means it's been validated)
938
965
  if (lesson.outcome === 'success' && (lesson.recall_count ?? 0) >= 1) {
939
966
  savedHere.push({
@@ -949,8 +976,11 @@ export async function handleBrainTool(name, args, getConnection, apiFetch) {
949
976
  }
950
977
  }
951
978
  // Metric 1 (time-to-first-recall): stamp the first time recall returned a
952
- // proven lesson. SET NX so only the first successful recall wins.
953
- if (savedHere.length > 0) {
979
+ // successful lesson. SET NX so only the first successful recall wins.
980
+ // Deliberately NOT gated on savedHere: savedHere requires a pre-existing
981
+ // recall_count >= 1, which would delay the stamp until the SECOND recall
982
+ // and inflate every TTFR percentile derived from it.
983
+ if (successRecallsThisCall > 0) {
954
984
  redis.set(`cachly:stats:first_recall_at:${instance_id}`, new Date().toISOString(), 'EX', 365 * 86400, 'NX').catch(() => { });
955
985
  }
956
986
  // ── Layer 2: Semantic search (parallel, optional) ────────────────────────