@phren/cli 0.1.32 → 0.1.33

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 (71) hide show
  1. package/dist/capabilities/cli.js +2 -2
  2. package/dist/cli/config-access.d.ts +1 -0
  3. package/dist/cli/config-access.js +59 -0
  4. package/dist/cli/config-llm.d.ts +1 -0
  5. package/dist/cli/config-llm.js +60 -0
  6. package/dist/cli/config-policy.d.ts +11 -0
  7. package/dist/cli/config-policy.js +328 -0
  8. package/dist/cli/config-proactivity.d.ts +15 -0
  9. package/dist/cli/config-proactivity.js +129 -0
  10. package/dist/cli/config-shared.d.ts +6 -0
  11. package/dist/cli/config-shared.js +23 -0
  12. package/dist/cli/config-synonyms.d.ts +1 -0
  13. package/dist/cli/config-synonyms.js +60 -0
  14. package/dist/cli/config.d.ts +6 -24
  15. package/dist/cli/config.js +13 -670
  16. package/dist/finding-graph-id.d.ts +15 -0
  17. package/dist/finding-graph-id.js +58 -0
  18. package/dist/generated/memory-ui-graph.browser.js +15 -15
  19. package/dist/governance/activity.d.ts +36 -0
  20. package/dist/governance/activity.js +83 -0
  21. package/dist/governance/rbac.d.ts +17 -0
  22. package/dist/governance/rbac.js +37 -1
  23. package/dist/memory-ui-graph.runtime.js +15 -15
  24. package/dist/phren-paths.d.ts +6 -0
  25. package/dist/phren-paths.js +8 -0
  26. package/dist/shared/governance.d.ts +1 -0
  27. package/dist/shared/governance.js +1 -0
  28. package/dist/shared.d.ts +1 -1
  29. package/dist/shared.js +1 -1
  30. package/dist/tools/config.js +39 -2
  31. package/dist/tools/search.js +28 -1
  32. package/dist/ui/data.d.ts +2 -0
  33. package/dist/ui/data.js +8 -3
  34. package/dist/ui/graph.js +2 -0
  35. package/dist/ui/page.js +45 -2
  36. package/dist/ui/scripts.d.ts +13 -0
  37. package/dist/ui/scripts.js +229 -2
  38. package/dist/ui/server.js +165 -1
  39. package/dist/ui/styles.d.ts +1 -0
  40. package/dist/ui/styles.js +38 -0
  41. package/package.json +1 -1
  42. package/dist/cli-hooks-prompt.d.ts +0 -18
  43. package/dist/cli-hooks-prompt.js +0 -359
  44. package/dist/cli-hooks-session-handlers.d.ts +0 -3
  45. package/dist/cli-hooks-session-handlers.js +0 -356
  46. package/dist/cli-hooks-stop.d.ts +0 -11
  47. package/dist/cli-hooks-stop.js +0 -584
  48. package/dist/init-bootstrap.d.ts +0 -5
  49. package/dist/init-bootstrap.js +0 -21
  50. package/dist/init-detect.d.ts +0 -8
  51. package/dist/init-detect.js +0 -38
  52. package/dist/init-env.d.ts +0 -6
  53. package/dist/init-env.js +0 -114
  54. package/dist/init-fresh.d.ts +0 -10
  55. package/dist/init-fresh.js +0 -234
  56. package/dist/init-hooks.d.ts +0 -5
  57. package/dist/init-hooks.js +0 -26
  58. package/dist/init-mcp.d.ts +0 -8
  59. package/dist/init-mcp.js +0 -65
  60. package/dist/init-modes.d.ts +0 -4
  61. package/dist/init-modes.js +0 -135
  62. package/dist/init-npm.d.ts +0 -10
  63. package/dist/init-npm.js +0 -37
  64. package/dist/init-project-local.d.ts +0 -2
  65. package/dist/init-project-local.js +0 -99
  66. package/dist/init-semantic.d.ts +0 -4
  67. package/dist/init-semantic.js +0 -48
  68. package/dist/init-types.d.ts +0 -59
  69. package/dist/init-types.js +0 -1
  70. package/dist/init-update.d.ts +0 -10
  71. package/dist/init-update.js +0 -96
@@ -37,6 +37,12 @@ export declare function shellStateFile(phrenPath: string): string;
37
37
  export declare function sessionMetricsFile(phrenPath: string): string;
38
38
  export declare function memoryScoresFile(phrenPath: string): string;
39
39
  export declare function memoryUsageLogFile(phrenPath: string): string;
40
+ /**
41
+ * Live "lookup events" log: one JSONL entry per memory a search lands on.
42
+ * Distinct from memory-usage.log (injection scoring) — this feed powers the
43
+ * real-time activity surfaces in the web UI and the VS Code extension.
44
+ */
45
+ export declare function lookupEventsLogFile(phrenPath: string): string;
40
46
  export declare function sessionMarker(phrenPath: string, name: string): string;
41
47
  export declare function debugLog(msg: string): void;
42
48
  /** Always-on structured error log (no PHREN_DEBUG gate). */
@@ -265,6 +265,14 @@ export function memoryScoresFile(phrenPath) {
265
265
  export function memoryUsageLogFile(phrenPath) {
266
266
  return path.join(runtimeDir(phrenPath), "memory-usage.log");
267
267
  }
268
+ /**
269
+ * Live "lookup events" log: one JSONL entry per memory a search lands on.
270
+ * Distinct from memory-usage.log (injection scoring) — this feed powers the
271
+ * real-time activity surfaces in the web UI and the VS Code extension.
272
+ */
273
+ export function lookupEventsLogFile(phrenPath) {
274
+ return path.join(runtimeDir(phrenPath), "lookup-events.jsonl");
275
+ }
268
276
  export function sessionMarker(phrenPath, name) {
269
277
  const dir = sessionsDir(phrenPath);
270
278
  fs.mkdirSync(dir, { recursive: true });
@@ -1,4 +1,5 @@
1
1
  export * from '../governance/policy.js';
2
2
  export * from '../governance/scores.js';
3
3
  export * from '../governance/audit.js';
4
+ export * from '../governance/activity.js';
4
5
  export { withFileLock, isFiniteNumber, hasValidSchemaVersion } from '../governance/locks.js';
@@ -1,4 +1,5 @@
1
1
  export * from '../governance/policy.js';
2
2
  export * from '../governance/scores.js';
3
3
  export * from '../governance/audit.js';
4
+ export * from '../governance/activity.js';
4
5
  export { withFileLock, isFiniteNumber, hasValidSchemaVersion } from '../governance/locks.js';
package/dist/shared.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export type { HookToolName } from "./provider-adapters.js";
2
2
  export { HOOK_TOOL_NAMES, hookConfigPath } from "./provider-adapters.js";
3
3
  export { EXEC_TIMEOUT_MS, EXEC_TIMEOUT_QUICK_MS, PhrenError, type PhrenErrorCode, type PhrenResult, phrenOk, phrenErr, forwardErr, parsePhrenErrorCode, isRecord, withDefaults, FINDING_TYPES, type FindingType, FINDING_TAGS, type FindingTag, KNOWN_OBSERVATION_TAGS, DOC_TYPES, type DocType, capCache, RESERVED_PROJECT_DIR_NAMES, } from "./phren-core.js";
4
- export { ROOT_MANIFEST_FILENAME, type InstallMode, type SyncMode, type PhrenRootManifest, type InstallContext, isInstallMode, homeDir, homePath, expandHomePath, defaultPhrenPath, rootManifestPath, readRootManifest, writeRootManifest, resolveInstallContext, findNearestPhrenPath, isProjectLocalMode, runtimeDir, tryUnlink, sessionsDir, runtimeFile, installPreferencesFile, runtimeHealthFile, shellStateFile, sessionMetricsFile, memoryScoresFile, memoryUsageLogFile, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, findProjectNameCaseInsensitive, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, } from "./phren-paths.js";
4
+ export { ROOT_MANIFEST_FILENAME, type InstallMode, type SyncMode, type PhrenRootManifest, type InstallContext, isInstallMode, homeDir, homePath, expandHomePath, defaultPhrenPath, rootManifestPath, readRootManifest, writeRootManifest, resolveInstallContext, findNearestPhrenPath, isProjectLocalMode, runtimeDir, tryUnlink, sessionsDir, runtimeFile, installPreferencesFile, runtimeHealthFile, shellStateFile, sessionMetricsFile, memoryScoresFile, memoryUsageLogFile, lookupEventsLogFile, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, findProjectNameCaseInsensitive, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, } from "./phren-paths.js";
5
5
  export { PROACTIVITY_LEVELS, type ProactivityLevel, parseProactivityLevel, getProactivityLevel, getProactivityLevelForFindings, getProactivityLevelForTask, hasExplicitFindingSignal, hasExplicitTaskSignal, hasExecutionIntent, hasDiscoveryIntent, shouldAutoCaptureFindingsForLevel, shouldAutoCaptureTaskForLevel, } from "./proactivity.js";
6
6
  export declare function normalizeMemoryScope(scope?: string | null): string | undefined;
7
7
  export declare function isMemoryScopeVisible(itemScope: string | undefined, activeScope?: string): boolean;
package/dist/shared.js CHANGED
@@ -6,7 +6,7 @@ import { withFileLock } from "./governance/locks.js";
6
6
  const MAX_LOG_LINES = 1000;
7
7
  export { HOOK_TOOL_NAMES, hookConfigPath } from "./provider-adapters.js";
8
8
  export { EXEC_TIMEOUT_MS, EXEC_TIMEOUT_QUICK_MS, PhrenError, phrenOk, phrenErr, forwardErr, parsePhrenErrorCode, isRecord, withDefaults, FINDING_TYPES, FINDING_TAGS, KNOWN_OBSERVATION_TAGS, DOC_TYPES, capCache, RESERVED_PROJECT_DIR_NAMES, } from "./phren-core.js";
9
- export { ROOT_MANIFEST_FILENAME, isInstallMode, homeDir, homePath, expandHomePath, defaultPhrenPath, rootManifestPath, readRootManifest, writeRootManifest, resolveInstallContext, findNearestPhrenPath, isProjectLocalMode, runtimeDir, tryUnlink, sessionsDir, runtimeFile, installPreferencesFile, runtimeHealthFile, shellStateFile, sessionMetricsFile, memoryScoresFile, memoryUsageLogFile, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, findProjectNameCaseInsensitive, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, } from "./phren-paths.js";
9
+ export { ROOT_MANIFEST_FILENAME, isInstallMode, homeDir, homePath, expandHomePath, defaultPhrenPath, rootManifestPath, readRootManifest, writeRootManifest, resolveInstallContext, findNearestPhrenPath, isProjectLocalMode, runtimeDir, tryUnlink, sessionsDir, runtimeFile, installPreferencesFile, runtimeHealthFile, shellStateFile, sessionMetricsFile, memoryScoresFile, memoryUsageLogFile, lookupEventsLogFile, sessionMarker, debugLog, appendIndexEvent, resolveFindingsPath, findPhrenPath, ensurePhrenPath, findPhrenPathWithArg, normalizeProjectNameForCreate, findProjectNameCaseInsensitive, findArchivedProjectNameCaseInsensitive, getProjectDirs, listInvalidProjectDirs, collectNativeMemoryFiles, computePhrenLiveStateToken, getPhrenPath, qualityMarkers, atomicWriteText, } from "./phren-paths.js";
10
10
  export { PROACTIVITY_LEVELS, parseProactivityLevel, getProactivityLevel, getProactivityLevelForFindings, getProactivityLevelForTask, hasExplicitFindingSignal, hasExplicitTaskSignal, hasExecutionIntent, hasDiscoveryIntent, shouldAutoCaptureFindingsForLevel, shouldAutoCaptureTaskForLevel, } from "./proactivity.js";
11
11
  const MEMORY_SCOPE_PATTERN = /^[a-z][a-z0-9_-]{0,63}$/;
12
12
  export function normalizeMemoryScope(scope) {
@@ -8,6 +8,7 @@ import { writeGovernanceInstallPreferences, } from "../init/preferences.js";
8
8
  import { FINDING_SENSITIVITY_CONFIG, buildProactivitySnapshot, checkProjectInProfile } from "../cli/config.js";
9
9
  import { readProjectConfig, updateProjectConfigOverrides, } from "../project-config.js";
10
10
  import { isValidProjectName, safeProjectPath } from "../utils.js";
11
+ import { ACCESS_ROLE_KEYS, setAccessRoles } from "../governance/rbac.js";
11
12
  import { readProjectTopics, writeProjectTopics, } from "../project-topics.js";
12
13
  import { buildConfigView } from "../config/resolve.js";
13
14
  import { getConfigField, CONFIG_DOMAINS } from "../config/schema.js";
@@ -451,6 +452,41 @@ async function handleSetConfig(ctx, { domain, settings, project }) {
451
452
  data: result.data,
452
453
  });
453
454
  }
455
+ // ── access ────────────────────────────────────────────────────
456
+ case "access": {
457
+ const patch = {};
458
+ let touched = false;
459
+ for (const key of ACCESS_ROLE_KEYS) {
460
+ const value = settings[key];
461
+ if (value === undefined)
462
+ continue;
463
+ if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
464
+ return mcpResponse({ ok: false, error: `Invalid access roles: "${key}" must be an array of strings.` });
465
+ }
466
+ patch[key] = value;
467
+ touched = true;
468
+ }
469
+ if (!touched) {
470
+ return mcpResponse({ ok: false, error: "Provide at least one of: admins, contributors, readers (each an array of actor names)." });
471
+ }
472
+ let warning;
473
+ if (project) {
474
+ const err = validateProject(project);
475
+ if (err)
476
+ return mcpResponse({ ok: false, error: err });
477
+ warning = checkProjectRegistered(phrenPath, project) ?? undefined;
478
+ }
479
+ const written = setAccessRoles(phrenPath, patch, project);
480
+ return mcpResponse({
481
+ ok: true,
482
+ message: project
483
+ ? (warning
484
+ ? `Access roles updated for project "${project}". WARNING: ${warning}`
485
+ : `Access roles updated for project "${project}".`)
486
+ : "Access roles updated.",
487
+ data: { ...(project ? { project } : {}), ...written, ...(warning ? { warning } : {}) },
488
+ });
489
+ }
454
490
  // ── index ─────────────────────────────────────────────────────
455
491
  case "index": {
456
492
  const { includeGlobs, excludeGlobs, includeHidden } = settings;
@@ -560,11 +596,12 @@ export function register(server, ctx) {
560
596
  "and set_topic_config. When project is provided, writes to that project's phren.project.yaml " +
561
597
  "instead of global .config/.",
562
598
  inputSchema: z.object({
563
- domain: z.enum(["proactivity", "taskMode", "findingSensitivity", "retention", "workflow", "index", "topic"]),
599
+ domain: z.enum(["proactivity", "taskMode", "findingSensitivity", "retention", "workflow", "access", "index", "topic"]),
564
600
  settings: z.record(z.string(), z.unknown()).describe("Domain-specific settings. proactivity: { level, scope? } | taskMode: { mode } | " +
565
601
  "findingSensitivity: { level } | retention: { ttlDays?, retentionDays?, autoAcceptThreshold?, " +
566
602
  "minInjectConfidence?, decay? } | workflow: { lowConfidenceThreshold?, riskySections?, taskMode?, " +
567
- "findingSensitivity? } | index: { includeGlobs?, excludeGlobs?, includeHidden? } | " +
603
+ "findingSensitivity? } | access: { admins?, contributors?, readers? } (each an array of actor names) | " +
604
+ "index: { includeGlobs?, excludeGlobs?, includeHidden? } | " +
568
605
  "topic: { topics, domain? }"),
569
606
  project: z.string().optional().describe("Project name. When provided, writes to that project's phren.project.yaml instead of global .config/. " +
570
607
  "Required for the 'topic' domain."),
@@ -11,7 +11,8 @@ import { debugLog, runtimeFile, DOC_TYPES, FINDING_TAGS, isMemoryScopeVisible, n
11
11
  import { FINDING_LIFECYCLE_STATUSES, parseFindingLifecycle, } from "../shared/content.js";
12
12
  import { decodeStringRow, queryRows, queryDocRows, queryFragmentLinks, logFragmentMiss, extractSnippet, queryDocBySourceKey, normalizeMemoryId, } from "../shared/index.js";
13
13
  import { runCustomHooks } from "../hooks.js";
14
- import { entryScoreKey, getQualityMultiplier, getRetentionPolicy } from "../shared/governance.js";
14
+ import { entryScoreKey, getQualityMultiplier, getRetentionPolicy, recordLookupEvents } from "../shared/governance.js";
15
+ import { bestFindingNodeId } from "../finding-graph-id.js";
15
16
  import { callLlm } from "../content/dedup.js";
16
17
  import { rankResults, searchKnowledgeRows, applyTrustFilter, searchFederatedStores } from "../shared/retrieval.js";
17
18
  import { formatActorAttribution, parseScopeComment, parseSourceComment } from "../content/citation.js";
@@ -378,6 +379,32 @@ async function handleSearchKnowledge(ctx, { query, limit, project, type, tag, si
378
379
  ...(federationSource ? { federation_source: federationSource } : {}),
379
380
  };
380
381
  });
382
+ // Live activity: record each memory this search landed on so the web UI and
383
+ // VS Code extension can surface lookups in real time. Best-effort only.
384
+ try {
385
+ const at = new Date().toISOString();
386
+ recordLookupEvents(phrenPath, results.map((r, i) => {
387
+ // For findings, resolve the specific finding node so phren can walk
388
+ // to it on the graph; otherwise the project node is used downstream.
389
+ const nodeId = r.type === "findings"
390
+ ? bestFindingNodeId(r.project, rows[i]?.content ?? "", query)
391
+ : null;
392
+ return {
393
+ at,
394
+ query,
395
+ project: r.project,
396
+ filename: r.filename,
397
+ type: r.type,
398
+ path: r.path,
399
+ snippet: r.snippet,
400
+ source: "search",
401
+ ...(nodeId ? { nodeId } : {}),
402
+ };
403
+ }));
404
+ }
405
+ catch (err) {
406
+ debugLog(`search_knowledge lookup-events: ${errorMessage(err)}`);
407
+ }
381
408
  let relatedFragments = [];
382
409
  try {
383
410
  const terms = query.toLowerCase().split(/\s+/).filter(t => t.length > 2);
package/dist/ui/data.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { SqlJsDatabase } from "../shared/index.js";
2
+ import { type LookupEvent } from "../governance/activity.js";
2
3
  interface EntryScore {
3
4
  impressions: number;
4
5
  helpful: number;
@@ -108,6 +109,7 @@ export declare function buildGraph(phrenPath: string, profile?: string, focusPro
108
109
  topics: GraphTopicMeta[];
109
110
  }>;
110
111
  export declare function recentUsage(phrenPath: string): string[];
112
+ export declare function recentLookups(phrenPath: string, limit?: number): LookupEvent[];
111
113
  export declare function recentAccepted(phrenPath: string): string[];
112
114
  export declare function collectProjectsForUI(phrenPath: string, profile?: string): ProjectInfo[];
113
115
  export {};
package/dist/ui/data.js CHANGED
@@ -14,6 +14,8 @@ import { FINDINGS_FILENAME } from "../data/access.js";
14
14
  import { buildIndex, queryDocBySourceKey, queryRows } from "../shared/index.js";
15
15
  import { readProjectTopics, classifyTopicForText } from "../project-topics.js";
16
16
  import { entryScoreKey } from "../governance/scores.js";
17
+ import { findingStableId } from "../finding-graph-id.js";
18
+ import { readRecentLookups } from "../governance/activity.js";
17
19
  import { logger } from "../logger.js";
18
20
  function extractGithubUrl(content) {
19
21
  const match = content.match(/https?:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+/);
@@ -262,7 +264,7 @@ export async function buildGraph(phrenPath, profile, focusProject, existingDb) {
262
264
  continue;
263
265
  const topic = classifyTopicForText(`[${currentHeadingTag}] ${text}`, projectTopics);
264
266
  const scoreKey = entryScoreKey(project, FINDINGS_FILENAME, `[${currentHeadingTag}] ${text}`);
265
- const nodeId = stableId("finding", scoreKey);
267
+ const nodeId = findingStableId(scoreKey);
266
268
  taggedCount++;
267
269
  nodes.push({
268
270
  id: nodeId,
@@ -297,7 +299,7 @@ export async function buildGraph(phrenPath, profile, focusProject, existingDb) {
297
299
  // Classify the finding using the project's topic system
298
300
  const topic = classifyTopicForText(`[${tag}] ${text}`, projectTopics);
299
301
  const scoreKey = entryScoreKey(project, FINDINGS_FILENAME, `[${tag}] ${text}`);
300
- const nodeId = stableId("finding", scoreKey);
302
+ const nodeId = findingStableId(scoreKey);
301
303
  taggedCount++;
302
304
  nodes.push({
303
305
  id: nodeId,
@@ -332,7 +334,7 @@ export async function buildGraph(phrenPath, profile, focusProject, existingDb) {
332
334
  // Classify using dynamic topics
333
335
  const topic = classifyTopicForText(text, projectTopics);
334
336
  const scoreKey = entryScoreKey(project, FINDINGS_FILENAME, text);
335
- const nodeId = stableId("finding", scoreKey);
337
+ const nodeId = findingStableId(scoreKey);
336
338
  untaggedAdded++;
337
339
  nodes.push({
338
340
  id: nodeId,
@@ -558,6 +560,9 @@ export function recentUsage(phrenPath) {
558
560
  const lines = fs.readFileSync(usage, "utf8").trim().split("\n").filter(Boolean);
559
561
  return lines.slice(-40).reverse();
560
562
  }
563
+ export function recentLookups(phrenPath, limit = 40) {
564
+ return readRecentLookups(phrenPath, limit);
565
+ }
561
566
  export function recentAccepted(phrenPath) {
562
567
  const audit = path.join(runtimeDir(phrenPath), "audit.log");
563
568
  if (!fs.existsSync(audit))
package/dist/ui/graph.js CHANGED
@@ -34,6 +34,8 @@ export function renderGraphScript() {
34
34
  onSelectionClear: function() {},
35
35
  clearSelection: function() {},
36
36
  selectNode: function() { return false; },
37
+ focusNode: function() { return false; },
38
+ walkTo: function() { return false; },
37
39
  getNodeAt: function() { return null; },
38
40
  getNodeDetail: function() { return null; },
39
41
  destroy: function() {}
package/dist/ui/page.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { WEB_UI_STYLES, renderWebUiScript } from "./assets.js";
2
2
  import { renderGraphScript } from "./graph.js";
3
- import { PROJECT_REFERENCE_UI_STYLES, REVIEW_UI_STYLES, SETTINGS_TAB_UI_STYLES, TASK_UI_STYLES } from "./styles.js";
3
+ import { LAYOUT_VIEWPORT_STYLES, PROJECT_REFERENCE_UI_STYLES, REVIEW_UI_STYLES, SETTINGS_TAB_UI_STYLES, TASK_UI_STYLES } from "./styles.js";
4
4
  import { PHREN_DEEP_VOID_STYLES } from "./deep-void.js";
5
- import { renderSharedWebUiHelpers, renderSkillUiEnhancementScript, renderProfileSwitcherScript, renderProjectReferenceEnhancementScript, renderTasksAndSettingsScript, renderReviewQueueKeyboardScript, renderSearchScript, renderEventWiringScript, renderGraphHostScript, } from "./scripts.js";
5
+ import { renderSharedWebUiHelpers, renderSkillUiEnhancementScript, renderProfileSwitcherScript, renderProjectReferenceEnhancementScript, renderTasksAndSettingsScript, renderReviewQueueKeyboardScript, renderSearchScript, renderEventWiringScript, renderGraphHostScript, renderActivityStreamScript, renderGraphWalkScript, } from "./scripts.js";
6
6
  function h(s) {
7
7
  return s
8
8
  .replace(/&/g, "&")
@@ -27,6 +27,7 @@ ${SETTINGS_TAB_UI_STYLES}
27
27
  ${TASK_UI_STYLES}
28
28
  ${REVIEW_UI_STYLES}
29
29
  ${PHREN_DEEP_VOID_STYLES}
30
+ ${LAYOUT_VIEWPORT_STYLES}
30
31
  </style>
31
32
  </head>
32
33
  <body>
@@ -106,6 +107,7 @@ ${PHREN_DEEP_VOID_STYLES}
106
107
  <nav class="nav">
107
108
  <button class="nav-item active" data-tab="projects">Projects</button>
108
109
  <button class="nav-item" data-tab="review">Review</button>
110
+ <button class="nav-item" data-tab="activity">Activity</button>
109
111
  <button class="nav-item" data-tab="search">Search</button>
110
112
  <button class="nav-item" data-tab="graph">Graph</button>
111
113
  <button class="nav-item" data-tab="tasks">Tasks</button>
@@ -171,6 +173,35 @@ ${PHREN_DEEP_VOID_STYLES}
171
173
  </div>
172
174
  </div>
173
175
 
176
+ <!-- ── Activity Tab ──────────────────────────────────────── -->
177
+ <div id="tab-activity" class="tab-content">
178
+ <style>
179
+ .activity-led{display:inline-block;width:10px;height:10px;border-radius:50%;background:var(--muted);flex:0 0 auto}
180
+ .activity-led-ok{background:var(--success);box-shadow:0 0 0 0 var(--success-dim);animation:activity-pulse 2s infinite}
181
+ .activity-led-warn{background:var(--warning)}
182
+ .activity-led-err{background:var(--danger)}
183
+ @keyframes activity-pulse{0%{box-shadow:0 0 0 0 var(--success-glow,rgba(16,185,129,.35))}70%{box-shadow:0 0 0 7px rgba(16,185,129,0)}100%{box-shadow:0 0 0 0 rgba(16,185,129,0)}}
184
+ .activity-feed{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:8px}
185
+ .activity-item{border:1px solid var(--border);border-radius:var(--radius-sm);padding:10px 12px;background:var(--surface);transition:background .6s ease,border-color .6s ease}
186
+ .activity-item-new{background:var(--accent-dim);border-color:var(--accent)}
187
+ .activity-row{display:flex;align-items:center;gap:8px}
188
+ .activity-type{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.04em;color:var(--accent);border:1px solid var(--border);border-radius:999px;padding:1px 8px;flex:0 0 auto}
189
+ .activity-loc{font-family:var(--mono);font-size:var(--text-sm);color:var(--ink);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
190
+ .activity-time{margin-left:auto;font-size:var(--text-xs);color:var(--muted);flex:0 0 auto}
191
+ .activity-query{font-size:var(--text-sm);color:var(--ink-secondary);margin-top:4px}
192
+ .activity-snippet{font-size:var(--text-sm);color:var(--muted);margin-top:4px;overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
193
+ </style>
194
+ <div style="max-width:860px;margin:0 auto">
195
+ <div style="display:flex;align-items:center;gap:10px;margin-bottom:6px">
196
+ <span id="activity-led" class="activity-led" title="Live status"></span>
197
+ <h2 style="font-size:var(--text-lg);font-weight:600;margin:0">Live Lookups</h2>
198
+ <span id="activity-status" class="text-muted" style="font-size:var(--text-sm);margin-left:auto">Connecting…</span>
199
+ </div>
200
+ <p class="text-muted" style="font-size:var(--text-sm);margin:0 0 16px 0">Memories phren lands on as it searches, streamed in real time.</p>
201
+ <ul id="activity-feed" class="activity-feed"><li style="color:var(--muted);list-style:none">Waiting for lookups…</li></ul>
202
+ </div>
203
+ </div>
204
+
174
205
  <!-- ── Search Tab ────────────────────────────────────────── -->
175
206
  <div id="tab-search" class="tab-content">
176
207
  <div style="max-width:720px;margin:0 auto">
@@ -321,6 +352,12 @@ ${PHREN_DEEP_VOID_STYLES}
321
352
  <div id="settings-workflow" style="color:var(--muted)">Loading...</div>
322
353
  </div>
323
354
  </section>
355
+ <section class="settings-section" style="border-top:3px solid color-mix(in srgb, var(--danger, var(--warning)) 45%, var(--border))">
356
+ <div class="settings-section-header">Access Control</div>
357
+ <div class="settings-section-body">
358
+ <div id="settings-access" style="color:var(--muted)">Loading...</div>
359
+ </div>
360
+ </section>
324
361
  <section class="settings-section" style="border-top:3px solid color-mix(in srgb, var(--cyan) 45%, var(--border))">
325
362
  <div class="settings-section-header">Index Policy</div>
326
363
  <div class="settings-section-body">
@@ -380,6 +417,12 @@ ${renderTasksAndSettingsScript(authToken || "")}
380
417
  ${renderReviewQueueKeyboardScript(authToken || "")}
381
418
  </script>
382
419
  <script${nonceAttr}>
420
+ ${renderActivityStreamScript(authToken || "")}
421
+ </script>
422
+ <script${nonceAttr}>
423
+ ${renderGraphWalkScript()}
424
+ </script>
425
+ <script${nonceAttr}>
383
426
  ${renderSearchScript(authToken || "")}
384
427
  </script>
385
428
  <script${nonceAttr}>
@@ -15,3 +15,16 @@ export declare function renderSearchScript(authToken: string): string;
15
15
  export declare function renderEventWiringScript(): string;
16
16
  export declare function renderGraphHostScript(): string;
17
17
  export declare function renderReviewQueueKeyboardScript(_authToken: string): string;
18
+ /**
19
+ * Live "Activity" tab: streams memory lookups from /api/lookups/stream (SSE)
20
+ * and prepends them to #activity-feed in real time, so you can watch phren land
21
+ * on memories as it searches. Falls back gracefully if EventSource is missing.
22
+ */
23
+ export declare function renderActivityStreamScript(_authToken: string): string;
24
+ /**
25
+ * Drives the graph mascot from the live lookup feed: each 'phren:lookup' event
26
+ * (dispatched by the activity stream) maps to a graph node and sends phren
27
+ * walking to it, so you can watch phren traverse the knowledge graph in real
28
+ * time. No-ops gracefully until the graph is mounted (Graph tab opened).
29
+ */
30
+ export declare function renderGraphWalkScript(): string;
@@ -956,6 +956,30 @@ export function renderTasksAndSettingsScript(authToken) {
956
956
  });
957
957
  }
958
958
 
959
+ function postAccess(role, value) {
960
+ var proj = getSettingsProject();
961
+ var csrfUrl = _tsAuthToken ? tsAuthUrl('/api/csrf-token') : '/api/csrf-token';
962
+ fetch(csrfUrl).then(function(r) { return r.json(); }).then(function(csrfData) {
963
+ var payload = {};
964
+ payload[role] = value || '';
965
+ if (proj) payload.project = proj;
966
+ var body = new URLSearchParams(payload);
967
+ if (csrfData.token) body.set('_csrf', csrfData.token);
968
+ var url = _tsAuthToken ? tsAuthUrl('/api/settings/access') : '/api/settings/access';
969
+ return fetch(url, { method: 'POST', body: body, headers: { 'content-type': 'application/x-www-form-urlencoded' } });
970
+ }).then(function(r) { return r.json(); }).then(function(data) {
971
+ if (!data.ok) {
972
+ setSettingsStatus(data.error || 'Failed to update access roles', 'err');
973
+ return;
974
+ }
975
+ _settingsLoaded = false;
976
+ loadSettings();
977
+ setSettingsStatus('Access roles updated', 'ok');
978
+ }).catch(function(err) {
979
+ setSettingsStatus('Failed: ' + String(err), 'err');
980
+ });
981
+ }
982
+
959
983
  function postGlobalWorkflow(field, value, clearField) {
960
984
  var csrfUrl = _tsAuthToken ? tsAuthUrl('/api/csrf-token') : '/api/csrf-token';
961
985
  fetch(csrfUrl).then(function(r) { return r.json(); }).then(function(csrfData) {
@@ -1167,6 +1191,11 @@ export function renderTasksAndSettingsScript(authToken) {
1167
1191
  retRow('Retention days', 'retentionDays', ret.retentionDays, 'Hard cutoff — memories past this age are removed.');
1168
1192
  retRow('Auto-accept threshold', 'autoAcceptThreshold', ret.autoAcceptThreshold, 'Confidence score (0–1) above which memories are auto-accepted.');
1169
1193
  retRow('Min inject confidence', 'minInjectConfidence', ret.minInjectConfidence, 'Minimum confidence score to inject a memory into context.');
1194
+ var decay = ret.decay || {};
1195
+ retRow('Decay @30d', 'decay.d30', decay.d30, 'Confidence multiplier (0–1) applied to memories ~30 days old.');
1196
+ retRow('Decay @60d', 'decay.d60', decay.d60, 'Confidence multiplier (0–1) applied to memories ~60 days old.');
1197
+ retRow('Decay @90d', 'decay.d90', decay.d90, 'Confidence multiplier (0–1) applied to memories ~90 days old.');
1198
+ retRow('Decay @120d', 'decay.d120', decay.d120, 'Confidence multiplier (0–1) applied to memories ~120 days old.');
1170
1199
  retentionEl.innerHTML = retHtml;
1171
1200
  }
1172
1201
 
@@ -1190,8 +1219,14 @@ export function renderTasksAndSettingsScript(authToken) {
1190
1219
  wfHtml += '<div class="settings-control-note">Memories below this confidence score are flagged for review.</div></div>';
1191
1220
  wfHtml += '<div class="settings-control">';
1192
1221
  wfHtml += '<div class="settings-control-header"><span class="settings-control-label">Risky sections</span>' + sourceBadge(riskySectionsOverride);
1193
- wfHtml += '<span class="settings-control-value" style="margin-left:auto">' + esc(Array.isArray(wf.riskySections) ? wf.riskySections.join(', ') : '—') + '</span></div>';
1194
- wfHtml += '<div class="settings-control-note">Sections that trigger approval gates when memories are written.</div></div>';
1222
+ if (isProject && riskySectionsOverride) {
1223
+ wfHtml += '<button data-ts-action="clearProjectOverride" data-field="riskySections" class="settings-chip" style="font-size:11px;margin-left:auto">Clear</button>';
1224
+ }
1225
+ wfHtml += '</div><div style="display:flex;gap:8px;align-items:center;margin-top:8px">' +
1226
+ '<input type="text" id="wf-input-riskySections" value="' + esc(Array.isArray(wf.riskySections) ? wf.riskySections.join(', ') : '') + '" placeholder="Review, Stale, Conflicts" style="flex:1;min-width:0;border:1px solid var(--border);border-radius:var(--radius-sm);padding:4px 8px;font-size:var(--text-sm);background:var(--surface);color:var(--ink)">' +
1227
+ '<button data-ts-action="' + (isProject ? 'setProjectWorkflow' : 'setGlobalWorkflow') + '" data-field="riskySections" class="settings-chip active" style="font-size:11px">Set</button>' +
1228
+ '</div>';
1229
+ wfHtml += '<div class="settings-control-note">Comma-separated sections that trigger approval gates when memories are written (Review, Stale, Conflicts).</div></div>';
1195
1230
  workflowEl.innerHTML = wfHtml;
1196
1231
  }
1197
1232
 
@@ -1219,6 +1254,35 @@ export function renderTasksAndSettingsScript(authToken) {
1219
1254
  indexEl.innerHTML = '<div style="color:var(--muted);font-size:var(--text-sm)">Index policy is global — switch to Global scope to edit it.</div>';
1220
1255
  }
1221
1256
 
1257
+ var accessEl = document.getElementById('settings-access');
1258
+ if (accessEl) {
1259
+ var accFields = (data.view && data.view.fields) ? data.view.fields : {};
1260
+ function accVal(role) {
1261
+ if (isProject) {
1262
+ return (rawOverrides && rawOverrides.access && Array.isArray(rawOverrides.access[role])) ? rawOverrides.access[role].join(', ') : '';
1263
+ }
1264
+ var f = accFields['access.' + role];
1265
+ return (f && Array.isArray(f.value)) ? f.value.join(', ') : '';
1266
+ }
1267
+ var accHtml = '';
1268
+ function accRow(label, role, note) {
1269
+ accHtml += '<div class="settings-control">';
1270
+ accHtml += '<div class="settings-control-header"><span class="settings-control-label">' + esc(label) + '</span></div>';
1271
+ accHtml += '<div class="settings-control-note">' + esc(note) + '</div>';
1272
+ accHtml += '<div style="display:flex;gap:8px;align-items:center;margin-top:8px">' +
1273
+ '<input type="text" id="access-input-' + esc(role) + '" value="' + esc(accVal(role)) + '" placeholder="comma,separated actors" style="flex:1;min-width:0;border:1px solid var(--border);border-radius:var(--radius-sm);padding:4px 8px;font-size:var(--text-sm);background:var(--surface);color:var(--ink)">' +
1274
+ '<button data-ts-action="setAccessRole" data-role="' + esc(role) + '" class="settings-chip active" style="font-size:11px">Set</button>' +
1275
+ '</div></div>';
1276
+ }
1277
+ accRow('Admins', 'admins', 'Full access — all actions, including config changes.');
1278
+ accRow('Contributors', 'contributors', 'Can add, edit, and remove findings and tasks.');
1279
+ accRow('Readers', 'readers', 'Read-only access (search and get).');
1280
+ accHtml += '<div class="settings-control-note">' + (isProject
1281
+ ? 'Editing the per-project access list for this project. Effective roles are the union of global and project lists.'
1282
+ : 'Editing the global access list. Effective roles are the union of global and per-project lists.') + ' All lists empty everywhere = open mode (everyone allowed).</div>';
1283
+ accessEl.innerHTML = accHtml;
1284
+ }
1285
+
1222
1286
  var integrationsEl = document.getElementById('settings-integrations');
1223
1287
  if (integrationsEl && !isProject) {
1224
1288
  var tools = Array.isArray(data.hookTools) ? data.hookTools : [];
@@ -1418,6 +1482,11 @@ export function renderTasksAndSettingsScript(authToken) {
1418
1482
  var nextHidden = actionEl.getAttribute('data-enabled') !== 'true';
1419
1483
  postSettings('/api/settings/index-policy', { includeHidden: String(nextHidden) }, 'Index policy updated.');
1420
1484
  }
1485
+ else if (action === 'setAccessRole') {
1486
+ var role = actionEl.getAttribute('data-role') || '';
1487
+ var inputEl = document.getElementById('access-input-' + role);
1488
+ postAccess(role, inputEl ? inputEl.value : '');
1489
+ }
1421
1490
  });
1422
1491
 
1423
1492
  // Keydown delegation for add-task inputs (Enter key)
@@ -2329,3 +2398,161 @@ export function renderReviewQueueKeyboardScript(_authToken) {
2329
2398
  });
2330
2399
  })();`;
2331
2400
  }
2401
+ /**
2402
+ * Live "Activity" tab: streams memory lookups from /api/lookups/stream (SSE)
2403
+ * and prepends them to #activity-feed in real time, so you can watch phren land
2404
+ * on memories as it searches. Falls back gracefully if EventSource is missing.
2405
+ */
2406
+ export function renderActivityStreamScript(_authToken) {
2407
+ return `(function() {
2408
+ var esc = window._phrenEsc;
2409
+ var authUrl = window._phrenAuthUrl;
2410
+ var MAX_ITEMS = 80;
2411
+ var feed = null, statusEl = null, ledEl = null;
2412
+ var emptyShown = true;
2413
+
2414
+ function el() {
2415
+ feed = document.getElementById('activity-feed');
2416
+ statusEl = document.getElementById('activity-status');
2417
+ ledEl = document.getElementById('activity-led');
2418
+ return !!feed;
2419
+ }
2420
+
2421
+ function relTime(iso) {
2422
+ var t = Date.parse(iso);
2423
+ if (isNaN(t)) return '';
2424
+ var s = Math.max(0, Math.round((Date.now() - t) / 1000));
2425
+ if (s < 5) return 'just now';
2426
+ if (s < 60) return s + 's ago';
2427
+ var m = Math.round(s / 60);
2428
+ if (m < 60) return m + 'm ago';
2429
+ var h = Math.round(m / 60);
2430
+ if (h < 24) return h + 'h ago';
2431
+ return Math.round(h / 24) + 'd ago';
2432
+ }
2433
+
2434
+ function setStatus(text, state) {
2435
+ if (statusEl) statusEl.textContent = text;
2436
+ if (ledEl) ledEl.className = 'activity-led' + (state ? ' activity-led-' + state : '');
2437
+ }
2438
+
2439
+ function renderItem(ev, isNew) {
2440
+ if (!feed) return;
2441
+ if (emptyShown) { feed.innerHTML = ''; emptyShown = false; }
2442
+ var li = document.createElement('li');
2443
+ li.className = 'activity-item' + (isNew ? ' activity-item-new' : '');
2444
+ var loc = esc((ev.project || '?') + '/' + (ev.filename || '?'));
2445
+ var type = esc(ev.type || '');
2446
+ var q = ev.query ? esc(ev.query) : '';
2447
+ var snip = ev.snippet ? esc(ev.snippet) : '';
2448
+ li.innerHTML =
2449
+ '<div class="activity-row">' +
2450
+ '<span class="activity-type activity-type-' + type + '">' + type + '</span>' +
2451
+ '<span class="activity-loc">' + loc + '</span>' +
2452
+ '<span class="activity-time">' + esc(relTime(ev.at)) + '</span>' +
2453
+ '</div>' +
2454
+ (q ? '<div class="activity-query">found via &ldquo;' + q + '&rdquo;</div>' : '') +
2455
+ (snip ? '<div class="activity-snippet">' + snip + '</div>' : '');
2456
+ feed.insertBefore(li, feed.firstChild);
2457
+ while (feed.children.length > MAX_ITEMS) feed.removeChild(feed.lastChild);
2458
+ if (isNew) {
2459
+ setTimeout(function() { li.classList.remove('activity-item-new'); }, 1500);
2460
+ }
2461
+ }
2462
+
2463
+ function loadInitial() {
2464
+ fetch(authUrl('/api/lookups')).then(function(r) { return r.json(); }).then(function(d) {
2465
+ var items = (d && d.lookups) || [];
2466
+ // Leave the feed placeholder and let the SSE connection drive the status
2467
+ // (avoids clobbering 'Live' when the snapshot is empty).
2468
+ if (!items.length) return;
2469
+ // API returns newest-first; render oldest-first so newest ends up on top.
2470
+ for (var i = items.length - 1; i >= 0; i--) renderItem(items[i], false);
2471
+ }).catch(function() { /* stream may still deliver */ });
2472
+ }
2473
+
2474
+ function connect() {
2475
+ if (typeof EventSource === 'undefined') {
2476
+ setStatus('Live updates unsupported — reload to refresh', 'err');
2477
+ return;
2478
+ }
2479
+ var src = new EventSource(authUrl('/api/lookups/stream'));
2480
+ src.onopen = function() { setStatus('Live', 'ok'); };
2481
+ src.onmessage = function(e) {
2482
+ try {
2483
+ var ev = JSON.parse(e.data);
2484
+ renderItem(ev, true);
2485
+ // Broadcast so other surfaces (e.g. the graph walk) can react without
2486
+ // opening a second SSE connection.
2487
+ try { window.dispatchEvent(new CustomEvent('phren:lookup', { detail: ev })); } catch (err2) {}
2488
+ } catch (err) {}
2489
+ setStatus('Live', 'ok');
2490
+ };
2491
+ src.onerror = function() {
2492
+ setStatus('Reconnecting…', 'warn');
2493
+ // EventSource auto-reconnects using the server's retry hint.
2494
+ };
2495
+ }
2496
+
2497
+ function init() {
2498
+ if (!el()) return;
2499
+ setStatus('Connecting…', 'warn');
2500
+ loadInitial();
2501
+ connect();
2502
+ }
2503
+
2504
+ if (document.readyState === 'loading') {
2505
+ document.addEventListener('DOMContentLoaded', init);
2506
+ } else {
2507
+ init();
2508
+ }
2509
+ })();`;
2510
+ }
2511
+ /**
2512
+ * Drives the graph mascot from the live lookup feed: each 'phren:lookup' event
2513
+ * (dispatched by the activity stream) maps to a graph node and sends phren
2514
+ * walking to it, so you can watch phren traverse the knowledge graph in real
2515
+ * time. No-ops gracefully until the graph is mounted (Graph tab opened).
2516
+ */
2517
+ export function renderGraphWalkScript() {
2518
+ return `(function() {
2519
+ function api() { return window.phrenGraph; }
2520
+
2521
+ function nodeIdForLookup(ev) {
2522
+ var g = api();
2523
+ if (!g || typeof g.getNodeDetail !== 'function' || typeof g.getData !== 'function') return null;
2524
+ if (!ev || !ev.project) return null;
2525
+
2526
+ // Precomputed node id (e.g. a specific finding) wins when it resolves.
2527
+ if (ev.nodeId && g.getNodeDetail(ev.nodeId)) return ev.nodeId;
2528
+
2529
+ // Reference lookups: prefer the specific reference node when present.
2530
+ if (ev.type === 'reference' && ev.filename) {
2531
+ var base = String(ev.filename).split('/').pop() || ev.filename;
2532
+ var candidates = [ev.project + ':ref:' + ev.filename, ev.project + ':ref:' + base];
2533
+ for (var i = 0; i < candidates.length; i++) {
2534
+ if (g.getNodeDetail(candidates[i])) return candidates[i];
2535
+ }
2536
+ var stem = base.replace(/\\.md$/, '');
2537
+ var refMatch = (g.getData().nodes || []).find(function(n) {
2538
+ return n.project === ev.project && n.group === 'reference' && String(n.label || '').indexOf(stem) !== -1;
2539
+ });
2540
+ if (refMatch) return refMatch.id;
2541
+ }
2542
+
2543
+ // Project node id is the project name — the reliable, always-present hop.
2544
+ if (g.getNodeDetail(ev.project)) return ev.project;
2545
+
2546
+ // Last resort: any visible node belonging to the project.
2547
+ var any = (g.getData().nodes || []).find(function(n) { return n.project === ev.project; });
2548
+ return any ? any.id : null;
2549
+ }
2550
+
2551
+ window.addEventListener('phren:lookup', function(e) {
2552
+ var g = api();
2553
+ if (!g || typeof g.walkTo !== 'function') return;
2554
+ var id = nodeIdForLookup(e.detail);
2555
+ if (id) { try { g.walkTo(id); } catch (err) {} }
2556
+ });
2557
+ })();`;
2558
+ }