@phren/cli 0.3.34 → 0.3.36

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 (68) hide show
  1. package/dist/bridge/agent-hooks.d.ts +11 -1
  2. package/dist/bridge/agent-hooks.js +56 -19
  3. package/dist/bridge/changes.js +30 -13
  4. package/dist/bridge/dispatch-command.js +3 -1
  5. package/dist/bridge/health.js +3 -1
  6. package/dist/bridge/host-key.d.ts +16 -0
  7. package/dist/bridge/host-key.js +35 -0
  8. package/dist/bridge/launch-brief.d.ts +2 -0
  9. package/dist/bridge/launch-brief.js +5 -0
  10. package/dist/bridge/link.js +11 -4
  11. package/dist/bridge/owner-inbox-sources.d.ts +5 -0
  12. package/dist/bridge/owner-inbox-sources.js +94 -0
  13. package/dist/bridge/owner-inbox-view.js +20 -1
  14. package/dist/bridge/owner-inbox.d.ts +7 -3
  15. package/dist/bridge/owner-inbox.js +113 -69
  16. package/dist/bridge/pair.js +3 -2
  17. package/dist/bridge/server.js +3 -23
  18. package/dist/bridge/sudo.d.ts +36 -6
  19. package/dist/bridge/sudo.js +180 -37
  20. package/dist/bridge/worker-reports.d.ts +8 -1
  21. package/dist/bridge/worker-reports.js +28 -7
  22. package/dist/bridge-hook.mjs +817 -473
  23. package/dist/clanker.d.ts +54 -0
  24. package/dist/clanker.js +188 -0
  25. package/dist/cli/config.js +30 -0
  26. package/dist/cli/hooks-output.d.ts +1 -1
  27. package/dist/cli/hooks-output.js +28 -21
  28. package/dist/cli/hooks.js +1 -1
  29. package/dist/cli/namespaces-skills.js +2 -2
  30. package/dist/cli/namespaces-tasks.js +46 -7
  31. package/dist/cli/session-start.js +12 -3
  32. package/dist/cli/session-stop.js +9 -0
  33. package/dist/cli/team.js +3 -0
  34. package/dist/cli-handlers.js +7 -0
  35. package/dist/cli-registry.js +1 -0
  36. package/dist/data/task-format.d.ts +5 -1
  37. package/dist/data/task-format.js +13 -5
  38. package/dist/index.js +82 -50
  39. package/dist/init/init-configure.d.ts +2 -0
  40. package/dist/init/init-configure.js +12 -0
  41. package/dist/init/init-uninstall.js +21 -2
  42. package/dist/init/init.d.ts +2 -0
  43. package/dist/init/init.js +11 -3
  44. package/dist/init/preferences.d.ts +6 -0
  45. package/dist/init/teardown.js +18 -4
  46. package/dist/link/doctor.js +2 -2
  47. package/dist/link/link.js +9 -0
  48. package/dist/link/refresh.d.ts +10 -0
  49. package/dist/link/refresh.js +34 -0
  50. package/dist/mcp/local-index.d.ts +20 -0
  51. package/dist/mcp/local-index.js +39 -1
  52. package/dist/shared/index.d.ts +14 -0
  53. package/dist/shared/index.js +88 -74
  54. package/dist/shared/retrieval.js +1 -1
  55. package/dist/skill/files.js +40 -11
  56. package/dist/skill/registry.d.ts +6 -0
  57. package/dist/skill/registry.js +21 -5
  58. package/dist/task/lifecycle.js +3 -1
  59. package/dist/tools/dispatch.js +5 -2
  60. package/dist/tools/finding.js +20 -11
  61. package/dist/tools/graph.d.ts +2 -0
  62. package/dist/tools/graph.js +2 -0
  63. package/dist/tools/search.d.ts +2 -0
  64. package/dist/tools/search.js +88 -6
  65. package/dist/tools/tasks.js +45 -0
  66. package/dist/tools/types.d.ts +3 -1
  67. package/dist/tools/types.js +3 -2
  68. package/package.json +1 -1
@@ -0,0 +1,54 @@
1
+ /** Where the clanker setting came from, for `phren config clanker`. */
2
+ export type ClankerSource = "PHREN_CLANKER" | "PHREN_FEATURE_PROGRESSIVE_DISCLOSURE" | "install preferences" | "default";
3
+ export declare function resolveClanker(phrenPath: string, env?: NodeJS.ProcessEnv): {
4
+ on: boolean;
5
+ source: ClankerSource;
6
+ };
7
+ export declare function clankerEnabled(phrenPath: string, env?: NodeJS.ProcessEnv): boolean;
8
+ export interface ClankerRow {
9
+ id: string;
10
+ project: string;
11
+ type: string;
12
+ title: string;
13
+ keywords: string[];
14
+ /** Share of the query's terms the entry contains, 0–1. Absent for plain lists. */
15
+ score?: number;
16
+ }
17
+ /** Hook rows are few and arrive unasked, so they get room for the entry's point, not just its subject. */
18
+ export declare const HOOK_TITLE_CHARS = 140;
19
+ /** Query terms as the snippet extractor reads them: lowercase, no FTS operators. */
20
+ export declare function queryTerms(query: string): string[];
21
+ /** Entry text without markers, comments, checkboxes or markdown decoration. */
22
+ export declare function plainEntryText(line: string): string;
23
+ export declare function rowTitle(text: string, max?: number): string;
24
+ /**
25
+ * A few words that say what the entry is about: up to two query terms it
26
+ * contains first, then identifier-looking words (paths, flags, names with dots,
27
+ * dashes or capitals), then the longest remaining words.
28
+ */
29
+ export declare function rowKeywords(text: string, terms?: string[], count?: number): string[];
30
+ export declare function termScore(text: string, terms: string[]): number;
31
+ /** One row per line: `id [project] title [keywords] score`. */
32
+ export declare function formatRow(row: ClankerRow, showProject?: boolean): string;
33
+ export interface DocEntry {
34
+ /** `fid:xxxxxxxx` or `bid:xxxxxxxx`. */
35
+ id: string;
36
+ line: string;
37
+ /** The bullet plus its indented continuation (task Context, citations). */
38
+ text: string;
39
+ }
40
+ /** The bullets in a findings, task or archive document that carry a stable id. */
41
+ export declare function docEntries(content: string): DocEntry[];
42
+ /** Find one entry by `fid:`/`bid:` id in a document's content. */
43
+ export declare function findEntry(content: string, id: string): DocEntry | null;
44
+ /**
45
+ * Rows for one search hit. Findings, tasks and archive topics become one row
46
+ * per matching entry (best first, at most `max`); other documents are one row
47
+ * for the matched line under the document's mem: id.
48
+ */
49
+ export declare function rowsForDoc(doc: {
50
+ project: string;
51
+ type: string;
52
+ content: string;
53
+ }, docId: string, terms: string[], bestLine: string, max: number): ClankerRow[];
54
+ export declare const CLANKER_FETCH_HINT = "Rows: id title [keywords], plus a 0-1 score on search hits. Full text: get_memory_detail id=<id>.";
@@ -0,0 +1,188 @@
1
+ /**
2
+ * Clanker mode: keyword-first retrieval.
3
+ *
4
+ * With it on, the prompt hook, search_knowledge, get_tasks and get_findings
5
+ * return one short row per hit (id, title, a few keywords, a score) instead
6
+ * of the text itself, and the agent fetches what it needs with
7
+ * get_memory_detail. Findings and tasks get their own fid:/bid: ids, so
8
+ * fetching one returns that entry, not the whole file it lives in.
9
+ *
10
+ * `phren config clanker on|off` sets it per install; PHREN_CLANKER overrides
11
+ * it, and the older PHREN_FEATURE_PROGRESSIVE_DISCLOSURE is read as an alias.
12
+ */
13
+ import { readInstallPreferences } from "./init/preferences.js";
14
+ import { STOP_WORDS } from "./utils.js";
15
+ const TRUE_VALUES = new Set(["1", "true", "on", "yes"]);
16
+ const FALSE_VALUES = new Set(["0", "false", "off", "no"]);
17
+ function parseSwitch(raw) {
18
+ const value = raw?.trim().toLowerCase();
19
+ if (!value)
20
+ return undefined;
21
+ if (TRUE_VALUES.has(value))
22
+ return true;
23
+ if (FALSE_VALUES.has(value))
24
+ return false;
25
+ return undefined;
26
+ }
27
+ export function resolveClanker(phrenPath, env = process.env) {
28
+ const fromEnv = parseSwitch(env.PHREN_CLANKER);
29
+ if (fromEnv !== undefined)
30
+ return { on: fromEnv, source: "PHREN_CLANKER" };
31
+ const legacy = parseSwitch(env.PHREN_FEATURE_PROGRESSIVE_DISCLOSURE);
32
+ if (legacy !== undefined)
33
+ return { on: legacy, source: "PHREN_FEATURE_PROGRESSIVE_DISCLOSURE" };
34
+ try {
35
+ const prefs = readInstallPreferences(phrenPath);
36
+ if (typeof prefs.clanker === "boolean")
37
+ return { on: prefs.clanker, source: "install preferences" };
38
+ }
39
+ catch {
40
+ // No preferences yet: the default applies.
41
+ }
42
+ return { on: false, source: "default" };
43
+ }
44
+ export function clankerEnabled(phrenPath, env = process.env) {
45
+ return resolveClanker(phrenPath, env).on;
46
+ }
47
+ const TITLE_CHARS = 90;
48
+ /** Hook rows are few and arrive unasked, so they get room for the entry's point, not just its subject. */
49
+ export const HOOK_TITLE_CHARS = 140;
50
+ const KEYWORD_COUNT = 4;
51
+ /** Query terms as the snippet extractor reads them: lowercase, no FTS operators. */
52
+ export function queryTerms(query) {
53
+ return [...new Set(query
54
+ .replace(/\b(AND|OR|NOT|NEAR)\b/g, " ")
55
+ .toLowerCase()
56
+ .replace(/[^\p{L}\p{N}\s_.-]/gu, " ")
57
+ .split(/\s+/)
58
+ .map((term) => term.replace(/^[.-]+|[.-]+$/g, ""))
59
+ .filter((term) => term.length > 1 && !STOP_WORDS.has(term)))];
60
+ }
61
+ /** Entry text without markers, comments, checkboxes or markdown decoration. */
62
+ export function plainEntryText(line) {
63
+ return line
64
+ .replace(/<!--[\s\S]*?-->/g, " ")
65
+ .replace(/^\s*[-*]\s+(\[[ xX]\]\s+)?/, "")
66
+ .replace(/^#+\s+/, "")
67
+ // Backticks and bold only: underscores and single stars belong to
68
+ // identifiers and globs (PHREN_PATH, node_modules, **/*.ts).
69
+ .replace(/`|\*\*/g, "")
70
+ .replace(/\s+/g, " ")
71
+ .trim();
72
+ }
73
+ export function rowTitle(text, max = TITLE_CHARS) {
74
+ const plain = plainEntryText(text);
75
+ if (plain.length <= max)
76
+ return plain;
77
+ return `${plain.slice(0, max - 1).trimEnd()}…`;
78
+ }
79
+ /**
80
+ * A few words that say what the entry is about: up to two query terms it
81
+ * contains first, then identifier-looking words (paths, flags, names with dots,
82
+ * dashes or capitals), then the longest remaining words.
83
+ */
84
+ export function rowKeywords(text, terms = [], count = KEYWORD_COUNT) {
85
+ const plain = plainEntryText(text);
86
+ const lower = plain.toLowerCase();
87
+ // Two matched query terms say why it hit; the rest say what else it covers.
88
+ const picked = [];
89
+ for (const term of terms) {
90
+ if (picked.length >= Math.min(2, count))
91
+ break;
92
+ if (lower.includes(term))
93
+ picked.push(term);
94
+ }
95
+ const words = plain
96
+ .split(/[\s,;:()[\]{}"'“”]+/)
97
+ .map((word) => word.replace(/^[.-]+|[.!?.,-]+$/g, ""))
98
+ .filter((word) => word.length > 3 && !STOP_WORDS.has(word.toLowerCase()) && !/^\d+$/.test(word));
99
+ const seen = new Set(picked);
100
+ const identifier = (word) => /[./_@#-]/.test(word) || /[a-z][A-Z]/.test(word) || /^[A-Z0-9]{2,}$/.test(word);
101
+ const candidates = [
102
+ ...words.filter(identifier),
103
+ ...words.filter((word) => !identifier(word)).sort((a, b) => b.length - a.length),
104
+ ];
105
+ for (const word of candidates) {
106
+ if (picked.length >= count)
107
+ break;
108
+ const key = word.toLowerCase();
109
+ if (seen.has(key) || word.length > 40)
110
+ continue;
111
+ seen.add(key);
112
+ picked.push(key);
113
+ }
114
+ return picked;
115
+ }
116
+ export function termScore(text, terms) {
117
+ if (!terms.length)
118
+ return 0;
119
+ const lower = text.toLowerCase();
120
+ const hits = terms.filter((term) => lower.includes(term)).length;
121
+ return Math.round((hits / terms.length) * 100) / 100;
122
+ }
123
+ /** One row per line: `id [project] title [keywords] score`. */
124
+ export function formatRow(row, showProject = false) {
125
+ const project = showProject ? ` ${row.project}:` : "";
126
+ const keywords = row.keywords.length ? ` [${row.keywords.join(", ")}]` : "";
127
+ const score = row.score !== undefined ? ` ${row.score.toFixed(2)}` : "";
128
+ return `${row.id}${project} ${row.title}${keywords}${score}`;
129
+ }
130
+ // ── Entries inside a document ────────────────────────────────────────────────
131
+ const ENTRY_ID = /<!--\s*(?:fid:([a-z0-9]{8})|bid:([a-f0-9]{8}))\b/i;
132
+ /** The bullets in a findings, task or archive document that carry a stable id. */
133
+ export function docEntries(content) {
134
+ const lines = content.split("\n");
135
+ const entries = [];
136
+ for (let i = 0; i < lines.length; i++) {
137
+ if (!/^\s*-\s/.test(lines[i]) || /^\s+/.test(lines[i]))
138
+ continue;
139
+ const match = lines[i].match(ENTRY_ID);
140
+ if (!match)
141
+ continue;
142
+ let end = i + 1;
143
+ while (end < lines.length && /^\s+\S/.test(lines[end]))
144
+ end++;
145
+ entries.push({
146
+ id: match[1] ? `fid:${match[1].toLowerCase()}` : `bid:${match[2].toLowerCase()}`,
147
+ line: lines[i],
148
+ text: lines.slice(i, end).join("\n"),
149
+ });
150
+ }
151
+ return entries;
152
+ }
153
+ /** Find one entry by `fid:`/`bid:` id in a document's content. */
154
+ export function findEntry(content, id) {
155
+ const wanted = id.toLowerCase();
156
+ return docEntries(content).find((entry) => entry.id === wanted) ?? null;
157
+ }
158
+ /**
159
+ * Rows for one search hit. Findings, tasks and archive topics become one row
160
+ * per matching entry (best first, at most `max`); other documents are one row
161
+ * for the matched line under the document's mem: id.
162
+ */
163
+ export function rowsForDoc(doc, docId, terms, bestLine, max) {
164
+ const entries = docEntries(doc.content)
165
+ .map((entry) => ({ entry, score: termScore(entry.line, terms) }))
166
+ .filter(({ score }) => score > 0)
167
+ .sort((a, b) => b.score - a.score)
168
+ .slice(0, max);
169
+ if (entries.length) {
170
+ return entries.map(({ entry, score }) => ({
171
+ id: entry.id,
172
+ project: doc.project,
173
+ type: doc.type,
174
+ title: rowTitle(entry.line),
175
+ keywords: rowKeywords(entry.line, terms),
176
+ score,
177
+ }));
178
+ }
179
+ return [{
180
+ id: docId,
181
+ project: doc.project,
182
+ type: doc.type,
183
+ title: rowTitle(bestLine || doc.content.split("\n").find((line) => line.trim() && !/^\s*(#|<!--)/.test(line)) || ""),
184
+ keywords: rowKeywords(bestLine || doc.content.slice(0, 2000), terms),
185
+ score: termScore(bestLine || doc.content, terms),
186
+ }];
187
+ }
188
+ export const CLANKER_FETCH_HINT = "Rows: id title [keywords], plus a 0-1 score on search hits. Full text: get_memory_detail id=<id>.";
@@ -3,6 +3,7 @@ import { listMachines as listMachinesStore, listProfiles as listProfilesStore }
3
3
  import { setTelemetryEnabled, getTelemetrySummary, resetTelemetry } from "../telemetry.js";
4
4
  import { readInstallPreferences, updateInstallPreferences } from "../init/preferences.js";
5
5
  import { resolveMcpProfile } from "../mcp/profile.js";
6
+ import { resolveClanker } from "../clanker.js";
6
7
  import { parsePullInterval, resolvePullInterval, periodicPullEnabled } from "../sync/pull.js";
7
8
  import * as path from "path";
8
9
  import { buildConfigView } from "../config/resolve.js";
@@ -120,6 +121,15 @@ export async function handleConfig(args) {
120
121
  return handleConfigTelemetry(rest);
121
122
  case "mcp-profile":
122
123
  return handleConfigMcpProfile(rest);
124
+ case "clanker":
125
+ return handleConfigClanker(rest);
126
+ case "set":
127
+ // `phren config set clanker on` reads naturally; clanker is the only key it takes.
128
+ if (rest[0] === "clanker")
129
+ return handleConfigClanker(rest.slice(1));
130
+ console.error("phren config set takes: clanker on|off. Other settings have their own subcommand (phren config).");
131
+ process.exitCode = 1;
132
+ return;
123
133
  case "pull-interval":
124
134
  return handleConfigPullInterval(rest);
125
135
  case "proactivity":
@@ -170,6 +180,8 @@ Subcommands:
170
180
  Manage project learned synonyms
171
181
  phren config machines Registered machines and profiles
172
182
  phren config profiles All profiles and their projects
183
+ phren config clanker [on|off] Compact keyword-first retrieval: hook, search and
184
+ lists return id/title/keyword rows; full text by id
173
185
  phren config pull-interval [seconds|off]
174
186
  Periodic MCP remote checks (default: off)
175
187
  phren config telemetry [on|off|reset] Local usage stats (opt-in, no external reporting)`);
@@ -259,6 +271,24 @@ function handleConfigMcpProfile(args) {
259
271
  ? "10 tools: search_knowledge, get_memory_detail, get_project_summary, add_finding, revise_finding, get_tasks, add_task, manage_task, session, phren_admin."
260
272
  : "Every tool by name. `phren config mcp-profile core` for the compact surface.");
261
273
  }
274
+ function handleConfigClanker(args) {
275
+ const phrenPath = getPhrenPath();
276
+ const want = args[0]?.trim().toLowerCase();
277
+ if (want === "on" || want === "off") {
278
+ updateInstallPreferences(phrenPath, () => ({ clanker: want === "on" }));
279
+ console.log(`Clanker mode ${want}. It applies from the next prompt and tool call.`);
280
+ }
281
+ else if (want) {
282
+ console.error(`Unknown value "${want}". Use on or off.`);
283
+ process.exitCode = 1;
284
+ return;
285
+ }
286
+ const { on, source } = resolveClanker(phrenPath);
287
+ console.log(`Clanker mode: ${on ? "on" : "off"} (${source})`);
288
+ console.log(on
289
+ ? "The prompt hook, search_knowledge, get_tasks and get_findings return id, title, keyword and score rows; get_memory_detail fetches an entry by id."
290
+ : "The prompt hook and tools return text snippets. `phren config clanker on` for compact rows.");
291
+ }
262
292
  function handleConfigTelemetry(args) {
263
293
  const action = args[0];
264
294
  switch (action) {
@@ -1,2 +1,2 @@
1
1
  import type { SelectedSnippet, GitContext } from "../shared/retrieval.js";
2
- export declare function buildHookOutput(selected: SelectedSnippet[], usedTokens: number, intent: string, gitCtx: GitContext | null, detectedProject: string | null, stage: Record<string, number>, tokenBudget: number, phrenPathLocal: string, sessionId?: string): string[];
2
+ export declare function buildHookOutput(selected: SelectedSnippet[], usedTokens: number, intent: string, gitCtx: GitContext | null, detectedProject: string | null, stage: Record<string, number>, tokenBudget: number, phrenPathLocal: string, sessionId?: string, keywords?: string): string[];
@@ -1,45 +1,49 @@
1
1
  import { recordInjection, recordRetrieval, } from "../shared/governance.js";
2
2
  import { getDocSourceKey, } from "../shared/index.js";
3
3
  import { logImpact, extractFindingIdsFromSnippet, } from "../finding/impact.js";
4
- import { isFeatureEnabled, errorMessage } from "../utils.js";
4
+ import { errorMessage } from "../utils.js";
5
+ import { HOOK_TITLE_CHARS, clankerEnabled, docEntries, queryTerms, rowKeywords, rowTitle, termScore } from "../clanker.js";
5
6
  import { annotateStale } from "./hooks-citations.js";
6
7
  import { approximateTokens, fileRelevanceBoost, branchMatchBoost, SNIPPET_OVERHEAD_TOKENS } from "../shared/retrieval.js";
7
8
  import { logger } from "../logger.js";
8
- // ── Progressive disclosure helpers ────────────────────────────────────────────
9
- function buildOneLiner(snippet) {
10
- const lines = snippet.split("\n").map(l => l.trim()).filter(l => l.length > 0);
11
- if (!lines.length)
12
- return "";
13
- const first = lines[0].replace(/^[-*#>\s]+/, "").trim();
14
- if (first.length <= 80)
15
- return first;
16
- return first.slice(0, 79) + "\u2026";
17
- }
18
- function buildCompactIndex(selected, phrenPathLocal) {
9
+ // ── Clanker mode: compact index ──────────────────────────────────────────────
10
+ function buildCompactIndex(selected, phrenPathLocal, terms) {
19
11
  const lines = [];
20
12
  for (const { doc, snippet, key } of selected) {
21
- const id = `mem:${getDocSourceKey(doc, phrenPathLocal)}`;
22
- const summary = buildOneLiner(snippet);
13
+ // A snippet that is one finding or task gets that entry's own id, so
14
+ // expanding it returns the entry rather than the whole file.
15
+ // Snippets are cut at a character budget, which often drops the id
16
+ // comment at the end of a long bullet, so match the bullet in the doc.
17
+ const textLines = snippet.split("\n").filter((l) => l.trim() && !l.trim().startsWith("<!--"));
18
+ // The line that matched most of the prompt, skipping headings and table rules.
19
+ const candidates = textLines.filter((l) => !/^\s*(#|\|?[\s:|-]+\|?\s*$)/.test(l));
20
+ const firstLine = candidates.reduce((best, l) => (best === undefined || termScore(l, terms) > termScore(best, terms) ? l : best), undefined) ?? textLines[0] ?? "";
21
+ const bullets = snippet.split("\n").filter((l) => /^-\s/.test(l));
22
+ const prefix = bullets.length === 1 ? bullets[0].replace(/…$/, "").slice(0, 120) : "";
23
+ const entry = prefix ? docEntries(doc.content).find((e) => e.line.startsWith(prefix)) : undefined;
24
+ const id = entry ? entry.id : `mem:${getDocSourceKey(doc, phrenPathLocal)}`;
25
+ const text = entry ? entry.line : firstLine;
26
+ const keywords = rowKeywords(text, terms);
23
27
  // The fb: key rides here too. memory_feedback's description promises it
24
28
  // appears in injected headers without qualification, and this path renders
25
- // instead of the full one whenever progressive disclosure is enabled.
26
- lines.push(`[${id}] fb:${key} ${doc.type}: ${summary}`);
29
+ // instead of the full one whenever clanker mode is on.
30
+ lines.push(`${id} fb:${key} ${rowTitle(text, HOOK_TITLE_CHARS)}${keywords.length ? ` [${keywords.join(", ")}]` : ""}`);
27
31
  }
28
32
  return lines;
29
33
  }
30
34
  // ── Hook output formatting ───────────────────────────────────────────────────
31
- export function buildHookOutput(selected, usedTokens, intent, gitCtx, detectedProject, stage, tokenBudget, phrenPathLocal, sessionId) {
35
+ export function buildHookOutput(selected, usedTokens, intent, gitCtx, detectedProject, stage, tokenBudget, phrenPathLocal, sessionId, keywords) {
32
36
  const projectLabel = detectedProject ? ` \u00b7 ${detectedProject}` : "";
33
37
  const resultLabel = selected.length === 1 ? "1 result" : `${selected.length} results`;
34
38
  const statusLine = `\u25c6 phren${projectLabel} \u00b7 ${resultLabel}`;
35
39
  const parts = [statusLine, "<phren-context>"];
36
40
  const impactEntries = [];
37
41
  const impactSessionId = sessionId ?? "none";
38
- const useCompactIndex = isFeatureEnabled("PHREN_FEATURE_PROGRESSIVE_DISCLOSURE", false) && selected.length >= 3;
39
- if (useCompactIndex) {
42
+ const clanker = clankerEnabled(phrenPathLocal);
43
+ if (clanker) {
40
44
  const indexEntries = selected.slice(0, 8);
41
- const indexLines = buildCompactIndex(indexEntries, phrenPathLocal);
42
- parts.push("Context index (use get_memory_detail to expand any entry):");
45
+ const indexLines = buildCompactIndex(indexEntries, phrenPathLocal, queryTerms(keywords ?? ""));
46
+ parts.push("Index (get_memory_detail id=<id> for full text):");
43
47
  for (const line of indexLines) {
44
48
  parts.push(line);
45
49
  }
@@ -125,6 +129,9 @@ export function buildHookOutput(selected, usedTokens, intent, gitCtx, detectedPr
125
129
  }
126
130
  logImpact(phrenPathLocal, impactEntries);
127
131
  parts.push("</phren-context>");
132
+ // The trace is for people reading the hook log; clanker mode spends no tokens on it.
133
+ if (clanker)
134
+ return parts;
128
135
  const changedCount = gitCtx?.changedFiles.size ?? 0;
129
136
  if (gitCtx) {
130
137
  const fileHits = selected.filter((r) => fileRelevanceBoost(r.doc.path, gitCtx.changedFiles) > 0).length;
package/dist/cli/hooks.js CHANGED
@@ -283,7 +283,7 @@ export async function handleHookPrompt() {
283
283
  catch (err) {
284
284
  debugLog(`hook-prompt lookup-events: ${errorMessage(err)}`);
285
285
  }
286
- const parts = buildHookOutput(budgetSelected, budgetUsedTokens, intent, gitCtx, detectedProject, stage, safeTokenBudget, getPhrenPath(), sessionId);
286
+ const parts = buildHookOutput(budgetSelected, budgetUsedTokens, intent, gitCtx, detectedProject, stage, safeTokenBudget, getPhrenPath(), sessionId, keywords);
287
287
  const taskLevel = resolvedConfig.proactivity.tasks
288
288
  ?? resolvedConfig.proactivity.base
289
289
  ?? getProactivityLevelForTask(getPhrenPath());
@@ -4,7 +4,7 @@ import { expandHomePath, getPhrenPath, getProjectDirs, homePath, hookConfigPath,
4
4
  import { isValidProjectName, errorMessage, getOptionValue } from "../utils.js";
5
5
  import { logger } from "../logger.js";
6
6
  import { readInstallPreferences, writeInstallPreferences } from "../init/preferences.js";
7
- import { buildSkillManifest, findLocalSkill, findSkill, getAllSkills } from "../skill/registry.js";
7
+ import { buildSkillManifest, findLocalSkill, findSkill, getAllSkills, skillMirrorPath } from "../skill/registry.js";
8
8
  import { detectSkillCollisions } from "../link/skills.js";
9
9
  import { setSkillEnabledAndSync, syncSkillLinksForScope } from "../skill/files.js";
10
10
  import { findProjectDir } from "../project-locator.js";
@@ -89,7 +89,7 @@ function printSkillDoctor(scope, manifest, destDir) {
89
89
  problems.push(`Missing generated command registry: ${path.join(parentDir, "skill-commands.json")}`);
90
90
  }
91
91
  for (const skill of manifest.skills.filter((entry) => entry.visibleToAgents)) {
92
- const dest = path.join(destDir, skill.format === "folder" ? skill.name : path.basename(skill.path));
92
+ const dest = skillMirrorPath(destDir, skill);
93
93
  try {
94
94
  if (!fs.existsSync(dest) || fs.realpathSync(dest) !== fs.realpathSync(skill.root)) {
95
95
  problems.push(`Mirror drift for ${skill.name}: expected ${dest} -> ${skill.root}`);
@@ -1,11 +1,14 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
1
3
  import { getPhrenPath } from "../shared.js";
2
- import { enableTaskFormat, taskFormatStatus, taskFormatMigrationHint } from "../data/task-format.js";
4
+ import { enableTaskFormat, taskFormatStatus, taskFormatMigrationHint, taskFormatCurrentWriters } from "../data/task-format.js";
5
+ import { resolveAllStores } from "../store-registry.js";
3
6
  import { addTask, completeTask, updateTask, reorderTask, pinTask, removeTask, workNextTask, tidyDoneTasks, linkTaskIssue, promoteTask, resolveTaskItem } from "../data/tasks.js";
4
7
  import { buildTaskIssueBody, createGithubIssueForTask, parseGithubIssueUrl, resolveProjectGithubRepo } from "../task/github.js";
5
8
  function printTaskUsage() {
6
9
  console.log("Usage:");
7
10
  console.log(' phren task list [profile] [--responsibility=human|agent] [--readiness=ready|waiting-on-human|waiting-on-task]');
8
- console.log(' phren task format [enable --all-writers-compatible]');
11
+ console.log(' phren task format [--json | enable --all-writers-compatible]');
9
12
  console.log(' phren task add <project> "<text>"');
10
13
  console.log(' phren task complete <project> "<text>"');
11
14
  console.log(' phren task remove <project> "<text>"');
@@ -19,6 +22,22 @@ function printTaskUsage() {
19
22
  console.log(' phren task pin <project> "<text>"');
20
23
  console.log(' phren task reorder <project> "<text>" --rank=<n>');
21
24
  }
25
+ /** The store whose folder holds the working directory, else the primary store. */
26
+ function taskFormatStore(phrenPath) {
27
+ const real = (p) => { try {
28
+ return fs.realpathSync(p);
29
+ }
30
+ catch {
31
+ return path.resolve(p);
32
+ } };
33
+ const cwd = real(process.cwd());
34
+ const stores = resolveAllStores(phrenPath).filter(s => s.available !== false);
35
+ const inside = stores
36
+ .map(s => ({ store: s, root: real(s.path) }))
37
+ .filter(({ root }) => cwd === root || cwd.startsWith(root + path.sep))
38
+ .sort((a, b) => b.root.length - a.root.length)[0]?.store;
39
+ return inside ?? stores.find(s => s.role === "primary") ?? { name: "primary", path: phrenPath, role: "primary" };
40
+ }
22
41
  export async function handleTaskNamespace(args) {
23
42
  const subcommand = args[0];
24
43
  if (!subcommand || subcommand === "--help" || subcommand === "-h") {
@@ -30,9 +49,24 @@ export async function handleTaskNamespace(args) {
30
49
  return handleTaskListArgs(args.slice(1), "default");
31
50
  }
32
51
  if (subcommand === "format") {
33
- const base = getPhrenPath();
34
- if (args.length === 1) {
35
- console.log(JSON.stringify(taskFormatStatus(base)));
52
+ const store = taskFormatStore(getPhrenPath());
53
+ const label = `${store.name} (${store.path})`;
54
+ if (args.length === 1 || (args.length === 2 && args[1] === "--json")) {
55
+ const status = taskFormatStatus(store.path);
56
+ if (args[1] === "--json") {
57
+ console.log(JSON.stringify({ ...status, store: store.name, path: store.path }));
58
+ return;
59
+ }
60
+ console.log(`Store: ${label}`);
61
+ console.log(`Task metadata: ${status.enabled ? `on${status.acknowledgedAt ? ` since ${status.acknowledgedAt.slice(0, 10)}` : ""}` : "off"}`);
62
+ console.log("");
63
+ console.log("Task metadata records who a task is for (you or an agent) and which tasks it waits on.");
64
+ if (status.enabled)
65
+ return;
66
+ console.log("It is off because an older app or tool could drop it when it rewrites a task.");
67
+ console.log(`These versions and later keep it: ${taskFormatCurrentWriters}.`);
68
+ console.log("Once every computer and phone that writes this store is current, turn it on:");
69
+ console.log(" phren task format enable --all-writers-compatible");
36
70
  return;
37
71
  }
38
72
  if (args.length !== 3 || args[1] !== "enable" || args[2] !== "--all-writers-compatible") {
@@ -40,9 +74,14 @@ export async function handleTaskNamespace(args) {
40
74
  process.exitCode = 1;
41
75
  return;
42
76
  }
77
+ if (store.role === "readonly") {
78
+ console.error(`Store ${label} is read-only on this computer. Turn task metadata on from a computer that writes it.`);
79
+ process.exitCode = 1;
80
+ return;
81
+ }
43
82
  try {
44
- enableTaskFormat(base, true);
45
- console.log("Task metadata enabled for this store. Your acknowledgement covers every CLI, MCP, Hook, sync and app writer; old binaries must no longer write this store.");
83
+ enableTaskFormat(store.path, true);
84
+ console.log(`Task metadata is on for store ${label}. Apps and tools older than ${taskFormatCurrentWriters} must no longer write it.`);
46
85
  }
47
86
  catch (error) {
48
87
  console.error(error instanceof Error ? error.message : String(error));
@@ -10,16 +10,19 @@ import { buildHookContext, handleGuardSkip, debugLog, appendAuditLog, runtimeFil
10
10
  import { TASKS_FILENAME } from "../data/tasks.js";
11
11
  import { FINDINGS_FILENAME } from "../data/access.js";
12
12
  import { readInstallPreferences } from "../init/preferences.js";
13
+ import { resolveManagementCapabilities } from "../init/management-preset.js";
14
+ import { storeAwareProjectPath } from "../store-routing.js";
13
15
  import { logger } from "../logger.js";
14
16
  import { sessionFileForId, readSessionStateFile, writeSessionStateFile, } from "../session/utils.js";
15
17
  import { runBestEffortGit, countUnsyncedCommits, pullAtSessionStart } from "./session-git.js";
16
- import { scheduleBackgroundMaintenance } from "./session-background.js";
18
+ import { scheduleBackgroundMaintenance, scheduleBackgroundSync } from "./session-background.js";
17
19
  import { runDoctor } from "./hooks-context.js";
18
20
  import { readClaudeHookPayload, registerUnmanagedClaude } from "./claude-unmanaged.js";
19
21
  const SESSION_START_ONBOARDING_MARKER = "session-start-onboarding-v1";
20
22
  const SYNC_WARN_MARKER = "sync-broken-warned-v1";
21
23
  function projectHasBootstrapSignals(phrenPath, project) {
22
- const projectDir = path.join(phrenPath, project);
24
+ // A team-store project keeps its findings and tasks in that store.
25
+ const projectDir = storeAwareProjectPath(phrenPath, project) ?? path.join(phrenPath, project);
23
26
  const findingsPath = path.join(projectDir, FINDINGS_FILENAME);
24
27
  if (fs.existsSync(findingsPath)) {
25
28
  const findings = fs.readFileSync(findingsPath, "utf8");
@@ -189,16 +192,22 @@ export async function handleHookSessionStart() {
189
192
  try {
190
193
  const { getNonPrimaryStores } = await import("../store-registry.js");
191
194
  const otherStores = getNonPrimaryStores(phrenPath);
195
+ let teamStoreAhead = false;
192
196
  for (const store of otherStores) {
193
197
  if (!fs.existsSync(store.path) || !fs.existsSync(path.join(store.path, ".git")))
194
198
  continue;
195
199
  try {
196
- await pullAtSessionStart(store.path);
200
+ const storePull = await pullAtSessionStart(store.path);
201
+ if (store.role === "team" && (storePull.counts?.ahead ?? 0) > 0)
202
+ teamStoreAhead = true;
197
203
  }
198
204
  catch (err) {
199
205
  debugLog(`session-start store-pull ${store.name}: ${errorMessage(err)}`);
200
206
  }
201
207
  }
208
+ // The pull commits local writes; the background sync pushes them.
209
+ if (teamStoreAhead && resolveManagementCapabilities(phrenPath).lifecycleAutomations)
210
+ scheduleBackgroundSync(phrenPath);
202
211
  }
203
212
  catch {
204
213
  // store-registry not available or no stores — skip silently
@@ -587,6 +587,15 @@ export async function handleBackgroundSync() {
587
587
  unsyncedCommits,
588
588
  }, failDetail);
589
589
  });
590
+ // Team stores are separate repos; without this their commits only left the
591
+ // machine when an agent called push_changes.
592
+ const { syncTeamStores } = await import("../tools/finding.js");
593
+ for (const result of await syncTeamStores(phrenPathLocal)) {
594
+ logSyncOutcome(phrenPathLocal, "team-sync", {
595
+ ok: result.pushed,
596
+ detail: result.pushed ? `pushed ${result.store}` : `${result.store}: ${result.error ?? "push failed"}`,
597
+ });
598
+ }
590
599
  }
591
600
  catch (err) {
592
601
  logSyncOutcome(phrenPathLocal, "background-sync", { ok: false, detail: errorMessage(err) });
package/dist/cli/team.js CHANGED
@@ -10,6 +10,7 @@ import { getPhrenPath } from "../shared.js";
10
10
  import { atomicWriteText } from "../phren-paths.js";
11
11
  import { FINDINGS_FILENAME } from "../data/access.js";
12
12
  import { TASKS_FILENAME } from "../data/tasks.js";
13
+ import { initializeTaskFormat } from "../data/task-format.js";
13
14
  import { isValidProjectName, getOptionValue, getPositionalArgs } from "../utils.js";
14
15
  import { addProjectToProfile, resolveActiveProfile } from "../profile-store.js";
15
16
  import { addStoreToRegistry, findStoreByName, generateStoreId, readTeamBootstrap, updateStoreProjects, } from "../store-registry.js";
@@ -61,6 +62,8 @@ async function handleTeamInit(args) {
61
62
  fs.mkdirSync(globalDir, { recursive: true });
62
63
  atomicWriteText(path.join(globalDir, "AGENTS.md"), `# ${name} Team Store\n\nShared knowledge for the ${name} team.\n`);
63
64
  atomicWriteText(path.join(globalDir, FINDINGS_FILENAME), `# global findings\n`);
65
+ // A new store has no old writers: give it an identity and start with task metadata on.
66
+ initializeTaskFormat(storePath);
64
67
  // Initialize git repo
65
68
  execFileSync("git", ["init"], {
66
69
  env: nonInteractiveGitEnv(),
@@ -132,6 +132,12 @@ export async function runInitCommand(args) {
132
132
  console.error(`Invalid --hooks value "${hooksArg}". Use "on" or "off".`);
133
133
  return 1;
134
134
  }
135
+ const clankerArg = getOptionValue(args, "--clanker");
136
+ const clankerMode = parseMcpMode(clankerArg ?? "");
137
+ if (clankerArg && !clankerMode) {
138
+ console.error(`Invalid --clanker value "${clankerArg}". Use "on" or "off".`);
139
+ return 1;
140
+ }
135
141
  const cloneUrl = getOptionValue(args, "--clone-url");
136
142
  try {
137
143
  await runInit({
@@ -140,6 +146,7 @@ export async function runInitCommand(args) {
140
146
  profile: profileIdx !== -1 ? args[profileIdx + 1] : undefined,
141
147
  mcp: mcpMode,
142
148
  hooks: hooksMode,
149
+ clanker: clankerMode,
143
150
  projectOwnershipDefault: ownershipMode,
144
151
  managementPreset,
145
152
  taskMode,
@@ -108,6 +108,7 @@ const CONFIG_SUBCOMMANDS = [
108
108
  { name: "profiles", usage: "phren config profiles", summary: "Profiles and projects" },
109
109
  { name: "telemetry", usage: "phren config telemetry [on|off]", summary: "Opt-in usage telemetry" },
110
110
  { name: "mcp-profile", usage: "phren config mcp-profile [core|full]", summary: "MCP tool surface: 10 core tools or all of them" },
111
+ { name: "clanker", usage: "phren config clanker [on|off]", summary: "Compact id/title/keyword rows from the hook and search/list tools; full text by id" },
111
112
  { name: "pull-interval", usage: "phren config pull-interval [seconds|off]", summary: "Periodic MCP remote checks (default: off; 0 disables)" },
112
113
  ];
113
114
  const MAINTAIN_SUBCOMMANDS = [
@@ -1,4 +1,6 @@
1
- export declare const taskFormatMigrationHint = "Task metadata is not enabled for this store. Upgrade every CLI, MCP, Hook, sync and app writer first; an owner can then run phren task format enable --all-writers-compatible. Existing writers must be replaced through the coordinated adoption workflow.";
1
+ /** The oldest writers that keep task metadata when they rewrite a task. */
2
+ export declare const taskFormatCurrentWriters = "Phren CLI, MCP and Hook 0.3.30, iOS build 177, Android 1.0.5";
3
+ export declare const taskFormatMigrationHint = "Task metadata is off for this store. Once every app and tool that writes it is current (Phren CLI, MCP and Hook 0.3.30, iOS build 177, Android 1.0.5 or later), an owner can turn it on with phren task format enable --all-writers-compatible.";
2
4
  /** An explicit store-owner acknowledgement, not inferred from one serving Hook.
3
5
  * It cannot fence an old binary that ignores this file: coordinated adoption of
4
6
  * every writer remains a prerequisite, and is stated at the activation boundary. */
@@ -18,3 +20,5 @@ export declare function taskWriterSafety(base: string): {
18
20
  acknowledgedAt?: string | undefined;
19
21
  };
20
22
  export declare function enableTaskFormat(base: string, allWritersCompatible: boolean): void;
23
+ /** A store phren has just created has no old writers, so metadata starts on. */
24
+ export declare function initializeTaskFormat(base: string): void;