@phren/cli 0.1.36 → 0.1.38

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.
package/README.md CHANGED
@@ -4,11 +4,12 @@ MCP server that indexes your personal phren and exposes it to AI agents via full
4
4
 
5
5
  On startup it walks your phren directory, reads all `.md` files, and builds an in-memory SQLite FTS5 index.
6
6
 
7
- Public surface: 54 MCP tools across 12 modules (search, tasks, findings, memory, data, graph, sessions, ops/review, skills, hooks, config, extraction).
7
+ Public surface: 59 MCP tools across 13 modules (search, tasks, findings, notes, memory, data, graph, sessions, ops/review, skills, hooks, config, extraction).
8
8
 
9
9
  Notable shipped capabilities:
10
10
  - finding lifecycle tools: `supersede_finding`, `retract_finding`, `resolve_contradiction`, `get_contradictions`
11
11
  - finding provenance: `add_finding.source` (`human|agent|hook|extract|consolidation|unknown`)
12
+ - lightweight daily notes: CRUD in `<project>/notes/YYYY-MM-DD.md`, explicit search, and promotion to findings without automatic prompt injection
12
13
  - cross-session continuity: task checkpoints + `session_history`
13
14
  - finding impact scoring from injected-context outcomes
14
15
  - skill registry behavior: scope precedence, alias-collision handling, visibility gating, generated `skill-manifest.json`
@@ -94,7 +95,7 @@ No parameters.
94
95
  5. Builds an in-memory SQLite FTS5 index with Porter stemming
95
96
  6. Serves tools over stdio using the MCP protocol
96
97
 
97
- File types are derived from filenames: `CLAUDE.md` -> "claude", `summary.md` -> "summary", `FINDINGS.md` -> "findings", `tasks.md` -> "task", files under `reference/` -> "reference", files under `skills/` -> "skill".
98
+ File types are derived from filenames and directories: `CLAUDE.md` -> "claude", `summary.md` -> "summary", `FINDINGS.md` -> "findings", `tasks.md` -> "task", files under `notes/` -> "notes", files under `reference/` -> "reference", files under `skills/` -> "skill".
98
99
 
99
100
  ## Development
100
101
 
package/dist/cli/hooks.js CHANGED
@@ -148,6 +148,9 @@ export async function handleHookPrompt() {
148
148
  const memoryTtlDays = Number.parseInt(process.env.PHREN_MEMORY_TTL_DAYS || String(policy.ttlDays), 10);
149
149
  const trustResult = applyTrustFilter(rows, Number.isNaN(memoryTtlDays) ? policy.ttlDays : memoryTtlDays, policy.minInjectConfidence, policy.decay, getPhrenPath());
150
150
  rows = trustResult.rows;
151
+ // Notes are intentionally available to explicit search, but are personal scratch
152
+ // context and should never be injected into an agent prompt automatically.
153
+ rows = rows.filter((row) => row.type !== "notes");
151
154
  stage.trustMs = Date.now() - tTrust0;
152
155
  if (!rows.length)
153
156
  process.exit(0);
@@ -0,0 +1 @@
1
+ export declare function handleNoteNamespace(args: string[], profile: string): Promise<void>;
@@ -0,0 +1,142 @@
1
+ import { getPhrenPath, FINDING_TYPES } from "../shared.js";
2
+ import { resolveProject } from "../store-routing.js";
3
+ import { addNote, editNote, listNotes, removeNote } from "../data/notes.js";
4
+ import { promoteNote } from "../core/note.js";
5
+ function usage() {
6
+ console.log("Usage:");
7
+ console.log(' phren note add <project> "<text>" [--date YYYY-MM-DD]');
8
+ console.log(" phren note list <project> [--date YYYY-MM-DD] [--limit N]");
9
+ console.log(' phren note edit <project> <nid> "<text>"');
10
+ console.log(" phren note remove <project> <nid>");
11
+ console.log(" phren note promote <project> <nid> [--type pattern]");
12
+ }
13
+ function option(args, name) {
14
+ const equal = args.find((arg) => arg.startsWith(`--${name}=`));
15
+ if (equal)
16
+ return equal.slice(name.length + 3);
17
+ const index = args.indexOf(`--${name}`);
18
+ return index >= 0 ? args[index + 1] : undefined;
19
+ }
20
+ function positionalAfter(args, start) {
21
+ const values = [];
22
+ for (let index = start; index < args.length; index++) {
23
+ const arg = args[index];
24
+ if (arg.startsWith("--")) {
25
+ if (!arg.includes("="))
26
+ index++;
27
+ continue;
28
+ }
29
+ values.push(arg);
30
+ }
31
+ return values;
32
+ }
33
+ function target(projectInput, profile) {
34
+ const resolved = resolveProject(getPhrenPath(), projectInput, profile);
35
+ if (resolved.store.role === "readonly")
36
+ throw new Error(`Store "${resolved.store.name}" is read-only.`);
37
+ return { phrenPath: resolved.store.path, project: resolved.projectName };
38
+ }
39
+ export async function handleNoteNamespace(args, profile) {
40
+ const subcommand = args[0];
41
+ if (!subcommand || subcommand === "--help" || subcommand === "-h") {
42
+ usage();
43
+ return;
44
+ }
45
+ const projectInput = args[1];
46
+ if (!projectInput) {
47
+ usage();
48
+ process.exitCode = 1;
49
+ return;
50
+ }
51
+ let resolved;
52
+ try {
53
+ resolved = target(projectInput, profile);
54
+ }
55
+ catch (err) {
56
+ console.error(err instanceof Error ? err.message : String(err));
57
+ process.exitCode = 1;
58
+ return;
59
+ }
60
+ const { phrenPath, project } = resolved;
61
+ if (subcommand === "list") {
62
+ const limitRaw = option(args, "limit");
63
+ const limit = limitRaw ? Number.parseInt(limitRaw, 10) : 100;
64
+ if (!Number.isFinite(limit) || limit < 1) {
65
+ console.error("--limit must be a positive integer.");
66
+ process.exitCode = 1;
67
+ return;
68
+ }
69
+ const result = listNotes(phrenPath, project, { date: option(args, "date"), limit });
70
+ if (!result.ok) {
71
+ console.error(result.error);
72
+ process.exitCode = 1;
73
+ return;
74
+ }
75
+ if (!result.data.length) {
76
+ console.log(`No notes found for "${project}".`);
77
+ return;
78
+ }
79
+ for (const note of result.data) {
80
+ console.log(`${note.date} ${note.time.slice(0, 5)} ${note.id}${note.promoted ? " [promoted]" : ""}`);
81
+ console.log(note.text.split("\n").map((line) => ` ${line}`).join("\n"));
82
+ }
83
+ return;
84
+ }
85
+ if (subcommand === "add") {
86
+ const text = positionalAfter(args, 2).join(" ");
87
+ const result = addNote(phrenPath, project, text, { date: option(args, "date") });
88
+ if (!result.ok) {
89
+ console.error(result.error);
90
+ process.exitCode = 1;
91
+ return;
92
+ }
93
+ console.log(`Note added: ${result.data.id} (${result.data.date})`);
94
+ return;
95
+ }
96
+ const note = args[2];
97
+ if (!note) {
98
+ usage();
99
+ process.exitCode = 1;
100
+ return;
101
+ }
102
+ if (subcommand === "edit") {
103
+ const text = positionalAfter(args, 3).join(" ");
104
+ const result = editNote(phrenPath, project, note, text);
105
+ if (!result.ok) {
106
+ console.error(result.error);
107
+ process.exitCode = 1;
108
+ return;
109
+ }
110
+ console.log(`Updated ${result.data.id}.`);
111
+ return;
112
+ }
113
+ if (subcommand === "remove") {
114
+ const result = removeNote(phrenPath, project, note);
115
+ if (!result.ok) {
116
+ console.error(result.error);
117
+ process.exitCode = 1;
118
+ return;
119
+ }
120
+ console.log(`Removed ${result.data.id}.`);
121
+ return;
122
+ }
123
+ if (subcommand === "promote") {
124
+ const typeRaw = option(args, "type");
125
+ if (typeRaw && !FINDING_TYPES.includes(typeRaw)) {
126
+ console.error(`Invalid finding type "${typeRaw}". Use: ${FINDING_TYPES.join(", ")}.`);
127
+ process.exitCode = 1;
128
+ return;
129
+ }
130
+ const result = promoteNote(phrenPath, project, note, typeRaw);
131
+ if (!result.ok) {
132
+ console.error(result.error);
133
+ process.exitCode = 1;
134
+ return;
135
+ }
136
+ console.log(`Promoted ${result.data.note.id} to a finding.`);
137
+ return;
138
+ }
139
+ console.error(`Unknown note subcommand: ${subcommand}`);
140
+ usage();
141
+ process.exitCode = 1;
142
+ }
@@ -3,7 +3,7 @@ import * as path from "path";
3
3
  import { execFileSync } from "child_process";
4
4
  import { getPhrenPath } from "../shared.js";
5
5
  import { isValidProjectName, errorMessage, getOptionValue } from "../utils.js";
6
- import { resolveAllStores, addStoreToRegistry, removeStoreFromRegistry, generateStoreId, readTeamBootstrap, } from "../store-registry.js";
6
+ import { resolveAllStores, addStoreToRegistry, removeStoreFromRegistry, generateStoreId, getStoreProjectDirs, readTeamBootstrap, } from "../store-registry.js";
7
7
  function printStoreUsage() {
8
8
  console.log("Usage:");
9
9
  console.log(" phren store list List registered stores");
@@ -18,8 +18,7 @@ function countStoreProjects(store) {
18
18
  if (!fs.existsSync(store.path))
19
19
  return 0;
20
20
  try {
21
- const storeRegistry = require("../store-registry.js");
22
- return storeRegistry.getStoreProjectDirs(store).length;
21
+ return getStoreProjectDirs(store).length;
23
22
  }
24
23
  catch {
25
24
  return 0;
@@ -2,6 +2,7 @@ export { handleSkillsNamespace, handleHooksNamespace, handleSkillList, handleDet
2
2
  export { handleProjectsNamespace } from "./namespaces-projects.js";
3
3
  export { handleTaskNamespace } from "./namespaces-tasks.js";
4
4
  export { handleFindingNamespace } from "./namespaces-findings.js";
5
+ export { handleNoteNamespace } from "./namespaces-notes.js";
5
6
  export { handleStoreNamespace, handlePromoteNamespace } from "./namespaces-store.js";
6
7
  export { handleProfileNamespace } from "./namespaces-profile.js";
7
8
  export { handleReviewNamespace } from "./namespaces-review.js";
@@ -3,6 +3,7 @@ export { handleSkillsNamespace, handleHooksNamespace, handleSkillList, handleDet
3
3
  export { handleProjectsNamespace } from "./namespaces-projects.js";
4
4
  export { handleTaskNamespace } from "./namespaces-tasks.js";
5
5
  export { handleFindingNamespace } from "./namespaces-findings.js";
6
+ export { handleNoteNamespace } from "./namespaces-notes.js";
6
7
  export { handleStoreNamespace, handlePromoteNamespace } from "./namespaces-store.js";
7
8
  export { handleProfileNamespace } from "./namespaces-profile.js";
8
9
  export { handleReviewNamespace } from "./namespaces-review.js";
@@ -27,7 +27,7 @@ export declare function runBestEffortGit(args: string[], cwd: string): Promise<{
27
27
  * list (notably `.runtime/`, secrets, build output) is skipped on session-stop
28
28
  * and `push_changes`.
29
29
  */
30
- export declare const TEAM_STORE_PATHSPECS: readonly ["*/journal/*", "*/tasks.md", "*/truths.md", "*/FINDINGS.md", "*/FINDINGS.md.bak", "*/summary.md", "*/review.md", "*/CLAUDE.md", "*/topic-config.json", "*/phren.project.yaml", "*/reference/**", "*/skills/**", ".phren-team.yaml"];
30
+ export declare const TEAM_STORE_PATHSPECS: readonly ["*/journal/*", "*/tasks.md", "*/truths.md", "*/FINDINGS.md", "*/FINDINGS.md.bak", "*/summary.md", "*/review.md", "*/CLAUDE.md", "*/topic-config.json", "*/phren.project.yaml", "*/reference/**", "*/skills/**", "*/notes/**", ".phren-team.yaml"];
31
31
  /**
32
32
  * Stage each team pathspec individually so a single no-match (e.g. a store
33
33
  * with no `truths.md` anywhere) doesn't abort the entire `git add` and strand
@@ -139,6 +139,7 @@ export const TEAM_STORE_PATHSPECS = [
139
139
  "*/phren.project.yaml",
140
140
  "*/reference/**",
141
141
  "*/skills/**",
142
+ "*/notes/**",
142
143
  ".phren-team.yaml",
143
144
  ];
144
145
  /**
@@ -304,6 +304,25 @@ export const REGISTRY = [
304
304
  await handleFindingNamespace(args);
305
305
  },
306
306
  },
307
+ {
308
+ name: "note",
309
+ aliases: ["notes"],
310
+ topic: "core",
311
+ usage: "phren note <add|list|edit|remove|promote>",
312
+ summary: "Manage lightweight daily notes",
313
+ subcommands: [
314
+ { name: "add", usage: 'phren note add <project> "<text>" [--date YYYY-MM-DD]', summary: "Add a daily note" },
315
+ { name: "list", usage: "phren note list <project> [--date YYYY-MM-DD]", summary: "List notes" },
316
+ { name: "edit", usage: 'phren note edit <project> <nid> "<text>"', summary: "Edit a note" },
317
+ { name: "remove", usage: "phren note remove <project> <nid>", summary: "Remove a note" },
318
+ { name: "promote", usage: "phren note promote <project> <nid> [--type <type>]", summary: "Promote a note to a finding" },
319
+ ],
320
+ featured: true,
321
+ run: async (args, ctx) => {
322
+ const { handleNoteNamespace } = await import("./cli/namespaces.js");
323
+ await handleNoteNamespace(args, ctx.profile());
324
+ },
325
+ },
307
326
  {
308
327
  name: "search-fragments",
309
328
  topic: "core",
@@ -0,0 +1,9 @@
1
+ import type { FindingType, PhrenResult } from "../shared.js";
2
+ import { type NoteItem } from "../data/notes.js";
3
+ export interface PromoteNoteResult {
4
+ note: NoteItem;
5
+ finding: string;
6
+ message: string;
7
+ }
8
+ /** Copy a note into durable findings while retaining and marking its daily-note source. */
9
+ export declare function promoteNote(phrenPath: string, project: string, selector: string, findingType?: FindingType): PhrenResult<PromoteNoteResult>;
@@ -0,0 +1,20 @@
1
+ import { forwardErr, phrenErr, phrenOk, PhrenError } from "../shared.js";
2
+ import { addFinding, applyFindingTypePrefix } from "./finding.js";
3
+ import { getNote, markNotePromoted } from "../data/notes.js";
4
+ /** Copy a note into durable findings while retaining and marking its daily-note source. */
5
+ export function promoteNote(phrenPath, project, selector, findingType) {
6
+ const found = getNote(phrenPath, project, selector);
7
+ if (!found.ok)
8
+ return forwardErr(found);
9
+ if (found.data.promoted) {
10
+ return phrenErr(`Note ${found.data.id} has already been promoted.`, PhrenError.VALIDATION_ERROR);
11
+ }
12
+ const added = addFinding(phrenPath, project, found.data.text, undefined, findingType);
13
+ if (!added.ok)
14
+ return phrenErr(added.message, PhrenError.VALIDATION_ERROR);
15
+ const marked = markNotePromoted(phrenPath, project, found.data.stableId);
16
+ if (!marked.ok)
17
+ return forwardErr(marked);
18
+ const finding = applyFindingTypePrefix(found.data.text, findingType);
19
+ return phrenOk({ note: marked.data, finding, message: added.message });
20
+ }
@@ -0,0 +1,28 @@
1
+ import { type PhrenResult } from "../shared.js";
2
+ export declare const NOTES_DIRNAME = "notes";
3
+ export declare const MAX_NOTE_LENGTH = 10000;
4
+ export interface NoteItem {
5
+ id: string;
6
+ stableId: string;
7
+ project: string;
8
+ date: string;
9
+ time: string;
10
+ text: string;
11
+ promoted: boolean;
12
+ path: string;
13
+ }
14
+ export interface ListNotesOptions {
15
+ date?: string;
16
+ limit?: number;
17
+ }
18
+ export interface AddNoteOptions {
19
+ date?: string;
20
+ now?: Date;
21
+ }
22
+ export declare function noteFilePath(phrenPath: string, project: string, date: string): PhrenResult<string>;
23
+ export declare function listNotes(phrenPath: string, project: string, options?: ListNotesOptions): PhrenResult<NoteItem[]>;
24
+ export declare function getNote(phrenPath: string, project: string, selector: string): PhrenResult<NoteItem>;
25
+ export declare function addNote(phrenPath: string, project: string, text: string, options?: AddNoteOptions): PhrenResult<NoteItem>;
26
+ export declare function editNote(phrenPath: string, project: string, selector: string, text: string): PhrenResult<NoteItem>;
27
+ export declare function removeNote(phrenPath: string, project: string, selector: string): PhrenResult<NoteItem>;
28
+ export declare function markNotePromoted(phrenPath: string, project: string, selector: string): PhrenResult<NoteItem>;
@@ -0,0 +1,193 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import { randomBytes } from "crypto";
4
+ import { PhrenError, forwardErr, phrenErr, phrenOk, } from "../shared.js";
5
+ import { scanForSecrets } from "../content/dedup.js";
6
+ import { atomicWriteText } from "../phren-paths.js";
7
+ import { ensureProject, withSafeLock } from "../shared/data-utils.js";
8
+ export const NOTES_DIRNAME = "notes";
9
+ export const MAX_NOTE_LENGTH = 10_000;
10
+ const NOTE_HEADING_RE = /^##\s+(\d{2}:\d{2}(?::\d{2})?)\s+<!--\s*nid:([a-f0-9]{8})\s*-->(?:\s+<!--\s*promoted\s*-->)?\s*$/i;
11
+ function isValidDate(value) {
12
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value))
13
+ return false;
14
+ const date = new Date(`${value}T00:00:00.000Z`);
15
+ return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value;
16
+ }
17
+ function notesDirectory(projectDir) {
18
+ return path.join(projectDir, NOTES_DIRNAME);
19
+ }
20
+ export function noteFilePath(phrenPath, project, date) {
21
+ if (!isValidDate(date)) {
22
+ return phrenErr(`Invalid note date "${date}". Use YYYY-MM-DD.`, PhrenError.VALIDATION_ERROR);
23
+ }
24
+ const ensured = ensureProject(phrenPath, project);
25
+ if (!ensured.ok)
26
+ return forwardErr(ensured);
27
+ return phrenOk(path.join(notesDirectory(ensured.data), `${date}.md`));
28
+ }
29
+ function normalizeNoteText(text) {
30
+ const normalized = text.replace(/\r\n?/g, "\n").trim();
31
+ if (!normalized)
32
+ return phrenErr("Note text cannot be empty.", PhrenError.EMPTY_INPUT);
33
+ if (normalized.length > MAX_NOTE_LENGTH) {
34
+ return phrenErr(`Note text exceeds ${MAX_NOTE_LENGTH} characters.`, PhrenError.VALIDATION_ERROR);
35
+ }
36
+ const secret = scanForSecrets(normalized);
37
+ if (secret) {
38
+ return phrenErr(`Rejected: note appears to contain a secret (${secret}). Strip credentials before saving.`, PhrenError.VALIDATION_ERROR);
39
+ }
40
+ // An exact internal heading inside a note would otherwise be parsed as a new note.
41
+ return phrenOk(normalized.split("\n").map((line) => NOTE_HEADING_RE.test(line) ? `#${line}` : line).join("\n"));
42
+ }
43
+ function parseDailyFile(filePath, project, date) {
44
+ if (!fs.existsSync(filePath))
45
+ return [];
46
+ const lines = fs.readFileSync(filePath, "utf8").split("\n");
47
+ const items = [];
48
+ let current = null;
49
+ const finish = () => {
50
+ if (!current)
51
+ return;
52
+ const text = current.body.join("\n").trim();
53
+ if (text) {
54
+ items.push({
55
+ id: `nid:${current.stableId}`,
56
+ stableId: current.stableId,
57
+ project,
58
+ date,
59
+ time: current.time.length === 5 ? `${current.time}:00` : current.time,
60
+ text,
61
+ promoted: current.promoted,
62
+ path: filePath,
63
+ });
64
+ }
65
+ };
66
+ for (const line of lines) {
67
+ const match = line.match(NOTE_HEADING_RE);
68
+ if (match) {
69
+ finish();
70
+ current = {
71
+ time: match[1],
72
+ stableId: match[2].toLowerCase(),
73
+ promoted: /<!--\s*promoted\s*-->/i.test(line),
74
+ body: [],
75
+ };
76
+ }
77
+ else if (current) {
78
+ current.body.push(line);
79
+ }
80
+ }
81
+ finish();
82
+ return items;
83
+ }
84
+ function renderDailyFile(project, date, notes) {
85
+ const entries = notes.map((note) => {
86
+ const promoted = note.promoted ? " <!-- promoted -->" : "";
87
+ return `## ${note.time} <!-- nid:${note.stableId} -->${promoted}\n\n${note.text}`;
88
+ });
89
+ return `# ${project} Notes — ${date}\n${entries.length ? `\n${entries.join("\n\n")}\n` : ""}`;
90
+ }
91
+ function selectorMatches(note, selector) {
92
+ const query = selector.trim().toLowerCase();
93
+ if (!query)
94
+ return false;
95
+ const stable = query.startsWith("nid:") ? query.slice(4) : query;
96
+ return note.stableId === stable || note.id === query || note.text.toLowerCase() === query || note.text.toLowerCase().includes(query);
97
+ }
98
+ function resolveNote(notes, selector) {
99
+ const matches = notes.filter((note) => selectorMatches(note, selector));
100
+ if (matches.length === 0)
101
+ return phrenErr(`No note matching "${selector}" was found.`, PhrenError.NOT_FOUND);
102
+ if (matches.length > 1) {
103
+ return phrenErr(`Multiple notes match "${selector}". Use a stable nid: ${matches.map((note) => note.id).join(", ")}.`, PhrenError.AMBIGUOUS_MATCH);
104
+ }
105
+ return phrenOk(matches[0]);
106
+ }
107
+ export function listNotes(phrenPath, project, options = {}) {
108
+ const ensured = ensureProject(phrenPath, project);
109
+ if (!ensured.ok)
110
+ return forwardErr(ensured);
111
+ if (options.date && !isValidDate(options.date)) {
112
+ return phrenErr(`Invalid note date "${options.date}". Use YYYY-MM-DD.`, PhrenError.VALIDATION_ERROR);
113
+ }
114
+ const dir = notesDirectory(ensured.data);
115
+ if (!fs.existsSync(dir))
116
+ return phrenOk([]);
117
+ const files = fs.readdirSync(dir)
118
+ .filter((name) => /^\d{4}-\d{2}-\d{2}\.md$/.test(name))
119
+ .filter((name) => !options.date || name === `${options.date}.md`)
120
+ .sort((a, b) => b.localeCompare(a));
121
+ const notes = files.flatMap((name) => parseDailyFile(path.join(dir, name), project, name.slice(0, 10)))
122
+ .sort((a, b) => `${b.date}T${b.time}`.localeCompare(`${a.date}T${a.time}`));
123
+ const limit = options.limit === undefined ? notes.length : Math.max(0, Math.floor(options.limit));
124
+ return phrenOk(notes.slice(0, limit));
125
+ }
126
+ export function getNote(phrenPath, project, selector) {
127
+ const notes = listNotes(phrenPath, project);
128
+ if (!notes.ok)
129
+ return forwardErr(notes);
130
+ return resolveNote(notes.data, selector);
131
+ }
132
+ export function addNote(phrenPath, project, text, options = {}) {
133
+ const normalized = normalizeNoteText(text);
134
+ if (!normalized.ok)
135
+ return forwardErr(normalized);
136
+ const now = options.now ?? new Date();
137
+ if (!Number.isFinite(now.getTime()))
138
+ return phrenErr("Invalid note timestamp.", PhrenError.VALIDATION_ERROR);
139
+ const date = options.date ?? now.toISOString().slice(0, 10);
140
+ const file = noteFilePath(phrenPath, project, date);
141
+ if (!file.ok)
142
+ return forwardErr(file);
143
+ return withSafeLock(file.data, () => {
144
+ const existing = parseDailyFile(file.data, project, date);
145
+ let stableId = randomBytes(4).toString("hex");
146
+ while (existing.some((note) => note.stableId === stableId))
147
+ stableId = randomBytes(4).toString("hex");
148
+ const note = {
149
+ id: `nid:${stableId}`,
150
+ stableId,
151
+ project,
152
+ date,
153
+ time: now.toISOString().slice(11, 19),
154
+ text: normalized.data,
155
+ promoted: false,
156
+ path: file.data,
157
+ };
158
+ atomicWriteText(file.data, renderDailyFile(project, date, [...existing, note]));
159
+ return phrenOk(note);
160
+ });
161
+ }
162
+ function mutateNote(phrenPath, project, selector, mutate) {
163
+ const found = getNote(phrenPath, project, selector);
164
+ if (!found.ok)
165
+ return forwardErr(found);
166
+ return withSafeLock(found.data.path, () => {
167
+ const notes = parseDailyFile(found.data.path, project, found.data.date);
168
+ const current = resolveNote(notes, found.data.stableId);
169
+ if (!current.ok)
170
+ return forwardErr(current);
171
+ const updated = mutate(current.data);
172
+ const next = updated
173
+ ? notes.map((note) => note.stableId === current.data.stableId ? updated : note)
174
+ : notes.filter((note) => note.stableId !== current.data.stableId);
175
+ if (next.length === 0)
176
+ fs.unlinkSync(found.data.path);
177
+ else
178
+ atomicWriteText(found.data.path, renderDailyFile(project, found.data.date, next));
179
+ return phrenOk(updated ?? current.data);
180
+ });
181
+ }
182
+ export function editNote(phrenPath, project, selector, text) {
183
+ const normalized = normalizeNoteText(text);
184
+ if (!normalized.ok)
185
+ return forwardErr(normalized);
186
+ return mutateNote(phrenPath, project, selector, (note) => ({ ...note, text: normalized.data }));
187
+ }
188
+ export function removeNote(phrenPath, project, selector) {
189
+ return mutateNote(phrenPath, project, selector, () => null);
190
+ }
191
+ export function markNotePromoted(phrenPath, project, selector) {
192
+ return mutateNote(phrenPath, project, selector, (note) => ({ ...note, promoted: true }));
193
+ }