@phren/cli 0.3.63 → 0.3.65

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.
@@ -477,10 +477,12 @@ async function startSession(server, data, options) {
477
477
  // mkdtemp keeps simultaneous chats with the same title isolated.
478
478
  let scratch;
479
479
  if (agentFolder) {
480
- const store = await realpath(defaultPhrenPath());
481
480
  // Runtime folders are excluded from project discovery and store sync.
481
+ // Created before resolving the store: it may not exist yet, on a
482
+ // computer without one or before the Hook's own startup made it.
483
+ await mkdir(path.join(defaultPhrenPath(), ".runtime"), { recursive: true, mode: 0o700 });
484
+ const store = await realpath(defaultPhrenPath());
482
485
  const runtime = path.join(store, ".runtime");
483
- await mkdir(runtime, { recursive: true, mode: 0o700 });
484
486
  if (await realpath(runtime) !== runtime)
485
487
  throw new BridgeError(403, "The runtime folder must be inside the Phren directory.");
486
488
  const agents = path.join(runtime, "agents");
@@ -151,6 +151,13 @@ export declare function claudeOAuthUsage(value: unknown, now?: Date): AccountUsa
151
151
  * own file, and nothing on macOS (its keychain item name is unverified).
152
152
  */
153
153
  export declare function readClaudeToken(execSecurity?: typeof execFile.__promisify__, platform?: NodeJS.Platform, home?: ClaudeHome): Promise<string | undefined>;
154
+ /**
155
+ * Two Claude homes signed in to one login are one allowance, and phones refuse
156
+ * an answer with two rows of one key: one row each, in the first home's place
157
+ * and under its name (the default home comes first), carrying the freshest
158
+ * report any of those homes has. Account choice reads `limits()` per home.
159
+ */
160
+ export declare function oneRowPerLogin(rows: AccountUsage[]): AccountUsage[];
154
161
  /** Fetch live limits; any failure falls back to the local snapshot. */
155
162
  export declare function fetchClaudeUsage(token: string, fetchImpl?: typeof fetch, now?: Date): Promise<AccountUsage>;
156
163
  /** Only initialize and read limits. Never create a thread, prompt, or login. */
@@ -540,6 +540,23 @@ export async function readClaudeToken(execSecurity = exec, platform = process.pl
540
540
  return undefined;
541
541
  }
542
542
  }
543
+ /**
544
+ * Two Claude homes signed in to one login are one allowance, and phones refuse
545
+ * an answer with two rows of one key: one row each, in the first home's place
546
+ * and under its name (the default home comes first), carrying the freshest
547
+ * report any of those homes has. Account choice reads `limits()` per home.
548
+ */
549
+ export function oneRowPerLogin(rows) {
550
+ const at = (row) => row.windows.length ? Date.parse(row.updatedAt ?? "") || 0 : -1;
551
+ const best = new Map();
552
+ for (const row of rows) {
553
+ const key = row.account?.key;
554
+ if (key && (!best.has(key) || at(row) > at(best.get(key))))
555
+ best.set(key, row);
556
+ }
557
+ return rows.filter(row => !row.account?.key || rows.find(other => other.account?.key === row.account.key) === row)
558
+ .map(row => row.account?.key ? { ...best.get(row.account.key), account: row.account } : row);
559
+ }
543
560
  /** Fetch live limits; any failure falls back to the local snapshot. */
544
561
  export async function fetchClaudeUsage(token, fetchImpl = fetch, now = new Date()) {
545
562
  const controller = new AbortController();
@@ -817,7 +834,7 @@ export class AccountUsageReader {
817
834
  async read(sources, allAccounts = false) {
818
835
  const [limits, spending] = await Promise.all([this.limits(allAccounts),
819
836
  this.spending(sources?.has("copilot") ?? true, sources?.has("elevenlabs") ?? true)]);
820
- return { accounts: [...limits, ...spending] };
837
+ return { accounts: [...oneRowPerLogin(limits), ...spending] };
821
838
  }
822
839
  /** Codex and every Claude home, without the spend readers: what a dispatch capacity probe asks. */
823
840
  async limits(allAccounts = true) {
@@ -24856,6 +24856,7 @@ __export(phren_paths_exports, {
24856
24856
  projectSlugFromPath: () => projectSlugFromPath,
24857
24857
  qualityMarkers: () => qualityMarkers,
24858
24858
  readRootManifest: () => readRootManifest,
24859
+ renameOverSync: () => renameOverSync,
24859
24860
  resolveFindingsPath: () => resolveFindingsPath,
24860
24861
  resolveInstallContext: () => resolveInstallContext,
24861
24862
  rootManifestPath: () => rootManifestPath,
@@ -24894,13 +24895,31 @@ function defaultPhrenPath() {
24894
24895
  function rootManifestPath(phrenPath) {
24895
24896
  return path9.join(phrenPath, ROOT_MANIFEST_FILENAME);
24896
24897
  }
24898
+ function renameOverSync(from, to) {
24899
+ const waiter = new Int32Array(new SharedArrayBuffer(4));
24900
+ for (let attempt = 0; ; attempt++) {
24901
+ try {
24902
+ return fs7.renameSync(from, to);
24903
+ } catch (error62) {
24904
+ const code = error62.code ?? "";
24905
+ if (process.platform !== "win32" || attempt >= 20 || !["EPERM", "EACCES", "EBUSY"].includes(code)) {
24906
+ try {
24907
+ fs7.unlinkSync(from);
24908
+ } catch {
24909
+ }
24910
+ throw error62;
24911
+ }
24912
+ Atomics.wait(waiter, 0, 0, 5 * (attempt + 1));
24913
+ }
24914
+ }
24915
+ }
24897
24916
  function atomicWriteText(filePath, content, opts = {}) {
24898
24917
  fs7.mkdirSync(path9.dirname(filePath), { recursive: true });
24899
24918
  const tmpPath = `${filePath}.tmp-${crypto2.randomUUID()}`;
24900
24919
  fs7.writeFileSync(tmpPath, content, opts.mode !== void 0 ? { mode: opts.mode } : void 0);
24901
24920
  try {
24902
24921
  if (opts.mode !== void 0 && process.platform !== "win32") fs7.chmodSync(tmpPath, opts.mode);
24903
- fs7.renameSync(tmpPath, filePath);
24922
+ renameOverSync(tmpPath, filePath);
24904
24923
  } catch (err) {
24905
24924
  try {
24906
24925
  fs7.unlinkSync(tmpPath);
@@ -25526,6 +25545,7 @@ function tryFileLock(filePath) {
25526
25545
  ${Date.now()}
25527
25546
  ${Math.random()}`;
25528
25547
  fs9.mkdirSync(path11.dirname(lockPath), { recursive: true });
25548
+ let refusedWithoutFile = 0;
25529
25549
  for (let attempt = 0; attempt < 2; attempt++) {
25530
25550
  try {
25531
25551
  fs9.writeFileSync(lockPath, owner2, { flag: "wx", mode: 384 });
@@ -25545,6 +25565,10 @@ ${Math.random()}`;
25545
25565
  present2 = statErr.code !== "ENOENT";
25546
25566
  }
25547
25567
  if (present2) return null;
25568
+ if (++refusedWithoutFile < 5) {
25569
+ attempt--;
25570
+ continue;
25571
+ }
25548
25572
  throw err;
25549
25573
  }
25550
25574
  if (code !== "EEXIST") throw err;
@@ -37414,7 +37438,7 @@ var init_package_metadata = __esm({
37414
37438
  __dirname = path35.dirname(fileURLToPath2(import.meta.url));
37415
37439
  ROOT = path35.join(__dirname, "..");
37416
37440
  PACKAGE_JSON_PATH = path35.join(ROOT, "package.json");
37417
- BUNDLED_VERSION = true ? "0.3.63" : "0.0.0";
37441
+ BUNDLED_VERSION = true ? "0.3.65" : "0.0.0";
37418
37442
  PACKAGE_JSON = readPackageJson();
37419
37443
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
37420
37444
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -39167,7 +39191,7 @@ function appendArchivedEntriesToTopicDoc(filePath, project, topic, entries2) {
39167
39191
  }
39168
39192
  const tmpPath = `${filePath}.tmp-${crypto6.randomUUID()}`;
39169
39193
  fs22.writeFileSync(tmpPath, existing.trimEnd() + "\n\n" + sections.join("\n"));
39170
- fs22.renameSync(tmpPath, filePath);
39194
+ renameOverSync(tmpPath, filePath);
39171
39195
  });
39172
39196
  }
39173
39197
  function readReferenceMarkdownFiles(referenceDir) {
@@ -39186,6 +39210,7 @@ var TOPIC_CONFIG_FILENAME, SOFTWARE_TOPICS, DOMAIN_TOPICS, GENERAL_TOPIC, DEFAUL
39186
39210
  var init_project_topics = __esm({
39187
39211
  "src/project-topics.ts"() {
39188
39212
  "use strict";
39213
+ init_phren_paths();
39189
39214
  init_shared();
39190
39215
  init_locks();
39191
39216
  init_utils();
@@ -39674,7 +39699,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
39674
39699
  }
39675
39700
  const tmpPath = learningsPath + `.tmp-${crypto7.randomUUID()}`;
39676
39701
  fs23.writeFileSync(tmpPath, cleaned.join("\n"));
39677
- fs23.renameSync(tmpPath, learningsPath);
39702
+ renameOverSync(tmpPath, learningsPath);
39678
39703
  const skippedCount = alreadyArchivedEntries.length;
39679
39704
  const failedTopics = [...byTopic.keys()].filter((t) => !successfulTopics.has(t));
39680
39705
  appendAuditLog(
@@ -39695,6 +39720,7 @@ function autoArchiveToReference(phrenPath, project, keepCount) {
39695
39720
  var init_archive = __esm({
39696
39721
  "src/content/archive.ts"() {
39697
39722
  "use strict";
39723
+ init_phren_paths();
39698
39724
  init_shared();
39699
39725
  init_utils();
39700
39726
  init_store_routing();
@@ -39970,6 +39996,7 @@ var init_validate = __esm({
39970
39996
  "src/content/validate.ts"() {
39971
39997
  "use strict";
39972
39998
  init_utils_helpers();
39999
+ init_phren_paths();
39973
40000
  init_shared();
39974
40001
  init_utils();
39975
40002
  init_archive();
@@ -40632,7 +40659,7 @@ var init_task_format = __esm({
40632
40659
  // src/bridge/memory-store.ts
40633
40660
  import { execFile as execFile6, spawn as spawn3 } from "node:child_process";
40634
40661
  import { createHash as createHash13 } from "node:crypto";
40635
- import { mkdirSync as mkdirSync14, readFileSync as readFileSync27, renameSync as renameSync9, unlinkSync as unlinkSync6, writeFileSync as writeFileSync15 } from "node:fs";
40662
+ import { mkdirSync as mkdirSync14, readFileSync as readFileSync27, renameSync as renameSync7, unlinkSync as unlinkSync6, writeFileSync as writeFileSync15 } from "node:fs";
40636
40663
  import { lstat as lstat7, mkdir as mkdir11, realpath as realpath7 } from "node:fs/promises";
40637
40664
  import path47 from "node:path";
40638
40665
  import { promisify as promisify5 } from "node:util";
@@ -40837,7 +40864,7 @@ function putStoreFile(store, data) {
40837
40864
  mkdirSync14(path47.dirname(file4), { recursive: true });
40838
40865
  const temporary = `${file4}.phren-${process.pid}-${Date.now()}`;
40839
40866
  writeFileSync15(temporary, content, { flag: "wx" });
40840
- renameSync9(temporary, file4);
40867
+ renameSync7(temporary, file4);
40841
40868
  });
40842
40869
  return { content: { sha: blobSha(content), path: input2.path }, commit: { sha: blobSha(content) } };
40843
40870
  });
@@ -41394,7 +41421,7 @@ function writeTaskDoc(doc) {
41394
41421
  const tmpPath = `${doc.path}.tmp-${randomUUID12()}`;
41395
41422
  const content = renderTask(doc);
41396
41423
  fs28.writeFileSync(tmpPath, content);
41397
- fs28.renameSync(tmpPath, doc.path);
41424
+ renameOverSync(tmpPath, doc.path);
41398
41425
  recordTaskWrite(doc.path, content);
41399
41426
  }
41400
41427
  function readTasks(phrenPath, project) {
@@ -41656,6 +41683,7 @@ var init_tasks = __esm({
41656
41683
  init_task_format();
41657
41684
  init_runtime();
41658
41685
  init_registry();
41686
+ init_phren_paths();
41659
41687
  init_shared();
41660
41688
  init_content();
41661
41689
  init_data_utils();
@@ -42071,7 +42099,7 @@ ${preparedForNewFile.finding.citationComment}
42071
42099
  `;
42072
42100
  const tmpPath2 = learningsPath + `.tmp-${crypto9.randomUUID()}`;
42073
42101
  fs31.writeFileSync(tmpPath2, newContent);
42074
- fs31.renameSync(tmpPath2, learningsPath);
42102
+ renameOverSync(tmpPath2, learningsPath);
42075
42103
  return phrenOk({
42076
42104
  content: newContent,
42077
42105
  citation: buildFindingCitation(resolvedCitationInput, nowIso, inferredRepo, headCommit),
@@ -42140,7 +42168,7 @@ ${preparedForNewFile.finding.citationComment}
42140
42168
  }
42141
42169
  const tmpPath = learningsPath + `.tmp-${crypto9.randomUUID()}`;
42142
42170
  fs31.writeFileSync(tmpPath, updated);
42143
- fs31.renameSync(tmpPath, learningsPath);
42171
+ renameOverSync(tmpPath, learningsPath);
42144
42172
  return phrenOk({
42145
42173
  content: updated,
42146
42174
  citation: buildFindingCitation(resolvedCitationInput, nowIso, inferredRepo, headCommit),
@@ -42249,7 +42277,7 @@ function addFindingsToFile(phrenPath, project, learnings, opts) {
42249
42277
  const tmpPath = learningsPath + `.tmp-${crypto9.randomUUID()}`;
42250
42278
  fs31.writeFileSync(tmpPath, content2.endsWith("\n") ? content2 : `${content2}
42251
42279
  `);
42252
- fs31.renameSync(tmpPath, learningsPath);
42280
+ renameOverSync(tmpPath, learningsPath);
42253
42281
  }
42254
42282
  return phrenOk({ content: content2, wrote: added.length > 0 });
42255
42283
  }
@@ -42290,7 +42318,7 @@ function addFindingsToFile(phrenPath, project, learnings, opts) {
42290
42318
  if (added.length > 0) {
42291
42319
  const tmpPath = learningsPath + `.tmp-${crypto9.randomUUID()}`;
42292
42320
  fs31.writeFileSync(tmpPath, content);
42293
- fs31.renameSync(tmpPath, learningsPath);
42321
+ renameOverSync(tmpPath, learningsPath);
42294
42322
  }
42295
42323
  return phrenOk({ content, wrote: added.length > 0 });
42296
42324
  });
@@ -42311,6 +42339,7 @@ var DEFAULT_FINDINGS_CAP, LIFECYCLE_ANNOTATION_RE;
42311
42339
  var init_learning = __esm({
42312
42340
  "src/content/learning.ts"() {
42313
42341
  "use strict";
42342
+ init_phren_paths();
42314
42343
  init_shared();
42315
42344
  init_shared();
42316
42345
  init_governance();
@@ -42563,7 +42592,7 @@ function removeFinding(phrenPath, project, match, opts = {}) {
42563
42592
  const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
42564
42593
  const tmp = filePath + ".tmp." + process.pid;
42565
42594
  fs32.writeFileSync(tmp, normalized);
42566
- fs32.renameSync(tmp, filePath);
42595
+ renameOverSync(tmp, filePath);
42567
42596
  return phrenOk(`Removed from ${project}: ${matched}`);
42568
42597
  });
42569
42598
  }
@@ -42602,7 +42631,7 @@ function editFinding(phrenPath, project, oldText, newText) {
42602
42631
  const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
42603
42632
  const tmp = findingsPath + ".tmp." + process.pid;
42604
42633
  fs32.writeFileSync(tmp, normalized);
42605
- fs32.renameSync(tmp, findingsPath);
42634
+ renameOverSync(tmp, findingsPath);
42606
42635
  return phrenOk(`Updated finding in ${project}`);
42607
42636
  });
42608
42637
  }
@@ -42610,6 +42639,7 @@ var withoutTypeTag;
42610
42639
  var init_access = __esm({
42611
42640
  "src/data/access.ts"() {
42612
42641
  "use strict";
42642
+ init_phren_paths();
42613
42643
  init_js_yaml();
42614
42644
  init_phren_core();
42615
42645
  init_shared();
@@ -42818,7 +42848,7 @@ function supersedeFinding(phrenPath, project, findingText, supersededBy) {
42818
42848
  const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
42819
42849
  const tmpPath = findingsPath + ".tmp." + process.pid;
42820
42850
  fs33.writeFileSync(tmpPath, normalized);
42821
- fs33.renameSync(tmpPath, findingsPath);
42851
+ renameOverSync(tmpPath, findingsPath);
42822
42852
  return phrenOk({ finding: matched.data.text, superseded_by: ref, status: "superseded" });
42823
42853
  });
42824
42854
  }
@@ -42841,7 +42871,7 @@ function retractFinding(phrenPath, project, findingText, reason3) {
42841
42871
  const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
42842
42872
  const tmpPath = findingsPath + ".tmp." + process.pid;
42843
42873
  fs33.writeFileSync(tmpPath, normalized);
42844
- fs33.renameSync(tmpPath, findingsPath);
42874
+ renameOverSync(tmpPath, findingsPath);
42845
42875
  return phrenOk({ finding: matched.data.text, reason: reasonText, status: "retracted" });
42846
42876
  });
42847
42877
  }
@@ -42897,7 +42927,7 @@ function resolveFindingContradiction(phrenPath, project, findingA, findingB, res
42897
42927
  const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
42898
42928
  const tmpPath = findingsPath + ".tmp." + process.pid;
42899
42929
  fs33.writeFileSync(tmpPath, normalized);
42900
- fs33.renameSync(tmpPath, findingsPath);
42930
+ renameOverSync(tmpPath, findingsPath);
42901
42931
  return phrenOk({
42902
42932
  resolution,
42903
42933
  finding_a: { text: matchedA.data.text, status: statusA },
@@ -42909,6 +42939,7 @@ var LIFECYCLE_PREFIX, FINDING_TYPE_DECAY;
42909
42939
  var init_lifecycle = __esm({
42910
42940
  "src/finding/lifecycle.ts"() {
42911
42941
  "use strict";
42942
+ init_phren_paths();
42912
42943
  init_phren_core();
42913
42944
  init_governance();
42914
42945
  init_utils();
@@ -43737,7 +43768,7 @@ var init_computer_names = __esm({
43737
43768
  // src/bridge/schedule-format.ts
43738
43769
  import { randomBytes as randomBytes4 } from "node:crypto";
43739
43770
  import { readFile as readFile18 } from "node:fs/promises";
43740
- import { mkdirSync as mkdirSync18, readFileSync as readFileSync36, renameSync as renameSync15, unlinkSync as unlinkSync7, writeFileSync as writeFileSync21 } from "node:fs";
43771
+ import { mkdirSync as mkdirSync18, readFileSync as readFileSync36, renameSync as renameSync9, unlinkSync as unlinkSync7, writeFileSync as writeFileSync21 } from "node:fs";
43741
43772
  import path59 from "node:path";
43742
43773
  function validateLocalTimestamp(value2) {
43743
43774
  localTimestamp.parse(value2);
@@ -43851,7 +43882,7 @@ function writeScheduleDocumentSync(projectDir, schedules, original = { version:
43851
43882
  const temporary = `${file4}.${randomBytes4(8).toString("hex")}.tmp`;
43852
43883
  try {
43853
43884
  writeFileSync21(temporary, text5, { mode: 384, flag: "wx" });
43854
- renameSync15(temporary, file4);
43885
+ renameSync9(temporary, file4);
43855
43886
  } finally {
43856
43887
  try {
43857
43888
  unlinkSync7(temporary);
@@ -49926,6 +49957,15 @@ async function readClaudeToken(execSecurity = exec10, platform = process.platfor
49926
49957
  return void 0;
49927
49958
  }
49928
49959
  }
49960
+ function oneRowPerLogin(rows2) {
49961
+ const at2 = (row) => row.windows.length ? Date.parse(row.updatedAt ?? "") || 0 : -1;
49962
+ const best = /* @__PURE__ */ new Map();
49963
+ for (const row of rows2) {
49964
+ const key4 = row.account?.key;
49965
+ if (key4 && (!best.has(key4) || at2(row) > at2(best.get(key4)))) best.set(key4, row);
49966
+ }
49967
+ return rows2.filter((row) => !row.account?.key || rows2.find((other) => other.account?.key === row.account.key) === row).map((row) => row.account?.key ? { ...best.get(row.account.key), account: row.account } : row);
49968
+ }
49929
49969
  async function fetchClaudeUsage(token, fetchImpl = fetch, now = /* @__PURE__ */ new Date()) {
49930
49970
  const controller = new AbortController();
49931
49971
  const timer = setTimeout(() => controller.abort(), 8e3);
@@ -50242,7 +50282,7 @@ var init_usage = __esm({
50242
50282
  this.limits(allAccounts),
50243
50283
  this.spending(sources?.has("copilot") ?? true, sources?.has("elevenlabs") ?? true)
50244
50284
  ]);
50245
- return { accounts: [...limits, ...spending] };
50285
+ return { accounts: [...oneRowPerLogin(limits), ...spending] };
50246
50286
  }
50247
50287
  /** Codex and every Claude home, without the spend readers: what a dispatch capacity probe asks. */
50248
50288
  async limits(allAccounts = true) {
@@ -72059,9 +72099,9 @@ async function startSession(server, data, options) {
72059
72099
  const worktree = worktreeRequest ? await createLaunchWorktree(projectDirectory, worktreeRequest) : void 0;
72060
72100
  let scratch;
72061
72101
  if (agentFolder) {
72102
+ await mkdir33(path132.join(defaultPhrenPath(), ".runtime"), { recursive: true, mode: 448 });
72062
72103
  const store = await realpath22(defaultPhrenPath());
72063
72104
  const runtime = path132.join(store, ".runtime");
72064
- await mkdir33(runtime, { recursive: true, mode: 448 });
72065
72105
  if (await realpath22(runtime) !== runtime) throw new BridgeError(403, "The runtime folder must be inside the Phren directory.");
72066
72106
  const agents = path132.join(runtime, "agents");
72067
72107
  await mkdir33(agents, { recursive: true, mode: 448 });
@@ -73705,7 +73745,7 @@ var init_file_resolve = __esm({
73705
73745
 
73706
73746
  // src/content/citation-freshness.ts
73707
73747
  import { execFileSync as execFileSync9 } from "node:child_process";
73708
- import { readFileSync as readFileSync56, realpathSync as realpathSync7, renameSync as renameSync18, statSync as statSync28, unlinkSync as unlinkSync8, writeFileSync as writeFileSync24 } from "node:fs";
73748
+ import { readFileSync as readFileSync56, realpathSync as realpathSync7, renameSync as renameSync12, statSync as statSync28, unlinkSync as unlinkSync8, writeFileSync as writeFileSync24 } from "node:fs";
73709
73749
  import path141 from "node:path";
73710
73750
  import { randomUUID as randomUUID31 } from "node:crypto";
73711
73751
  function git8(root, timeoutMs, ...args) {
@@ -73818,7 +73858,7 @@ function save2(file4, entries2) {
73818
73858
  const sorted = Object.entries(merged).filter(([, value2]) => Date.now() - Date.parse(value2.checkedAt) <= ("value" in value2 ? RESOLUTION_TTL : RETENTION)).sort((a, b) => Date.parse(b[1].checkedAt) - Date.parse(a[1].checkedAt)).slice(0, 5e3);
73819
73859
  const saved = Object.fromEntries(sorted);
73820
73860
  writeFileSync24(temp, JSON.stringify(saved), { mode: 384 });
73821
- renameSync18(temp, file4);
73861
+ renameSync12(temp, file4);
73822
73862
  rememberCache(file4, saved);
73823
73863
  } catch {
73824
73864
  } finally {
@@ -82812,7 +82852,7 @@ async function main() {
82812
82852
  return askpass2(args[1]);
82813
82853
  }
82814
82854
  const { runBridge: runBridge2 } = await Promise.resolve().then(() => (init_command(), command_exports));
82815
- return runBridge2(args, "0.3.63");
82855
+ return runBridge2(args, "0.3.65");
82816
82856
  }
82817
82857
  main().then((code) => {
82818
82858
  process.exitCode = code;
@@ -1,5 +1,6 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
+ import { renameOverSync } from "../phren-paths.js";
3
4
  import * as crypto from "crypto";
4
5
  import { debugLog, runtimeFile, phrenOk, phrenErr, PhrenError, appendAuditLog, tryUnlink } from "../shared.js";
5
6
  import { isValidProjectName, errorMessage } from "../utils.js";
@@ -258,7 +259,7 @@ export function autoArchiveToReference(phrenPath, project, keepCount) {
258
259
  }
259
260
  const tmpPath = learningsPath + `.tmp-${crypto.randomUUID()}`;
260
261
  fs.writeFileSync(tmpPath, cleaned.join("\n"));
261
- fs.renameSync(tmpPath, learningsPath);
262
+ renameOverSync(tmpPath, learningsPath);
262
263
  const skippedCount = alreadyArchivedEntries.length;
263
264
  const failedTopics = [...byTopic.keys()].filter(t => !successfulTopics.has(t));
264
265
  appendAuditLog(phrenPath, "auto_archive_reference", `project=${project} archived=${successfullyArchived.length} skipped_duplicates=${skippedCount}${failedTopics.length ? ` failed_topics=${failedTopics.join(",")}` : ""} topics=${[...successfulTopics].join(",")}`);
@@ -1,5 +1,6 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
+ import { renameOverSync } from "../phren-paths.js";
3
4
  import * as crypto from "crypto";
4
5
  import { debugLog, appendAuditLog, phrenOk, phrenErr, PhrenError } from "../shared.js";
5
6
  import { normalizeMemoryScope } from "../shared.js";
@@ -223,7 +224,7 @@ export function upsertCanonical(phrenPath, project, memory) {
223
224
  const content = updated.endsWith("\n") ? updated : updated + "\n";
224
225
  const tmpPath = canonicalPath + `.tmp-${crypto.randomUUID()}`;
225
226
  fs.writeFileSync(tmpPath, content);
226
- fs.renameSync(tmpPath, canonicalPath);
227
+ renameOverSync(tmpPath, canonicalPath);
227
228
  }
228
229
  }
229
230
  });
@@ -281,7 +282,7 @@ export function addFindingToFile(phrenPath, project, learning, citationInput, op
281
282
  const newContent = `# ${project} Findings\n\n## ${today}\n\n${preparedForNewFile.finding.bullet}\n${preparedForNewFile.finding.citationComment}\n`;
282
283
  const tmpPath = learningsPath + `.tmp-${crypto.randomUUID()}`;
283
284
  fs.writeFileSync(tmpPath, newContent);
284
- fs.renameSync(tmpPath, learningsPath);
285
+ renameOverSync(tmpPath, learningsPath);
285
286
  return phrenOk({
286
287
  content: newContent,
287
288
  citation: buildFindingCitation(resolvedCitationInput, nowIso, inferredRepo, headCommit),
@@ -354,7 +355,7 @@ export function addFindingToFile(phrenPath, project, learning, citationInput, op
354
355
  }
355
356
  const tmpPath = learningsPath + `.tmp-${crypto.randomUUID()}`;
356
357
  fs.writeFileSync(tmpPath, updated);
357
- fs.renameSync(tmpPath, learningsPath);
358
+ renameOverSync(tmpPath, learningsPath);
358
359
  return phrenOk({
359
360
  content: updated,
360
361
  citation: buildFindingCitation(resolvedCitationInput, nowIso, inferredRepo, headCommit),
@@ -459,7 +460,7 @@ export function addFindingsToFile(phrenPath, project, learnings, opts) {
459
460
  if (added.length > 0) {
460
461
  const tmpPath = learningsPath + `.tmp-${crypto.randomUUID()}`;
461
462
  fs.writeFileSync(tmpPath, content.endsWith("\n") ? content : `${content}\n`);
462
- fs.renameSync(tmpPath, learningsPath);
463
+ renameOverSync(tmpPath, learningsPath);
463
464
  }
464
465
  return phrenOk({ content, wrote: added.length > 0 });
465
466
  }
@@ -494,7 +495,7 @@ export function addFindingsToFile(phrenPath, project, learnings, opts) {
494
495
  if (added.length > 0) {
495
496
  const tmpPath = learningsPath + `.tmp-${crypto.randomUUID()}`;
496
497
  fs.writeFileSync(tmpPath, content);
497
- fs.renameSync(tmpPath, learningsPath);
498
+ renameOverSync(tmpPath, learningsPath);
498
499
  }
499
500
  return phrenOk({ content, wrote: added.length > 0 });
500
501
  });
@@ -1,6 +1,7 @@
1
1
  import { nonInteractiveGitEnv } from "../utils-helpers.js";
2
2
  import * as fs from "fs";
3
3
  import * as path from "path";
4
+ import { renameOverSync } from "../phren-paths.js";
4
5
  import * as crypto from "crypto";
5
6
  import { execFileSync } from "child_process";
6
7
  import { debugLog, EXEC_TIMEOUT_MS, getProjectDirs } from "../shared.js";
@@ -574,7 +575,7 @@ export function autoMergeConflicts(phrenPath) {
574
575
  : mergeTask(versions.ours, versions.theirs);
575
576
  const tmpMergePath = fullPath + `.tmp-${crypto.randomUUID()}`;
576
577
  fs.writeFileSync(tmpMergePath, merged);
577
- fs.renameSync(tmpMergePath, fullPath);
578
+ renameOverSync(tmpMergePath, fullPath);
578
579
  execFileSync("git", ["add", "--", relFile], { env: nonInteractiveGitEnv(), cwd: phrenPath, stdio: ["ignore", "ignore", "ignore"], timeout: EXEC_TIMEOUT_MS });
579
580
  debugLog(`Auto-merged: ${relFile}`);
580
581
  }
@@ -3,6 +3,7 @@
3
3
  // and owns finding/queue logic directly.
4
4
  import * as fs from "fs";
5
5
  import * as path from "path";
6
+ import { renameOverSync } from "../phren-paths.js";
6
7
  import * as yaml from "js-yaml";
7
8
  import { loadYamlDocument } from "../phren-core.js";
8
9
  import { appendAuditLog, phrenErr, PhrenError, phrenOk, forwardErr, getProjectDirs, isRecord, } from "../shared.js";
@@ -358,7 +359,7 @@ export function removeFinding(phrenPath, project, match, opts = {}) {
358
359
  const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
359
360
  const tmp = filePath + ".tmp." + process.pid;
360
361
  fs.writeFileSync(tmp, normalized);
361
- fs.renameSync(tmp, filePath);
362
+ renameOverSync(tmp, filePath);
362
363
  return phrenOk(`Removed from ${project}: ${matched}`);
363
364
  });
364
365
  }
@@ -408,7 +409,7 @@ export function removeFindings(phrenPath, project, matches) {
408
409
  const normalized = filtered.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
409
410
  const tmp = findingsPath + ".tmp." + process.pid;
410
411
  fs.writeFileSync(tmp, normalized);
411
- fs.renameSync(tmp, findingsPath);
412
+ renameOverSync(tmp, findingsPath);
412
413
  }
413
414
  return phrenOk({ removed, errors });
414
415
  });
@@ -455,7 +456,7 @@ export function editFinding(phrenPath, project, oldText, newText) {
455
456
  const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
456
457
  const tmp = findingsPath + ".tmp." + process.pid;
457
458
  fs.writeFileSync(tmp, normalized);
458
- fs.renameSync(tmp, findingsPath);
459
+ renameOverSync(tmp, findingsPath);
459
460
  return phrenOk(`Updated finding in ${project}`);
460
461
  });
461
462
  }
@@ -549,7 +550,7 @@ function writeQueueLines(file, lines) {
549
550
  const content = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
550
551
  const tmp = file + ".tmp." + process.pid;
551
552
  fs.writeFileSync(tmp, content);
552
- fs.renameSync(tmp, file);
553
+ renameOverSync(tmp, file);
553
554
  }
554
555
  /**
555
556
  * Read-only lookup of a queue line. Returns the *stored* line (not the caller's
@@ -788,7 +789,7 @@ export function rejectQueueItemDetailed(phrenPath, project, lineText) {
788
789
  const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
789
790
  const tmp = `${target.file}.tmp.${process.pid}`;
790
791
  fs.writeFileSync(tmp, normalized);
791
- fs.renameSync(tmp, target.file);
792
+ renameOverSync(tmp, target.file);
792
793
  return phrenOk(undefined);
793
794
  });
794
795
  if (!purge.ok)
@@ -4,6 +4,7 @@ import { moduleEnabled } from "../modules/runtime.js";
4
4
  import { disabledHint } from "../modules/registry.js";
5
5
  import * as fs from "fs";
6
6
  import * as path from "path";
7
+ import { renameOverSync } from "../phren-paths.js";
7
8
  import { createHash, randomBytes, randomUUID } from "crypto";
8
9
  import { phrenErr, PhrenError, phrenOk, forwardErr, getProjectDirs, } from "../shared.js";
9
10
  import { validateTaskFormat } from "../shared/content.js";
@@ -408,7 +409,7 @@ function writeTaskDoc(doc) {
408
409
  const tmpPath = `${doc.path}.tmp-${randomUUID()}`;
409
410
  const content = renderTask(doc);
410
411
  fs.writeFileSync(tmpPath, content);
411
- fs.renameSync(tmpPath, doc.path);
412
+ renameOverSync(tmpPath, doc.path);
412
413
  recordTaskWrite(doc.path, content);
413
414
  }
414
415
  function taskArchivePath(phrenPath, project) {
@@ -1134,7 +1135,7 @@ export function tidyDoneTasks(phrenPath, project, keep = 30, dryRun) {
1134
1135
  const prior = fs.existsSync(archiveFile) ? fs.readFileSync(archiveFile, "utf8") : `# ${project} tasks archive\n\n`;
1135
1136
  const tmpPath = `${archiveFile}.tmp-${randomUUID()}`;
1136
1137
  fs.writeFileSync(tmpPath, prior + block);
1137
- fs.renameSync(tmpPath, archiveFile);
1138
+ renameOverSync(tmpPath, archiveFile);
1138
1139
  writeTaskDoc(parsed.data);
1139
1140
  return phrenOk(`Tidied ${project}: archived ${archived.length} done item(s), kept ${safeKeep}.`);
1140
1141
  });
@@ -1,5 +1,6 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
+ import { renameOverSync } from "../phren-paths.js";
3
4
  import { PhrenError, phrenErr, phrenOk } from "../phren-core.js";
4
5
  // Phren lifecycle comment prefix. No backward compat.
5
6
  const LIFECYCLE_PREFIX = "phren";
@@ -235,7 +236,7 @@ export function supersedeFinding(phrenPath, project, findingText, supersededBy)
235
236
  const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
236
237
  const tmpPath = findingsPath + ".tmp." + process.pid;
237
238
  fs.writeFileSync(tmpPath, normalized);
238
- fs.renameSync(tmpPath, findingsPath);
239
+ renameOverSync(tmpPath, findingsPath);
239
240
  return phrenOk({ finding: matched.data.text, superseded_by: ref, status: "superseded" });
240
241
  });
241
242
  }
@@ -257,7 +258,7 @@ export function retractFinding(phrenPath, project, findingText, reason) {
257
258
  const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
258
259
  const tmpPath = findingsPath + ".tmp." + process.pid;
259
260
  fs.writeFileSync(tmpPath, normalized);
260
- fs.renameSync(tmpPath, findingsPath);
261
+ renameOverSync(tmpPath, findingsPath);
261
262
  return phrenOk({ finding: matched.data.text, reason: reasonText, status: "retracted" });
262
263
  });
263
264
  }
@@ -309,7 +310,7 @@ export function resolveFindingContradiction(phrenPath, project, findingA, findin
309
310
  const normalized = lines.join("\n").replace(/\n{3,}/g, "\n\n").trimEnd() + "\n";
310
311
  const tmpPath = findingsPath + ".tmp." + process.pid;
311
312
  fs.writeFileSync(tmpPath, normalized);
312
- fs.renameSync(tmpPath, findingsPath);
313
+ renameOverSync(tmpPath, findingsPath);
313
314
  return phrenOk({
314
315
  resolution,
315
316
  finding_a: { text: matchedA.data.text, status: statusA },
@@ -89,6 +89,7 @@ export function tryFileLock(filePath) {
89
89
  const lockPath = filePath + ".lock";
90
90
  const owner = `${process.pid}\n${Date.now()}\n${Math.random()}`;
91
91
  fs.mkdirSync(path.dirname(lockPath), { recursive: true });
92
+ let refusedWithoutFile = 0;
92
93
  for (let attempt = 0; attempt < 2; attempt++) {
93
94
  try {
94
95
  fs.writeFileSync(lockPath, owner, { flag: "wx", mode: 0o600 });
@@ -104,7 +105,10 @@ export function tryFileLock(filePath) {
104
105
  const code = err.code;
105
106
  // Windows refuses to create a lock another process is deleting (still
106
107
  // open somewhere) with EPERM, EACCES or EBUSY: it is held, not broken.
107
- // With no lock file there at all, the error is a real permission problem.
108
+ // With no lock file there, the delete may have finished since the
109
+ // create, and another process may lock and release again before the
110
+ // next create: try a few times without spending an attempt. Refused
111
+ // every time with no file, the error is a real permission problem.
108
112
  if (process.platform === "win32" && (code === "EPERM" || code === "EACCES" || code === "EBUSY")) {
109
113
  let present = true;
110
114
  try {
@@ -115,6 +119,10 @@ export function tryFileLock(filePath) {
115
119
  }
116
120
  if (present)
117
121
  return null;
122
+ if (++refusedWithoutFile < 5) {
123
+ attempt--;
124
+ continue;
125
+ }
118
126
  throw err;
119
127
  }
120
128
  if (code !== "EEXIST")
@@ -27,6 +27,15 @@ export interface AtomicWriteOptions {
27
27
  */
28
28
  mode?: number;
29
29
  }
30
+ /**
31
+ * Windows refuses to replace a file another process holds open (an MCP server
32
+ * or hook reading the same tasks.md or FINDINGS.md) with EPERM, EACCES or
33
+ * EBUSY, where POSIX replaces it atomically. Readers hold it for
34
+ * milliseconds, so retry briefly before giving up. bridge/protocol.ts does
35
+ * the same for the Hook's async writes. `from` is a temp file: when the
36
+ * rename fails for good it is removed, so no tmp file is left in the store.
37
+ */
38
+ export declare function renameOverSync(from: string, to: string): void;
30
39
  export declare function atomicWriteText(filePath: string, content: string | Uint8Array, opts?: AtomicWriteOptions): void;
31
40
  /**
32
41
  * Create (or tighten) a directory that holds per-user private data — runtime
@@ -31,6 +31,33 @@ export function defaultPhrenPath() {
31
31
  export function rootManifestPath(phrenPath) {
32
32
  return path.join(phrenPath, ROOT_MANIFEST_FILENAME);
33
33
  }
34
+ /**
35
+ * Windows refuses to replace a file another process holds open (an MCP server
36
+ * or hook reading the same tasks.md or FINDINGS.md) with EPERM, EACCES or
37
+ * EBUSY, where POSIX replaces it atomically. Readers hold it for
38
+ * milliseconds, so retry briefly before giving up. bridge/protocol.ts does
39
+ * the same for the Hook's async writes. `from` is a temp file: when the
40
+ * rename fails for good it is removed, so no tmp file is left in the store.
41
+ */
42
+ export function renameOverSync(from, to) {
43
+ const waiter = new Int32Array(new SharedArrayBuffer(4));
44
+ for (let attempt = 0;; attempt++) {
45
+ try {
46
+ return fs.renameSync(from, to);
47
+ }
48
+ catch (error) {
49
+ const code = error.code ?? "";
50
+ if (process.platform !== "win32" || attempt >= 20 || !["EPERM", "EACCES", "EBUSY"].includes(code)) {
51
+ try {
52
+ fs.unlinkSync(from);
53
+ }
54
+ catch { /* never written, or already gone */ }
55
+ throw error;
56
+ }
57
+ Atomics.wait(waiter, 0, 0, 5 * (attempt + 1));
58
+ }
59
+ }
60
+ }
34
61
  export function atomicWriteText(filePath, content, opts = {}) {
35
62
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
36
63
  const tmpPath = `${filePath}.tmp-${crypto.randomUUID()}`;
@@ -41,7 +68,7 @@ export function atomicWriteText(filePath, content, opts = {}) {
41
68
  // other process can have the file open under its final name.
42
69
  if (opts.mode !== undefined && process.platform !== "win32")
43
70
  fs.chmodSync(tmpPath, opts.mode);
44
- fs.renameSync(tmpPath, filePath);
71
+ renameOverSync(tmpPath, filePath);
45
72
  }
46
73
  catch (err) {
47
74
  try {
@@ -1,6 +1,7 @@
1
1
  import * as crypto from "crypto";
2
2
  import * as fs from "fs";
3
3
  import * as path from "path";
4
+ import { renameOverSync } from "./phren-paths.js";
4
5
  import { debugLog } from "./shared.js";
5
6
  import { withFileLock } from "./governance/locks.js";
6
7
  import { STOP_WORDS, errorMessage, extractKeywords, isValidProjectName } from "./utils.js";
@@ -605,7 +606,7 @@ function writePinnedTopics(phrenPath, project, pinnedTopics) {
605
606
  };
606
607
  const tmpPath = `${configPath}.tmp-${crypto.randomUUID()}`;
607
608
  fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2) + "\n");
608
- fs.renameSync(tmpPath, configPath);
609
+ renameOverSync(tmpPath, configPath);
609
610
  });
610
611
  return { ok: true, pinnedTopics: pinned };
611
612
  }
@@ -639,7 +640,7 @@ export function writeProjectTopics(phrenPath, project, topics) {
639
640
  };
640
641
  const tmpPath = `${configPath}.tmp-${crypto.randomUUID()}`;
641
642
  fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2) + "\n");
642
- fs.renameSync(tmpPath, configPath);
643
+ renameOverSync(tmpPath, configPath);
643
644
  });
644
645
  return { ok: true, topics: normalized };
645
646
  }
@@ -718,7 +719,7 @@ export function appendArchivedEntriesToTopicDoc(filePath, project, topic, entrie
718
719
  }
719
720
  const tmpPath = `${filePath}.tmp-${crypto.randomUUID()}`;
720
721
  fs.writeFileSync(tmpPath, existing.trimEnd() + "\n\n" + sections.join("\n"));
721
- fs.renameSync(tmpPath, filePath);
722
+ renameOverSync(tmpPath, filePath);
722
723
  });
723
724
  }
724
725
  export function ensureTopicReferenceDoc(phrenPath, project, topic) {
@@ -733,7 +734,7 @@ export function ensureTopicReferenceDoc(phrenPath, project, topic) {
733
734
  return;
734
735
  const tmpPath = `${filePath}.tmp-${crypto.randomUUID()}`;
735
736
  fs.writeFileSync(tmpPath, topicDocHeader(project, topic));
736
- fs.renameSync(tmpPath, filePath);
737
+ renameOverSync(tmpPath, filePath);
737
738
  });
738
739
  }
739
740
  return { ok: true, path: filePath };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.63",
3
+ "version": "0.3.65",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {