@trama-dev/runtime 0.4.0 → 0.5.0

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/dist/types.d.ts CHANGED
@@ -6,13 +6,13 @@ export interface Ctx {
6
6
  };
7
7
  /**
8
8
  * Persistent state. Must be strictly JSON-serializable.
9
- * Local working copy — only checkpoint() and done() persist to disk.
9
+ * Local working copy — only checkpoint(), yield() and done() persist to disk.
10
10
  * Reserved keys: any key starting with `__trama_` is reserved.
11
11
  */
12
12
  state: Record<string, unknown>;
13
13
  /**
14
14
  * Current iteration counter (starts at 0).
15
- * Advances only when checkpoint() or done() is called.
15
+ * Advances only when checkpoint(), yield() or done() is called.
16
16
  */
17
17
  iteration: number;
18
18
  /** Max iterations hint. Not enforced by runtime. */
@@ -30,7 +30,10 @@ export interface Ctx {
30
30
  * Idempotent: second call is a no-op.
31
31
  */
32
32
  ready(data?: Record<string, unknown>): Promise<void>;
33
- /** Persist current ctx.state to disk */
33
+ /**
34
+ * Persist current ctx.state to disk.
35
+ * Throws once done() or yield() has been called: the run has ended, and its state is settled.
36
+ */
34
37
  checkpoint(): Promise<void>;
35
38
  /**
36
39
  * Signal program completion. Persists state (logging is best-effort).
@@ -1,2 +1,9 @@
1
1
  import type { Workspace } from "./types.js";
2
+ /**
3
+ * Make sure a workspace directory exists where `workspaceDir` leads, and
4
+ * return its resolved path. Unlike a project, a workspace is nothing but its
5
+ * path and is made as needed — also when `workspaceDir` is a link whose target
6
+ * is not there yet.
7
+ */
8
+ export declare function ensureWorkspaceDir(workspaceDir: string): string;
2
9
  export declare function createWorkspace(workspaceDir: string, signal?: AbortSignal): Workspace;
package/dist/workspace.js CHANGED
@@ -1,27 +1,24 @@
1
- import { readFileSync, writeFileSync, mkdirSync, readdirSync, readlinkSync, realpathSync, lstatSync, statSync, renameSync, fdatasyncSync, openSync, closeSync, } from "fs";
2
- import { resolve, dirname, relative, sep } from "path";
3
- import { guardPath, isInside, realRootOf, resolveBounded } from "./path-guard.js";
1
+ import { readFileSync, mkdirSync, readdirSync, statSync } from "fs";
2
+ import { resolve, relative, sep } from "path";
3
+ import { onAbort } from "./abort.js";
4
+ import { guardPath, realRootOf } from "./path-guard.js";
5
+ import { isStagedName, stageFile } from "./replace-file.js";
4
6
  const OBSERVE_POLL_MS = 250;
5
7
  /**
6
- * Match a simple glob pattern against a relative path.
7
- * Supports `*` (any segment chars), `?` (single char), and `**` (any path segments).
8
- * `** /` matches zero or more directory segments (including root).
8
+ * Compile a simple glob pattern for matching relative paths: `*` is any run
9
+ * of characters within a segment, `?` one of them, `**` any run of characters
10
+ * at all, and `**` with its slash any number of whole segments, none included
11
+ * (so `**` + `/*.md` matches at the root too). Every other character is itself.
12
+ *
13
+ * The pattern is taken apart at its operators and each piece between them
14
+ * escaped whole — nothing is put into the pattern on the way, so there is no
15
+ * text a pattern could hold that is mistaken for an operator.
9
16
  */
10
- function matchGlob(pattern, filePath) {
11
- // Replace ** with placeholders before escaping
12
- let regex = pattern
13
- .replace(/\*\*\//g, "\x00GLOBSTARSLASH\x00")
14
- .replace(/\*\*/g, "\x00GLOBSTAR\x00");
15
- // Escape regex special chars except * and ?
16
- regex = regex
17
- .replace(/[.+^${}()|[\]\\]/g, "\\$&")
18
- .replace(/\*/g, "[^/]*")
19
- .replace(/\?/g, "[^/]");
20
- // Restore placeholders
21
- regex = regex
22
- .replace(/\x00GLOBSTARSLASH\x00/g, "(?:.+/)?")
23
- .replace(/\x00GLOBSTAR\x00/g, ".*");
24
- return new RegExp(`^${regex}$`).test(filePath);
17
+ function compileGlob(pattern) {
18
+ const literal = (text) => text.replace(/[.+^${}()|[\]\\]/g, "\\$&");
19
+ const within = (segment) => segment.split("?").map((part) => part.split("*").map(literal).join("[^/]*")).join("[^/]");
20
+ const regex = pattern.split("**/").map((part) => part.split("**").map(within).join(".*")).join("(?:.+/)?");
21
+ return new RegExp(`^${regex}$`);
25
22
  }
26
23
  /**
27
24
  * A pattern with no glob operators names exactly one artifact.
@@ -31,81 +28,89 @@ function isExactPath(pattern) {
31
28
  return !/[*?]/.test(pattern);
32
29
  }
33
30
  /**
34
- * Recursively list all files under a directory, as forward-slash paths relative to root.
35
- * Includes symlinks to files and follows symlinked directories, but only if
36
- * they resolve inside the bounded root (prevents symlink escapes).
31
+ * List the files under a directory of a workspace, as forward-slash paths
32
+ * relative to `root`, into `found`. Links to files are included, and links
33
+ * to directories followed, but only those the guard lets through: what is
34
+ * listed is what can be read.
37
35
  *
38
- * Cycle detection: only symlinked directories are tracked in the `visited` set
39
- * (by their resolved realpath). Regular directories cannot create cycles on their
40
- * own, so they are traversed unconditionally. This allows legitimate directory
41
- * aliases (symlink pointing to another dir in the workspace) to produce their
42
- * own workspace-relative paths alongside the original directory's paths.
36
+ * A link to a directory is an alias: what is in that directory is listed
37
+ * under the link's name too. It is followed where it really is — in a
38
+ * directory reached by no link — and not again where it is come upon by way
39
+ * of another link (`byLink`). So every alias of a shared directory is listed,
40
+ * a loop is gone round once, and the work is bounded by the links there are
41
+ * times what they lead to; following links found through links, it is
42
+ * bounded by nothing but the length of a path. What this leaves unlisted,
43
+ * though it can be read: what lies beyond a second link to a directory. (A
44
+ * link to a file costs nothing to list, wherever it is come upon.)
43
45
  */
44
- function listFilesRecursive(dir, root, realRoot, visited = new Set()) {
45
- const results = [];
46
+ function listFiles(dir, root, found, byLink = false) {
46
47
  let entries;
47
48
  try {
48
49
  entries = readdirSync(dir, { withFileTypes: true });
49
50
  }
50
51
  catch {
51
- return results;
52
+ return;
52
53
  }
53
- const addFile = (full) => results.push(relative(root, full).split(sep).join("/"));
54
+ // A temp file left by a write that was cut off is not an artifact.
55
+ const addFile = (full) => { if (!isStagedName(full))
56
+ found.push(relative(root, full).split(sep).join("/")); };
54
57
  for (const entry of entries) {
55
58
  const full = resolve(dir, entry.name);
56
59
  if (entry.isSymbolicLink()) {
57
- let real;
60
+ let stat;
58
61
  try {
59
- real = realpathSync(full);
62
+ guardPath(root, full); // leads out of the workspace, or nowhere: not listed
63
+ stat = statSync(full);
60
64
  }
61
65
  catch {
62
- continue; /* dangling symlink */
66
+ continue;
63
67
  }
64
- if (!isInside(real, realRoot))
65
- continue; // escapes workspace
66
- try {
67
- const stat = statSync(full);
68
- if (stat.isDirectory()) {
69
- if (visited.has(real))
70
- continue;
71
- visited.add(real);
72
- results.push(...listFilesRecursive(full, root, realRoot, visited));
73
- }
74
- else if (stat.isFile()) {
75
- addFile(full);
76
- }
77
- }
78
- catch { /* stat failed */ }
68
+ if (stat.isFile())
69
+ addFile(full);
70
+ else if (stat.isDirectory() && !byLink)
71
+ listFiles(full, root, found, true);
79
72
  }
80
73
  else if (entry.isDirectory()) {
81
- results.push(...listFilesRecursive(full, root, realRoot, visited));
74
+ listFiles(full, root, found, byLink);
82
75
  }
83
76
  else if (entry.isFile()) {
84
77
  addFile(full);
85
78
  }
86
79
  }
87
- return results;
88
80
  }
89
81
  /** Resolve after `ms`, or reject as soon as `signal` aborts. */
90
82
  function sleep(ms, signal) {
91
83
  return new Promise((resolve, reject) => {
92
- const onAbort = () => {
93
- clearTimeout(timer);
94
- reject(new Error("workspace.observe() aborted"));
95
- };
96
84
  const timer = setTimeout(() => {
97
- signal?.removeEventListener("abort", onAbort);
85
+ offAbort();
98
86
  resolve();
99
87
  }, ms);
100
- signal?.addEventListener("abort", onAbort, { once: true });
88
+ const offAbort = onAbort(signal, () => {
89
+ clearTimeout(timer);
90
+ reject(new Error("workspace.observe() aborted"));
91
+ });
101
92
  });
102
93
  }
103
- export function createWorkspace(workspaceDir, signal) {
94
+ /**
95
+ * Make sure a workspace directory exists where `workspaceDir` leads, and
96
+ * return its resolved path. Unlike a project, a workspace is nothing but its
97
+ * path and is made as needed — also when `workspaceDir` is a link whose target
98
+ * is not there yet.
99
+ */
100
+ export function ensureWorkspaceDir(workspaceDir) {
104
101
  const root = resolve(workspaceDir);
105
- mkdirSync(root, { recursive: true });
106
- const realRoot = realRootOf(root);
102
+ mkdirSync(realRootOf(root), { recursive: true });
103
+ return root;
104
+ }
105
+ export function createWorkspace(workspaceDir, signal) {
106
+ const root = ensureWorkspaceDir(workspaceDir);
107
107
  /** All artifact paths matching a glob, sorted. */
108
- const listMatching = (pattern) => listFilesRecursive(root, root, realRoot).filter(f => matchGlob(pattern, f)).sort();
108
+ const listMatching = (pattern) => {
109
+ const re = compileGlob(pattern);
110
+ const found = [];
111
+ listFiles(root, root, found);
112
+ return found.filter(f => re.test(f)).sort();
113
+ };
109
114
  /** Read an artifact, or null if it is missing, unreadable, or escapes the workspace. */
110
115
  const readIfPresent = (path) => {
111
116
  try {
@@ -128,42 +133,9 @@ export function createWorkspace(workspaceDir, signal) {
128
133
  }
129
134
  },
130
135
  async write(path, content) {
131
- const target = guardPath(root, path);
132
- mkdirSync(dirname(target), { recursive: true });
133
- // If the target is a symlink, write to what it points at rather than
134
- // replacing the link (matches tools.write). guardPath has already
135
- // verified the destination stays inside the workspace.
136
- let writePath = target;
137
- try {
138
- if (lstatSync(target).isSymbolicLink()) {
139
- try {
140
- writePath = realpathSync(target);
141
- }
142
- catch (e) {
143
- if (e.code !== "ENOENT")
144
- throw e;
145
- // Dangling symlink — resolve the link destination manually
146
- writePath = resolve(dirname(target), readlinkSync(target));
147
- mkdirSync(dirname(writePath), { recursive: true });
148
- }
149
- }
150
- }
151
- catch (e) {
152
- if (e.code !== "ENOENT")
153
- throw e;
154
- }
155
- // Atomic write: temp file in the same directory, fsync, rename.
156
- // Readers see either the old content or the new — never a partial file.
157
- const tmpFile = writePath + `.trama-tmp-${process.pid}-${Date.now()}`;
158
- const fd = openSync(tmpFile, "w");
159
- try {
160
- writeFileSync(fd, content);
161
- fdatasyncSync(fd);
162
- }
163
- finally {
164
- closeSync(fd);
165
- }
166
- renameSync(tmpFile, writePath);
136
+ // One move, so that readers see either the old content or the new, never
137
+ // a partial file. A link is written through rather than replaced.
138
+ stageFile(root, path, content).commit();
167
139
  },
168
140
  async list(pattern) {
169
141
  return listMatching(pattern);
@@ -177,10 +149,24 @@ export function createWorkspace(workspaceDir, signal) {
177
149
  throw new Error(`workspace.observe(): timeout must be a non-negative number (got ${timeout})`);
178
150
  }
179
151
  const needed = expect ?? 1;
152
+ const exact = isExactPath(pattern);
180
153
  // One exact path, one artifact wanted → the caller gets its content as a string.
181
- const single = isExactPath(pattern) && needed === 1;
182
- if (single)
183
- resolveBounded(root, pattern); // reject traversal up front rather than polling forever
154
+ const single = exact && needed === 1;
155
+ // A path that will never be read is refused now, rather than waited for: one that leads out of the
156
+ // workspace, or cannot be followed as things stand, whatever is asked of it. (What comes to be in its way
157
+ // later, while it waits — a link, a file where a directory is to be — is waited out like anything that is
158
+ // not there yet.)
159
+ if (exact)
160
+ guardPath(root, pattern);
161
+ // And one path, wanted as one text, is none while a directory is there: that is said as soon as it is seen.
162
+ const isDirectory = () => {
163
+ try {
164
+ return statSync(guardPath(root, pattern)).isDirectory();
165
+ }
166
+ catch {
167
+ return false;
168
+ }
169
+ };
184
170
  const collectMatches = () => {
185
171
  const matches = [];
186
172
  for (const path of single ? [pattern] : listMatching(pattern)) {
@@ -191,14 +177,17 @@ export function createWorkspace(workspaceDir, signal) {
191
177
  return matches;
192
178
  };
193
179
  // Level-triggered: artifacts that already exist count immediately.
194
- const startTime = Date.now();
180
+ const startTime = performance.now();
195
181
  while (true) {
196
182
  if (signal?.aborted)
197
183
  throw new Error("workspace.observe() aborted");
184
+ if (single && isDirectory()) {
185
+ throw Object.assign(new Error(`EISDIR: illegal operation on a directory, read '${pattern}'`), { code: "EISDIR" });
186
+ }
198
187
  const matches = collectMatches();
199
188
  if (matches.length >= needed)
200
189
  return single ? matches[0].content : matches;
201
- if (timeout !== undefined && (Date.now() - startTime) >= timeout) {
190
+ if (timeout !== undefined && (performance.now() - startTime) >= timeout) {
202
191
  throw new Error(`workspace.observe("${pattern}") timed out after ${timeout}ms. ` +
203
192
  `Found ${matches.length}/${needed} matching artifacts.`);
204
193
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trama-dev/runtime",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {