@pi-chamber/web 0.9.5 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/assets/DiagramView-0Iq1ak1I.js +1 -0
  2. package/dist/assets/{DiffView-BmIVvheE.js → DiffView-DD1AFRi3.js} +1 -1
  3. package/dist/assets/FileSaveConflictDialog-CoKwDovb.js +3 -0
  4. package/dist/assets/FilesView-B_BF39ef.js +6 -0
  5. package/dist/assets/{GitView-BNkzec7G.js → GitView-LFEpCasf.js} +3 -3
  6. package/dist/assets/{JsonTreeView-C1Kzaybf.js → JsonTreeView-Cwjgvh4g.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-qmKiFVpO.js → MarkdownRendererImpl-_7kV1yNw.js} +2 -2
  8. package/dist/assets/{PatchDiff-D9JesZL1.js → PatchDiff-DG43C1HW.js} +1 -1
  9. package/dist/assets/{SessionSwitcherContent-DplV_ApH.js → SessionSwitcherContent-DCFXPY3d.js} +1 -1
  10. package/dist/assets/{SessionSwitcherDropdown-DdgDKT6K.js → SessionSwitcherDropdown-QY7FKuEQ.js} +2 -2
  11. package/dist/assets/{SessionUnreadDot-BdSDgvhC.js → SessionUnreadDot-DGT31A3z.js} +1 -1
  12. package/dist/assets/{SettingsView-z8uf0XyM.js → SettingsView-eG-wN-yY.js} +2 -2
  13. package/dist/assets/{SettingsWindow-CPDmgNg2.js → SettingsWindow-Dvnp8YrA.js} +1 -1
  14. package/dist/assets/{ToolOutputDialog-DaF1xcM0.js → ToolOutputDialog-IlCrS6BR.js} +1 -1
  15. package/dist/assets/{ToolPartDiffPreview-Di6Uo0Dt.js → ToolPartDiffPreview-D68JV0rR.js} +1 -1
  16. package/dist/assets/{VirtualizedFileDiff-wqcrY0yr.js → VirtualizedFileDiff-Bl-rAYeh.js} +1 -1
  17. package/dist/assets/{collapsible-DBQnXTNm.js → collapsible-BjniCdZ5.js} +1 -1
  18. package/dist/assets/{computeVirtualFileMetrics-Cr3jh0d6.js → computeVirtualFileMetrics-FSOm2VrW.js} +2 -2
  19. package/dist/assets/{contextFileOpenGuard-C_AOTYQD.js → contextFileOpenGuard-Bxb6AIPa.js} +1 -1
  20. package/dist/assets/{gitStatusPredicates-BvPOjeOy.js → gitStatusPredicates-DxolDpMd.js} +1 -1
  21. package/dist/assets/index-BpmGBboM.css +1 -0
  22. package/dist/assets/index-DZnzXhTs.js +8 -0
  23. package/dist/assets/{index-B8Wt2aN3.js → index-Dh58uD3I.js} +1 -1
  24. package/dist/assets/{isDiffPlainText-L9uvgz2F.js → isDiffPlainText-D3_04XCh.js} +1 -1
  25. package/dist/assets/{isFilePlainText-C4yk5BOo.js → isFilePlainText-CHouYQhH.js} +1 -1
  26. package/dist/assets/{main-DCK6lLCo.js → main-CH3EqGJI.js} +2 -2
  27. package/dist/assets/{main-C1OSzD-E.js → main-HzTrVvbB.js} +3 -3
  28. package/dist/assets/{markdownCore-Czb_lINQ.js → markdownCore-DJU4KvHP.js} +1 -1
  29. package/dist/assets/{miniChat-CXiSlptL.js → miniChat-Ca3TpaaA.js} +2 -2
  30. package/dist/assets/{mobile-D0HVxiyJ.js → mobile-lj4gpGsO.js} +2 -2
  31. package/dist/assets/{renderElectronMiniChatApp-BcG209a4.js → renderElectronMiniChatApp-rUFfaD-T.js} +2 -2
  32. package/dist/assets/{renderMobileApp-B5x_PWlc.js → renderMobileApp-CcWQ1sCf.js} +3 -3
  33. package/dist/assets/{runtimeEndpointReset-CUiPe6dQ.js → runtimeEndpointReset-D2MmSbDk.js} +8 -8
  34. package/dist/assets/{runtimeSurface-vilE4xyj.js → runtimeSurface-CE_VNjdH.js} +1 -1
  35. package/dist/assets/{useAppFontEffects-BP07Vl6M.js → useAppFontEffects-BvFAP9zG.js} +86 -86
  36. package/dist/assets/useFilesViewSearch-BD79p3A2.js +7 -0
  37. package/dist/assets/{usePushVisibilityBeacon-CChMvoTL.js → usePushVisibilityBeacon-CWg0j-Wg.js} +1 -1
  38. package/dist/assets/{useSwitcherItems-_RSo3F-A.js → useSwitcherItems-CazJ6Yox.js} +1 -1
  39. package/dist/assets/{vendor-codemirror-language-data-BJrrV83E.js → vendor-codemirror-language-data-CP3j3-xu.js} +2 -2
  40. package/dist/assets/{web-components-B5sMa_kC.js → web-components-DWuadqra.js} +1 -1
  41. package/dist/index.html +4 -4
  42. package/dist/mini-chat.html +3 -3
  43. package/dist/mobile.html +3 -3
  44. package/package.json +1 -1
  45. package/server/lib/fs/DOCUMENTATION.md +15 -3
  46. package/server/lib/fs/routes.js +369 -51
  47. package/server/lib/fs/routes.test.js +565 -3
  48. package/server/lib/fs/search.js +74 -29
  49. package/server/lib/pi/routes.js +56 -3
  50. package/server/lib/pi/routes.test.js +165 -0
  51. package/server/lib/pi/session-daemon/DOCUMENTATION.md +3 -2
  52. package/server/lib/pi/session-daemon/prompt-operations.test.js +9 -3
  53. package/server/lib/pi/session-daemon/prompt-preflight.test.js +556 -0
  54. package/server/lib/pi/session-daemon/send-operation-dedup.test.js +331 -0
  55. package/server/lib/pi/session-daemon/send-operation-registry.js +264 -0
  56. package/server/lib/pi/session-daemon/send-operation-registry.test.js +205 -0
  57. package/server/lib/pi/session-daemon/session-daemon-extensions.e2e.test.js +16 -5
  58. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +3 -1
  59. package/server/lib/pi/session-daemon/session-daemon.js +284 -31
  60. package/server/lib/pi/session-daemon/session-daemon.test.js +37 -13
  61. package/server/lib/pi/session-daemon/session-idle-residency.test.js +8 -1
  62. package/server/lib/pi/session-daemon/session-replay.test.js +3 -1
  63. package/server/lib/server/cors.js +6 -0
  64. package/server/lib/server/cors.test.js +3 -0
  65. package/server/lib/workspace/host.js +6 -2
  66. package/server/lib/workspace/host.test.js +15 -0
  67. package/dist/assets/DiagramEditor-BPDkGHsj.js +0 -1
  68. package/dist/assets/DiagramView-D_EfDz2d.js +0 -1
  69. package/dist/assets/FilesView-CJytSUAX.js +0 -6
  70. package/dist/assets/index-DIF8b4bh.css +0 -1
  71. package/dist/assets/index-jrfQYSvP.js +0 -8
  72. package/dist/assets/useFilesViewSearch-oxIKk-ea.js +0 -7
@@ -1,6 +1,7 @@
1
1
  import { createRealpathCache } from '../path-realpath-cache.js';
2
2
  import nodeFsPromises from 'node:fs/promises';
3
3
  import nodePath from 'node:path';
4
+ import { createHash } from 'node:crypto';
4
5
  import { resolvePiChamberDataDir } from '../pichamber-data-dir.js';
5
6
  import { createFsSearchRuntime } from './search.js';
6
7
  import { pickHostDirectory } from './pick-directory.js';
@@ -29,6 +30,155 @@ const sendOsPermissionDenied = (res, message) => (
29
30
  res.status(403).json({ error: message, reason: 'os-permission' })
30
31
  );
31
32
 
33
+ // File-save revision protocol (finding #8).
34
+ //
35
+ // Cooperating PiChamber writers attach the opaque `expectedRevision` they read
36
+ // to every save. The server serializes compare+atomic-replace per canonical
37
+ // file so two writers with the same base revision cannot both win: the first
38
+ // commits, the second receives a typed 409 `file-revision-conflict` with the
39
+ // current revision and re-reads before retrying.
40
+ //
41
+ // Revision format is opaque to clients (exact string compare only):
42
+ // `v1:<size>:<mtimeMs>:<sha256hex>` for hashed text, or
43
+ // `v1:<size>:<mtimeMs>` when content exceeds the hash ceiling.
44
+ // A missing file has revision `null` on the wire; `expectedRevision: null`
45
+ // (or the literal `'missing'`) means "create only". `overwrite: true` is
46
+ // the explicit force path that bypasses the check. Omitting
47
+ // `expectedRevision` preserves legacy unconditional writes for older clients
48
+ // and non-editor callers.
49
+ //
50
+ // External processes that write without this protocol are non-cooperating:
51
+ // check and replace cannot be atomic against them. Last writer still wins on
52
+ // disk; the next cooperating save observes a revision mismatch and conflicts
53
+ // instead of silently overwriting. See DOCUMENTATION.md.
54
+ const FILE_REVISION_PREFIX = 'v1';
55
+ const FILE_REVISION_MISSING_LITERAL = 'missing';
56
+ const FILE_REVISION_HASH_MAX_BYTES = 5 * 1024 * 1024;
57
+ const FILE_REVISION_HEADER = 'x-pichamber-file-revision';
58
+
59
+ const fileWriteLocks = new Map();
60
+
61
+ // Canonical write-lock key. Locking on the pre-realpath workspace path would
62
+ // let symlink aliases of the same file bypass serialization, so key on the
63
+ // realpath target instead. For a missing target (create-only writes) walk up
64
+ // to the deepest existing ancestor so aliases of the same missing file still
65
+ // share one key; the write body re-keys inside the lock when the target
66
+ // appears or is re-pointed between key resolution and lock acquisition.
67
+ const canonicalFileWriteLockKey = async (fsPromises, path, target) => {
68
+ try {
69
+ return await fsPromises.realpath(target);
70
+ } catch (error) {
71
+ if (!error || typeof error !== 'object' || error.code !== 'ENOENT') {
72
+ return path.resolve(target);
73
+ }
74
+ let current = target;
75
+ const segments = [];
76
+ for (;;) {
77
+ const parent = path.dirname(current);
78
+ if (parent === current) return path.resolve(target);
79
+ segments.unshift(path.basename(current));
80
+ try {
81
+ const realParent = await fsPromises.realpath(parent);
82
+ return path.join(realParent, ...segments);
83
+ } catch (parentError) {
84
+ if (parentError && typeof parentError === 'object' && parentError.code === 'ENOENT') {
85
+ current = parent;
86
+ continue;
87
+ }
88
+ return path.resolve(target);
89
+ }
90
+ }
91
+ }
92
+ };
93
+
94
+ const withFileWriteLock = (key, fn) => {
95
+ const previous = fileWriteLocks.get(key) || Promise.resolve();
96
+ const next = previous.then(fn, fn);
97
+ const tracked = next.catch(() => {});
98
+ fileWriteLocks.set(key, tracked);
99
+ void tracked.finally(() => {
100
+ if (fileWriteLocks.get(key) === tracked) {
101
+ fileWriteLocks.delete(key);
102
+ }
103
+ });
104
+ return next;
105
+ };
106
+
107
+ const hashBytes = (buffer) => {
108
+ try {
109
+ return createHash('sha256').update(buffer).digest('hex');
110
+ } catch {
111
+ return null;
112
+ }
113
+ };
114
+
115
+ const buildFileRevision = ({ size, mtimeMs, hash }) => {
116
+ const safeSize = Number.isFinite(Number(size)) ? Number(size) : 0;
117
+ const safeMtime = Number.isFinite(Number(mtimeMs)) ? Number(mtimeMs) : 0;
118
+ if (typeof hash === 'string' && hash.length > 0) {
119
+ return `${FILE_REVISION_PREFIX}:${safeSize}:${safeMtime}:${hash}`;
120
+ }
121
+ return `${FILE_REVISION_PREFIX}:${safeSize}:${safeMtime}`;
122
+ };
123
+
124
+ const revisionForContentAndStat = (content, stats) => {
125
+ const size = typeof stats?.size === 'number' ? stats.size : Buffer.byteLength(typeof content === 'string' ? content : String(content ?? ''), 'utf8');
126
+ const mtimeMs = typeof stats?.mtimeMs === 'number' ? stats.mtimeMs : 0;
127
+ if (size > FILE_REVISION_HASH_MAX_BYTES) {
128
+ return buildFileRevision({ size, mtimeMs, hash: null });
129
+ }
130
+ const hash = hashBytes(Buffer.from(typeof content === 'string' ? content : String(content ?? ''), 'utf8'));
131
+ return buildFileRevision({ size, mtimeMs, hash });
132
+ };
133
+
134
+ const revisionForBufferAndStat = (buffer, stats) => {
135
+ const size = typeof stats?.size === 'number' ? stats.size : buffer.length;
136
+ const mtimeMs = typeof stats?.mtimeMs === 'number' ? stats.mtimeMs : 0;
137
+ if (size > FILE_REVISION_HASH_MAX_BYTES) {
138
+ return buildFileRevision({ size, mtimeMs, hash: null });
139
+ }
140
+ return buildFileRevision({ size, mtimeMs, hash: hashBytes(buffer) });
141
+ };
142
+
143
+ const normalizeExpectedRevision = (value) => {
144
+ if (value === undefined) return { mode: 'legacy' };
145
+ if (value === null) return { mode: 'missing' };
146
+ if (typeof value === 'string') {
147
+ if (value === FILE_REVISION_MISSING_LITERAL) return { mode: 'missing' };
148
+ // Opaque: retain exact, compare exact. Empty string is invalid.
149
+ if (value.length === 0) return { mode: 'invalid' };
150
+ return { mode: 'revision', revision: value };
151
+ }
152
+ return { mode: 'invalid' };
153
+ };
154
+
155
+ // Parses a client-supplied `knownRevision` for the stat cheap-path. Opaque
156
+ // contract: a v1 revision is only ever compared for size/mtime equality, and
157
+ // the exact client string is echoed back; anything else returns null and the
158
+ // route computes a fresh revision the normal way.
159
+ const parseKnownStatRevision = (value) => {
160
+ if (typeof value !== 'string' || !value.startsWith(`${FILE_REVISION_PREFIX}:`)) return null;
161
+ const parts = value.split(':');
162
+ if (parts.length !== 3 && parts.length !== 4) return null;
163
+ const size = Number(parts[1]);
164
+ const mtimeMs = Number(parts[2]);
165
+ if (!Number.isFinite(size) || !Number.isFinite(mtimeMs)) return null;
166
+ if (parts.length === 3) return { size, mtimeMs, hash: null };
167
+ const hash = parts[3];
168
+ if (!/^[0-9a-f]{64}$/.test(hash)) return null;
169
+ return { size, mtimeMs, hash };
170
+ };
171
+
172
+ const sendFileRevisionConflict = (res, { path: conflictPath, currentRevision, exists }) => (
173
+ res.status(409).json({
174
+ error: 'File has changed on disk',
175
+ reason: 'file-revision-conflict',
176
+ path: conflictPath,
177
+ exists: Boolean(exists),
178
+ currentRevision: exists ? currentRevision : null,
179
+ })
180
+ );
181
+
32
182
  export const mintOutsideFileGrant = async (targetPath, {
33
183
  scopes = ['stat', 'read', 'raw'],
34
184
  fsPromises = nodeFsPromises,
@@ -433,6 +583,13 @@ export const registerFsRoutes = (app, dependencies) => {
433
583
  const commandTimeoutMs = createCommandTimeoutMs();
434
584
  const gitReadCacheTtlMs = createGitReadCacheTtlMs();
435
585
  const gitCheckIgnoreTimeoutMs = createGitCheckIgnoreTimeoutMs();
586
+ const fsSearchRuntime = createFsSearchRuntime({
587
+ fsPromises,
588
+ path,
589
+ spawn,
590
+ resolveGitBinaryForSpawn,
591
+ gitCheckIgnoreTimeoutMs,
592
+ });
436
593
  const gitReadCache = new Map();
437
594
  const inFlightGitReadCache = new Map();
438
595
 
@@ -779,7 +936,44 @@ export const registerFsRoutes = (app, dependencies) => {
779
936
  return res.status(400).json({ error: 'Specified path is not a file' });
780
937
  }
781
938
 
782
- return res.json({ path: canonicalPath, isFile: true, size: stats.size, mtimeMs: stats.mtimeMs });
939
+ // Cheap-path for change polling: when the client sends the exact
940
+ // revision it already holds and size+mtime are unchanged, skip the
941
+ // full read+hash a fresh revision would require. A same-size,
942
+ // same-mtime external write is already undetectable to metadata
943
+ // polling, so this preserves the polling contract while removing the
944
+ // per-poll read+hash of large files. The hash-ceiling category must
945
+ // match too; a size that crossed the ceiling means the content
946
+ // changed and the real revision must be computed.
947
+ const known = parseKnownStatRevision(req.query?.knownRevision);
948
+ if (known
949
+ && known.size === stats.size
950
+ && known.mtimeMs === stats.mtimeMs
951
+ && (known.hash !== null) === (stats.size <= FILE_REVISION_HASH_MAX_BYTES)) {
952
+ return res.json({
953
+ path: canonicalPath,
954
+ isFile: true,
955
+ size: stats.size,
956
+ mtimeMs: stats.mtimeMs,
957
+ revision: req.query.knownRevision,
958
+ exists: true,
959
+ });
960
+ }
961
+
962
+ let revision = null;
963
+ try {
964
+ const size = typeof stats.size === 'number' ? stats.size : 0;
965
+ if (size <= FILE_REVISION_HASH_MAX_BYTES && typeof fsPromises.readFile === 'function') {
966
+ const buffer = await fsPromises.readFile(canonicalPath);
967
+ const bytes = Buffer.isBuffer(buffer) ? buffer : Buffer.from(typeof buffer === 'string' ? buffer : String(buffer ?? ''), 'utf8');
968
+ revision = revisionForBufferAndStat(bytes, stats);
969
+ } else {
970
+ revision = buildFileRevision({ size, mtimeMs: stats.mtimeMs, hash: null });
971
+ }
972
+ } catch {
973
+ revision = buildFileRevision({ size: stats.size, mtimeMs: stats.mtimeMs, hash: null });
974
+ }
975
+
976
+ return res.json({ path: canonicalPath, isFile: true, size: stats.size, mtimeMs: stats.mtimeMs, revision, exists: true });
783
977
  } catch (error) {
784
978
  const err = error;
785
979
  if (err && typeof err === 'object' && err.code === 'ENOENT') {
@@ -851,11 +1045,16 @@ export const registerFsRoutes = (app, dependencies) => {
851
1045
  console.warn(`Read retry exhausted for ${canonicalPath}: stat reported ${stats.size} bytes but content is empty`);
852
1046
  }
853
1047
  }
1048
+ const revision = revisionForContentAndStat(content, stats);
1049
+ res.setHeader(FILE_REVISION_HEADER, revision);
1050
+ res.setHeader('Cache-Control', 'no-store');
854
1051
  return res.type('text/plain').send(content);
855
1052
  } catch (error) {
856
1053
  const err = error;
857
1054
  if (err && typeof err === 'object' && err.code === 'ENOENT') {
858
1055
  if (optional) {
1056
+ res.setHeader('x-pichamber-file-exists', 'false');
1057
+ res.setHeader('Cache-Control', 'no-store');
859
1058
  return res.type('text/plain').send('');
860
1059
  }
861
1060
  return res.status(404).json({ error: 'File not found' });
@@ -1015,13 +1214,18 @@ export const registerFsRoutes = (app, dependencies) => {
1015
1214
  });
1016
1215
 
1017
1216
  app.post('/api/fs/write', async (req, res) => {
1018
- const { path: filePath, content } = req.body || {};
1217
+ const { path: filePath, content, expectedRevision, overwrite } = req.body || {};
1019
1218
  if (!filePath || typeof filePath !== 'string') {
1020
1219
  return res.status(400).json({ error: 'Path is required' });
1021
1220
  }
1022
1221
  if (typeof content !== 'string') {
1023
1222
  return res.status(400).json({ error: 'Content is required' });
1024
1223
  }
1224
+ const expectation = normalizeExpectedRevision(expectedRevision);
1225
+ if (expectation.mode === 'invalid') {
1226
+ return res.status(400).json({ error: 'Invalid expectedRevision' });
1227
+ }
1228
+ const forceOverwrite = overwrite === true;
1025
1229
 
1026
1230
  try {
1027
1231
  const resolved = await resolveWorkspacePathFromContext({
@@ -1037,35 +1241,131 @@ export const registerFsRoutes = (app, dependencies) => {
1037
1241
  return res.status(400).json({ error: resolved.error });
1038
1242
  }
1039
1243
 
1040
- const writePath = await fsPromises.realpath(resolved.resolved).catch((error) => {
1041
- if (error && typeof error === 'object' && error.code === 'ENOENT') {
1042
- return resolved.resolved;
1244
+ // Serialize cooperating writers by canonical (realpath-resolved) path
1245
+ // so two saves with the same base revision cannot interleave
1246
+ // check+replace, including writes that arrive through different
1247
+ // symlink spellings of the same file.
1248
+ let lockKey = await canonicalFileWriteLockKey(fsPromises, path, resolved.resolved);
1249
+ let outcome = null;
1250
+ for (let attempt = 0; attempt < 3; attempt++) {
1251
+ outcome = await withFileWriteLock(lockKey, async () => {
1252
+ const writePath = await fsPromises.realpath(resolved.resolved).catch((error) => {
1253
+ if (error && typeof error === 'object' && error.code === 'ENOENT') {
1254
+ return resolved.resolved;
1255
+ }
1256
+ throw error;
1257
+ });
1258
+ // The target may have been created or re-pointed between lock-key
1259
+ // resolution and lock acquisition (delete/recreate races). Re-key
1260
+ // onto the canonical path so the compare+replace below still runs
1261
+ // under the lock other writers of the same file will observe.
1262
+ if (writePath !== lockKey && attempt < 2) {
1263
+ return { __rekey: writePath };
1264
+ }
1265
+ const canonicalBase = await fsPromises.realpath(resolved.base).catch(() => path.resolve(resolved.base));
1266
+ if (!isPathWithinRoot(writePath, canonicalBase, path, os)) {
1267
+ return res.status(403).json({ error: 'Access denied' });
1043
1268
  }
1044
- throw error;
1045
- });
1046
- const canonicalBase = await fsPromises.realpath(resolved.base).catch(() => path.resolve(resolved.base));
1047
- if (!isPathWithinRoot(writePath, canonicalBase, path, os)) {
1048
- return res.status(403).json({ error: 'Access denied' });
1049
- }
1050
1269
 
1051
- const existing = await fsPromises.readFile(writePath, 'utf8').catch(() => null);
1052
- if (existing === content) {
1053
- return res.json({ success: true, path: resolved.resolved });
1054
- }
1270
+ let existing = null;
1271
+ let existingStats = null;
1272
+ let exists = false;
1273
+ try {
1274
+ const stats = await fsPromises.stat(writePath);
1275
+ if (!stats.isFile()) {
1276
+ // Preserve existing behavior for directory targets: read as text
1277
+ // fails, so treat as missing content for comparison. Stat
1278
+ // already proved the path exists but is not a file; writing
1279
+ // through rename would replace it, which must stay an error.
1280
+ // Fall through to the write attempt so the filesystem reports
1281
+ // the real failure instead of inventing a revision.
1282
+ exists = true;
1283
+ existingStats = stats;
1284
+ existing = null;
1285
+ } else {
1286
+ exists = true;
1287
+ existingStats = stats;
1288
+ existing = await fsPromises.readFile(writePath, 'utf8').catch(() => null);
1289
+ }
1290
+ } catch (error) {
1291
+ if (error && typeof error === 'object' && error.code === 'ENOENT') {
1292
+ exists = false;
1293
+ } else {
1294
+ throw error;
1295
+ }
1296
+ }
1055
1297
 
1056
- await fsPromises.mkdir(path.dirname(writePath), { recursive: true });
1298
+ let currentRevision = null;
1299
+ if (exists && existing !== null && existingStats) {
1300
+ currentRevision = revisionForContentAndStat(existing, existingStats);
1301
+ } else if (exists && existingStats) {
1302
+ currentRevision = buildFileRevision({ size: existingStats.size, mtimeMs: existingStats.mtimeMs, hash: null });
1303
+ }
1057
1304
 
1058
- // Atomic write: write to temp then rename to avoid concurrent readers
1059
- // seeing an empty file during the O_TRUNC window of direct writeFile.
1060
- const tmp = `${writePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1061
- try {
1062
- await fsPromises.writeFile(tmp, content, 'utf8');
1063
- await fsPromises.rename(tmp, writePath);
1064
- } catch (error) {
1065
- await fsPromises.unlink(tmp).catch(() => {});
1066
- throw error;
1305
+ // Idempotent no-op: identical content never conflicts and never
1306
+ // rewrites, preserving mtime/mode and avoiding spurious 409s when
1307
+ // two writers converge on the same bytes.
1308
+ if (exists && existing === content) {
1309
+ return res.json({ success: true, path: resolved.resolved, revision: currentRevision, noop: true });
1310
+ }
1311
+
1312
+ if (!forceOverwrite && expectation.mode !== 'legacy') {
1313
+ if (expectation.mode === 'missing') {
1314
+ if (exists) {
1315
+ return sendFileRevisionConflict(res, { path: resolved.resolved, currentRevision, exists: true });
1316
+ }
1317
+ } else if (expectation.mode === 'revision') {
1318
+ if (!exists) {
1319
+ return sendFileRevisionConflict(res, { path: resolved.resolved, currentRevision: null, exists: false });
1320
+ }
1321
+ if (currentRevision !== expectation.revision) {
1322
+ return sendFileRevisionConflict(res, { path: resolved.resolved, currentRevision, exists: true });
1323
+ }
1324
+ }
1325
+ }
1326
+
1327
+ await fsPromises.mkdir(path.dirname(writePath), { recursive: true });
1328
+
1329
+ // Preserve access mode across atomic replace; rename creates a new
1330
+ // inode with default permissions, so copy the existing mode onto the
1331
+ // temp file first. New files keep the process default.
1332
+ const existingMode = exists && existingStats && typeof existingStats.mode === 'number'
1333
+ ? existingStats.mode & 0o777
1334
+ : null;
1335
+
1336
+ // Atomic write: write to temp then rename to avoid concurrent readers
1337
+ // seeing an empty file during the O_TRUNC window of direct writeFile.
1338
+ // Bytes are written exactly as received; line-ending normalization
1339
+ // stays in the editor serializer, symlinks stay intact because
1340
+ // writePath is the realpath target, and binary content is never
1341
+ // decoded here.
1342
+ const tmp = `${writePath}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1343
+ try {
1344
+ await fsPromises.writeFile(tmp, content, 'utf8');
1345
+ if (existingMode !== null && typeof fsPromises.chmod === 'function') {
1346
+ await fsPromises.chmod(tmp, existingMode).catch(() => {});
1347
+ }
1348
+ await fsPromises.rename(tmp, writePath);
1349
+ } catch (error) {
1350
+ await fsPromises.unlink(tmp).catch(() => {});
1351
+ throw error;
1352
+ }
1353
+ let newRevision = null;
1354
+ try {
1355
+ const nextStats = await fsPromises.stat(writePath);
1356
+ newRevision = revisionForContentAndStat(content, nextStats);
1357
+ } catch {
1358
+ newRevision = revisionForContentAndStat(content, { size: Buffer.byteLength(content, 'utf8'), mtimeMs: Date.now() });
1359
+ }
1360
+ return res.json({ success: true, path: resolved.resolved, revision: newRevision });
1361
+ });
1362
+ if (outcome && typeof outcome === 'object' && outcome.__rekey) {
1363
+ lockKey = outcome.__rekey;
1364
+ continue;
1365
+ }
1366
+ return outcome;
1067
1367
  }
1068
- return res.json({ success: true, path: resolved.resolved });
1368
+ return outcome;
1069
1369
  } catch (error) {
1070
1370
  const err = error;
1071
1371
  if (isOsPermissionError(err)) {
@@ -1475,46 +1775,64 @@ export const registerFsRoutes = (app, dependencies) => {
1475
1775
  if (!rawPath.trim()) return res.status(400).json({ error: 'Directory path is required' });
1476
1776
 
1477
1777
  try {
1478
- const { canonicalPath } = await resolveWorkspacePath(rawPath, { scope: 'read' });
1778
+ const resolved = await resolveWorkspacePathFromContext({
1779
+ req,
1780
+ targetPath: rawPath,
1781
+ resolveProjectDirectory,
1782
+ path,
1783
+ os,
1784
+ normalizeDirectoryPath,
1785
+ pichamberUserConfigRoot,
1786
+ });
1787
+ if (!resolved.ok) {
1788
+ return res.status(400).json({ error: resolved.error });
1789
+ }
1790
+
1791
+ const [canonicalPath, canonicalBase] = await Promise.all([
1792
+ realpathCache.resolve(resolved.resolved),
1793
+ realpathCache.resolve(resolved.base).catch(() => path.resolve(resolved.base)),
1794
+ ]);
1795
+ if (!isPathWithinRoot(canonicalPath, canonicalBase, path, os)) {
1796
+ return res.status(403).json({ error: 'Access to directory denied' });
1797
+ }
1798
+
1799
+ const stats = await fsPromises.stat(canonicalPath);
1800
+ if (!stats.isDirectory()) {
1801
+ return res.status(400).json({ error: 'Specified path is not a directory', reason: 'not-directory' });
1802
+ }
1803
+
1479
1804
  const query = typeof req.query.query === 'string' ? req.query.query : '';
1480
- const limit = Number.isSafeInteger(Number(req.query.limit)) ? Math.min(Number(req.query.limit), 500) : 60;
1805
+ const requestedLimit = Number(req.query.limit);
1806
+ const limit = Number.isSafeInteger(requestedLimit) ? Math.max(1, Math.min(requestedLimit, 500)) : 60;
1481
1807
  const includeHidden = req.query.includeHidden === 'true';
1482
1808
  const respectGitignore = req.query.respectGitignore !== 'false';
1483
1809
  const type = req.query.type === 'directory' ? 'directory' : req.query.type === 'file' ? 'file' : undefined;
1484
1810
 
1485
- const fsSearchRuntime = createFsSearchRuntime({ fsPromises, path, spawn, resolveGitBinaryForSpawn });
1486
1811
  const rawHits = await fsSearchRuntime.searchFilesystemFiles(canonicalPath, {
1487
1812
  query,
1488
1813
  limit,
1489
1814
  includeHidden,
1490
1815
  respectGitignore,
1816
+ type,
1491
1817
  });
1492
1818
 
1493
- const files = rawHits
1494
- .filter((hit) => {
1495
- if (type === 'file' && hit.isDir) return false;
1496
- if (type === 'directory' && !hit.isDir) return false;
1497
- return true;
1498
- })
1499
- .map((hit) => {
1500
- const hitPath = hit.path.replace(/\\/g, '/');
1501
- const rootNorm = canonicalPath.replace(/\\/g, '/');
1502
- const relativePath = hitPath.startsWith(rootNorm)
1503
- ? hitPath.slice(rootNorm.length).replace(/^\//, '')
1504
- : path.basename(hitPath);
1505
- const name = path.basename(hitPath);
1506
- return {
1507
- name,
1508
- path: hitPath,
1509
- relativePath,
1510
- ...(name.includes('.') ? { extension: name.split('.').pop().toLowerCase() } : {}),
1511
- };
1512
- });
1819
+ const logicalRoot = path.resolve(resolved.resolved);
1820
+ const files = rawHits.map((hit) => {
1821
+ const relativePath = hit.relativePath.replace(/\\/g, '/');
1822
+ const hitPath = path.join(logicalRoot, hit.relativePath).replace(/\\/g, '/');
1823
+ const name = hit.name;
1824
+ return {
1825
+ name,
1826
+ path: hitPath,
1827
+ relativePath,
1828
+ ...(hit.extension ? { extension: hit.extension } : {}),
1829
+ };
1830
+ });
1513
1831
 
1514
1832
  return res.json({ files });
1515
1833
  } catch (error) {
1516
- if (error && error.code === 'WORKSPACE_ACCESS_DENIED') {
1517
- return sendWorkspaceAccessDenied(res, 'Access to directory denied');
1834
+ if (isOsPermissionError(error)) {
1835
+ return sendOsPermissionDenied(res, 'Access to directory denied');
1518
1836
  }
1519
1837
  return res.status(500).json({ error: (error && error.message) || 'Failed to search files' });
1520
1838
  }