@phren/cli 0.1.23 → 0.1.26

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.
@@ -13,6 +13,6 @@ export declare function filterToolFindingsForProactivity(candidates: Array<{
13
13
  confidence: number;
14
14
  explicit?: boolean;
15
15
  }>;
16
- export declare function extractToolFindings(toolName: string, input: Record<string, unknown>, responseStr: string): LearningCandidate[];
16
+ export declare function extractToolFindings(toolName: string, input: Record<string, unknown>, responseStr: string, toolResponse?: unknown): LearningCandidate[];
17
17
  export declare function handleHookContext(): Promise<void>;
18
18
  export {};
@@ -160,7 +160,7 @@ export async function handleHookTool() {
160
160
  const findingsLevelForTool = getProactivityLevelForFindings(ctx.phrenPath);
161
161
  if (activeProject && findingsLevelForTool !== "low") {
162
162
  try {
163
- const candidates = filterToolFindingsForProactivity(extractToolFindings(toolName, input, responseStr), findingsLevelForTool);
163
+ const candidates = filterToolFindingsForProactivity(extractToolFindings(toolName, input, responseStr, data.tool_response), findingsLevelForTool);
164
164
  for (const { text, confidence } of candidates) {
165
165
  appendReviewQueue(ctx.phrenPath, activeProject, "Review", [text]);
166
166
  debugLog(`hook-tool: queued candidate for review (conf=${confidence}): ${text.slice(0, 60)}`);
@@ -207,7 +207,11 @@ export async function handleHookTool() {
207
207
  process.exit(0);
208
208
  }
209
209
  }
210
- const EXPLICIT_TAG_PATTERN = /\[(pitfall|decision|pattern|tradeoff|architecture|bug)\]\s*(.+)/i;
210
+ // Negative lookahead `(?!\(|\[)` rejects markdown link/reference patterns:
211
+ // [Architecture](#architecture) ← TOC anchor, content was being captured as "(#architecture)"
212
+ // [bug][1] ← markdown reference link, content was being captured as "[1]"
213
+ // produced garbage review-queue entries like "[architecture] (#architecture)".
214
+ const EXPLICIT_TAG_PATTERN = /\[(pitfall|decision|pattern|tradeoff|architecture|bug)\](?!\(|\[)\s*(.+)/i;
211
215
  export function filterToolFindingsForProactivity(candidates, level = getProactivityLevelForFindings(getPhrenPath())) {
212
216
  if (level === "high")
213
217
  return candidates;
@@ -215,7 +219,39 @@ export function filterToolFindingsForProactivity(candidates, level = getProactiv
215
219
  return [];
216
220
  return candidates.filter((candidate) => candidate.explicit === true);
217
221
  }
218
- export function extractToolFindings(toolName, input, responseStr) {
222
+ // Bash commands whose non-zero exit codes are routine signal, not bugs.
223
+ // grep/rg/ag/find returning exit 1 (no match) is the common case; conditional
224
+ // shell tests evaluating false is another. Don't surface these as findings.
225
+ const NOISY_BASH_COMMAND_PATTERNS = [
226
+ /^\s*(?:grep|rg|ag|ack)\b/,
227
+ /^\s*find\b/,
228
+ /^\s*which\b/,
229
+ /^\s*command\s+-v\b/,
230
+ /^\s*test\b/,
231
+ /^\s*\[\s/,
232
+ /^\s*\[\[\s/,
233
+ /^\s*pgrep\b/,
234
+ /^\s*pkill\b/,
235
+ /^\s*git\s+diff\s+--quiet/,
236
+ ];
237
+ function isNoisyBashCommand(cmd) {
238
+ if (/\|\|\s*true\b/.test(cmd))
239
+ return true;
240
+ if (/2>\s*\/dev\/null/.test(cmd))
241
+ return true;
242
+ return NOISY_BASH_COMMAND_PATTERNS.some((re) => re.test(cmd));
243
+ }
244
+ function extractToolErrorSignal(toolResponse) {
245
+ if (!toolResponse || typeof toolResponse !== "object") {
246
+ return { isError: false, hasExitCode: false };
247
+ }
248
+ const tr = toolResponse;
249
+ const isError = Boolean(tr.is_error ?? tr.isError);
250
+ const rawExit = tr.exit_code ?? tr.exitCode;
251
+ const exitCode = typeof rawExit === "number" ? rawExit : undefined;
252
+ return { isError, exitCode, hasExitCode: exitCode !== undefined };
253
+ }
254
+ export function extractToolFindings(toolName, input, responseStr, toolResponse) {
219
255
  const candidates = [];
220
256
  const changedContent = (toolName === "Edit" || toolName === "Write")
221
257
  ? String(input.new_string ?? input.content ?? "")
@@ -242,25 +278,24 @@ export function extractToolFindings(toolName, input, responseStr) {
242
278
  });
243
279
  }
244
280
  }
245
- if (/\btry\s*\{[\s\S]*?\bcatch\b/.test(changedContent)) {
246
- const meaningfulLine = changedContent.split("\n").find((l) => l.trim().length > 10 && !/^\s*(try|catch|\{|\})/.test(l));
247
- if (meaningfulLine) {
248
- candidates.push({
249
- text: `[pitfall] ${filename}: error handling added near "${meaningfulLine.trim().slice(0, 100)}"`,
250
- confidence: 0.45,
251
- explicit: false,
252
- });
253
- }
254
- }
281
+ // (Removed: try/catch additions used to emit "[pitfall] ... error handling added near ..."
282
+ // candidates. Adding error handling is normal code, not a pitfall — the heuristic produced
283
+ // ~21 false positives for every real one in observed stores.)
255
284
  }
256
285
  if (toolName === "Bash") {
257
- const cmd = String(input.command ?? "").slice(0, 30);
258
- const hasError = /(error|exception|failed|ENOENT|command not found|permission denied)/i.test(responseStr);
259
- if (hasError && cmd) {
286
+ const fullCmd = String(input.command ?? "");
287
+ const cmdShort = fullCmd.slice(0, 30);
288
+ const errorSignal = extractToolErrorSignal(toolResponse);
289
+ // Only emit a [bug] candidate when (a) we have a definite error signal from the tool
290
+ // result (is_error or non-zero exit_code) and (b) the command isn't a known-noisy one
291
+ // like grep/find/test where exit 1 just means "didn't match".
292
+ const hasDefiniteError = errorSignal.isError || (errorSignal.hasExitCode && (errorSignal.exitCode ?? 0) !== 0);
293
+ if (hasDefiniteError && cmdShort && !isNoisyBashCommand(fullCmd)) {
260
294
  const firstErrorLine = responseStr.split("\n").find((l) => /(error|exception|failed|ENOENT|command not found|permission denied)/i.test(l));
261
- if (firstErrorLine) {
295
+ const detail = (firstErrorLine ?? responseStr.split("\n")[0] ?? "").trim().slice(0, 150);
296
+ if (detail) {
262
297
  candidates.push({
263
- text: `[bug] command '${cmd}' failed: ${firstErrorLine.trim().slice(0, 150)}`,
298
+ text: `[bug] command '${cmdShort}' failed: ${detail}`,
264
299
  confidence: 0.55,
265
300
  explicit: false,
266
301
  });
@@ -14,5 +14,5 @@ export declare function filterToolFindingsForProactivity(candidates: Array<{
14
14
  confidence: number;
15
15
  explicit?: boolean;
16
16
  }>;
17
- export declare function extractToolFindings(toolName: string, input: Record<string, unknown>, responseStr: string): LearningCandidate[];
17
+ export declare function extractToolFindings(toolName: string, input: Record<string, unknown>, responseStr: string, toolResponse?: unknown): LearningCandidate[];
18
18
  export {};
@@ -212,7 +212,7 @@ export async function handleHookTool() {
212
212
  const findingsLevelForTool = getProactivityLevelForFindings(ctx.phrenPath);
213
213
  if (activeProject && findingsLevelForTool !== "low") {
214
214
  try {
215
- const candidates = filterToolFindingsForProactivity(extractToolFindings(toolName, input, responseStr), findingsLevelForTool);
215
+ const candidates = filterToolFindingsForProactivity(extractToolFindings(toolName, input, responseStr, data.tool_response), findingsLevelForTool);
216
216
  for (const { text, confidence } of candidates) {
217
217
  appendReviewQueue(ctx.phrenPath, activeProject, "Review", [text]);
218
218
  debugLog(`hook-tool: queued candidate for review (conf=${confidence}): ${text.slice(0, 60)}`);
@@ -259,7 +259,11 @@ export async function handleHookTool() {
259
259
  process.exit(0);
260
260
  }
261
261
  }
262
- const EXPLICIT_TAG_PATTERN = /\[(pitfall|decision|pattern|tradeoff|architecture|bug)\]\s*(.+)/i;
262
+ // Negative lookahead `(?!\(|\[)` rejects markdown link/reference patterns:
263
+ // [Architecture](#architecture) ← TOC anchor, content was being captured as "(#architecture)"
264
+ // [bug][1] ← markdown reference link, content was being captured as "[1]"
265
+ // produced garbage review-queue entries like "[architecture] (#architecture)".
266
+ const EXPLICIT_TAG_PATTERN = /\[(pitfall|decision|pattern|tradeoff|architecture|bug)\](?!\(|\[)\s*(.+)/i;
263
267
  export function filterToolFindingsForProactivity(candidates, level = getProactivityLevelForFindings(getPhrenPath())) {
264
268
  if (level === "high")
265
269
  return candidates;
@@ -267,7 +271,39 @@ export function filterToolFindingsForProactivity(candidates, level = getProactiv
267
271
  return [];
268
272
  return candidates.filter((candidate) => candidate.explicit === true);
269
273
  }
270
- export function extractToolFindings(toolName, input, responseStr) {
274
+ // Bash commands whose non-zero exit codes are routine signal, not bugs.
275
+ // grep/rg/ag/find returning exit 1 (no match) is the common case; conditional
276
+ // shell tests evaluating false is another. Don't surface these as findings.
277
+ const NOISY_BASH_COMMAND_PATTERNS = [
278
+ /^\s*(?:grep|rg|ag|ack)\b/,
279
+ /^\s*find\b/,
280
+ /^\s*which\b/,
281
+ /^\s*command\s+-v\b/,
282
+ /^\s*test\b/,
283
+ /^\s*\[\s/,
284
+ /^\s*\[\[\s/,
285
+ /^\s*pgrep\b/,
286
+ /^\s*pkill\b/,
287
+ /^\s*git\s+diff\s+--quiet/,
288
+ ];
289
+ function isNoisyBashCommand(cmd) {
290
+ if (/\|\|\s*true\b/.test(cmd))
291
+ return true;
292
+ if (/2>\s*\/dev\/null/.test(cmd))
293
+ return true;
294
+ return NOISY_BASH_COMMAND_PATTERNS.some((re) => re.test(cmd));
295
+ }
296
+ function extractToolErrorSignal(toolResponse) {
297
+ if (!toolResponse || typeof toolResponse !== "object") {
298
+ return { isError: false, hasExitCode: false };
299
+ }
300
+ const tr = toolResponse;
301
+ const isError = Boolean(tr.is_error ?? tr.isError);
302
+ const rawExit = tr.exit_code ?? tr.exitCode;
303
+ const exitCode = typeof rawExit === "number" ? rawExit : undefined;
304
+ return { isError, exitCode, hasExitCode: exitCode !== undefined };
305
+ }
306
+ export function extractToolFindings(toolName, input, responseStr, toolResponse) {
271
307
  const candidates = [];
272
308
  const changedContent = (toolName === "Edit" || toolName === "Write")
273
309
  ? String(input.new_string ?? input.content ?? "")
@@ -294,25 +330,25 @@ export function extractToolFindings(toolName, input, responseStr) {
294
330
  });
295
331
  }
296
332
  }
297
- if (/\btry\s*\{[\s\S]*?\bcatch\b/.test(changedContent)) {
298
- const meaningfulLine = changedContent.split("\n").find((l) => l.trim().length > 10 && !/^\s*(try|catch|\{|\})/.test(l));
299
- if (meaningfulLine) {
300
- candidates.push({
301
- text: `[pitfall] ${filename}: error handling added near "${meaningfulLine.trim().slice(0, 100)}"`,
302
- confidence: 0.45,
303
- explicit: false,
304
- });
305
- }
306
- }
333
+ // (Removed: try/catch additions used to emit "[pitfall] ... error handling added near ..."
334
+ // candidates. Adding error handling is normal code, not a pitfall — the heuristic produced
335
+ // ~21 false positives for every real one in observed stores. If we ever need this back,
336
+ // gate on a *removed* try/catch, not an added one.)
307
337
  }
308
338
  if (toolName === "Bash") {
309
- const cmd = String(input.command ?? "").slice(0, 30);
310
- const hasError = /(error|exception|failed|ENOENT|command not found|permission denied)/i.test(responseStr);
311
- if (hasError && cmd) {
339
+ const fullCmd = String(input.command ?? "");
340
+ const cmdShort = fullCmd.slice(0, 30);
341
+ const errorSignal = extractToolErrorSignal(toolResponse);
342
+ // Only emit a [bug] candidate when (a) we have a definite error signal from the tool
343
+ // result (is_error or non-zero exit_code) and (b) the command isn't a known-noisy one
344
+ // like grep/find/test where exit 1 just means "didn't match" rather than a failure.
345
+ const hasDefiniteError = errorSignal.isError || (errorSignal.hasExitCode && (errorSignal.exitCode ?? 0) !== 0);
346
+ if (hasDefiniteError && cmdShort && !isNoisyBashCommand(fullCmd)) {
312
347
  const firstErrorLine = responseStr.split("\n").find((l) => /(error|exception|failed|ENOENT|command not found|permission denied)/i.test(l));
313
- if (firstErrorLine) {
348
+ const detail = (firstErrorLine ?? responseStr.split("\n")[0] ?? "").trim().slice(0, 150);
349
+ if (detail) {
314
350
  candidates.push({
315
- text: `[bug] command '${cmd}' failed: ${firstErrorLine.trim().slice(0, 150)}`,
351
+ text: `[bug] command '${cmdShort}' failed: ${detail}`,
316
352
  confidence: 0.55,
317
353
  explicit: false,
318
354
  });
@@ -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 });
@@ -3,6 +3,13 @@ interface FindingResult {
3
3
  message: string;
4
4
  data?: unknown;
5
5
  }
6
+ /**
7
+ * Prepend `[findingType]` to a finding only when the text doesn't already
8
+ * start with a bracketed tag. Prevents accumulation like `[pattern] [pattern] X`
9
+ * when callers pass both `findingType` and a finding that's already tagged
10
+ * (a common shape — many MCP callers prefix manually for human readability).
11
+ */
12
+ export declare function applyFindingTypePrefix(finding: string, findingType?: string): string;
6
13
  /**
7
14
  * Validate and add a single finding. Shared validation logic used by
8
15
  * both CLI `phren add-finding` and MCP `add_finding` tool.
@@ -2,6 +2,20 @@ import { isValidProjectName } from "../utils.js";
2
2
  import { addFindingToFile, } from "../shared/content.js";
3
3
  import { removeFinding as removeFindingStore, } from "../data/access.js";
4
4
  import { MAX_FINDING_LENGTH } from "../content/validate.js";
5
+ const FINDING_TAG_PREFIX_RE = /^\s*\[[^\]]+\]\s*/;
6
+ /**
7
+ * Prepend `[findingType]` to a finding only when the text doesn't already
8
+ * start with a bracketed tag. Prevents accumulation like `[pattern] [pattern] X`
9
+ * when callers pass both `findingType` and a finding that's already tagged
10
+ * (a common shape — many MCP callers prefix manually for human readability).
11
+ */
12
+ export function applyFindingTypePrefix(finding, findingType) {
13
+ if (!findingType)
14
+ return finding;
15
+ if (FINDING_TAG_PREFIX_RE.test(finding))
16
+ return finding;
17
+ return `[${findingType}] ${finding}`;
18
+ }
5
19
  /**
6
20
  * Validate and add a single finding. Shared validation logic used by
7
21
  * both CLI `phren add-finding` and MCP `add_finding` tool.
@@ -13,7 +27,7 @@ export function addFinding(phrenPath, project, finding, citation, findingType) {
13
27
  if (finding.length > MAX_FINDING_LENGTH) {
14
28
  return { ok: false, message: `Finding text exceeds ${MAX_FINDING_LENGTH} character limit.` };
15
29
  }
16
- const taggedFinding = findingType ? `[${findingType}] ${finding}` : finding;
30
+ const taggedFinding = applyFindingTypePrefix(finding, findingType);
17
31
  const result = addFindingToFile(phrenPath, project, taggedFinding, citation);
18
32
  if (!result.ok) {
19
33
  return { ok: false, message: result.error };
@@ -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,
@@ -19,10 +19,16 @@ function normalizePriority(text) {
19
19
  return m[1].toLowerCase();
20
20
  }
21
21
  function stripPriorityTag(text) {
22
- return text
23
- .replace(/\s*\[(high|medium|low)\](?=\s*(?:\[pinned\])?\s*$)/gi, "")
24
- .replace(/\s{2,}/g, " ")
25
- .trim();
22
+ // Strip ALL trailing priority tags (with optional [pinned] interleaved or at the end).
23
+ // Previous regex only stripped the last one and required [pinned] (if present) to be the
24
+ // final token — meaning accumulated `[high] [high] ... [pinned]` only lost one tag per
25
+ // call, so each updateTask grew the line by one tag (observed: 48× [high] on one task).
26
+ let prev;
27
+ do {
28
+ prev = text;
29
+ text = text.replace(/\s*\[(high|medium|low)\](?=\s*(?:\[pinned\])?\s*$)/gi, "");
30
+ } while (text !== prev);
31
+ return text.replace(/\s{2,}/g, " ").trim();
26
32
  }
27
33
  function detectPinned(text) {
28
34
  return /\[pinned\]/i.test(text);
@@ -172,7 +178,10 @@ export function resolveTaskFilePath(phrenPath, project) {
172
178
  return canonicalTaskFilePath(phrenPath, project);
173
179
  }
174
180
  function normalizeTaskItemLine(item) {
175
- let text = stripPinnedTag(item.line.replace(/\s*\[(high|medium|low)\]\s*$/gi, "")).trim();
181
+ // Strip pinned first so the priority strip can clear ALL trailing priority tags
182
+ // (otherwise [pinned] sat between accumulated [high]s and the end-anchor, leaking
183
+ // one tag per render — see stripPriorityTag for the pre-fix shape).
184
+ let text = stripPinnedTag(item.line).replace(/(\s*\[(high|medium|low)\])+\s*$/gi, "").trim();
176
185
  if (item.priority)
177
186
  text = `${text} [${item.priority}]`;
178
187
  if (item.pinned)
@@ -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
  }