@jc_stack/ez-library 0.1.0-beta.20 → 0.1.0-beta.22

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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.0-beta.22
4
+
5
+ - Files and directories the Library creates under `files/` (`put`, `gzip`, `replace`, `organize` destinations) are now group read/write (`0660`/`0770`) instead of `0600`/`0700`. On a host where the content directory carries a default ACL for another account (the Stocks VM grants the agent's executor `ezrelay` this way), a `0600` file or `0700` directory made the ACL mask empty, so the executor got `Permission denied` on every new or rewritten file until the ACL was repaired by hand. Others still get nothing; receipts, history, locks and other state stay `0600`/`0700`.
6
+
7
+ ## 0.1.0-beta.21
8
+
9
+ - Git sync can no longer hang forever holding the writer lock. The SSH command adds `ServerAliveInterval=15` and `ServerAliveCountMax=4`, and every remote-touching Git call (fetch, push, ls-remote, in sync, text mirror and adoption) is bounded at 5 minutes: on expiry the child is stopped (SIGTERM, then SIGKILL after 5 seconds) and the cycle fails `UNAVAILABLE`, so the lock is released and the next interval retries. Before this, a connection that stalled after connect left `sync-status` at `syncing` and every writer `BUSY` until the service was restarted (#53).
10
+ - `sync/status.json` records the current `step` while a cycle runs (`fetch`, `push`, `verify`, then `mirror-read`, `mirror-fetch`, `mirror-push` and `index`); a failed Git transfer or index keeps its step, so `sync-status` shows where it stopped. A text-mirror failure is reported in `textMirror.error`, naming the failed operation.
11
+ - Requires Ez core 0.1.0-beta.50 or newer (unchanged).
12
+
3
13
  ## 0.1.0-beta.20
4
14
 
5
15
  - Reclaim a writer lock left by a dead process on the same host. The lock owner now records a per-process id; a same-host lock whose pid no longer exists, or that names this process's pid without its id (a restarted container reusing pid and hostname), is removed. Reclaimers take turns under an exclusive mutex and remove the lock only if it still names the same dead owner, so concurrent callers never take over a live lock. Before this, a restarted resident worker read the dead writer's lock as its own and failed `BUSY` on every cycle until the lock was removed by hand. Locks from other hosts, locks without an owner and an unreadable owner pid still fail closed; a reclaim mutex left by a crash makes writers wait and fail `BUSY` naming it. Same hostname is taken to mean the same pid namespace (Docker's default).
package/ez-plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "id": "library",
4
- "version": "0.1.0-beta.20",
4
+ "version": "0.1.0-beta.22",
5
5
  "description": "Dockerized agent library files, QMD retrieval and explicit persistence settings",
6
6
  "example": "library search 'quarterly budget' --all --limit 5",
7
7
  "commands": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jc_stack/ez-library",
3
- "version": "0.1.0-beta.20",
3
+ "version": "0.1.0-beta.22",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "latest"
@@ -2,7 +2,7 @@ import * as fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { atomic, fail, hash, jsonBytes, locked, safePath } from './store.mjs';
4
4
  import { inventory } from './indexer.mjs';
5
- import { git, repositoryURL, tree } from './git-sync.mjs';
5
+ import { git, network, repositoryURL, tree } from './git-sync.mjs';
6
6
  import { native, succeeded } from './native.mjs';
7
7
 
8
8
  const file = root => path.join(root, 'sync/text-mirror.json');
@@ -88,13 +88,13 @@ export async function mirrorAdopt(root, repository, branch = 'main', extensions
88
88
  if (origin.code !== 0) succeeded(await mirrorGit(root, config, ['remote', 'add', 'origin', repositoryURL(repository)]), 'Set mirror remote');
89
89
  // Existing history requires an exact reviewed remote revision and a safe
90
90
  // projection. Adoption never writes source files or pushes a remote change.
91
- const existing = succeeded(await mirrorGit(root, config, ['ls-remote', 'origin', 'refs/heads/' + branch]), 'Check mirror destination');
91
+ const existing = succeeded(await mirrorGit(root, config, ['ls-remote', 'origin', 'refs/heads/' + branch], network()), 'Check mirror destination');
92
92
  const remoteHead = existing.trim().split(/\s+/)[0];
93
93
  if (expectedRemote !== undefined && !/^[a-f0-9]{40}$/.test(expectedRemote)) fail('INVALID', 'Use the full expected remote commit SHA');
94
94
  if (remoteHead && !expectedRemote) fail('CONFLICT', 'Existing mirror history requires --expected-remote with the reviewed commit SHA');
95
95
  if (expectedRemote && remoteHead !== expectedRemote) fail('CONFLICT', 'Mirror remote no longer matches the expected commit');
96
96
  if (remoteHead) {
97
- succeeded(await mirrorGit(root, config, ['fetch', '--no-tags', 'origin', 'refs/heads/' + branch]), 'Fetch existing mirror');
97
+ succeeded(await mirrorGit(root, config, ['fetch', '--no-tags', 'origin', 'refs/heads/' + branch], network()), 'Fetch existing mirror');
98
98
  if (succeeded(await mirrorGit(root, config, ['rev-parse', 'FETCH_HEAD']), 'Read fetched mirror').trim() !== expectedRemote) fail('CONFLICT', 'Mirror changed during adoption');
99
99
  const entries = await tree(root, { ...config, textMirror: true }, 'FETCH_HEAD');
100
100
  canonicalHistory(entries);
@@ -123,20 +123,22 @@ export async function mirrorPolicy(root, expected, mode) {
123
123
  });
124
124
  }
125
125
  // Caller holds the Library writer lock, after a successful folder transfer.
126
- export async function mirrorTransfer(root) {
126
+ export async function mirrorTransfer(root, step = async () => {}) {
127
127
  const { config } = await mirrorStatus(root);
128
128
  if (!config || config.mode === 'paused') return { state: config ? 'paused' : 'disabled' };
129
129
  const selected = textProjection(await inventory(path.join(root, 'files')), config);
130
130
  const run = (args, options) => mirrorGit(root, config, args, options);
131
131
  if (succeeded(await run(['remote', 'get-url', 'origin']), 'Check mirror remote').trim() !== repositoryURL(config.repository)) fail('CONFLICT', 'Mirror remote changed');
132
- const remote = succeeded(await run(['ls-remote', 'origin', 'refs/heads/' + config.branch]), 'Read mirror head').trim().split(/\s+/)[0];
132
+ await step('mirror-read');
133
+ const remote = succeeded(await run(['ls-remote', 'origin', 'refs/heads/' + config.branch], network()), 'Read mirror head').trim().split(/\s+/)[0];
133
134
  const local = await run(['rev-parse', '--verify', 'HEAD']);
134
135
  if (local.code === 0) canonicalHistory(await tree(root, { ...config, textMirror: true }, 'HEAD'));
135
136
  if (remote) {
136
137
  if (config.lastCommit && remote !== config.lastCommit && remote !== local.stdout.trim()) fail('CONFLICT', 'Mirror branch was changed externally');
137
138
  if (local.code !== 0) fail('CONFLICT', 'Mirror remote changed before first commit');
138
139
  if (remote !== local.stdout.trim()) {
139
- succeeded(await run(['fetch', '--no-tags', 'origin', 'refs/heads/' + config.branch]), 'Fetch mirror head');
140
+ await step('mirror-fetch');
141
+ succeeded(await run(['fetch', '--no-tags', 'origin', 'refs/heads/' + config.branch], network()), 'Fetch mirror head');
140
142
  if ((await run(['merge-base', '--is-ancestor', 'FETCH_HEAD', 'HEAD'])).code !== 0) fail('CONFLICT', 'GitHub mirror was edited externally; preserve and reconcile it before resuming');
141
143
  }
142
144
  } else if (config.lastCommit) fail('CONFLICT', 'Mirror branch disappeared; no automatic recreation');
@@ -163,8 +165,9 @@ export async function mirrorTransfer(root) {
163
165
  const commit = succeeded(await run(['rev-parse', 'HEAD']), 'Read mirror commit').trim();
164
166
  // The remote head read above already proves an unchanged projection.
165
167
  if (remote !== commit) {
166
- succeeded(await run(['push', 'origin', 'HEAD:refs/heads/' + config.branch]), 'Push text mirror');
167
- const verified = succeeded(await run(['ls-remote', 'origin', 'refs/heads/' + config.branch]), 'Verify text mirror').trim().split(/\s+/)[0];
168
+ await step('mirror-push');
169
+ succeeded(await run(['push', 'origin', 'HEAD:refs/heads/' + config.branch], network()), 'Push text mirror');
170
+ const verified = succeeded(await run(['ls-remote', 'origin', 'refs/heads/' + config.branch], network()), 'Verify text mirror').trim().split(/\s+/)[0];
168
171
  if (verified !== commit) fail('UNCERTAIN', 'Mirror advanced during verification');
169
172
  }
170
173
  if (config.lastCommit !== commit) await atomic(file(root), jsonBytes({ ...config, lastCommit: commit }));
package/src/git-sync.mjs CHANGED
@@ -32,6 +32,10 @@ export async function gitKey(root, repository) {
32
32
  });
33
33
  }
34
34
 
35
+ // Remote-touching Git calls are bounded so a stalled transport ends the cycle
36
+ // (UNAVAILABLE) and releases the writer lock instead of blocking every writer.
37
+ export const network = () => ({ timeout: Number(process.env.EZ_LIBRARY_GIT_TIMEOUT_MS) || 5 * 60 * 1000 });
38
+
35
39
  export function git(root, config, args, options = {}) {
36
40
  const dir = privateDir(root, config.repository);
37
41
  const workTree = path.join(root, config.textMirror ? 'sync/text-mirror/files' : 'files');
@@ -41,7 +45,7 @@ export function git(root, config, args, options = {}) {
41
45
  '-c', 'user.name=Ez Library', '-c', 'user.email=library@localhost', ...args], {
42
46
  ...options, env: { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0',
43
47
  GIT_ALLOW_PROTOCOL: path.isAbsolute(config.repository) ? 'file' : 'ssh',
44
- GIT_SSH_COMMAND: ['/usr/bin/ssh', '-F', '/dev/null', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'IdentitiesOnly=yes',
48
+ GIT_SSH_COMMAND: ['/usr/bin/ssh', '-F', '/dev/null', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'ServerAliveInterval=15', '-o', 'ServerAliveCountMax=4', '-o', 'IdentitiesOnly=yes',
45
49
  '-o', 'StrictHostKeyChecking=yes', '-o', 'UserKnownHostsFile=' + path.join(dir, 'known_hosts'), '-i', path.join(dir, 'key')].map(quote).join(' ') } });
46
50
  }
47
51
 
@@ -106,7 +110,7 @@ export async function gitAdopt(root, repository, branch = 'main', stateRoot = ro
106
110
  if (reuseCheckout) {
107
111
  config.checkoutOrigin = await existingCheckout(root, config);
108
112
  await tree(root, config, 'HEAD');
109
- succeeded(await git(root, config, ['fetch', '--no-tags', remote, 'refs/heads/' + branch]), 'Verify selected remote');
113
+ succeeded(await git(root, config, ['fetch', '--no-tags', remote, 'refs/heads/' + branch], network()), 'Verify selected remote');
110
114
  await tree(root, config, 'FETCH_HEAD');
111
115
  // No checkout, reset, commit or push during adoption. Native history and
112
116
  // eligible unstaged edits remain owned by the existing checkout.
@@ -129,7 +133,7 @@ export async function gitAdopt(root, repository, branch = 'main', stateRoot = ro
129
133
  succeeded(await git(root, config, ['remote', 'add', 'origin', remote]), 'Set Git remote');
130
134
  // A failed setup leaves the prepared binding paused, never silently rebound.
131
135
  await atomic(binding, jsonBytes(config));
132
- succeeded(await git(root, config, ['fetch', '--no-tags', 'origin', 'refs/heads/' + branch]), 'Fetch existing branch');
136
+ succeeded(await git(root, config, ['fetch', '--no-tags', 'origin', 'refs/heads/' + branch], network()), 'Fetch existing branch');
133
137
  const entries = await tree(root, config, 'FETCH_HEAD');
134
138
  const existing = new Map(local.map(f => [f.path, f]));
135
139
  for (const entry of entries) {
@@ -148,7 +152,7 @@ export async function gitAdopt(root, repository, branch = 'main', stateRoot = ro
148
152
  });
149
153
  }
150
154
 
151
- export async function gitTransfer(root, config) {
155
+ export async function gitTransfer(root, config, step = async () => {}) {
152
156
  if (!['two-way', 'pull-only'].includes(config.mode)) fail('INVALID', 'Use two-way or pull-only Git sync');
153
157
  const pullOnly = config.mode === 'pull-only';
154
158
  await checkPolicy(root, config.repository, config.branch);
@@ -172,7 +176,8 @@ export async function gitTransfer(root, config) {
172
176
  }
173
177
  const transport = config.existingCheckout ? repositoryURL(config.repository) : 'origin';
174
178
  const trackingRef = 'refs/remotes/origin/' + config.branch;
175
- succeeded(await git(root, config, ['fetch', '--no-tags', transport, 'refs/heads/' + config.branch]), 'Fetch remote changes');
179
+ await step('fetch');
180
+ succeeded(await git(root, config, ['fetch', '--no-tags', transport, 'refs/heads/' + config.branch], network()), 'Fetch remote changes');
176
181
  await tree(root, config, 'FETCH_HEAD');
177
182
  // Native fetch may itself update origin's tracking ref, including when its
178
183
  // URL was supplied directly. Compare-and-swap against that post-fetch value.
@@ -190,8 +195,9 @@ export async function gitTransfer(root, config) {
190
195
  succeeded(merge, 'Merge remote changes');
191
196
  }
192
197
  const commit = succeeded(await git(root, config, ['rev-parse', 'HEAD']), 'Read synchronized commit').trim();
193
- if (!pullOnly) succeeded(await git(root, config, ['push', transport, 'HEAD:refs/heads/' + config.branch]), 'Push Library changes');
194
- const remote = succeeded(await git(root, config, ['ls-remote', '--exit-code', transport, 'refs/heads/' + config.branch]), 'Verify remote commit').trim().split(/\s+/)[0];
198
+ if (!pullOnly) { await step('push'); succeeded(await git(root, config, ['push', transport, 'HEAD:refs/heads/' + config.branch], network()), 'Push Library changes'); }
199
+ await step('verify');
200
+ const remote = succeeded(await git(root, config, ['ls-remote', '--exit-code', transport, 'refs/heads/' + config.branch], network()), 'Verify remote commit').trim().split(/\s+/)[0];
195
201
  if (remote !== commit) fail('UNCERTAIN', 'Remote advanced during verification; fetch/reconcile on the next cycle');
196
202
  if (config.existingCheckout) {
197
203
  // Push can also record the verified tracking value itself. Keep the guard
package/src/native.mjs CHANGED
@@ -10,7 +10,7 @@ export function environment(root) {
10
10
  ...(process.env.EZ_LIBRARY_EMBED_SOCKET ? { EZ_LIBRARY_EMBED_SOCKET: process.env.EZ_LIBRARY_EMBED_SOCKET } : {}), LANG: 'C.UTF-8',
11
11
  RCLONE_CONFIG: path.join(root, 'sync/rclone.conf') };
12
12
  }
13
- export function native(root, executable, args, { inherit = false, env = {}, input } = {}) {
13
+ export function native(root, executable, args, { inherit = false, env = {}, input, timeout } = {}) {
14
14
  return new Promise((resolve, reject) => {
15
15
  const child = spawn(executable, args, { cwd: root, env: { ...environment(root), ...env }, stdio: inherit ? 'inherit' : [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] });
16
16
  if (!inherit && input !== undefined) { child.stdin.on('error', () => {}); child.stdin.end(input); }
@@ -24,10 +24,25 @@ export function native(root, executable, args, { inherit = false, env = {}, inpu
24
24
  const terminate = () => child.kill('SIGTERM');
25
25
  const interrupt = () => child.kill('SIGINT');
26
26
  process.once('SIGTERM', terminate); process.once('SIGINT', interrupt);
27
- const cleanup = () => { process.removeListener('SIGTERM', terminate); process.removeListener('SIGINT', interrupt); };
27
+ // A bounded call that stalls is killed (SIGKILL after a grace period) and
28
+ // fails UNAVAILABLE as soon as the child exits, even if an orphaned
29
+ // grandchild still holds its pipes open.
30
+ let timedOut = false, timer, killer;
31
+ if (timeout) timer = setTimeout(() => {
32
+ timedOut = true; child.kill('SIGTERM');
33
+ killer = setTimeout(() => child.kill('SIGKILL'), 5000);
34
+ }, timeout);
35
+ const cleanup = () => { clearTimeout(timer); clearTimeout(killer); process.removeListener('SIGTERM', terminate); process.removeListener('SIGINT', interrupt); };
28
36
  child.once('error', e => { cleanup(); reject(e); });
37
+ child.once('exit', () => {
38
+ // Exited in time: the bound is met even if a grandchild still holds the pipes until close.
39
+ if (!timedOut) { clearTimeout(timer); return; }
40
+ cleanup();
41
+ try { fail('UNAVAILABLE', `${path.basename(executable)} timed out after ${Math.round(timeout / 1000)}s and was stopped`); } catch (e) { reject(e); }
42
+ });
29
43
  child.once('close', code => {
30
44
  cleanup();
45
+ if (timedOut) return;
31
46
  if (bytes > 32 * 1024 * 1024) reject(Error('Native output exceeded 32 MiB'));
32
47
  else resolve({ code: code ?? 130, stdout: out, stderr: err });
33
48
  });
package/src/store.mjs CHANGED
@@ -16,6 +16,10 @@ export const MAX_FILE_BYTES = 512 * 1024 * 1024;
16
16
  export const MAX_READ_BYTES = 512 * 1024;
17
17
  export const MAX_REPLACE_BYTES = 256 * 1024;
18
18
  const MAX_TEXT_BYTES = 8 * 1024 * 1024;
19
+ // Library content (files/) is read and edited by the agent's executor, which is not the Library's user:
20
+ // owner and group read/write, nothing for others. Under a default ACL the group bits become the ACL mask,
21
+ // so 0600 (or 0700 for a directory) would silently mask every named-user entry to no access. State stays 0600/0700.
22
+ export const CONTENT_MODE = 0o660, CONTENT_DIR_MODE = 0o770;
19
23
  export const defaults = () => ({ schemaVersion: 1, storage: { mode: 'local' }, backup: { mode: 'off' } });
20
24
 
21
25
  function keys(value, allowed) {
@@ -60,13 +64,14 @@ export async function rootDir(root, create = false) {
60
64
  if (!stat.isDirectory() || stat.isSymbolicLink()) fail('UNSAFE_PATH', 'State must be a real private directory');
61
65
  return fs.realpath(root);
62
66
  }
67
+ // makeParents creates private parents; a number sets their mode instead (content directories).
63
68
  export async function safePath(root, relative, makeParents = false) {
64
69
  if (typeof relative !== 'string' || !relative || relative.length > 1024 || /[\\\x00-\x1f\x7f]/.test(relative) || relative.split('/').some(p => !p || p.startsWith('.'))) fail('UNSAFE_PATH', 'Use a relative path without hidden, empty or parent components');
65
70
  const parts = relative.split('/');
66
71
  let target = root;
67
72
  for (let i = 0; i < parts.length; i++) {
68
73
  target = path.join(target, parts[i]);
69
- if (makeParents && i < parts.length - 1) await fs.mkdir(target, { mode: 0o700 }).catch(e => { if (e.code !== 'EEXIST') throw e; });
74
+ if (makeParents && i < parts.length - 1) await fs.mkdir(target, { mode: typeof makeParents === 'number' ? makeParents : 0o700 }).catch(e => { if (e.code !== 'EEXIST') throw e; });
70
75
  const st = await fs.lstat(target).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
71
76
  if (st && (st.isSymbolicLink() || (i < parts.length - 1 ? !st.isDirectory() : !st.isFile()))) fail('UNSAFE_PATH', 'Symlinks and special files are unsupported');
72
77
  }
@@ -204,9 +209,9 @@ export async function readRange(file, { offset, length, expected }) {
204
209
  } finally { await handle.close(); }
205
210
  }
206
211
  async function current(file) { return digest(file).catch(e => { if (e.code === 'ENOENT') return null; throw e; }); }
207
- export async function atomic(file, data) {
212
+ export async function atomic(file, data, mode = 0o600) {
208
213
  const temp = `${file}.${randomUUID()}.tmp`;
209
- try { await fs.writeFile(temp, data, { mode: 0o600, flag: 'wx' }); await fs.rename(temp, file); }
214
+ try { await fs.writeFile(temp, data, { mode, flag: 'wx' }); await fs.rename(temp, file); }
210
215
  finally { await fs.rm(temp, { force: true }); }
211
216
  }
212
217
  const jsonBytes = value => Buffer.from(JSON.stringify(value, null, 2) + '\n');
@@ -229,7 +234,7 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
229
234
  const receiptFile = operationPath(root, key);
230
235
  await safePath(root, path.relative(root, receiptFile));
231
236
  if (kind === 'file' && (typeof relative !== 'string' || !relative)) fail('INVALID', 'Supply a relative file path');
232
- const target = await safePath(root, kind === 'settings' ? 'settings.json' : 'files/' + relative, true);
237
+ const target = await safePath(root, kind === 'settings' ? 'settings.json' : 'files/' + relative, CONTENT_DIR_MODE);
233
238
  // files may be a separate bind mount: stage on the destination filesystem.
234
239
  const temp = path.join(path.dirname(target), '.ez-library-put-' + randomUUID() + '.tmp');
235
240
  let bytes = 0; const sha = createHash('sha256');
@@ -238,7 +243,7 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
238
243
  bytes += chunk.length;
239
244
  if (bytes > maxBytes) return cb(new LibraryError('TOO_LARGE', `Input exceeds ${maxBytes} bytes`));
240
245
  sha.update(chunk); cb(null, chunk);
241
- } }), createWriteStream(temp, { flags: 'wx', mode: 0o600 }));
246
+ } }), createWriteStream(temp, { flags: 'wx', mode: kind === 'file' ? CONTENT_MODE : 0o600 }));
242
247
  const request = { kind, path: kind === 'settings' ? 'settings.json' : relative, bytes, sha256: sha.digest('hex'), expected,
243
248
  ...(source ? { source } : {}) };
244
249
  const oldReceipt = await fs.readFile(receiptFile, 'utf8').then(JSON.parse).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
@@ -342,7 +347,7 @@ export async function replaceText(root, relative, replacement, { key } = {}) {
342
347
  await fs.copyFile(target, history, constants.COPYFILE_EXCL).catch(error => { if (error.code !== 'EEXIST') throw error; });
343
348
  await fs.chmod(history, 0o600);
344
349
  await atomic(receiptFile, jsonBytes(request));
345
- await atomic(target, next);
350
+ await atomic(target, next, CONTENT_MODE);
346
351
  const after = await replacementView(root, request);
347
352
  if (after.state !== 'stored' || after.sha256 !== hash(next)) fail('UNCERTAIN', 'Replacement readback differs; inspect operation before retry');
348
353
  return { ...after, replay: false };
@@ -354,7 +359,7 @@ export async function organize(root, { path: relative, to, expected, key }) {
354
359
  if (relative === 'LIBRARY_SYNC_ACCESS' || to === 'LIBRARY_SYNC_ACCESS') fail('INVALID', 'The sync access marker is reserved');
355
360
  return locked(root, async root => {
356
361
  const source = await safePath(root, 'files/' + relative);
357
- const target = to === undefined ? null : await safePath(root, 'files/' + to, true);
362
+ const target = to === undefined ? null : await safePath(root, 'files/' + to, CONTENT_DIR_MODE);
358
363
  if (target === source) fail('INVALID', 'Source and destination must differ');
359
364
  const receipt = { kind: target ? 'move' : 'remove', path: relative, ...(target ? { to } : {}), expected };
360
365
  const file = await safePath(root, path.relative(root, operationPath(root, key)));
package/src/sync.mjs CHANGED
@@ -151,17 +151,20 @@ export async function syncRun(root, stateRoot = root, { signal } = {}) {
151
151
  if (!config && mirror?.mode !== 'one-way') return { state: mirror ? 'paused' : 'unconfigured' };
152
152
  let status = { state: 'syncing', startedAt: new Date().toISOString() };
153
153
  await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
154
+ // Record where a slow cycle is; the step stays on a failed status.
155
+ const step = async name => { status.step = name; await atomic(path.join(root, 'sync/status.json'), jsonBytes(status)); };
154
156
  try {
155
- if (config?.backend === 'git') status.git = await gitTransfer(root, config);
157
+ if (config?.backend === 'git') status.git = await gitTransfer(root, config, step);
156
158
  else if (config) {
157
159
  if (config.mode !== 'two-way') fail('INVALID', 'Folder sync requires two-way mode');
158
160
  if (await remoteIdentity(root, config.remote, stateRoot) !== config.identity) fail('CONFLICT', 'Mapped folder disappeared or changed identity; no automatic recreation');
159
161
  succeeded(await rclone(root, bisyncArgs(root, config)), 'Native bisync');
160
162
  }
161
- status = { ...status, state: 'indexing', syncedAt: new Date().toISOString() };
163
+ status = { ...status, state: 'indexing', step: 'index', syncedAt: new Date().toISOString() };
162
164
  await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
163
- try { status.textMirror = await mirrorTransfer(root); }
165
+ try { status.textMirror = await mirrorTransfer(root, step); }
164
166
  catch (error) { status.textMirror = { state: 'pending', error: { code: error.code || 'UNAVAILABLE', message: error.message } }; }
167
+ await step('index');
165
168
  const index = await refreshIndex(root);
166
169
  status = { ...status, state: index.conflicts?.length ? 'synced-with-conflicts' : index.pending.length ? 'indexed-with-pending-extraction' : 'synced-and-indexed', indexedAt: index.indexedAt, embedded: index.embedded };
167
170
  } catch (error) {
@@ -169,6 +172,7 @@ export async function syncRun(root, stateRoot = root, { signal } = {}) {
169
172
  await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
170
173
  throw error;
171
174
  }
175
+ delete status.step;
172
176
  await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
173
177
  if (status.textMirror?.state === 'pending') fail('UNAVAILABLE', 'GitHub text mirror pending: ' + status.textMirror.error.message);
174
178
  return status;
@@ -27,7 +27,7 @@ test('gzip keeps large binary data inside Library and records source/target proo
27
27
  assert.equal(result.source.sha256, hash(data));
28
28
  assert.equal(result.source.bytes, data.length);
29
29
  assert.equal(result.state, 'stored');
30
- assert.equal((await fs.stat(path.join(root, 'files', request.to))).mode & 0o777, 0o600);
30
+ assert.equal((await fs.stat(path.join(root, 'files', request.to))).mode & 0o047, 0o040); // group-readable, nothing for others
31
31
  assert.deepEqual(await fs.readFile(path.join(root, 'files', request.path)), data);
32
32
  assert.equal((await operation(root, request.key)).state, 'stored');
33
33
  assert.equal((await gzipFile(root, request)).replay, true);
@@ -7,7 +7,7 @@ import { execFileSync } from 'node:child_process';
7
7
  import { Readable } from 'node:stream';
8
8
  import { gitAdopt, gitTransfer, git, repositoryURL } from '../src/git-sync.mjs';
9
9
  import { locked, put, digest, organize, jsonBytes } from '../src/store.mjs';
10
- import { syncPolicy, syncStatus } from '../src/sync.mjs';
10
+ import { syncPolicy, syncRun, syncStatus } from '../src/sync.mjs';
11
11
 
12
12
  async function setup(t) {
13
13
  const base = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'library-git-')));
@@ -302,3 +302,39 @@ test('existing checkout rejects staged work, branch changes and origin changes w
302
302
  await assert.rejects(cycle(root, config), { code: 'CONFLICT' });
303
303
  assert.equal(await fs.readFile(path.join(checkout, 'note0.md'), 'utf8'), 'User staged edit');
304
304
  });
305
+
306
+ test('a stalled Git transport ends the cycle UNAVAILABLE, releases the writer lock and the next sync succeeds', async t => {
307
+ const { base, root, remote, outside } = await setup(t);
308
+ const { config } = await gitAdopt(root, remote);
309
+ // A transport that connects, then never answers.
310
+ const stall = path.join(base, 'stall.sh');
311
+ await fs.writeFile(stall, '#!/bin/sh\nexec sleep 120\n', { mode: 0o755 });
312
+ await git(root, config, ['config', 'remote.origin.uploadpack', stall]);
313
+ await put(root, 'stalled.md', Readable.from(['# Stalled\nMarigold ledger.']), { expected: 'new', key: 'stalled' });
314
+ const previous = process.env.EZ_LIBRARY_GIT_TIMEOUT_MS;
315
+ process.env.EZ_LIBRARY_GIT_TIMEOUT_MS = '1500';
316
+ t.after(() => { if (previous === undefined) delete process.env.EZ_LIBRARY_GIT_TIMEOUT_MS; else process.env.EZ_LIBRARY_GIT_TIMEOUT_MS = previous; });
317
+ const started = Date.now();
318
+ await assert.rejects(syncRun(root), { code: 'UNAVAILABLE', message: /timed out/ });
319
+ assert(Date.now() - started < 30000, 'the stalled fetch was stopped, not waited for');
320
+ const failed = (await syncStatus(root)).status;
321
+ assert.equal(failed.state, 'sync-error');
322
+ assert.equal(failed.step, 'fetch');
323
+ assert.equal(failed.error.code, 'UNAVAILABLE');
324
+ // The writer lock is free: another writer is not BUSY.
325
+ await put(root, 'after.md', Readable.from(['# After\nHeron.']), { expected: 'new', key: 'after' });
326
+ await git(root, config, ['config', '--unset', 'remote.origin.uploadpack']);
327
+ // The next cycle takes the same writer lock and transfers both files.
328
+ const result = await cycle(root, config);
329
+ assert.equal(result.remoteVerified, true);
330
+ assert.match(outside(['--git-dir', remote, 'show', 'main:stalled.md']), /Marigold/);
331
+ assert.match(outside(['--git-dir', remote, 'show', 'main:after.md']), /Heron/);
332
+ });
333
+
334
+ test('a bounded call that exits in time settles even while a grandchild still holds its pipes', async t => {
335
+ const { native } = await import('../src/native.mjs');
336
+ const root = await fs.mkdtemp(path.join(tmpdir(), 'ez-library-native-'));
337
+ t.after(() => fs.rm(root, { recursive: true, force: true }));
338
+ const result = await native(root, '/bin/sh', ['-c', 'sleep 2 & exit 0'], { timeout: 500 });
339
+ assert.equal(result.code, 0);
340
+ });
@@ -23,7 +23,7 @@ test('intake preserves binary bytes, private modes, literal paths and replay acr
23
23
  const r = await put(root, relative, input(data), { key: 'binary:1', expected: 'new' });
24
24
  assert.equal(r.state, 'stored'); assert.equal(r.sha256, hash(data));
25
25
  assert.deepEqual(await fs.readFile(path.join(root, 'files', relative)), data);
26
- assert.equal((await fs.stat(path.join(root, 'files', relative))).mode & 0o777, 0o600);
26
+ assert.equal((await fs.stat(path.join(root, 'files', relative))).mode & 0o047, 0o040); // group-readable, nothing for others
27
27
  assert.equal((await put(root, relative, input(data), { key: 'binary:1', expected: 'new' })).replay, true);
28
28
  const read = spawnSync(process.execPath, [cli, 'get', '--path', relative, '--raw'], { env: { ...process.env, EZ_LIBRARY_STATE: root } });
29
29
  assert.equal(read.status, 0); assert.deepEqual(read.stdout, data);
@@ -29,7 +29,7 @@ test('scoped replacements preserve interleaved writers, exact bytes and replay',
29
29
  assert.equal((await replaceText(root, 'runs/day.md', a, { key: 'a' })).replay, true);
30
30
  assert.equal(await read(root), expected);
31
31
  assert.equal(await fs.readFile(path.join(root, 'history', hash(initial)), 'utf8'), initial);
32
- assert.equal((await fs.stat(path.join(root, 'files/runs/day.md'))).mode & 0o777, 0o600);
32
+ assert.equal((await fs.stat(path.join(root, 'files/runs/day.md'))).mode & 0o047, 0o040); // group-readable, nothing for others
33
33
  assert.equal('before' in await operation(root, 'a'), false);
34
34
  // A changed owning block does not become a stale overwrite on replay.
35
35
  await replaceText(root, 'runs/day.md', { before: a.after, after: a.after + 'new progress\r\n' }, { key: 'a2' });
@@ -88,3 +88,20 @@ test('replace CLI uses bounded JSON, not shell or regex interpretation', async t
88
88
  assert.equal(run(Buffer.from([255])).status, 2);
89
89
  assert.equal(run(' '.repeat(MAX_REPLACE_BYTES + 1)).status, 2);
90
90
  });
91
+
92
+ test('content files and directories are group read/write for the executor; state stays private', async t => {
93
+ // A default ACL on the content directory turns the group bits into its mask, so a 0600 file hides every
94
+ // named-user ACL entry (the agent's executor) from its own workspace. Keep the creation mode, whatever the umask.
95
+ const previous = process.umask(0); t.after(() => process.umask(previous));
96
+ const root = await fixture(t);
97
+ const mode = file => fs.stat(path.join(root, file)).then(s => s.mode & 0o777);
98
+ assert.equal(await mode('files/runs/day.md'), 0o660);
99
+ assert.equal(await mode('files/runs'), 0o770);
100
+ await replaceText(root, 'runs/day.md', a, { key: 'mode-a' });
101
+ assert.equal(await mode('files/runs/day.md'), 0o660);
102
+ await replaceText(root, 'runs/day.md', b, { key: 'mode-b' });
103
+ const stateFiles = [...await fs.readdir(path.join(root, 'history')).then(n => n.map(x => 'history/' + x)),
104
+ ...await fs.readdir(path.join(root, 'operations')).then(n => n.map(x => 'operations/' + x))];
105
+ assert.ok(stateFiles.length >= 3);
106
+ for (const file of stateFiles) assert.equal(await mode(file), 0o600, file);
107
+ });