@phren/cli 0.1.22 → 0.1.24

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.
@@ -39,6 +39,8 @@ export declare function inferCitationLocation(repoPath: string, commit: string):
39
39
  line?: number;
40
40
  };
41
41
  export declare function buildCitationComment(citation: FindingCitation): string;
42
+ /** Format actor/machine attribution for human-readable display. */
43
+ export declare function formatActorAttribution(actor: string | undefined, machine: string | undefined): string;
42
44
  export declare function buildSourceComment(source: FindingProvenance): string;
43
45
  /** Build a standalone scope comment. Returns empty string if scope is unset or "shared". */
44
46
  export declare function buildScopeComment(scope: string | undefined): string;
@@ -72,6 +72,12 @@ function readSourceToken(match) {
72
72
  }
73
73
  return raw;
74
74
  }
75
+ /** Format actor/machine attribution for human-readable display. */
76
+ export function formatActorAttribution(actor, machine) {
77
+ if (!actor && !machine)
78
+ return "";
79
+ return `[from:${actor ?? "?"}${machine ? `@${machine}` : ""}]`;
80
+ }
75
81
  export function buildSourceComment(source) {
76
82
  const parts = [];
77
83
  if (source.source)
@@ -1,9 +1,10 @@
1
1
  import { type PhrenResult } from "../shared.js";
2
- import { type FindingCitation } from "./citation.js";
2
+ import { type FindingCitation, type FindingProvenance } from "./citation.js";
3
3
  interface AddFindingOptions {
4
4
  extraAnnotations?: string[];
5
5
  sessionId?: string;
6
6
  scope?: string;
7
+ provenance?: FindingProvenance;
7
8
  }
8
9
  export interface AddFindingResult {
9
10
  message: string;
@@ -16,6 +17,7 @@ export declare function addFindingsToFile(phrenPath: string, project: string, le
16
17
  extraAnnotationsByFinding?: string[][];
17
18
  sessionId?: string;
18
19
  scope?: string;
20
+ provenance?: FindingProvenance;
19
21
  }): PhrenResult<{
20
22
  added: string[];
21
23
  skipped: string[];
@@ -5,7 +5,7 @@ import { debugLog, appendAuditLog, phrenOk, phrenErr, PhrenError } from "../shar
5
5
  import { normalizeMemoryScope } from "../shared.js";
6
6
  import { withFileLock } from "../shared/governance.js";
7
7
  import { isValidProjectName, safeProjectPath } from "../utils.js";
8
- import { buildCitationComment, buildScopeComment, getHeadCommit, getRepoRoot, inferCitationLocation, } from "./citation.js";
8
+ import { buildCitationComment, buildScopeComment, buildSourceComment, getHeadCommit, getRepoRoot, inferCitationLocation, } from "./citation.js";
9
9
  import { isDuplicateFinding, scanForSecrets, normalizeObservationTags, resolveCoref, detectConflicts, extractDynamicEntities } from "./dedup.js";
10
10
  import { validateFindingsFormat, validateFinding } from "./validate.js";
11
11
  import { countActiveFindings, autoArchiveToReference } from "./archive.js";
@@ -81,7 +81,7 @@ export function autoDetectFindingType(text) {
81
81
  return null;
82
82
  }
83
83
  function prepareFinding(opts) {
84
- const { finding: learning, project, fullHistory, extraAnnotations, citationInput, scope, nowIso, inferredRepo, headCommit, phrenPath } = opts;
84
+ const { finding: learning, project, fullHistory, extraAnnotations, citationInput, scope, provenance, nowIso, inferredRepo, headCommit, phrenPath } = opts;
85
85
  const secretType = scanForSecrets(learning);
86
86
  if (secretType) {
87
87
  return { status: "rejected", reason: `Contains ${secretType}` };
@@ -107,6 +107,9 @@ function prepareFinding(opts) {
107
107
  let bullet = `${normalizedLearning.startsWith("- ") ? normalizedLearning : `- ${normalizedLearning}`} ${fidComment} ${createdComment}`;
108
108
  if (scopeComment)
109
109
  bullet += ` ${scopeComment}`;
110
+ const sourceComment = provenance ? buildSourceComment(provenance) : "";
111
+ if (sourceComment)
112
+ bullet += ` ${sourceComment}`;
110
113
  if (isDuplicateFinding(fullHistory, bullet)) {
111
114
  return { status: "duplicate" };
112
115
  }
@@ -251,7 +254,7 @@ export function addFindingToFile(phrenPath, project, learning, citationInput, op
251
254
  const result = withFileLock(learningsPath, () => {
252
255
  const preparedForNewFile = prepareFinding({
253
256
  finding: learning, project, fullHistory: "", extraAnnotations: opts?.extraAnnotations,
254
- citationInput: resolvedCitationInput, scope, nowIso, inferredRepo, headCommit, phrenPath,
257
+ citationInput: resolvedCitationInput, scope, provenance: opts?.provenance, nowIso, inferredRepo, headCommit, phrenPath,
255
258
  });
256
259
  if (!fs.existsSync(learningsPath)) {
257
260
  if (preparedForNewFile.status === "rejected") {
@@ -284,7 +287,7 @@ export function addFindingToFile(phrenPath, project, learning, citationInput, op
284
287
  : content;
285
288
  const prepared = prepareFinding({
286
289
  finding: learning, project, fullHistory: historyForDedup, extraAnnotations: opts?.extraAnnotations,
287
- citationInput: resolvedCitationInput, scope, nowIso, inferredRepo, headCommit, phrenPath,
290
+ citationInput: resolvedCitationInput, scope, provenance: opts?.provenance, nowIso, inferredRepo, headCommit, phrenPath,
288
291
  });
289
292
  if (prepared.status === "rejected") {
290
293
  return phrenErr(`Rejected: finding appears to contain a secret (${prepared.reason.replace(/^Contains /, "")}). Strip credentials before saving.`, PhrenError.VALIDATION_ERROR);
@@ -400,7 +403,7 @@ export function addFindingsToFile(phrenPath, project, learnings, opts) {
400
403
  }
401
404
  const prepared = prepareFinding({
402
405
  finding: learning, project, fullHistory: content, extraAnnotations,
403
- citationInput: resolvedCitationInput, scope, nowIso, inferredRepo, headCommit, phrenPath,
406
+ citationInput: resolvedCitationInput, scope, provenance: opts?.provenance, nowIso, inferredRepo, headCommit, phrenPath,
404
407
  });
405
408
  if (prepared.status === "rejected") {
406
409
  rejected.push({ text: learning, reason: prepared.reason });
@@ -19,6 +19,10 @@ export interface FindingItem {
19
19
  taskItem?: string;
20
20
  confidence?: number;
21
21
  scope?: string;
22
+ /** Machine hostname where this finding was originally recorded. */
23
+ machine?: string;
24
+ /** Actor (username) who recorded this finding. */
25
+ actor?: string;
22
26
  /** First 60 chars of the newer finding that supersedes this one. Set when this finding is stale. */
23
27
  supersededBy?: string;
24
28
  /** First 60 chars of the older finding this one replaces. */
@@ -174,7 +174,10 @@ export function readFindings(phrenPath, project, opts = {}) {
174
174
  const next = lines[i + 1] || "";
175
175
  const citation = isCitationLine(next) ? next.trim() : undefined;
176
176
  const citationData = citation ? parseCitationComment(citation) ?? undefined : undefined;
177
- const scope = parseScopeComment(line) ?? parseSourceComment(line)?.scope;
177
+ const provenance = parseSourceComment(line);
178
+ const scope = parseScopeComment(line) ?? provenance?.scope;
179
+ const machine = provenance?.machine;
180
+ const actor = provenance?.actor;
178
181
  const stableId = parseFindingId(line);
179
182
  const rawText = line.replace(/^-\s+/, "").trim();
180
183
  const textWithoutComments = stripComments(rawText);
@@ -198,6 +201,8 @@ export function readFindings(phrenPath, project, opts = {}) {
198
201
  citationData,
199
202
  taskItem: citationData?.task_item,
200
203
  scope,
204
+ machine,
205
+ actor,
201
206
  supersededBy: supersededByMatch ? supersededByMatch[1] : undefined,
202
207
  supersedes: supersedesMatch ? supersedesMatch[1] : undefined,
203
208
  contradicts: contradictsMatches.length > 0 ? contradictsMatches : undefined,
@@ -394,22 +394,29 @@ export async function runTopLevelCommand(argv, opts = {}) {
394
394
  return finish(1);
395
395
  }
396
396
  const cloneUrl = getOptionValue(initArgs, "--clone-url");
397
- await runInit({
398
- mode: modeArg,
399
- machine: machineIdx !== -1 ? initArgs[machineIdx + 1] : undefined,
400
- profile: profileIdx !== -1 ? initArgs[profileIdx + 1] : undefined,
401
- mcp: mcpMode,
402
- projectOwnershipDefault: ownershipMode,
403
- taskMode,
404
- findingsProactivity,
405
- taskProactivity,
406
- template: templateIdx !== -1 ? initArgs[templateIdx + 1] : undefined,
407
- applyStarterUpdate: initArgs.includes("--apply-starter-update"),
408
- dryRun: initArgs.includes("--dry-run"),
409
- yes: initArgs.includes("--yes") || initArgs.includes("-y"),
410
- express: initArgs.includes("--express"),
411
- _walkthroughCloneUrl: cloneUrl,
412
- });
397
+ try {
398
+ await runInit({
399
+ mode: modeArg,
400
+ machine: machineIdx !== -1 ? initArgs[machineIdx + 1] : undefined,
401
+ profile: profileIdx !== -1 ? initArgs[profileIdx + 1] : undefined,
402
+ mcp: mcpMode,
403
+ projectOwnershipDefault: ownershipMode,
404
+ taskMode,
405
+ findingsProactivity,
406
+ taskProactivity,
407
+ template: templateIdx !== -1 ? initArgs[templateIdx + 1] : undefined,
408
+ applyStarterUpdate: initArgs.includes("--apply-starter-update"),
409
+ dryRun: initArgs.includes("--dry-run"),
410
+ yes: initArgs.includes("--yes") || initArgs.includes("-y"),
411
+ express: initArgs.includes("--express"),
412
+ force: initArgs.includes("--force"),
413
+ _walkthroughCloneUrl: cloneUrl,
414
+ });
415
+ }
416
+ catch (err) {
417
+ console.error(errorMessage(err));
418
+ return finish(1);
419
+ }
413
420
  return finish();
414
421
  }
415
422
  if (argvCommand === "uninstall") {
@@ -1,5 +1,5 @@
1
1
  import { PhrenResult } from "../shared.js";
2
- import type { FindingProvenanceSource } from "../content/citation.js";
2
+ import { type FindingProvenanceSource } from "../content/citation.js";
3
3
  interface FindingJournalCompactResult {
4
4
  filesProcessed: number;
5
5
  entriesProcessed: number;
@@ -20,7 +20,7 @@ export declare function compactFindingJournals(phrenPath: string, project?: stri
20
20
  * Each actor gets one file per day — no merge conflicts possible.
21
21
  * These are markdown files committed to git (not runtime JSONL).
22
22
  */
23
- export declare function appendTeamJournal(storePath: string, project: string, finding: string, actor?: string): PhrenResult<string>;
23
+ export declare function appendTeamJournal(storePath: string, project: string, finding: string, actor?: string, machine?: string): PhrenResult<string>;
24
24
  /**
25
25
  * Read all team journal entries for a project, newest first.
26
26
  */
@@ -5,6 +5,8 @@ import { runtimeDir, phrenOk, phrenErr, PhrenError, atomicWriteText } from "../s
5
5
  import { withFileLock } from "../shared/governance.js";
6
6
  import { addFindingToFile } from "../shared/content.js";
7
7
  import { isValidProjectName, errorMessage } from "../utils.js";
8
+ import { buildSourceComment } from "../content/citation.js";
9
+ import { getCurrentActor } from "../machine-identity.js";
8
10
  import { FINDINGS_FILENAME } from "../data/access.js";
9
11
  function journalRoot(phrenPath) {
10
12
  const dir = path.join(runtimeDir(phrenPath), "finding-journal");
@@ -127,15 +129,16 @@ const TEAM_JOURNAL_DIR = "journal";
127
129
  * Each actor gets one file per day — no merge conflicts possible.
128
130
  * These are markdown files committed to git (not runtime JSONL).
129
131
  */
130
- export function appendTeamJournal(storePath, project, finding, actor) {
131
- const resolvedActor = actor || process.env.PHREN_ACTOR || process.env.USER || "unknown";
132
+ export function appendTeamJournal(storePath, project, finding, actor, machine) {
133
+ const resolvedActor = actor || getCurrentActor();
132
134
  const date = new Date().toISOString().slice(0, 10);
133
135
  const journalDir = path.join(storePath, project, TEAM_JOURNAL_DIR);
134
136
  const journalFile = `${date}-${resolvedActor}.md`;
135
137
  const journalPath = path.join(journalDir, journalFile);
136
138
  try {
137
139
  fs.mkdirSync(journalDir, { recursive: true });
138
- const entry = `- ${finding}\n`;
140
+ const sourceComment = buildSourceComment({ source: "human", machine, actor: resolvedActor });
141
+ const entry = `- ${finding}${sourceComment ? ` ${sourceComment}` : ""}\n`;
139
142
  if (fs.existsSync(journalPath)) {
140
143
  fs.appendFileSync(journalPath, entry);
141
144
  }
@@ -192,7 +195,9 @@ export function materializeTeamFindings(storePath, project) {
192
195
  lines.push(`## ${date}`);
193
196
  for (const { actor, entries } of actors) {
194
197
  for (const entry of entries) {
195
- lines.push(`- ${entry} <!-- author:${actor} -->`);
198
+ const hasSource = /<!--\s*source:.*?-->/.test(entry);
199
+ const fallback = hasSource ? "" : ` ${buildSourceComment({ source: "human", actor })}`;
200
+ lines.push(`- ${entry}${fallback}`);
196
201
  count++;
197
202
  }
198
203
  }
@@ -0,0 +1,6 @@
1
+ export interface WiringConflict {
2
+ location: string;
3
+ existingPath: string;
4
+ }
5
+ export declare function findConflictingGlobalWiring(newPhrenPath: string): WiringConflict[];
6
+ export declare function assertNoGlobalWiringConflict(newPhrenPath: string, force: boolean): void;
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Guards against `phren init` silently repointing the user's global wiring
3
+ * (CLI wrapper at ~/.local/bin/phren and Claude settings.json hooks/MCP) at a
4
+ * different phren root than the one currently in use.
5
+ *
6
+ * Why: `phren init` is also exercised by tests/smoke scripts that invoke it
7
+ * with `PHREN_PATH=/tmp/...`. Without an isolated $HOME the install logic
8
+ * cheerfully rewrites the user's real wrapper and Claude hooks to point at
9
+ * the throwaway path, which then disappears with `rm -rf /tmp/foo`. The next
10
+ * Claude session boots with a SessionStart hook that throws
11
+ * `NOT_FOUND: phren root not found. Run 'phren init'.`
12
+ *
13
+ * Behavior: before any global file is rewritten, scan the three known
14
+ * locations. If any of them already references a *different* path that
15
+ * resolves to a valid phren root, refuse to proceed unless `--force` is
16
+ * passed. Stale wiring (existing path missing or not a phren root) is not a
17
+ * conflict — init is the right tool to repair it.
18
+ */
19
+ import * as fs from "fs";
20
+ import * as path from "path";
21
+ import { homePath, isRecord } from "../shared.js";
22
+ import { hookConfigPath } from "../provider-adapters.js";
23
+ const WRAPPER_POSIX_RE = /PHREN_PATH="\$\{PHREN_PATH:-([^}]+)\}"/;
24
+ const WRAPPER_WIN_RE = /set "PHREN_PATH=([^"]+)"/;
25
+ const HOOK_PHREN_PATH_RE = /PHREN_PATH=(?:'([^']+)'|"([^"]+)"|(\S+))/;
26
+ function samePath(a, b) {
27
+ return path.resolve(a) === path.resolve(b);
28
+ }
29
+ /**
30
+ * A path counts as a "valid phren root" only if it currently looks like one
31
+ * — root manifest, machines.yaml, or the global skills tree. We deliberately
32
+ * tolerate partial roots so a clean `phren init` repair still works.
33
+ */
34
+ function looksLikePhrenRoot(candidate) {
35
+ if (!fs.existsSync(candidate))
36
+ return false;
37
+ if (fs.existsSync(path.join(candidate, "phren.root.yaml")))
38
+ return true;
39
+ if (fs.existsSync(path.join(candidate, "machines.yaml")))
40
+ return true;
41
+ if (fs.existsSync(path.join(candidate, "global")))
42
+ return true;
43
+ return false;
44
+ }
45
+ function readWrapperPath() {
46
+ const wrapperName = process.platform === "win32" ? "phren.cmd" : "phren";
47
+ const wrapperFile = path.join(homePath(".local", "bin"), wrapperName);
48
+ if (!fs.existsSync(wrapperFile))
49
+ return null;
50
+ let content;
51
+ try {
52
+ content = fs.readFileSync(wrapperFile, "utf8");
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ if (!content.includes("PHREN_CLI_WRAPPER"))
58
+ return null;
59
+ const re = process.platform === "win32" ? WRAPPER_WIN_RE : WRAPPER_POSIX_RE;
60
+ const m = content.match(re);
61
+ return m?.[1] ?? null;
62
+ }
63
+ function extractHookPhrenPath(command) {
64
+ const m = command.match(HOOK_PHREN_PATH_RE);
65
+ if (!m)
66
+ return null;
67
+ return m[1] ?? m[2] ?? m[3] ?? null;
68
+ }
69
+ function readClaudeSettings() {
70
+ const settingsPath = hookConfigPath("claude");
71
+ if (!fs.existsSync(settingsPath))
72
+ return null;
73
+ try {
74
+ return JSON.parse(fs.readFileSync(settingsPath, "utf8"));
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ }
80
+ export function findConflictingGlobalWiring(newPhrenPath) {
81
+ const conflicts = [];
82
+ const seen = new Set();
83
+ const record = (location, existingPath) => {
84
+ if (samePath(existingPath, newPhrenPath))
85
+ return;
86
+ if (!looksLikePhrenRoot(existingPath))
87
+ return;
88
+ const key = `${location}:${path.resolve(existingPath)}`;
89
+ if (seen.has(key))
90
+ return;
91
+ seen.add(key);
92
+ conflicts.push({ location, existingPath });
93
+ };
94
+ const wrapperPath = readWrapperPath();
95
+ if (wrapperPath) {
96
+ record(`~/.local/bin/${process.platform === "win32" ? "phren.cmd" : "phren"} wrapper`, wrapperPath);
97
+ }
98
+ const settings = readClaudeSettings();
99
+ if (isRecord(settings)) {
100
+ const mcpServers = settings.mcpServers;
101
+ if (isRecord(mcpServers)) {
102
+ const phrenServer = mcpServers.phren;
103
+ if (isRecord(phrenServer) && Array.isArray(phrenServer.args) && phrenServer.args.length > 0) {
104
+ const last = phrenServer.args[phrenServer.args.length - 1];
105
+ if (typeof last === "string") {
106
+ record("~/.claude/settings.json mcpServers.phren", last);
107
+ }
108
+ }
109
+ }
110
+ const hooks = settings.hooks;
111
+ if (isRecord(hooks)) {
112
+ for (const eventName of ["UserPromptSubmit", "Stop", "SessionStart", "PostToolUse"]) {
113
+ const eventHooks = hooks[eventName];
114
+ if (!Array.isArray(eventHooks))
115
+ continue;
116
+ for (const entry of eventHooks) {
117
+ if (!isRecord(entry))
118
+ continue;
119
+ const inner = entry.hooks;
120
+ if (!Array.isArray(inner))
121
+ continue;
122
+ for (const h of inner) {
123
+ if (!isRecord(h))
124
+ continue;
125
+ const command = typeof h.command === "string" ? h.command : "";
126
+ if (!command)
127
+ continue;
128
+ const extracted = extractHookPhrenPath(command);
129
+ if (extracted) {
130
+ record(`~/.claude/settings.json hooks.${eventName}`, extracted);
131
+ }
132
+ }
133
+ }
134
+ }
135
+ }
136
+ }
137
+ return conflicts;
138
+ }
139
+ export function assertNoGlobalWiringConflict(newPhrenPath, force) {
140
+ if (force)
141
+ return;
142
+ const conflicts = findConflictingGlobalWiring(newPhrenPath);
143
+ if (conflicts.length === 0)
144
+ return;
145
+ const lines = [
146
+ `phren init: refusing to repoint global wiring at ${newPhrenPath}.`,
147
+ "",
148
+ "Existing files reference a different phren root that still looks valid:",
149
+ ];
150
+ for (const c of conflicts) {
151
+ lines.push(` - ${c.location} → ${c.existingPath}`);
152
+ }
153
+ lines.push("");
154
+ lines.push("If you intend to switch the global wiring to the new path, re-run with --force.");
155
+ lines.push("If you're running a smoke test, set HOME (and XDG_*) to a sandbox before invoking init.");
156
+ throw new Error(lines.join("\n"));
157
+ }
@@ -44,6 +44,14 @@ export interface InitOptions {
44
44
  yes?: boolean;
45
45
  /** Skip walkthrough entirely with recommended defaults (express mode) */
46
46
  express?: boolean;
47
+ /**
48
+ * Allow init to repoint global wiring (~/.local/bin/phren wrapper and
49
+ * Claude settings.json hooks/mcpServers.phren) at a different phren root
50
+ * than the one currently in use. Without this, init refuses when an
51
+ * existing global file references a different valid phren root — protects
52
+ * against tests/smoke runs that forget to sandbox $HOME.
53
+ */
54
+ force?: boolean;
47
55
  template?: "python-project" | "monorepo" | "library" | "frontend" | string;
48
56
  /** Set by walkthrough to pass project name to init logic */
49
57
  _walkthroughProject?: string;
package/dist/init/init.js CHANGED
@@ -23,6 +23,7 @@ export { runUninstall } from "./init-uninstall.js";
23
23
  // Internal imports from extracted modules (used by runInit)
24
24
  import { configureMcpTargets, configureHooksIfEnabled, applyOnboardingPreferences, writeWalkthroughEnvDefaults, collectRepairedAssetLabels, applyProjectStorageBindings, warmSemanticSearch, runProjectLocalInit, } from "./init-configure.js";
25
25
  import { runWalkthrough, createWalkthroughPrompts, createWalkthroughStyle } from "./init-walkthrough.js";
26
+ import { assertNoGlobalWiringConflict } from "./guard-globals.js";
26
27
  import { getMcpEnabledPreference, getHooksEnabledPreference, writeInstallPreferences, readInstallPreferences, } from "./preferences.js";
27
28
  import { ensureGovernanceFiles, repairPreexistingInstall, runPostInitVerify, applyStarterTemplateUpdates, listTemplates, applyTemplate, ensureProjectScaffold, ensureLocalGitRepo, bootstrapFromExisting, updateMachinesYaml, detectProjectDir, isProjectTracked, } from "./setup.js";
28
29
  import { DEFAULT_PHREN_PATH, STARTER_DIR, VERSION, log } from "./shared.js";
@@ -101,6 +102,9 @@ export async function runInit(opts = {}) {
101
102
  }
102
103
  let phrenPath = resolveInitPhrenPath(opts);
103
104
  const dryRun = Boolean(opts.dryRun);
105
+ if (!dryRun) {
106
+ assertNoGlobalWiringConflict(phrenPath, Boolean(opts.force));
107
+ }
104
108
  // Migrate the legacy hidden store directory into ~/.phren when upgrading
105
109
  // from the previous product name. Only runs when the resolved phrenPath
106
110
  // doesn't exist yet but the legacy directory does.
@@ -2,3 +2,4 @@ export declare function machineFilePath(): string;
2
2
  export declare function defaultMachineName(): string;
3
3
  export declare function getMachineName(): string;
4
4
  export declare function persistMachineName(machine: string): void;
5
+ export declare function getCurrentActor(): string;
@@ -13,18 +13,25 @@ export function defaultMachineName() {
13
13
  }
14
14
  return os.hostname();
15
15
  }
16
+ let cachedMachineName = null;
16
17
  export function getMachineName() {
18
+ if (cachedMachineName !== null)
19
+ return cachedMachineName;
17
20
  const filePath = machineFilePath();
18
21
  if (fs.existsSync(filePath)) {
19
22
  const persisted = fs.readFileSync(filePath, "utf8").trim();
20
23
  if (persisted)
21
- return persisted;
24
+ return (cachedMachineName = persisted);
22
25
  }
23
- return defaultMachineName();
26
+ return (cachedMachineName = defaultMachineName());
24
27
  }
25
28
  export function persistMachineName(machine) {
26
29
  const normalized = machine.trim();
27
30
  if (!normalized)
28
31
  return;
29
32
  atomicWriteText(machineFilePath(), `${normalized}\n`);
33
+ cachedMachineName = normalized;
34
+ }
35
+ export function getCurrentActor() {
36
+ return process.env.PHREN_ACTOR || process.env.USER || "unknown";
30
37
  }
@@ -68,6 +68,7 @@ import { isInactiveFindingLine } from "../finding/lifecycle.js";
68
68
  import { invalidateDfCache } from "./search-fallback.js";
69
69
  import { errorMessage } from "../utils.js";
70
70
  import { logger } from "../logger.js";
71
+ import { formatActorAttribution, parseSourceComment } from "../content/citation.js";
71
72
  import { beginUserFragmentBuildCache, endUserFragmentBuildCache, extractAndLinkFragments, ensureGlobalEntitiesTable, } from "./fragment-graph.js";
72
73
  import { bootstrapSqlJs } from "./sqljs.js";
73
74
  import { getProjectOwnershipMode, getProjectSourcePath, readProjectConfig } from "../project-config.js";
@@ -521,7 +522,10 @@ export function normalizeIndexedContent(content, type, phrenPath, maxChars) {
521
522
  .replace(/<!-- phren:archive:start -->[\s\S]*?<!-- phren:archive:end -->/g, "")
522
523
  .replace(/<details>[\s\S]*?<\/details>/gi, "")
523
524
  .replace(/<!--\s*created:\s*.*?-->/g, "")
524
- .replace(/<!--\s*source:\s*.*?-->/g, "")
525
+ .replace(/<!--\s*source:.*?-->/g, (match) => {
526
+ const parsed = parseSourceComment(match);
527
+ return formatActorAttribution(parsed?.actor, parsed?.machine);
528
+ })
525
529
  .replace(/<!--\s*phren:cite\s+\{[\s\S]*?\}\s*-->/g, "");
526
530
  normalized = resolveImports(normalized, phrenPath);
527
531
  if (type === "task") {
@@ -6,6 +6,7 @@ import { logger } from "../logger.js";
6
6
  import { isValidProjectName, safeProjectPath, errorMessage } from "../utils.js";
7
7
  import { removeFinding as removeFindingCore, removeFindings as removeFindingsCore, } from "../core/finding.js";
8
8
  import { debugLog, EXEC_TIMEOUT_MS, FINDING_TYPES, normalizeMemoryScope, } from "../shared.js";
9
+ import { getCurrentActor, getMachineName } from "../machine-identity.js";
9
10
  import { addFindingToFile, addFindingsToFile, checkSemanticConflicts, autoMergeConflicts, } from "../shared/content.js";
10
11
  import { jaccardTokenize, jaccardSimilarity, stripMetadata } from "../content/dedup.js";
11
12
  import { runCustomHooks } from "../hooks.js";
@@ -103,6 +104,12 @@ async function handleAddFinding(ctx, params) {
103
104
  const addFindingDenied = permissionDeniedError(phrenPath, "add_finding", project);
104
105
  if (addFindingDenied)
105
106
  return mcpResponse({ ok: false, error: addFindingDenied });
107
+ const provenance = {
108
+ source: "human",
109
+ machine: getMachineName(),
110
+ actor: getCurrentActor(),
111
+ session_id: sessionId,
112
+ };
106
113
  // Team stores: use append-only journal (no FINDINGS.md mutation, no merge conflicts)
107
114
  {
108
115
  const storeResolved = resolveStoreForProject(ctx, params.project);
@@ -112,7 +119,7 @@ async function handleAddFinding(ctx, params) {
112
119
  const added = [];
113
120
  for (const f of findings) {
114
121
  const taggedFinding = findingType ? `[${findingType}] ${f}` : f;
115
- const result = appendTeamJournal(phrenPath, project, taggedFinding);
122
+ const result = appendTeamJournal(phrenPath, project, taggedFinding, provenance.actor, provenance.machine);
116
123
  if (result.ok)
117
124
  added.push(taggedFinding);
118
125
  }
@@ -150,6 +157,7 @@ async function handleAddFinding(ctx, params) {
150
157
  extraAnnotationsByFinding,
151
158
  sessionId,
152
159
  scope: normalizedScope,
160
+ provenance,
153
161
  });
154
162
  if (!result.ok)
155
163
  return mcpResponse({ ok: false, error: result.error });
@@ -189,6 +197,7 @@ async function handleAddFinding(ctx, params) {
189
197
  sessionId,
190
198
  scope: normalizedScope,
191
199
  extraAnnotations: semanticConflicts.checked ? semanticConflicts.annotations : undefined,
200
+ provenance,
192
201
  });
193
202
  if (!result.ok) {
194
203
  return mcpResponse({ ok: false, error: result.error });
@@ -14,7 +14,7 @@ import { runCustomHooks } from "../hooks.js";
14
14
  import { entryScoreKey, getQualityMultiplier, getRetentionPolicy } from "../shared/governance.js";
15
15
  import { callLlm } from "../content/dedup.js";
16
16
  import { rankResults, searchKnowledgeRows, applyTrustFilter, searchFederatedStores } from "../shared/retrieval.js";
17
- import { parseScopeComment, parseSourceComment } from "../content/citation.js";
17
+ import { formatActorAttribution, parseScopeComment, parseSourceComment } from "../content/citation.js";
18
18
  import { resolveActiveSessionScope } from "./session.js";
19
19
  import { logger } from "../logger.js";
20
20
  /**
@@ -668,7 +668,8 @@ async function handleGetFindings(ctx, { project, limit, include_superseded, incl
668
668
  if (entry.tier === "archived")
669
669
  metadata.push("tier=archived");
670
670
  const idLabel = entry.stableId ? `${entry.id}|fid:${entry.stableId}` : entry.id;
671
- return `- [${idLabel}] ${entry.date}: ${entry.text}${entry.confidence !== undefined ? ` [confidence ${entry.confidence.toFixed(2)}]` : ""}${metadata.length > 0 ? ` [${metadata.join(" ")}]` : ""}${entry.citation ? ` (${entry.citation})` : ""}`;
671
+ const attribution = formatActorAttribution(entry.actor, entry.machine);
672
+ return `- [${idLabel}] ${entry.date}: ${entry.text}${attribution ? ` ${attribution}` : ""}${entry.confidence !== undefined ? ` [confidence ${entry.confidence.toFixed(2)}]` : ""}${metadata.length > 0 ? ` [${metadata.join(" ")}]` : ""}${entry.citation ? ` (${entry.citation})` : ""}`;
672
673
  });
673
674
  const hiddenHistoryCount = includeHistory ? 0 : historyCount;
674
675
  const historyNote = hiddenHistoryCount > 0 ? ` (${hiddenHistoryCount} historical hidden)` : "";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.1.22",
3
+ "version": "0.1.24",
4
4
  "description": "Knowledge layer for AI agents — CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {