iit-mcp-autotask 0.62.1 → 0.62.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -327,7 +327,7 @@ Two per-call options change the result form:
327
327
  | Option | Effect |
328
328
  |--------|--------|
329
329
  | `format: 'tsv'` | serves the table as `data.result.tsv` — a header row of column names plus one tab-separated line per record — with `result.columns` and `result.rowCount`, and **omits `result.items`** (that omission is the size saving; the JSON form stays the default). Inside a value a literal backslash is written as `\\`, a tab as `\t`, a newline as `\n` and a carriage return as `\r`; the `<untrusted_content>` markers survive inside cells. |
330
- | `output_path: '<relative path>'` | **stdio transport only**: walks the FULL match set with the resource's own query iterator, writes the envelope JSON to a file under `AUTOTASK_OUTPUT_DIR`, and returns a summary (`outputPath`, `columns`, `rowCount`, the first rows, `bytes`) instead of the table. |
330
+ | `output_path: '<relative path>'` | **stdio transport only**: walks the FULL match set through the SDK's governed query path, writes the envelope JSON to a file under `AUTOTASK_OUTPUT_DIR`, and returns a summary (`outputPath`, `columns`, `rowCount`, the first rows, `bytes`) instead of the table. |
331
331
 
332
332
  `output_path` is deliberately strict: the deployment sets an **absolute** `AUTOTASK_OUTPUT_DIR`
333
333
  that already exists and is not the filesystem root (a configured root that is missing is refused —
@@ -353,6 +353,18 @@ containment (a caller path can never make the server create or write outside the
353
353
  against a same-user process racing the server. A hard link at the target path is an existing entry,
354
354
  so `O_EXCL` refuses it too.
355
355
 
356
+ Query files are processed page by page instead of collecting the whole walk in server memory.
357
+ TSV preserves columns first seen on later pages by replaying sanitized rows from an anonymous,
358
+ request-local spool after the final column union is known; it still performs one vendor walk.
359
+ The spool and final file can coexist temporarily, so TSV uses extra disk space while writing.
360
+ Both formats share the existing path guard and an awaited writer; failures and cancellation
361
+ attempt cleanup of owned partial files before returning. Any stop of an in-progress stdio server —
362
+ including client shutdown/restart, `SIGTERM`, Ctrl-C/`SIGINT`, a crash, OOM or `SIGKILL` — can exit
363
+ before asynchronous cleanup finishes. A partial target may remain and block reuse of that path.
364
+ The target is visible while the walk is running; consume it only after a successful response.
365
+ After an interrupted server shutdown, check/remove the incomplete file or choose a new path before retrying. If the filesystem prevents proving ownership,
366
+ cleanup also preserves the path rather than deleting an unknown file. See [performance measurements](docs/performance.md).
367
+
356
368
  The walk stops at 10,000 rows with an explicit truncation note in the summary (`hasMore: true` then
357
369
  means the cap, not only the query limit). The call is refused outright on the `http` transport (the
358
370
  caller is a request, not the process owner), and it cannot be combined with `latest` or
@@ -703,15 +715,17 @@ guards (rate limiter, 429 cooldown) — a worse security posture, not a safer on
703
715
  apply to each pooled tenant client (SDK 0.9.0's default-on change: read ~5 min, the reference
704
716
  tables ~1 h, field metadata ~5 min). Repeated reads of the same record are served from that
705
717
  tenant's cache until TTL expiry; composites de-duplicate their 3–8 fan-out reads through it.
706
- `off` sends `cache: false` (every read re-dials the vendor).
718
+ `off` sends `cache: false` (every read re-dials the vendor). SDK metadata projections reuse
719
+ derived work only within the same cache entry; they do not extend TTL or cache query/report results.
707
720
  Fuzzy company search always performs an uncached live fragment query (at most 500 rows).
708
721
  Separately, the SDK lazily builds a slim company-name index in the background, refreshes it
709
722
  every 30 minutes and clears it after company writes (rebuild debounced for one second).
710
723
  `AUTOTASK_CACHE=off` disables that index; results remain live-only with `index.state: "off"`.
711
724
  Cold/building indexes and capped live searches can miss companies: inspect the returned metadata.
712
725
  - **Boundaries — never relaxed:** in-process only (never on disk), **per-tenant** (one tenant's
713
- cached records or limiter state can never answer another tenant's request), TTL-bounded, cleared
714
- on eviction and on `401`. The same boundary covers the limiter/cooldown state.
726
+ cached records never answer another tenant's request), TTL-bounded, cleared on eviction and
727
+ on `401`. Client-local budgets and cooldown remain scoped; the SDK's shared object/origin
728
+ admission deliberately coordinates clients in the same runtime (see [Gateway assumptions](#gateway-assumptions)).
715
729
  - **stdio** uses one process-lifetime client (the env is the whole identity) — no pool, and the
716
730
  cache/limiter state is that single tenant's by construction.
717
731
  - **Multi-process gateways:** pool/cache/limiter state is per-process; an N-process gateway runs N
@@ -4,6 +4,24 @@ const UTC_ALIAS = /^(etc\/)?(utc|gmt|uct|universal|zulu)$/i;
4
4
  const ETC_OFFSET = /^etc\/gmt[+-]\d+$/i;
5
5
  /** The names Intl lists, by lower case: the case fix for a name typed in the wrong case. */
6
6
  const LISTED = new Map(Intl.supportedValuesOf('timeZone').map((z) => [z.toLowerCase(), z]));
7
+ /** Formatters retain zone configuration only; the Date and offset are recomputed on every call. */
8
+ const CLOCK_FORMATTER_LIMIT = 32;
9
+ const CLOCK_FORMATTERS = new Map();
10
+ function clockFormatter(zone) {
11
+ const key = UTC_ALIAS.test(zone) ? 'utc' : zone.toLowerCase();
12
+ const cached = CLOCK_FORMATTERS.get(key);
13
+ if (cached !== undefined) {
14
+ CLOCK_FORMATTERS.delete(key);
15
+ CLOCK_FORMATTERS.set(key, cached);
16
+ return cached;
17
+ }
18
+ // Intl validates before insertion, so invalid input never consumes a retained slot.
19
+ const formatter = new Intl.DateTimeFormat('en-US', { timeZone: zone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', timeZoneName: 'longOffset' });
20
+ CLOCK_FORMATTERS.set(key, formatter);
21
+ if (CLOCK_FORMATTERS.size > CLOCK_FORMATTER_LIMIT)
22
+ CLOCK_FORMATTERS.delete(CLOCK_FORMATTERS.keys().next().value);
23
+ return formatter;
24
+ }
7
25
  /**
8
26
  * The IANA name of `zone` as the operator spelled it (only the case of a listed name is fixed), or
9
27
  * undefined. Intl does the validation; the name is never swapped for another spelling, so Europe/Kyiv
@@ -17,7 +35,7 @@ export function canonicalTimeZone(zone) {
17
35
  if (!zone.includes('/') || ETC_OFFSET.test(zone))
18
36
  return undefined;
19
37
  try {
20
- const resolved = new Intl.DateTimeFormat('en-US', { timeZone: zone }).resolvedOptions().timeZone;
38
+ const resolved = clockFormatter(zone).resolvedOptions().timeZone;
21
39
  if (UTC_ALIAS.test(resolved))
22
40
  return 'UTC';
23
41
  // ponytail: a valid name Intl does not list (a modern or link name such as Asia/Kolkata) keeps its case as typed; a case table per link name if wrong-case input shows up
@@ -29,7 +47,7 @@ export function canonicalTimeZone(zone) {
29
47
  }
30
48
  /** The clock of `zone` at `now`; the offset is the one in force at `now`, so it follows daylight saving. */
31
49
  export function zoneClock(zone, now = new Date()) {
32
- const parts = new Intl.DateTimeFormat('en-US', { timeZone: zone, hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', timeZoneName: 'longOffset' }).formatToParts(now);
50
+ const parts = clockFormatter(zone).formatToParts(now);
33
51
  const p = (type) => parts.find((x) => x.type === type)?.value ?? '';
34
52
  const gmt = p('timeZoneName'); // "GMT", "GMT+11:00", "GMT-03:30"
35
53
  const utcOffset = gmt === 'GMT' ? '+00:00' : gmt.replace('GMT', '').replace('−', '-');
@@ -38,4 +38,4 @@ export declare const defaultToolOps: ToolOps;
38
38
  * handler then answers the typed cancellation; the handler's generic catch would otherwise
39
39
  * re-report it as a tool error, so this wrapper throws the SDK's typed `AbortError` instead.
40
40
  */
41
- export declare function withSignal(client: ToolClient, signal: AbortSignal | undefined, fn: () => Promise<unknown>): Promise<unknown>;
41
+ export declare function withSignal<T>(client: ToolClient, signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T>;
@@ -1,6 +1,6 @@
1
1
  /** SDK client construction (base options, placeholder, stdio client) and the default SDK ops bundle (issue #91). */
2
2
  import { AutotaskClient } from 'node-autotask';
3
- import { invokeDelete, invokeRead, invokeWrite, relationshipMap, resolveAny, searchAcrossResources } from 'node-autotask/operations';
3
+ import { invokeDelete, invokeRead, invokeReadPages, invokeWrite, relationshipMap, resolveAny, searchAcrossResources } from 'node-autotask/operations';
4
4
  import { serverCredentialDefaults } from '../../config/load.js';
5
5
  import { normalizeBaseUrl } from '../../base-hosts.js';
6
6
  import { sdkCacheOptions } from '../catalog-data.js';
@@ -118,6 +118,7 @@ export function buildStdioClient(config, log) {
118
118
  */
119
119
  export const defaultToolOps = {
120
120
  invokeRead: (client, operation, args, opts, signal) => withSignal(client, signal, () => invokeRead(client, operation, args, opts ?? {})),
121
+ invokeReadPages: (client, operation, args, onPage, opts, signal) => withSignal(client, signal, () => invokeReadPages(client, operation, args, onPage, opts ?? {})),
121
122
  invokeWrite: (client, operation, args, opts, signal) => withSignal(client, signal, () => invokeWrite(client, operation, args, opts ?? {})),
122
123
  invokeDelete: (client, operation, args, opts, signal) => withSignal(client, signal, () => invokeDelete(client, operation, args, opts ?? {})),
123
124
  resolveAny: (client, identifier, opts, signal) => withSignal(client, signal, () => resolveAny(client, identifier, opts ?? {})),
@@ -32,7 +32,7 @@
32
32
  */
33
33
  import type { ClientPool } from 'node-autotask/pool';
34
34
  import type { AutotaskConfig } from 'node-autotask';
35
- import type { InvokeOptions } from 'node-autotask/operations';
35
+ import type { BoundedQueryPageConsumer, BoundedQuerySummary, InvokeOptions } from 'node-autotask/operations';
36
36
  import type { Config } from '../../config/schema.js';
37
37
  import type { Logger } from '../../logger.js';
38
38
  import type { RefusalKind } from '../results/errors.js';
@@ -54,6 +54,7 @@ export interface HourlyBudget {
54
54
  export interface ToolOps {
55
55
  /** The MCP request's AbortSignal, when the transport provides one: an abandoned request stops consuming vendor budget. */
56
56
  invokeRead(client: ToolClient, operation: string, args?: readonly unknown[], opts?: InvokeOptions, signal?: AbortSignal): Promise<unknown>;
57
+ invokeReadPages(client: ToolClient, operation: string, args: readonly unknown[], onPage: BoundedQueryPageConsumer, opts?: InvokeOptions, signal?: AbortSignal): Promise<BoundedQuerySummary | undefined>;
57
58
  invokeWrite(client: ToolClient, operation: string, args?: readonly unknown[], opts?: InvokeOptions, signal?: AbortSignal): Promise<unknown>;
58
59
  invokeDelete(client: ToolClient, operation: string, args?: readonly unknown[], opts?: InvokeOptions, signal?: AbortSignal): Promise<unknown>;
59
60
  resolveAny(client: ToolClient, identifier: number | string, opts?: {
@@ -23,7 +23,9 @@ export interface Skill {
23
23
  export declare function parseSkill(text: string): Skill;
24
24
  /** Every packaged skill, read once at boot, by name. */
25
25
  export declare const SKILLS: ReadonlyMap<string, Skill>;
26
- /** The skills whose steps use `operation` (the `playbooks[]` reverse index). */
26
+ /** Compile packaged definitions once; duplicate references still name a skill only once. @internal */
27
+ export declare function indexPlaybooks(skills: Iterable<Pick<Skill, 'name' | 'ops'>>): Map<string, string[]>;
28
+ /** The skills whose steps use `operation`; every caller owns its returned array. */
27
29
  export declare function playbooksFor(operation: string): string[];
28
30
  /** The skills a profile can run (operator skills are listed only where the write path is served). */
29
31
  export declare function skillsFor(profile: string): Skill[];
@@ -58,9 +58,27 @@ export const SKILLS = (() => {
58
58
  }
59
59
  return out;
60
60
  })();
61
- /** The skills whose steps use `operation` (the `playbooks[]` reverse index). */
61
+ /** Compile packaged definitions once; duplicate references still name a skill only once. @internal */
62
+ export function indexPlaybooks(skills) {
63
+ const index = new Map();
64
+ for (const skill of skills) {
65
+ const operations = new Set(skill.ops.map((entry) => entry.split(':')[1]));
66
+ for (const operation of operations) {
67
+ if (operation === undefined)
68
+ continue;
69
+ const names = index.get(operation);
70
+ if (names === undefined)
71
+ index.set(operation, [skill.name]);
72
+ else
73
+ names.push(skill.name);
74
+ }
75
+ }
76
+ return index;
77
+ }
78
+ const PLAYBOOKS_BY_OPERATION = indexPlaybooks(SKILLS.values());
79
+ /** The skills whose steps use `operation`; every caller owns its returned array. */
62
80
  export function playbooksFor(operation) {
63
- return [...SKILLS.values()].filter((s) => s.ops.some((o) => o.split(':')[1] === operation)).map((s) => s.name);
81
+ return [...(PLAYBOOKS_BY_OPERATION.get(operation) ?? [])];
64
82
  }
65
83
  /** The skills a profile can run (operator skills are listed only where the write path is served). */
66
84
  export function skillsFor(profile) {
@@ -14,7 +14,8 @@ import { abortedAnswer, InputInvalidError } from './dispatch.js';
14
14
  import { runAggregate } from './aggregate.js';
15
15
  import { markResult, markServerField, sanitiseVendorOutput } from './results/untrusted.js';
16
16
  import { ok } from './results/envelope.js';
17
- import { sampleRows, toTsv, tsvColumns } from './tsv.js';
17
+ import { toTsv } from './tsv.js';
18
+ import { exportQueryFile, QueryExportIncompleteError } from './query-export.js';
18
19
  import { OUTPUT_MAX_ROWS, resolveOutputTarget } from './output-file.js';
19
20
  import { assertOperationPermitted } from '../policy.js';
20
21
  import { scopeRequiredInput } from './scope-guard.js';
@@ -142,50 +143,22 @@ async function outputPathAnswer(ctx, resource, operation, noun, fields, args, si
142
143
  transport: ctx.config.MCP_TRANSPORT,
143
144
  relativePath: args.output_path,
144
145
  });
145
- const result = await ctx.ops.invokeRead(ctx.client, operation, [{
146
- filter: args.filter,
147
- limit: 500,
148
- walk: { maxRows: OUTPUT_MAX_ROWS },
149
- ...(args.include_fields === undefined ? {} : { includeFields: args.include_fields }),
150
- ...(args.acknowledge_unscoped === undefined ? {} : { acknowledgeUnscoped: args.acknowledge_unscoped }),
151
- }], undefined, signal).catch((err) => { throw fieldNameInput(scopeRequiredInput(err, 'filter', true), true); });
152
- if (result === undefined)
153
- return abortedAnswer(ctx.correlationId);
154
- const walked = result;
155
- const walkNotes = sanitiseVendorOutput({
156
- ...(walked.scopeNote === undefined ? {} : { scopeNote: walked.scopeNote }),
157
- ...(walked.names === undefined ? {} : { names: walked.names }),
158
- ...(walked.relationNote === undefined ? {} : { relationNote: walked.relationNote }),
159
- ...(walked.blindSurface === undefined ? {} : { blindSurface: walked.blindSurface }),
160
- ...(walked.emptyReason === undefined ? {} : { emptyReason: walked.emptyReason }),
161
- }, { cap: false });
162
- // M8: the file form keeps the full text (no 500-char cap) but is still stripped of control/bidi chars.
163
- // The file is an output channel too: every vendor string is cleaned (never capped) before writing.
164
- const marked = sanitiseVendorOutput(markResult(walked.items, fields), { cap: false });
165
- const columns = tsvColumns(marked);
166
- const rowCount = marked.length;
167
- const truncatedNote = walked.truncated
168
- ? `the walk is incomplete after ${rowCount} rows (maximum ${OUTPUT_MAX_ROWS}); narrow the filter to capture the remainder`
169
- : undefined;
170
- const envelope = {
171
- items: marked,
172
- fetched: rowCount,
173
- hasMore: walked.truncated,
174
- ...walkNotes,
175
- ...(truncatedNote !== undefined ? { truncated: true, truncatedNote } : {}),
176
- };
177
146
  const asTsv = args.format === 'tsv';
178
- const bytes = await target.write(asTsv ? toTsv(marked, { spreadsheetSafe: true }).tsv : JSON.stringify(envelope, null, 2));
179
- // The sample rows are built from the RAW walked items and recorded by provenance (sanitiser
180
- // review S7), so the choke point cleans, caps and wraps them once; built from the file's already
181
- // wrapped cells, a cut would leave half a wrapper that then crossed raw (0.9.0: the escape is
182
- // gone, issue #70).
183
- const firstRows = sampleRows(walked.items, columns);
184
- for (const row of firstRows)
185
- for (const column of columns)
186
- if (fields.includes(column))
187
- markServerField(row, column, 'wrap');
188
- const capNote = walked.truncated ? ` The walk is incomplete after ${rowCount} rows (truncated).` : '';
147
+ const exported = await exportQueryFile({
148
+ target, fields, format: asTsv ? 'tsv' : 'json', signal,
149
+ readPages: consume => ctx.ops.invokeReadPages(ctx.client, operation, [{
150
+ filter: args.filter,
151
+ limit: 500,
152
+ walk: { maxRows: OUTPUT_MAX_ROWS },
153
+ ...(args.include_fields === undefined ? {} : { includeFields: args.include_fields }),
154
+ ...(args.acknowledge_unscoped === undefined ? {} : { acknowledgeUnscoped: args.acknowledge_unscoped }),
155
+ }], consume, undefined, signal).catch((err) => { throw fieldNameInput(scopeRequiredInput(err, 'filter', true), true); }),
156
+ }).catch((error) => { if (error instanceof QueryExportIncompleteError)
157
+ return undefined; throw error; });
158
+ if (exported === undefined)
159
+ return abortedAnswer(ctx.correlationId);
160
+ const { columns, rowCount, hasMore, walkNotes, firstRows, bytes, truncatedNote } = exported;
161
+ const capNote = hasMore ? ` The walk is incomplete after ${rowCount} rows (truncated).` : '';
189
162
  return ok(`Wrote ${rowCount} ${noun} as ${asTsv ? 'TSV' : 'JSON'} to the output directory.${capNote} The summary carries the path, ${columns.length} column(s) and the first rows; result.items is omitted.`, {
190
163
  resource,
191
164
  result: {
@@ -194,7 +167,7 @@ async function outputPathAnswer(ctx, resource, operation, noun, fields, args, si
194
167
  columns,
195
168
  rowCount,
196
169
  fetched: rowCount,
197
- hasMore: walked.truncated,
170
+ hasMore,
198
171
  ...walkNotes,
199
172
  firstRows,
200
173
  bytes,
@@ -12,11 +12,26 @@ export interface OutputTargetRequest {
12
12
  /** The caller's path, RELATIVE to the root. */
13
13
  relativePath: string;
14
14
  }
15
+ export interface OutputSink {
16
+ /** Await each call: concurrent or post-completion writes are refused. */
17
+ write(chunk: string | Buffer): Promise<void>;
18
+ }
19
+ export interface OutputSpool {
20
+ /** Append only already-sanitized export rows; never raw vendor records. */
21
+ append(row: unknown): Promise<void>;
22
+ /** One replay, after all appends; awaits each consumer before serving another row. */
23
+ replay(consume: (row: unknown) => Promise<void>): Promise<void>;
24
+ }
25
+ export interface OutputWriteOptions {
26
+ signal?: AbortSignal;
27
+ }
15
28
  /** A validated target: the canonical path (as served in `outputPath`) and its one-shot writer. */
16
29
  export interface OutputTarget {
17
30
  path: string;
18
31
  /** Create the file (never overwrite) and write `data` (UTF-8 string, or raw bytes); returns the byte size. */
19
32
  write(data: string | Buffer): Promise<number>;
33
+ writeChunks(produce: (sink: OutputSink) => Promise<void>, options?: OutputWriteOptions): Promise<number>;
34
+ withSpool<T>(use: (spool: OutputSpool) => Promise<T>, options?: OutputWriteOptions): Promise<T>;
20
35
  }
21
36
  /**
22
37
  * Validate an `output_path` before any vendor wire and return its writer. Creates the target's missing
@@ -19,9 +19,9 @@
19
19
  * write-time parent check and the open (no portable `openat` in Node).
20
20
  */
21
21
  import { constants } from 'node:fs';
22
- import { lstat, mkdir, open, realpath, stat, unlink } from 'node:fs/promises';
22
+ import { lstat, mkdir, mkdtemp, open, realpath, rmdir, stat, unlink } from 'node:fs/promises';
23
23
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
24
- import { AutotaskConfigError } from 'node-autotask';
24
+ import { AutotaskAbortError, AutotaskConfigError } from 'node-autotask';
25
25
  /** The `output_path` walk cap: rows written at most, with an explicit truncation note. */
26
26
  export const OUTPUT_MAX_ROWS = 10_000;
27
27
  /** The default output root's directory name under `AUTOTASK_STATE_DIR` (issue #101). */
@@ -44,10 +44,10 @@ async function fsStep(what, fn, onExist) {
44
44
  catch (err) {
45
45
  if (err instanceof AutotaskConfigError)
46
46
  throw err;
47
- const code = err.code;
47
+ const code = err?.code;
48
48
  if (code === 'EEXIST' && onExist !== undefined)
49
49
  return onExist();
50
- return refuse(`could not ${what} (${typeof code === 'string' ? code : 'UNKNOWN'})`);
50
+ return refuse(`could not ${what} (${typeof code === 'string' && /^[A-Z][A-Z0-9_]+$/.test(code) ? code : 'UNKNOWN'})`);
51
51
  }
52
52
  }
53
53
  /** `lstat` (or `stat`: the root may be a symlink); ENOENT -> undefined. */
@@ -116,25 +116,309 @@ export async function resolveOutputTarget(req) {
116
116
  refuse('the target is not a regular file');
117
117
  if (found !== undefined)
118
118
  exists(path);
119
- return {
119
+ const recheckParent = async () => {
120
+ if (await escapes(dirname(path)))
121
+ refuse('the resolved directory escapes AUTOTASK_OUTPUT_DIR (the filesystem changed after validation)');
122
+ };
123
+ const target = {
120
124
  path,
121
- async write(data) {
122
- if (await escapes(dirname(path)))
123
- refuse('the resolved directory escapes AUTOTASK_OUTPUT_DIR (the filesystem changed after validation)');
125
+ write(data) { return target.writeChunks(async (sink) => { await sink.write(data); }); },
126
+ async writeChunks(produce, { signal } = {}) {
127
+ assertActive(signal);
128
+ await recheckParent();
129
+ assertActive(signal);
124
130
  const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
125
131
  const handle = await fsStep('open the result file', () => open(path, flags, 0o666), () => exists(path));
132
+ let identity;
133
+ let failed = false, failure, bytes = 0;
134
+ const writer = new BufferedOutput(handle, signal);
135
+ try {
136
+ identity = await fsStep('inspect the result file', () => handle.stat());
137
+ assertActive(signal);
138
+ await produce(writer);
139
+ bytes = await writer.finish();
140
+ assertActive(signal);
141
+ }
142
+ catch (error) {
143
+ failed = true;
144
+ failure = error;
145
+ }
146
+ // A producer can fail while a noncancelable write is in flight. Drain before close.
147
+ await writer.stop().catch(error => { if (!failed) {
148
+ failed = true;
149
+ failure = error;
150
+ } });
151
+ try {
152
+ await fsStep('close the result file', () => handle.close());
153
+ }
154
+ catch (error) {
155
+ if (!failed) {
156
+ failed = true;
157
+ failure = error;
158
+ }
159
+ }
160
+ try {
161
+ assertActive(signal);
162
+ if (!failed && identity !== undefined) {
163
+ const current = await inspect(path);
164
+ if (current === undefined || !current.isFile() || current.isSymbolicLink() || current.dev !== identity.dev || current.ino !== identity.ino)
165
+ refuse('the result file changed during output creation');
166
+ assertActive(signal);
167
+ }
168
+ }
169
+ catch (error) {
170
+ if (!failed) {
171
+ failed = true;
172
+ failure = error;
173
+ }
174
+ }
175
+ if (failed) {
176
+ if (identity !== undefined)
177
+ await removeOwned(path, identity, false).catch(() => undefined);
178
+ throw failure;
179
+ }
180
+ return bytes;
181
+ },
182
+ async withSpool(use, { signal } = {}) {
183
+ assertActive(signal);
184
+ // Scratch creation shares this target's validated root authority, not /tmp or caller paths.
185
+ const currentRoot = await fsStep('resolve the output root', () => realpath(rootReal));
186
+ if (currentRoot !== rootReal)
187
+ refuse('the resolved output root changed after validation');
188
+ assertActive(signal);
189
+ const directory = await fsStep('create a private output spool', () => mkdtemp(join(rootReal, '.autotask-export-')));
190
+ let directoryIdentity, fileIdentity, handle;
191
+ const scratch = join(directory, 'rows');
192
+ let failed = false, failure, result;
193
+ let writer;
194
+ let active = true, replayPending, replayFailed = false, replayFailure;
126
195
  try {
127
- await fsStep('write the result file', () => handle.writeFile(data));
196
+ directoryIdentity = await fsStep('inspect the private output spool', () => lstat(directory));
197
+ assertActive(signal);
198
+ handle = await fsStep('open the output spool', () => open(scratch, constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600));
199
+ fileIdentity = await fsStep('inspect the output spool', () => handle.stat());
200
+ // Retain the exclusive FD, unlink its name immediately, then remove the empty directory.
201
+ // Replay never reopens a pathname and a process crash cannot leave row data behind.
202
+ await removeOwned(scratch, fileIdentity, false);
203
+ await removeOwned(directory, directoryIdentity, true);
204
+ writer = new BufferedOutput(handle, signal);
205
+ let replayed = false;
206
+ const spool = {
207
+ async append(row) {
208
+ assertActive(signal);
209
+ if (!active)
210
+ refuse('the output spool is already closed');
211
+ if (replayed)
212
+ refuse('the output spool is already sealed');
213
+ // JSON array semantics: undefined/function/symbol rows become null, not missing rows.
214
+ const line = JSON.stringify(row) ?? 'null';
215
+ await writer.write(`${line}\n`);
216
+ },
217
+ replay(consume) {
218
+ if (!active)
219
+ return Promise.reject(new AutotaskConfigError('output_path: the output spool is already closed', { operation: 'output_path' }));
220
+ if (replayed)
221
+ return Promise.reject(new AutotaskConfigError('output_path: the output spool can only be replayed once', { operation: 'output_path' }));
222
+ replayed = true;
223
+ replayPending = (async () => {
224
+ assertActive(signal);
225
+ const size = await writer.finish();
226
+ await replayRows(handle, size, consume, signal);
227
+ })();
228
+ void replayPending.catch(error => { replayFailed = true; replayFailure = error; });
229
+ return replayPending;
230
+ },
231
+ };
232
+ assertActive(signal);
233
+ result = await use(spool);
234
+ await writer.stop();
235
+ assertActive(signal);
128
236
  }
129
- catch (err) {
130
- await unlink(path).catch(() => undefined); // this handle created the file exclusively: a partial file must not block the retry
131
- throw err;
237
+ catch (error) {
238
+ failed = true;
239
+ failure = error;
240
+ }
241
+ active = false;
242
+ if (replayPending !== undefined)
243
+ await replayPending.catch(error => { if (!failed) {
244
+ failed = true;
245
+ failure = error;
246
+ } });
247
+ if (!failed && replayFailed) {
248
+ failed = true;
249
+ failure = replayFailure;
250
+ }
251
+ if (writer !== undefined)
252
+ await writer.stop().catch(error => { if (!failed) {
253
+ failed = true;
254
+ failure = error;
255
+ } });
256
+ if (handle !== undefined) {
257
+ try {
258
+ await fsStep('close the output spool', () => handle.close());
259
+ }
260
+ catch (error) {
261
+ if (!failed) {
262
+ failed = true;
263
+ failure = error;
264
+ }
265
+ }
266
+ }
267
+ // Only relevant if setup failed before the anonymous FD was established. Never recursive.
268
+ try {
269
+ if (fileIdentity !== undefined)
270
+ await removeOwned(scratch, fileIdentity, false);
271
+ if (directoryIdentity !== undefined)
272
+ await removeOwned(directory, directoryIdentity, true);
273
+ assertActive(signal);
132
274
  }
133
- finally {
134
- await handle.close().catch(() => undefined);
275
+ catch (error) {
276
+ if (!failed) {
277
+ failed = true;
278
+ failure = error;
279
+ }
135
280
  }
136
- return Buffer.byteLength(data);
281
+ if (failed)
282
+ throw failure;
283
+ return result;
137
284
  },
138
285
  };
286
+ return target;
287
+ }
288
+ const BUFFER_BYTES = 64 * 1024;
289
+ function assertActive(signal) {
290
+ if (signal?.aborted)
291
+ throw new AutotaskAbortError('Output creation aborted by the caller', { operation: 'output_path' });
292
+ }
293
+ /** Bounded batching for final output and spool alike; one accepted write at a time. */
294
+ class BufferedOutput {
295
+ handle;
296
+ signal;
297
+ buffer = Buffer.allocUnsafe(BUFFER_BYTES);
298
+ used = 0;
299
+ position = 0;
300
+ sealed = false;
301
+ pending;
302
+ failed = false;
303
+ failure;
304
+ constructor(handle, signal) {
305
+ this.handle = handle;
306
+ this.signal = signal;
307
+ }
308
+ write(chunk) {
309
+ if (this.sealed)
310
+ return Promise.reject(new AutotaskConfigError('output_path: the output writer is already closed', { operation: 'output_path' }));
311
+ if (this.pending !== undefined)
312
+ return Promise.reject(new AutotaskConfigError('output_path: await each output write before writing again', { operation: 'output_path' }));
313
+ const task = this.accept(chunk);
314
+ this.pending = task;
315
+ // Observe even an incorrectly unawaited write, while retaining its failure for finish/stop.
316
+ void task.catch(error => { this.failed = true; this.failure = error; });
317
+ void task.finally(() => { if (this.pending === task)
318
+ this.pending = undefined; }).catch(() => undefined);
319
+ return task;
320
+ }
321
+ async accept(chunk) {
322
+ assertActive(this.signal);
323
+ if (this.failed)
324
+ throw this.failure;
325
+ if (typeof chunk !== 'string' && !Buffer.isBuffer(chunk))
326
+ refuse('could not write the result file (ERR_INVALID_ARG_TYPE)');
327
+ const bytes = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk;
328
+ if (bytes.length >= BUFFER_BYTES) {
329
+ await this.flush();
330
+ await this.writeAll(bytes);
331
+ }
332
+ else {
333
+ if (this.used + bytes.length > BUFFER_BYTES)
334
+ await this.flush();
335
+ bytes.copy(this.buffer, this.used);
336
+ this.used += bytes.length;
337
+ }
338
+ assertActive(this.signal);
339
+ }
340
+ async writeAll(bytes) {
341
+ let offset = 0;
342
+ while (offset < bytes.length) {
343
+ assertActive(this.signal);
344
+ const { bytesWritten } = await fsStep('write the result file', () => this.handle.write(bytes, offset, bytes.length - offset, this.position));
345
+ if (!Number.isSafeInteger(bytesWritten) || bytesWritten <= 0 || bytesWritten > bytes.length - offset)
346
+ refuse('could not write the result file (EIO)');
347
+ offset += bytesWritten;
348
+ this.position += bytesWritten;
349
+ assertActive(this.signal);
350
+ }
351
+ }
352
+ async flush() {
353
+ if (this.used === 0)
354
+ return;
355
+ await this.writeAll(this.buffer.subarray(0, this.used));
356
+ this.used = 0;
357
+ }
358
+ async finish() {
359
+ this.sealed = true;
360
+ if (this.pending !== undefined)
361
+ await this.pending;
362
+ if (this.failed)
363
+ throw this.failure;
364
+ assertActive(this.signal);
365
+ await this.flush();
366
+ assertActive(this.signal);
367
+ return this.position;
368
+ }
369
+ async stop() {
370
+ this.sealed = true;
371
+ if (this.pending !== undefined)
372
+ await this.pending;
373
+ if (this.failed)
374
+ throw this.failure;
375
+ }
376
+ }
377
+ /** Do not delete a deterministic concurrent replacement. The lstat/unlink window is not atomic. */
378
+ async function removeOwned(path, identity, directory) {
379
+ const current = await inspect(path);
380
+ if (current === undefined || current.dev !== identity.dev || current.ino !== identity.ino || current.isSymbolicLink())
381
+ return;
382
+ if (directory ? !current.isDirectory() : !current.isFile())
383
+ return;
384
+ await fsStep('remove a partial output file', () => directory ? rmdir(path) : unlink(path));
385
+ }
386
+ /** Bounded block reads, retaining at most one encoded row, with an awaited consumer. */
387
+ async function replayRows(handle, size, consume, signal) {
388
+ let position = 0, fragments = [];
389
+ while (position < size) {
390
+ assertActive(signal);
391
+ const block = Buffer.allocUnsafe(Math.min(BUFFER_BYTES, size - position));
392
+ const { bytesRead } = await fsStep('read the output spool', () => handle.read(block, 0, block.length, position));
393
+ if (!Number.isSafeInteger(bytesRead) || bytesRead <= 0 || bytesRead > block.length)
394
+ refuse('could not read the output spool (EIO)');
395
+ position += bytesRead;
396
+ assertActive(signal);
397
+ let offset = 0;
398
+ while (offset < bytesRead) {
399
+ const end = block.indexOf(10, offset);
400
+ if (end < 0 || end >= bytesRead) {
401
+ fragments.push(block.subarray(offset, bytesRead));
402
+ break;
403
+ }
404
+ const part = block.subarray(offset, end);
405
+ const line = fragments.length === 0 ? part : Buffer.concat([...fragments, part]);
406
+ fragments = [];
407
+ let row;
408
+ try {
409
+ row = JSON.parse(line.toString('utf8'));
410
+ }
411
+ catch {
412
+ throw new Error('Invalid output spool record');
413
+ }
414
+ assertActive(signal);
415
+ await consume(row);
416
+ assertActive(signal);
417
+ offset = end + 1;
418
+ }
419
+ }
420
+ if (fragments.length > 0)
421
+ throw new Error('Incomplete output spool record');
422
+ assertActive(signal);
139
423
  }
140
424
  //# sourceMappingURL=output-file.js.map
@@ -0,0 +1,25 @@
1
+ /** Incremental file projection; the SDK owns the governed walk and its completion evidence. */
2
+ import { AutotaskAbortError } from 'node-autotask';
3
+ import type { BoundedQueryPageConsumer, BoundedQuerySummary } from 'node-autotask/operations';
4
+ import type { OutputTarget } from './output-file.js';
5
+ /** Undefined SDK/mock completion retains the handler's existing cancelled-result envelope. */
6
+ export declare class QueryExportIncompleteError extends AutotaskAbortError {
7
+ constructor();
8
+ }
9
+ export interface QueryExportRequest {
10
+ target: Pick<OutputTarget, 'writeChunks' | 'withSpool'>;
11
+ fields: readonly string[];
12
+ format: 'json' | 'tsv';
13
+ readPages(consume: BoundedQueryPageConsumer): Promise<BoundedQuerySummary | undefined>;
14
+ signal?: AbortSignal;
15
+ }
16
+ /** Kept callable with an in-memory target for bounded, read-only verification. */
17
+ export declare function exportQueryFile(request: QueryExportRequest): Promise<{
18
+ columns: string[];
19
+ rowCount: number;
20
+ hasMore: boolean | undefined;
21
+ walkNotes: Record<string, unknown>;
22
+ firstRows: Record<string, string>[];
23
+ bytes: number;
24
+ truncatedNote: string | undefined;
25
+ }>;
@@ -0,0 +1,89 @@
1
+ /** Incremental file projection; the SDK owns the governed walk and its completion evidence. */
2
+ import { AutotaskAbortError } from 'node-autotask';
3
+ import { OUTPUT_MAX_ROWS } from './output-file.js';
4
+ import { markResult, markServerField, sanitiseVendorOutput } from './results/untrusted.js';
5
+ import { addTsvColumns, SAMPLE_ROWS, sampleRows, tsvHeader, tsvRecord } from './tsv.js';
6
+ /** Undefined SDK/mock completion retains the handler's existing cancelled-result envelope. */
7
+ export class QueryExportIncompleteError extends AutotaskAbortError {
8
+ constructor() { super('The MCP request was cancelled before the upstream call settled; no result was produced.'); }
9
+ }
10
+ /** Kept callable with an in-memory target for bounded, read-only verification. */
11
+ export async function exportQueryFile(request) {
12
+ const { target, fields, signal } = request;
13
+ const active = () => { if (signal?.aborted)
14
+ throw new AutotaskAbortError('Query export aborted by the caller'); };
15
+ const columns = new Set();
16
+ const samples = [];
17
+ let rowCount = 0;
18
+ let walked;
19
+ let walkNotes = {};
20
+ let truncatedNote;
21
+ const consumeRows = async (accept) => {
22
+ walked = await request.readPages(async (page) => {
23
+ for (const raw of page.items) {
24
+ active();
25
+ if (samples.length < SAMPLE_ROWS)
26
+ samples.push(raw);
27
+ // Both shared projections count the outer array toward their depth limit.
28
+ const row = sanitiseVendorOutput(markResult([raw], fields), { cap: false })[0];
29
+ const projected = row === undefined || typeof row === 'function' || typeof row === 'symbol' ? null : row;
30
+ addTsvColumns(projected, columns);
31
+ await accept(projected);
32
+ rowCount++;
33
+ active();
34
+ }
35
+ });
36
+ active();
37
+ if (walked === undefined)
38
+ throw new QueryExportIncompleteError();
39
+ walkNotes = sanitiseVendorOutput({
40
+ ...(walked.scopeNote === undefined ? {} : { scopeNote: walked.scopeNote }),
41
+ ...(walked.names === undefined ? {} : { names: walked.names }),
42
+ ...(walked.relationNote === undefined ? {} : { relationNote: walked.relationNote }),
43
+ ...(walked.blindSurface === undefined ? {} : { blindSurface: walked.blindSurface }),
44
+ ...(walked.emptyReason === undefined ? {} : { emptyReason: walked.emptyReason }),
45
+ }, { cap: false });
46
+ truncatedNote = walked.truncated
47
+ ? `the walk is incomplete after ${rowCount} rows (maximum ${OUTPUT_MAX_ROWS}); narrow the filter to capture the remainder`
48
+ : undefined;
49
+ };
50
+ active();
51
+ const bytes = await target.writeChunks(async (sink) => {
52
+ if (request.format === 'tsv') {
53
+ // Cleanup is inside the producer: a scratch failure also removes the owned output.
54
+ await target.withSpool(async (spool) => {
55
+ await consumeRows(row => spool.append(row));
56
+ if (columns.size === 0)
57
+ return;
58
+ const schema = [...columns];
59
+ await sink.write(tsvHeader(schema));
60
+ await spool.replay(async (row) => { active(); await sink.write(`\n${tsvRecord(row, schema, true)}`); active(); });
61
+ }, { signal });
62
+ }
63
+ else {
64
+ await sink.write('{\n "items": [');
65
+ await consumeRows(async (row) => {
66
+ const json = JSON.stringify(row, null, 2);
67
+ await sink.write(`${rowCount === 0 ? '\n' : ',\n'} ${json.replace(/\n/g, '\n ')}`);
68
+ });
69
+ await sink.write(rowCount === 0 ? ']' : '\n ]');
70
+ const tail = {
71
+ fetched: rowCount,
72
+ hasMore: walked.truncated,
73
+ ...walkNotes,
74
+ ...(truncatedNote === undefined ? {} : { truncated: true, truncatedNote }),
75
+ };
76
+ await sink.write(`,${JSON.stringify(tail, null, 2).slice(1)}`);
77
+ }
78
+ active();
79
+ }, { signal });
80
+ active();
81
+ const schema = [...columns];
82
+ const firstRows = sampleRows(samples, schema);
83
+ for (const row of firstRows)
84
+ for (const column of schema)
85
+ if (fields.includes(column))
86
+ markServerField(row, column, 'wrap');
87
+ return { columns: schema, rowCount, hasMore: walked.truncated, walkNotes, firstRows, bytes, truncatedNote };
88
+ }
89
+ //# sourceMappingURL=query-export.js.map
@@ -33,6 +33,10 @@ export declare const SAMPLE_ROWS = 3;
33
33
  export declare function tsvCell(value: unknown, safe?: boolean): string;
34
34
  /** The column names of a record set: the union of the records' keys in first-appearance order. */
35
35
  export declare function tsvColumns(items: readonly unknown[]): string[];
36
+ /** Extend the same first-appearance schema one record at a time. */
37
+ export declare function addTsvColumns(item: unknown, columns: Set<string>): void;
38
+ export declare function tsvHeader(columns: readonly string[]): string;
39
+ export declare function tsvRecord(item: unknown, columns: readonly string[], spreadsheetSafe?: boolean): string;
36
40
  /**
37
41
  * Format a record set as TSV: the header row + one escaped line per record.
38
42
  * An empty record set yields an empty string (no columns are known).
package/dist/tools/tsv.js CHANGED
@@ -46,19 +46,24 @@ export function tsvCell(value, safe = false) {
46
46
  }
47
47
  /** The column names of a record set: the union of the records' keys in first-appearance order. */
48
48
  export function tsvColumns(items) {
49
- const columns = [];
50
- const seen = new Set();
51
- for (const item of items) {
52
- if (item === null || typeof item !== 'object' || Array.isArray(item))
53
- continue;
54
- for (const key of Object.keys(item)) {
55
- if (seen.has(key))
56
- continue;
57
- seen.add(key);
58
- columns.push(key);
59
- }
60
- }
61
- return columns;
49
+ const columns = new Set();
50
+ for (const item of items)
51
+ addTsvColumns(item, columns);
52
+ return [...columns];
53
+ }
54
+ /** Extend the same first-appearance schema one record at a time. */
55
+ export function addTsvColumns(item, columns) {
56
+ if (item === null || typeof item !== 'object' || Array.isArray(item))
57
+ return;
58
+ for (const key of Object.keys(item))
59
+ columns.add(key);
60
+ }
61
+ export function tsvHeader(columns) {
62
+ return columns.map(column => tsvCell(column)).join('\t');
63
+ }
64
+ export function tsvRecord(item, columns, spreadsheetSafe = false) {
65
+ const record = item !== null && typeof item === 'object' && !Array.isArray(item) ? item : {};
66
+ return columns.map(column => tsvCell(record[column], spreadsheetSafe)).join('\t');
62
67
  }
63
68
  /**
64
69
  * Format a record set as TSV: the header row + one escaped line per record.
@@ -69,11 +74,9 @@ export function toTsv(items, opts = {}) {
69
74
  const rowCount = items.length;
70
75
  if (columns.length === 0)
71
76
  return { tsv: '', columns, rowCount };
72
- const lines = [columns.map((column) => tsvCell(column)).join('\t')];
73
- for (const item of items) {
74
- const record = item !== null && typeof item === 'object' && !Array.isArray(item) ? item : {};
75
- lines.push(columns.map((column) => tsvCell(record[column], opts.spreadsheetSafe === true)).join('\t'));
76
- }
77
+ const lines = [tsvHeader(columns)];
78
+ for (const item of items)
79
+ lines.push(tsvRecord(item, columns, opts.spreadsheetSafe === true));
77
80
  return { tsv: lines.join('\n'), columns, rowCount };
78
81
  }
79
82
  /**
@@ -1,7 +1,11 @@
1
1
  import type { Logger } from '../../logger.js';
2
2
  import type { OpLock } from './op-lock.js';
3
3
  import type { StateStore } from './types.js';
4
- export type Ledger = Pick<StateStore, 'lookup' | 'append' | 'counters' | 'coolingDown'>;
4
+ export type Ledger = Pick<StateStore, 'lookup' | 'append' | 'counters' | 'coolingDown'> & {
5
+ /** Internal: one successful store op-lock acquisition, never a network leg. */
6
+ beginScope(): void;
7
+ endScope(): void;
8
+ };
5
9
  export declare function bootRewrite({ ledgerPath, auditPath, holdersDir, opLock, now, log }: {
6
10
  ledgerPath: string;
7
11
  auditPath: string;
@@ -47,27 +47,40 @@ export function bootRewrite({ ledgerPath, auditPath, holdersDir, opLock, now, lo
47
47
  }
48
48
  }
49
49
  export function createLedger({ ledgerPath }) {
50
+ let scoped = false;
51
+ let rows;
52
+ const read = () => {
53
+ if (!scoped)
54
+ return scanJsonl(ledgerPath);
55
+ // The shared op lock excludes peer appends/boot rewrites for this short scope.
56
+ // No view survives release/reacquire or any append attempt.
57
+ return rows ??= scanJsonl(ledgerPath);
58
+ };
50
59
  return {
60
+ beginScope() { rows = undefined; scoped = true; },
61
+ endScope() { scoped = false; rows = undefined; },
51
62
  lookup: (idemKey) => {
52
- // Fresh scan (issue #68): the file is the single source of truth, so a peer's appends are
53
- // visible without any in-process bookkeeping.
63
+ // Outside one held op-lock acquisition every read is fresh (issue #68).
54
64
  let hit;
55
- for (const e of scanJsonl(ledgerPath))
65
+ for (const e of read())
56
66
  if (e.idemKey === idemKey)
57
67
  hit = e;
58
- return hit;
68
+ return hit === undefined || !scoped ? hit : structuredClone(hit);
59
69
  },
60
70
  append(entry) {
71
+ // Clear before even attempting the append: a write/fsync failure may still
72
+ // have changed the file, so a caught error must never expose an older view.
73
+ rows = undefined;
61
74
  // The stamp is what the boot rewrite reads back: which `sending` lines belong to live
62
75
  // holders (issue #68). One O_APPEND line: open, write, fsync, close.
63
76
  appendJsonl(ledgerPath, { ...entry, boot: BOOT_ID, pid: process.pid });
64
77
  },
65
78
  counters(op, at) {
66
- // ponytail: a linear scan of the last 24 h; index the ledger if volume grows.
79
+ // Preserve file-order first eligible sending entry per key within 24 h.
67
80
  // One write per idempotency key (pre-release V6): a same-plan retry after a 429 (nothing
68
81
  // written) does not consume the limits a second time.
69
82
  const seenKeys = new Set();
70
- const sent = scanJsonl(ledgerPath).filter((e) => e.state === 'sending' && at - e.at < DAY_MS && !seenKeys.has(e.idemKey) && (seenKeys.add(e.idemKey), true));
83
+ const sent = read().filter((e) => e.state === 'sending' && at - e.at < DAY_MS && !seenKeys.has(e.idemKey) && (seenKeys.add(e.idemKey), true));
71
84
  return {
72
85
  hour: sent.filter((e) => at - e.at < HOUR_MS).length,
73
86
  day: sent.length,
@@ -77,7 +90,7 @@ export function createLedger({ ledgerPath }) {
77
90
  // A lingering `sending` (the vendor write ran but its outcome was never recorded) cools down too (F8).
78
91
  coolingDown: (targetKey, at) => {
79
92
  const latest = new Map();
80
- for (const e of scanJsonl(ledgerPath))
93
+ for (const e of read())
81
94
  latest.set(e.idemKey, e);
82
95
  return [...latest.values()].some((e) => (e.state === 'unknown' || e.state === 'sending') && e.targetKey === targetKey && at - e.at < COOLDOWN_MS);
83
96
  },
@@ -127,7 +127,7 @@ export interface StateStore {
127
127
  savePlan(plan: PlanRecord): void;
128
128
  /** The decrypted plan, or undefined when absent or not authentic (forged, edited, swapped). */
129
129
  loadPlan(handle: string): PlanRecord | undefined;
130
- /** The latest ledger entry for an idempotency key (a fresh scan of the file). */
130
+ /** Latest entry from the authoritative ledger: fresh outside one short op-lock acquisition. */
131
131
  lookup(idemKey: string): LedgerEntry | undefined;
132
132
  /** Append + fsync (one O_APPEND line; the line is stamped with this boot's identity). */
133
133
  append(entry: LedgerEntry): void;
@@ -54,7 +54,8 @@
54
54
  * and reads as absent (`PLAN_NOT_FOUND`); payload args and PII are unreadable at rest. The
55
55
  * random handles make concurrent saves collision-free.
56
56
  * - `ledger.jsonl` (0600): the idempotency ledger — the single source of truth, re-read from disk
57
- * on every lookup/count. Appends are one O_APPEND line (open, write, fsync, close): there is no
57
+ * outside each op-lock acquisition; its short locked checks share one parsed view. Appends
58
+ * are one O_APPEND line (open, write, fsync, close): there is no
58
59
  * persistent append fd, because a boot-rewrite rename would orphan a peer's open descriptor on
59
60
  * a different inode. Every line carries the writer's `boot` and `pid`; entries still `sending`
60
61
  * at boot become `unknown` when their origin is not a live holder; 14-day retention, pruned at
@@ -109,8 +110,6 @@ export function openStateStore(dir, opts) {
109
110
  const { takeover, ownsLock } = takeLock(lockPath, log, now, opLockWaitMs);
110
111
  // ---- the per-operation lock (issue #68): the short critical sections that make sharing safe ----
111
112
  const opLock = createOpLock({ dir, now, opLockWaitMs });
112
- const acquireOpLock = opLock.acquire;
113
- const releaseOpLock = opLock.release;
114
113
  const key = stateKey(join(dir, 'state.key'), now);
115
114
  const tenantKey = Buffer.from(hkdfSync('sha256', key, Buffer.alloc(0), 'iit-mcp-autotask tenant id', 32));
116
115
  const planStore = createPlanStore({ dir, key, now });
@@ -144,14 +143,30 @@ export function openStateStore(dir, opts) {
144
143
  killed() {
145
144
  return this.blocked() !== undefined;
146
145
  },
147
- acquireOpLock,
148
- releaseOpLock,
146
+ acquireOpLock() {
147
+ // A distinct successful acquisition owns its view. Failed/throwing acquires
148
+ // cannot inherit one, even when no read happened between releases.
149
+ ledger.endScope();
150
+ const blocked = opLock.acquire();
151
+ if (blocked === undefined)
152
+ ledger.beginScope();
153
+ return blocked;
154
+ },
155
+ releaseOpLock() {
156
+ try {
157
+ opLock.release();
158
+ }
159
+ finally {
160
+ ledger.endScope();
161
+ }
162
+ },
149
163
  withApplyLock(fn) {
150
164
  const run = applyQueue.then(fn, fn);
151
165
  applyQueue = run.catch(() => undefined);
152
166
  return run;
153
167
  },
154
168
  close() {
169
+ ledger.endScope();
155
170
  if (closed)
156
171
  return;
157
172
  closed = true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iit-mcp-autotask",
3
- "version": "0.62.1",
3
+ "version": "0.62.2",
4
4
  "description": "MCP server for the Autotask (Datto) PSA domain, built on the node-autotask SDK",
5
5
  "license": "MIT",
6
6
  "author": "Max Soukhomlinov",
@@ -54,7 +54,7 @@
54
54
  },
55
55
  "dependencies": {
56
56
  "@modelcontextprotocol/server": "^2.2.0",
57
- "node-autotask": "0.69.1",
57
+ "node-autotask": "0.70.0",
58
58
  "zod": "^4.6.7"
59
59
  },
60
60
  "devDependencies": {
package/server.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "iit-mcp-autotask",
3
- "version": "0.62.1",
3
+ "version": "0.62.2",
4
4
  "description": "MCP server for the Autotask (Datto) PSA API, powered by the node-autotask SDK",
5
5
  "mcpProtocolBaseline": "2026-07-28",
6
6
  "legacyProtocolFallback": "2025-11-25",
@@ -62,7 +62,7 @@
62
62
  "capabilitiesManifest": "capabilities.json",
63
63
  "sdk": {
64
64
  "package": "node-autotask",
65
- "versionRange": "0.69.1"
65
+ "versionRange": "0.70.0"
66
66
  },
67
67
  "vendorExtensions": false,
68
68
  "credentialModelNote": "per-request; server-held under stdio or, on HTTP, only behind AUTOTASK_HTTP_AUTH=tokens; operator plans and the ledger are keyed by principal and tenant id, never by credential, and an apply authenticates the request credential and restores the plan's per-write impersonation"