iit-mcp-autotask 0.54.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.
Files changed (164) hide show
  1. package/.env.example +123 -0
  2. package/LICENSE +21 -0
  3. package/README.md +788 -0
  4. package/capabilities.json +487 -0
  5. package/dist/access/gate.d.ts +34 -0
  6. package/dist/access/gate.js +76 -0
  7. package/dist/access/grants.d.ts +20 -0
  8. package/dist/access/grants.js +35 -0
  9. package/dist/access/write-env.d.ts +41 -0
  10. package/dist/access/write-env.js +166 -0
  11. package/dist/auth.d.ts +74 -0
  12. package/dist/auth.js +129 -0
  13. package/dist/base-hosts.d.ts +38 -0
  14. package/dist/base-hosts.js +70 -0
  15. package/dist/config/load.d.ts +28 -0
  16. package/dist/config/load.js +105 -0
  17. package/dist/config/schema.d.ts +166 -0
  18. package/dist/config/schema.js +311 -0
  19. package/dist/credential.d.ts +28 -0
  20. package/dist/credential.js +32 -0
  21. package/dist/doctor.d.ts +112 -0
  22. package/dist/doctor.js +154 -0
  23. package/dist/http-guard.d.ts +57 -0
  24. package/dist/http-guard.js +134 -0
  25. package/dist/http.d.ts +50 -0
  26. package/dist/http.js +290 -0
  27. package/dist/lifecycle.d.ts +29 -0
  28. package/dist/lifecycle.js +52 -0
  29. package/dist/logger.d.ts +26 -0
  30. package/dist/logger.js +28 -0
  31. package/dist/main.d.ts +12 -0
  32. package/dist/main.js +283 -0
  33. package/dist/policy.d.ts +54 -0
  34. package/dist/policy.js +80 -0
  35. package/dist/tools/aggregate.d.ts +16 -0
  36. package/dist/tools/aggregate.js +64 -0
  37. package/dist/tools/capabilities-manifest.d.ts +4 -0
  38. package/dist/tools/capabilities-manifest.js +94 -0
  39. package/dist/tools/catalog-data.d.ts +116 -0
  40. package/dist/tools/catalog-data.js +207 -0
  41. package/dist/tools/clock.d.ts +17 -0
  42. package/dist/tools/clock.js +43 -0
  43. package/dist/tools/composites.d.ts +36 -0
  44. package/dist/tools/composites.js +305 -0
  45. package/dist/tools/context/client.d.ts +41 -0
  46. package/dist/tools/context/client.js +139 -0
  47. package/dist/tools/context/derive.d.ts +9 -0
  48. package/dist/tools/context/derive.js +32 -0
  49. package/dist/tools/context/scope.d.ts +24 -0
  50. package/dist/tools/context/scope.js +180 -0
  51. package/dist/tools/context/types.d.ts +141 -0
  52. package/dist/tools/context/types.js +2 -0
  53. package/dist/tools/dispatch.d.ts +78 -0
  54. package/dist/tools/dispatch.js +272 -0
  55. package/dist/tools/field-pointer.d.ts +25 -0
  56. package/dist/tools/field-pointer.js +45 -0
  57. package/dist/tools/guide.d.ts +30 -0
  58. package/dist/tools/guide.js +97 -0
  59. package/dist/tools/lists.d.ts +9 -0
  60. package/dist/tools/lists.js +205 -0
  61. package/dist/tools/meta.d.ts +22 -0
  62. package/dist/tools/meta.js +709 -0
  63. package/dist/tools/output-file.d.ts +26 -0
  64. package/dist/tools/output-file.js +140 -0
  65. package/dist/tools/rank.d.ts +21 -0
  66. package/dist/tools/rank.js +57 -0
  67. package/dist/tools/reasons.d.ts +33 -0
  68. package/dist/tools/reasons.js +121 -0
  69. package/dist/tools/register.d.ts +23 -0
  70. package/dist/tools/register.js +50 -0
  71. package/dist/tools/resolves.d.ts +28 -0
  72. package/dist/tools/resolves.js +399 -0
  73. package/dist/tools/results/envelope.d.ts +55 -0
  74. package/dist/tools/results/envelope.js +63 -0
  75. package/dist/tools/results/errors.d.ts +147 -0
  76. package/dist/tools/results/errors.js +384 -0
  77. package/dist/tools/results/untrusted.d.ts +129 -0
  78. package/dist/tools/results/untrusted.js +218 -0
  79. package/dist/tools/revenue-rollup.d.ts +8 -0
  80. package/dist/tools/revenue-rollup.js +112 -0
  81. package/dist/tools/schemas.d.ts +467 -0
  82. package/dist/tools/schemas.js +444 -0
  83. package/dist/tools/scope-guard.d.ts +2 -0
  84. package/dist/tools/scope-guard.js +11 -0
  85. package/dist/tools/server-version.d.ts +3 -0
  86. package/dist/tools/server-version.js +14 -0
  87. package/dist/tools/server.d.ts +92 -0
  88. package/dist/tools/server.js +170 -0
  89. package/dist/tools/surface.d.ts +37 -0
  90. package/dist/tools/surface.js +94 -0
  91. package/dist/tools/tsv.d.ts +52 -0
  92. package/dist/tools/tsv.js +95 -0
  93. package/dist/tools/write/apply.d.ts +40 -0
  94. package/dist/tools/write/apply.js +500 -0
  95. package/dist/tools/write/checks.d.ts +39 -0
  96. package/dist/tools/write/checks.js +137 -0
  97. package/dist/tools/write/common.d.ts +23 -0
  98. package/dist/tools/write/common.js +33 -0
  99. package/dist/tools/write/facts.d.ts +52 -0
  100. package/dist/tools/write/facts.js +151 -0
  101. package/dist/tools/write/outcome.d.ts +23 -0
  102. package/dist/tools/write/outcome.js +67 -0
  103. package/dist/tools/write/parse.d.ts +37 -0
  104. package/dist/tools/write/parse.js +166 -0
  105. package/dist/tools/write/payload.d.ts +44 -0
  106. package/dist/tools/write/payload.js +119 -0
  107. package/dist/tools/write/preview.d.ts +3 -0
  108. package/dist/tools/write/preview.js +317 -0
  109. package/dist/tools/write/snapshot.d.ts +68 -0
  110. package/dist/tools/write/snapshot.js +360 -0
  111. package/dist/tools/write-guidance.d.ts +174 -0
  112. package/dist/tools/write-guidance.js +317 -0
  113. package/dist/tools/write.d.ts +9 -0
  114. package/dist/tools/write.js +10 -0
  115. package/dist/write/canonical.d.ts +12 -0
  116. package/dist/write/canonical.js +31 -0
  117. package/dist/write/evaluate.d.ts +77 -0
  118. package/dist/write/evaluate.js +91 -0
  119. package/dist/write/hard-rules.d.ts +49 -0
  120. package/dist/write/hard-rules.js +48 -0
  121. package/dist/write/runtime.d.ts +37 -0
  122. package/dist/write/runtime.js +72 -0
  123. package/dist/write/store/audit-log.d.ts +13 -0
  124. package/dist/write/store/audit-log.js +25 -0
  125. package/dist/write/store/constants.d.ts +34 -0
  126. package/dist/write/store/constants.js +35 -0
  127. package/dist/write/store/files.d.ts +44 -0
  128. package/dist/write/store/files.js +157 -0
  129. package/dist/write/store/heartbeat.d.ts +9 -0
  130. package/dist/write/store/heartbeat.js +65 -0
  131. package/dist/write/store/ledger.d.ts +15 -0
  132. package/dist/write/store/ledger.js +86 -0
  133. package/dist/write/store/lifecycle.d.ts +35 -0
  134. package/dist/write/store/lifecycle.js +114 -0
  135. package/dist/write/store/lock.d.ts +97 -0
  136. package/dist/write/store/lock.js +464 -0
  137. package/dist/write/store/op-lock.d.ts +13 -0
  138. package/dist/write/store/op-lock.js +175 -0
  139. package/dist/write/store/plan-store.d.ts +7 -0
  140. package/dist/write/store/plan-store.js +48 -0
  141. package/dist/write/store/plans.d.ts +5 -0
  142. package/dist/write/store/plans.js +19 -0
  143. package/dist/write/store/types.d.ts +195 -0
  144. package/dist/write/store/types.js +2 -0
  145. package/dist/write/store.d.ts +6 -0
  146. package/dist/write/store.js +182 -0
  147. package/examples/agentgateway.write-gate.yaml +29 -0
  148. package/package.json +71 -0
  149. package/server.json +69 -0
  150. package/skills/ar-aging.md +65 -0
  151. package/skills/company-360.md +69 -0
  152. package/skills/contract-profitability.md +65 -0
  153. package/skills/crm-management.md +87 -0
  154. package/skills/filter-semantics.md +75 -0
  155. package/skills/invoice-export.md +61 -0
  156. package/skills/log-time-entry.md +77 -0
  157. package/skills/non-chargeable-work.md +67 -0
  158. package/skills/portfolio-margin.md +66 -0
  159. package/skills/recurring-revenue.md +65 -0
  160. package/skills/revenue-rollup.md +65 -0
  161. package/skills/slim-reads.md +67 -0
  162. package/skills/ticket-triage.md +64 -0
  163. package/skills/unbilled-work-review.md +66 -0
  164. package/skills/wip-hours.md +68 -0
@@ -0,0 +1,48 @@
1
+ import { isSecretOperation } from '../policy.js';
2
+ /** The hard rule for one registry record. */
3
+ export function hardRuleFor(operation, record) {
4
+ if (isSecretOperation(operation))
5
+ return { never: 'credential-minting operation (never served)', hazards: [] };
6
+ if (record === undefined)
7
+ return { never: 'not in the capability registry', hazards: [] };
8
+ if (record.effect === 'read')
9
+ return { never: 'a read: reads go through autotask_read', hazards: [] };
10
+ const hazards = [];
11
+ if (record.flags.includes('requiresApproval'))
12
+ hazards.push('requires_approval');
13
+ if (record.flags.includes('sensitive'))
14
+ hazards.push('sensitive');
15
+ if (record.effect === 'destructive')
16
+ hazards.push('destructive');
17
+ if (record.metadata?.accountWide === true)
18
+ hazards.push('account_wide');
19
+ if (hazards.includes('requires_approval') || hazards.includes('sensitive'))
20
+ return { approval: 'always', hazards };
21
+ return { hazards };
22
+ }
23
+ /**
24
+ * The only operations that may take the `move` shape (issue #107): the SDK's create-verify-delete move
25
+ * engine. An allowlist, not the signature alone: a future SDK op that happened to share the signature
26
+ * must not be driven as a move (it takes the generic `call` shape instead, which never snapshots or
27
+ * recovers a source record).
28
+ */
29
+ export const MOVE_OPS = ['time_entries.moveToTicket', 'ticket_charges.moveToTicket'];
30
+ const SHAPES = {
31
+ 'create:data': 'create',
32
+ 'create:parentId,data': 'create_child',
33
+ 'update:id,data': 'update',
34
+ 'update:parentId,id,data': 'update_child',
35
+ 'delete:id': 'delete',
36
+ 'delete:parentId,id': 'delete_child',
37
+ 'moveToTicket:sourceId,toTicketId': 'move',
38
+ };
39
+ /**
40
+ * The write shape of a record. Every non-read record has one: the six CRUD shapes, the move shape for
41
+ * {@link MOVE_OPS}, and `call` for every other signature (so no write silently drops out of
42
+ * AUTOTASK_WRITE, issue #191).
43
+ */
44
+ export function writeShape(record) {
45
+ const shape = SHAPES[`${record.operation}:${Object.keys(record.inputSchema).join(',')}`];
46
+ return shape === 'move' && !MOVE_OPS.includes(record.id) ? 'call' : (shape ?? 'call');
47
+ }
48
+ //# sourceMappingURL=hard-rules.js.map
@@ -0,0 +1,37 @@
1
+ /**
2
+ * write/runtime.ts — the operator deployment's boot (M5): what makes a process stateful, and what
3
+ * it must have before it serves a write tool.
4
+ *
5
+ * A process is an operator deployment when `AUTOTASK_PROFILE=operator` or any token in the tokens
6
+ * file has `profile: operator`. Boot then requires `AUTOTASK_WRITE` (resolved against the registry
7
+ * before anything is opened), `AUTOTASK_STATE_DIR` (0700) and its lock, a run scope for every
8
+ * operator principal (`AUTOTASK_RUN_SCOPE` without tokens, `runScope` on each operator token with
9
+ * them) and no allow-any base host. The write variables are refused outside an operator deployment.
10
+ * Readonly deployments never open state. Readonly tokens in an operator process get the readonly
11
+ * tools and never touch it.
12
+ */
13
+ import { type Config } from '../config/schema.js';
14
+ import type { TokenStore } from '../http-guard.js';
15
+ import type { Logger } from '../logger.js';
16
+ import { type LoadedPolicy } from '../access/write-env.js';
17
+ import { type StateStore } from './store.js';
18
+ import { SessionGrants } from '../access/grants.js';
19
+ /** The apply wait cap (the SDK write is never aborted; past this the outcome is unknown). */
20
+ export declare const APPLY_CAP_MS = 90000;
21
+ export interface WriteRuntime {
22
+ store: StateStore;
23
+ loaded: LoadedPolicy;
24
+ now: () => number;
25
+ applyCapMs: number;
26
+ /** stdio "remember for this session" grants (#302): in memory, this process only. */
27
+ grants: SessionGrants;
28
+ }
29
+ export declare function isOperatorDeployment(config: Pick<Config, 'AUTOTASK_PROFILE'>, tokens?: TokenStore): boolean;
30
+ /**
31
+ * Open the write runtime when this is an operator deployment (undefined otherwise). Throws
32
+ * ConfigError naming every missing requirement; nothing is opened unless all are present.
33
+ */
34
+ export declare function openWriteRuntime(config: Config, log: Logger, tokens?: TokenStore, opts?: {
35
+ now?: () => number;
36
+ applyCapMs?: number;
37
+ }): WriteRuntime | undefined;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * write/runtime.ts — the operator deployment's boot (M5): what makes a process stateful, and what
3
+ * it must have before it serves a write tool.
4
+ *
5
+ * A process is an operator deployment when `AUTOTASK_PROFILE=operator` or any token in the tokens
6
+ * file has `profile: operator`. Boot then requires `AUTOTASK_WRITE` (resolved against the registry
7
+ * before anything is opened), `AUTOTASK_STATE_DIR` (0700) and its lock, a run scope for every
8
+ * operator principal (`AUTOTASK_RUN_SCOPE` without tokens, `runScope` on each operator token with
9
+ * them) and no allow-any base host. The write variables are refused outside an operator deployment.
10
+ * Readonly deployments never open state. Readonly tokens in an operator process get the readonly
11
+ * tools and never touch it.
12
+ */
13
+ import { ConfigError } from '../config/schema.js';
14
+ import { resolveWritePolicy } from '../access/write-env.js';
15
+ import { openStateStore } from './store.js';
16
+ import { SessionGrants } from '../access/grants.js';
17
+ /** The apply wait cap (the SDK write is never aborted; past this the outcome is unknown). */
18
+ export const APPLY_CAP_MS = 90_000;
19
+ export function isOperatorDeployment(config, tokens) {
20
+ return config.AUTOTASK_PROFILE === 'operator' || (tokens?.entries.some((e) => e.profile === 'operator') ?? false);
21
+ }
22
+ /**
23
+ * Open the write runtime when this is an operator deployment (undefined otherwise). Throws
24
+ * ConfigError naming every missing requirement; nothing is opened unless all are present.
25
+ */
26
+ export function openWriteRuntime(config, log, tokens, opts = {}) {
27
+ if (!isOperatorDeployment(config, tokens)) {
28
+ const stray = ['AUTOTASK_WRITE', 'AUTOTASK_DEDUP', 'AUTOTASK_EXPENSE_REPORT_SUBMITTER_PIN'].filter((k) => config[k] !== undefined);
29
+ if (stray.length > 0)
30
+ throw new ConfigError(`Invalid configuration:\n ${stray.map((k) => `${k} is set but this is not an operator deployment; set AUTOTASK_PROFILE=operator or remove it`).join('\n ')}`);
31
+ return undefined;
32
+ }
33
+ const problems = [];
34
+ if (config.AUTOTASK_WRITE === undefined)
35
+ problems.push('AUTOTASK_WRITE is required in an operator deployment (unlisted writes are read-only; see docs/write-gate.md)');
36
+ if (config.AUTOTASK_STATE_DIR === undefined)
37
+ problems.push('AUTOTASK_STATE_DIR is required in an operator deployment');
38
+ if (config.AUTOTASK_ALLOW_ANY_BASE_HOST)
39
+ problems.push('AUTOTASK_ALLOW_ANY_BASE_HOST is lab-only and is refused in an operator deployment');
40
+ if (tokens !== undefined) {
41
+ const unscoped = tokens.entries.filter((e) => e.profile === 'operator' && e.runScope === undefined).map((e) => e.principal);
42
+ if (unscoped.length > 0)
43
+ problems.push(`every operator token needs a runScope; missing for principal(s) ${unscoped.join(', ')}`);
44
+ if (config.AUTOTASK_RUN_SCOPE !== undefined)
45
+ problems.push('AUTOTASK_RUN_SCOPE is not used with tokens auth; set runScope on each operator token');
46
+ }
47
+ else if (config.AUTOTASK_RUN_SCOPE === undefined) {
48
+ problems.push('AUTOTASK_RUN_SCOPE is required for the operator profile ({"companyIds":[...]} or {"all":true})');
49
+ }
50
+ if (problems.length > 0)
51
+ throw new ConfigError(`Invalid operator configuration:\n ${problems.join('\n ')}`);
52
+ const loaded = resolveWritePolicy({
53
+ write: config.AUTOTASK_WRITE,
54
+ transport: config.MCP_TRANSPORT,
55
+ ...(config.AUTOTASK_DEDUP !== undefined ? { dedup: config.AUTOTASK_DEDUP } : {}),
56
+ ...(config.AUTOTASK_EXPENSE_REPORT_SUBMITTER_PIN !== undefined ? { expensePin: config.AUTOTASK_EXPENSE_REPORT_SUBMITTER_PIN } : {}),
57
+ });
58
+ const grants = new SessionGrants();
59
+ const store = openStateStore(config.AUTOTASK_STATE_DIR, {
60
+ log,
61
+ // the kill file ends every stdio session grant (#302), even when no write runs while it exists (#311);
62
+ // they are not restored when it clears
63
+ onKill: () => grants.clear(),
64
+ ...(config.AUTOTASK_KILL_FILE !== undefined ? { killFile: config.AUTOTASK_KILL_FILE } : {}),
65
+ ...(opts.now !== undefined ? { now: opts.now } : {}),
66
+ });
67
+ for (const warning of loaded.warnings)
68
+ log.warn(warning);
69
+ log.info('operator write path ready', { policyHash: loaded.policyHash, ops: loaded.table.size, gating: config.MCP_TRANSPORT === 'stdio' ? 'server' : 'client' });
70
+ return { store, loaded, now: opts.now ?? Date.now, applyCapMs: opts.applyCapMs ?? APPLY_CAP_MS, grants };
71
+ }
72
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +1,13 @@
1
+ /** #250 deliberately removes tamper evidence; directory permissions and serialized appends bound this JSONL audit. */
2
+ import type { Logger } from '../../logger.js';
3
+ import type { OpLock } from './op-lock.js';
4
+ import type { AuditEvent } from './types.js';
5
+ export interface AuditLog {
6
+ append: (event: AuditEvent, at: number) => void;
7
+ }
8
+ export declare function createAuditLog({ auditPath, log, opLock, isClosed }: {
9
+ auditPath: string;
10
+ log: Logger;
11
+ opLock: OpLock;
12
+ isClosed: () => boolean;
13
+ }): AuditLog;
@@ -0,0 +1,25 @@
1
+ import { appendJsonl } from './files.js';
2
+ export function createAuditLog({ auditPath, log, opLock, isClosed }) {
3
+ return {
4
+ append(event, at) {
5
+ if (isClosed())
6
+ return;
7
+ const reacquired = !opLock.held();
8
+ if (reacquired) {
9
+ const blocked = opLock.acquire();
10
+ if (blocked !== undefined) {
11
+ log.warn('the op lock is unavailable; the audit line was not appended', { event: event.event, detail: blocked.detail });
12
+ return;
13
+ }
14
+ }
15
+ try {
16
+ appendJsonl(auditPath, { at: new Date(at).toISOString(), ...event });
17
+ }
18
+ finally {
19
+ if (reacquired)
20
+ opLock.release();
21
+ }
22
+ },
23
+ };
24
+ }
25
+ //# sourceMappingURL=audit-log.js.map
@@ -0,0 +1,34 @@
1
+ /** Retention windows, TTLs and lock timings of the state store (issue #88: split out of store.ts). */
2
+ export declare const PLAN_TTL_MS: number;
3
+ /** An undecryptable plan file is removed at boot once it is older than this (a plan lives 15 minutes, PLAN_TTL_MS; the rest is margin). */
4
+ export declare const UNREADABLE_PLAN_MAX_AGE_MS: number;
5
+ export declare const LEDGER_RETENTION_MS: number;
6
+ export declare const COOLDOWN_MS: number;
7
+ /** The cooldown duration in minutes for the served messages (issue #252: one home for the conversion). */
8
+ export declare const COOLDOWN_MINUTES: number;
9
+ /**
10
+ * The lease heartbeat: while it is primary, the holder rewrites `<state>/lock.lease` atomically
11
+ * at this interval (issue #55); EVERY process also refreshes its own registration's lease here
12
+ * (issue #68) — one timer, both heartbeats.
13
+ *
14
+ * 5 s: one small 0600 file rewrite + fsync every 5 s is negligible against the apply path, and it
15
+ * keeps the takeover delay after a container replacement short (the lease is dead within one
16
+ * expiry window of the holder's last beat).
17
+ */
18
+ export declare const LEASE_REFRESH_MS = 5000;
19
+ /**
20
+ * A lease older than this is expired: the holder has been silent for three full refresh cycles,
21
+ * so its lock may be taken over. A healthy event loop does not stall for 15 s (GC, fsync and OS
22
+ * scheduling are far shorter), so a live holder is never taken in practice; a pathological stall
23
+ * longer than this CAN be taken over, and the stalled process detects the loss and stops new
24
+ * writes (`STATE_UNAVAILABLE`) the moment it resumes. The same expiry window is the op lock's
25
+ * dead-man's switch: holds are milliseconds, so a holder whose op lease went stale is a crashed
26
+ * mid-op process, and the next acquire takes the op lock over.
27
+ */
28
+ export declare const LEASE_EXPIRY_MS: number;
29
+ /** The op lock's poll interval while a peer holds it (holds are milliseconds; 10 ms is plenty). */
30
+ export declare const OP_LOCK_POLL_MS = 10;
31
+ /** The op lock's wait cap: a live holder almost always releases long before this. */
32
+ export declare const OP_LOCK_WAIT_MS = 10000;
33
+ export declare const HOUR_MS = 3600000;
34
+ export declare const DAY_MS: number;
@@ -0,0 +1,35 @@
1
+ /** Retention windows, TTLs and lock timings of the state store (issue #88: split out of store.ts). */
2
+ export const PLAN_TTL_MS = 15 * 60_000;
3
+ /** An undecryptable plan file is removed at boot once it is older than this (a plan lives 15 minutes, PLAN_TTL_MS; the rest is margin). */
4
+ export const UNREADABLE_PLAN_MAX_AGE_MS = 70 * 60_000;
5
+ export const LEDGER_RETENTION_MS = 14 * 24 * 3_600_000;
6
+ export const COOLDOWN_MS = 10 * 60_000;
7
+ /** The cooldown duration in minutes for the served messages (issue #252: one home for the conversion). */
8
+ export const COOLDOWN_MINUTES = Math.round(COOLDOWN_MS / 60_000);
9
+ /**
10
+ * The lease heartbeat: while it is primary, the holder rewrites `<state>/lock.lease` atomically
11
+ * at this interval (issue #55); EVERY process also refreshes its own registration's lease here
12
+ * (issue #68) — one timer, both heartbeats.
13
+ *
14
+ * 5 s: one small 0600 file rewrite + fsync every 5 s is negligible against the apply path, and it
15
+ * keeps the takeover delay after a container replacement short (the lease is dead within one
16
+ * expiry window of the holder's last beat).
17
+ */
18
+ export const LEASE_REFRESH_MS = 5_000;
19
+ /**
20
+ * A lease older than this is expired: the holder has been silent for three full refresh cycles,
21
+ * so its lock may be taken over. A healthy event loop does not stall for 15 s (GC, fsync and OS
22
+ * scheduling are far shorter), so a live holder is never taken in practice; a pathological stall
23
+ * longer than this CAN be taken over, and the stalled process detects the loss and stops new
24
+ * writes (`STATE_UNAVAILABLE`) the moment it resumes. The same expiry window is the op lock's
25
+ * dead-man's switch: holds are milliseconds, so a holder whose op lease went stale is a crashed
26
+ * mid-op process, and the next acquire takes the op lock over.
27
+ */
28
+ export const LEASE_EXPIRY_MS = LEASE_REFRESH_MS * 3;
29
+ /** The op lock's poll interval while a peer holds it (holds are milliseconds; 10 ms is plenty). */
30
+ export const OP_LOCK_POLL_MS = 10;
31
+ /** The op lock's wait cap: a live holder almost always releases long before this. */
32
+ export const OP_LOCK_WAIT_MS = 10_000;
33
+ export const HOUR_MS = 3_600_000;
34
+ export const DAY_MS = 24 * HOUR_MS;
35
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1,44 @@
1
+ export declare const LOOSE_MODE = 63;
2
+ export declare function refuse(message: string): never;
3
+ /**
4
+ * The kill switch fails closed (review F9): only a definite "no such file" means writes may run;
5
+ * any other answer about the kill file (permission denied, an unreadable directory) means killed.
6
+ */
7
+ export declare function killFilePresent(path: string): boolean;
8
+ /**
9
+ * The 32-byte state key: created on first boot (0600), else read and checked (issue #68: two
10
+ * processes can race the very first boot — a concurrent create leaves a PARTIALLY written key,
11
+ * which is re-read for up to a second; the create itself stays O_EXCL + write, because renaming
12
+ * over an existing key would clobber it).
13
+ */
14
+ export declare function stateKey(path: string, now: () => number): Buffer;
15
+ /** Read a JSONL file, skipping (and counting) lines that do not parse. The boot rewrite's authority. */
16
+ export declare function readJsonl<T>(path: string): {
17
+ rows: T[];
18
+ bad: number;
19
+ };
20
+ /** Rewrite a JSONL file atomically (0600, fsync, rename). */
21
+ export declare function rewriteJsonl(path: string, rows: unknown[]): void;
22
+ /**
23
+ * One O_APPEND line: open, write, fsync, close (issue #68). The write is a single write(2) of the
24
+ * whole line, so a peer's fresh read sees the line whole or not at all; the per-append close is
25
+ * what makes the boot-rewrite rename safe for every process (no persistent fd to orphan).
26
+ */
27
+ export declare function appendJsonl(path: string, row: unknown): void;
28
+ /**
29
+ * A fresh scan of a JSONL file (issue #68: the file is the single source of truth). Tolerates a
30
+ * torn FINAL line (a peer crashed mid-append, or this read raced one): if only the final line
31
+ * fails to parse, the file is re-read once, and if it still fails the final line is dropped
32
+ * WITHOUT counting it as a bad line (the boot rewrite is the authority that counts bad lines).
33
+ * A bad line anywhere else is skipped here and counted at the next boot.
34
+ */
35
+ export declare function scanJsonl<T>(path: string): T[];
36
+ export declare const BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
37
+ /** `pln_` + 26 base32 characters (130 random bits). */
38
+ export declare function handle(): string;
39
+ /**
40
+ * A synchronous sleep for the bounded re-read waits (the state key's partial write, the op
41
+ * lock's poll loop): Atomics.wait parks the thread without a busy spin and without yielding to
42
+ * the event loop (the caller is inside a critical section and must not interleave).
43
+ */
44
+ export declare function sleepSync(ms: number): void;
@@ -0,0 +1,157 @@
1
+ /** Small file helpers: JSONL read/scan/append/rewrite, the state key, the kill file, handles (issue #88). */
2
+ import { randomBytes } from 'node:crypto';
3
+ import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, statSync, writeSync } from 'node:fs';
4
+ import { ConfigError } from '../../config/schema.js';
5
+ import { OP_LOCK_POLL_MS } from './constants.js';
6
+ export const LOOSE_MODE = 0o077;
7
+ export function refuse(message) {
8
+ throw new ConfigError(`AUTOTASK_STATE_DIR: ${message}`);
9
+ }
10
+ /**
11
+ * The kill switch fails closed (review F9): only a definite "no such file" means writes may run;
12
+ * any other answer about the kill file (permission denied, an unreadable directory) means killed.
13
+ */
14
+ export function killFilePresent(path) {
15
+ try {
16
+ statSync(path);
17
+ return true;
18
+ }
19
+ catch (err) {
20
+ return err.code !== 'ENOENT';
21
+ }
22
+ }
23
+ /**
24
+ * The 32-byte state key: created on first boot (0600), else read and checked (issue #68: two
25
+ * processes can race the very first boot — a concurrent create leaves a PARTIALLY written key,
26
+ * which is re-read for up to a second; the create itself stays O_EXCL + write, because renaming
27
+ * over an existing key would clobber it).
28
+ */
29
+ export function stateKey(path, now) {
30
+ try {
31
+ const fd = openSync(path, 'wx', 0o600);
32
+ const key = randomBytes(32);
33
+ writeSync(fd, key);
34
+ fsyncSync(fd);
35
+ closeSync(fd);
36
+ return key;
37
+ }
38
+ catch (err) {
39
+ if (err.code !== 'EEXIST')
40
+ throw err;
41
+ }
42
+ if ((statSync(path).mode & LOOSE_MODE) !== 0)
43
+ refuse(`${path} must be mode 0600`);
44
+ const deadline = now() + 1_000;
45
+ for (;;) {
46
+ const key = readFileSync(path);
47
+ if (key.length === 32)
48
+ return key;
49
+ if (now() >= deadline)
50
+ refuse(`${path} is not a 32-byte key`);
51
+ sleepSync(OP_LOCK_POLL_MS);
52
+ }
53
+ }
54
+ /** Read a JSONL file, skipping (and counting) lines that do not parse. The boot rewrite's authority. */
55
+ export function readJsonl(path) {
56
+ if (!existsSync(path))
57
+ return { rows: [], bad: 0 };
58
+ const rows = [];
59
+ let bad = 0;
60
+ for (const line of readFileSync(path, 'utf8').split('\n')) {
61
+ if (line.trim() === '')
62
+ continue;
63
+ try {
64
+ rows.push(JSON.parse(line));
65
+ }
66
+ catch {
67
+ bad += 1;
68
+ }
69
+ }
70
+ return { rows, bad };
71
+ }
72
+ /** Rewrite a JSONL file atomically (0600, fsync, rename). */
73
+ export function rewriteJsonl(path, rows) {
74
+ const tmp = `${path}.tmp`;
75
+ const fd = openSync(tmp, 'w', 0o600);
76
+ writeSync(fd, rows.map((r) => `${JSON.stringify(r)}\n`).join(''));
77
+ fsyncSync(fd);
78
+ closeSync(fd);
79
+ renameSync(tmp, path);
80
+ }
81
+ /**
82
+ * One O_APPEND line: open, write, fsync, close (issue #68). The write is a single write(2) of the
83
+ * whole line, so a peer's fresh read sees the line whole or not at all; the per-append close is
84
+ * what makes the boot-rewrite rename safe for every process (no persistent fd to orphan).
85
+ */
86
+ export function appendJsonl(path, row) {
87
+ const fd = openSync(path, 'a', 0o600);
88
+ try {
89
+ writeSync(fd, `${JSON.stringify(row)}\n`);
90
+ fsyncSync(fd);
91
+ }
92
+ finally {
93
+ closeSync(fd);
94
+ }
95
+ }
96
+ /**
97
+ * A fresh scan of a JSONL file (issue #68: the file is the single source of truth). Tolerates a
98
+ * torn FINAL line (a peer crashed mid-append, or this read raced one): if only the final line
99
+ * fails to parse, the file is re-read once, and if it still fails the final line is dropped
100
+ * WITHOUT counting it as a bad line (the boot rewrite is the authority that counts bad lines).
101
+ * A bad line anywhere else is skipped here and counted at the next boot.
102
+ */
103
+ export function scanJsonl(path) {
104
+ const attempt = () => {
105
+ let text;
106
+ try {
107
+ text = readFileSync(path, 'utf8');
108
+ }
109
+ catch (err) {
110
+ if (err.code !== 'ENOENT')
111
+ throw err;
112
+ return { rows: [], tornTail: false };
113
+ }
114
+ const lines = text.split('\n').filter((l) => l.trim() !== '');
115
+ const rows = [];
116
+ let tornTail = false;
117
+ for (let i = 0; i < lines.length; i++) {
118
+ try {
119
+ rows.push(JSON.parse(lines[i]));
120
+ }
121
+ catch {
122
+ if (i === lines.length - 1)
123
+ tornTail = true;
124
+ // a bad line mid-file: skip it here; the next boot rewrite counts it
125
+ }
126
+ }
127
+ return { rows, tornTail };
128
+ };
129
+ const first = attempt();
130
+ return first.tornTail ? attempt().rows : first.rows;
131
+ }
132
+ export const BASE32 = 'abcdefghijklmnopqrstuvwxyz234567';
133
+ /** `pln_` + 26 base32 characters (130 random bits). */
134
+ export function handle() {
135
+ const bytes = randomBytes(17);
136
+ let bits = 0;
137
+ let value = 0;
138
+ let out = '';
139
+ for (const byte of bytes) {
140
+ value = (value << 8) | byte;
141
+ bits += 8;
142
+ while (bits >= 5 && out.length < 26) {
143
+ out += BASE32[(value >>> (bits - 5)) & 31];
144
+ bits -= 5;
145
+ }
146
+ }
147
+ return `pln_${out}`;
148
+ }
149
+ /**
150
+ * A synchronous sleep for the bounded re-read waits (the state key's partial write, the op
151
+ * lock's poll loop): Atomics.wait parks the thread without a busy spin and without yielding to
152
+ * the event loop (the caller is inside a critical section and must not interleave).
153
+ */
154
+ export function sleepSync(ms) {
155
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
156
+ }
157
+ //# sourceMappingURL=files.js.map
@@ -0,0 +1,9 @@
1
+ import type { Logger } from '../../logger.js';
2
+ export declare function startHeartbeat({ myHolder, lockPath, leasePath, ownsLock, log, now }: {
3
+ myHolder: string;
4
+ lockPath: string;
5
+ leasePath: string;
6
+ ownsLock: boolean;
7
+ log: Logger;
8
+ now: () => number;
9
+ }): NodeJS.Timeout;
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The state-lock heartbeat (issue #55, #68, #88): one timer that refreshes this process's own holder-registration lease and, while
3
+ * this store IS the primary, the primary lock's lease. Nothing here reads the store's `closed` flag: `close()` clears the timer.
4
+ */
5
+ import { statSync } from 'node:fs';
6
+ import { LEASE_REFRESH_MS } from './constants.js';
7
+ import { lockState, writeLease } from './lock.js';
8
+ export function startHeartbeat({ myHolder, lockPath, leasePath, ownsLock, log, now }) {
9
+ // The heartbeats (issue #55 + #68): every LEASE_REFRESH_MS the timer (1) refreshes this
10
+ // process's own registration lease while the registration file is present — a deleted
11
+ // registration stops the beat (the runtime-deletion case, mirroring the old "a holder that
12
+ // loses the lock at runtime stops refreshing") — and (2) refreshes the primary lock's lease
13
+ // only while this process IS the primary (a lost lock belongs to the successor; a third taker
14
+ // must not see ours still fresh). The timer no longer self-stops on a lost lock (the
15
+ // registration beat may still be needed); close() clears it. A transient UNREADABLE lock
16
+ // (EACCES, EIO, EMFILE) skips the lock beat and keeps the timer alive: one transient read
17
+ // error must not kill the heartbeat of a healthy holder, or the holder would be taken over
18
+ // once its lease went stale (S2-B1). A failed lease write (ENOSPC, a rename failure) is
19
+ // logged, not thrown: the process must not die of an uncaughtException — a persistently
20
+ // failing heartbeat degrades to the normal dead-pid / expired-lease recovery instead.
21
+ const leaseTimer = setInterval(() => {
22
+ let holderGone = false;
23
+ try {
24
+ statSync(myHolder);
25
+ }
26
+ catch (err) {
27
+ if (err.code === 'ENOENT') {
28
+ holderGone = true; // the registration was deleted at runtime: stop beating its lease
29
+ }
30
+ else {
31
+ log.warn('the holder registration could not be checked just now; this beat was skipped', { file: myHolder });
32
+ return;
33
+ }
34
+ }
35
+ if (!holderGone) {
36
+ try {
37
+ writeLease(`${myHolder}.lease`, now());
38
+ }
39
+ catch (err) {
40
+ log.warn('the holder-lease heartbeat write failed; this process may be taken for dead once its lease is stale', {
41
+ file: `${myHolder}.lease`,
42
+ error: String(err?.message ?? err),
43
+ });
44
+ }
45
+ }
46
+ if (!ownsLock)
47
+ return; // this store is not the one that took the lock (a second store of the
48
+ // same process): the owner beats its lease
49
+ const st = lockState(lockPath);
50
+ if (st !== 'held')
51
+ return; // unknown: transient, skip this beat; lost: the successor beats its own lease
52
+ try {
53
+ writeLease(leasePath, now());
54
+ }
55
+ catch (err) {
56
+ log.warn('the lease heartbeat write failed; the lock may be taken over once its lease is stale', {
57
+ file: 'lock.lease',
58
+ error: String(err?.message ?? err),
59
+ });
60
+ }
61
+ }, LEASE_REFRESH_MS);
62
+ leaseTimer.unref();
63
+ return leaseTimer;
64
+ }
65
+ //# sourceMappingURL=heartbeat.js.map
@@ -0,0 +1,15 @@
1
+ import type { Logger } from '../../logger.js';
2
+ import type { OpLock } from './op-lock.js';
3
+ import type { StateStore } from './types.js';
4
+ export type Ledger = Pick<StateStore, 'lookup' | 'append' | 'counters' | 'coolingDown'>;
5
+ export declare function bootRewrite({ ledgerPath, auditPath, holdersDir, opLock, now, log }: {
6
+ ledgerPath: string;
7
+ auditPath: string;
8
+ holdersDir: string;
9
+ opLock: OpLock;
10
+ now: () => number;
11
+ log: Logger;
12
+ }): void;
13
+ export declare function createLedger({ ledgerPath }: {
14
+ ledgerPath: string;
15
+ }): Ledger;
@@ -0,0 +1,86 @@
1
+ /** Shared-directory ledger: locked boot rewrite, fresh replay scans, pinned-create counters and cooldowns. */
2
+ import { closeSync, existsSync, openSync } from 'node:fs';
3
+ import { COOLDOWN_MS, DAY_MS, HOUR_MS, LEDGER_RETENTION_MS } from './constants.js';
4
+ import { appendJsonl, readJsonl, refuse, rewriteJsonl, scanJsonl } from './files.js';
5
+ import { BOOT_ID, holderNames } from './lock.js';
6
+ export function bootRewrite({ ledgerPath, auditPath, holdersDir, opLock, now, log }) {
7
+ // ---- ledger: prune past retention, `sending` -> `unknown` (the boot rewrite, under the op lock) ----
8
+ // A `sending` entry becomes `unknown` only when its origin is NOT a live holder (issue #68):
9
+ // no registry file for its boot (the sweep just removed the dead ones) or no boot at all (a
10
+ // legacy line — today's behaviour for pre-0.8.0 entries). A LIVE peer's in-flight write stays
11
+ // `sending`, and single-process semantics are exact (this process's previous boot was swept
12
+ // dead a moment ago, so its `sending` lines become `unknown` as before).
13
+ const bootBlocked = opLock.acquire();
14
+ if (bootBlocked !== undefined) {
15
+ refuse(`the op lock could not be taken at boot: ${bootBlocked.detail}`);
16
+ }
17
+ try {
18
+ const loaded = readJsonl(ledgerPath);
19
+ if (loaded.bad > 0)
20
+ log.warn('ledger lines that do not parse were skipped', { lines: loaded.bad });
21
+ const liveHolders = new Set(holderNames(holdersDir));
22
+ const entries = loaded.rows.filter((e) => now() - e.at <= LEDGER_RETENTION_MS);
23
+ const latest = new Map();
24
+ for (const e of entries)
25
+ latest.set(e.idemKey, e);
26
+ for (const e of latest.values()) {
27
+ if (e.state !== 'sending')
28
+ continue;
29
+ // A LIVE peer's in-flight write stays `sending`: its boot is registered (and is not this
30
+ // process's own — a line stamped with this BOOT_ID is from a PREVIOUS store of this
31
+ // process, which is closed, so its write is over and the line goes `unknown`).
32
+ if (e.boot !== undefined && e.boot !== BOOT_ID && liveHolders.has(e.boot))
33
+ continue;
34
+ entries.push({ ...e, state: 'unknown', at: now() });
35
+ log.warn('a write still sending at the last shutdown is now unknown', { op: e.op, planHash: e.planHash });
36
+ }
37
+ rewriteJsonl(ledgerPath, entries);
38
+ // The audit file exists from the first boot (the pre-0.8.0 boot opened it as a persistent
39
+ // fd; the per-append open needs the same invariant for readers that expect the file).
40
+ if (!existsSync(auditPath)) {
41
+ const fd = openSync(auditPath, 'a', 0o600);
42
+ closeSync(fd);
43
+ }
44
+ }
45
+ finally {
46
+ opLock.release();
47
+ }
48
+ }
49
+ export function createLedger({ ledgerPath }) {
50
+ return {
51
+ 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.
54
+ let hit;
55
+ for (const e of scanJsonl(ledgerPath))
56
+ if (e.idemKey === idemKey)
57
+ hit = e;
58
+ return hit;
59
+ },
60
+ append(entry) {
61
+ // The stamp is what the boot rewrite reads back: which `sending` lines belong to live
62
+ // holders (issue #68). One O_APPEND line: open, write, fsync, close.
63
+ appendJsonl(ledgerPath, { ...entry, boot: BOOT_ID, pid: process.pid });
64
+ },
65
+ counters(op, at) {
66
+ // ponytail: a linear scan of the last 24 h; index the ledger if volume grows.
67
+ // One write per idempotency key (pre-release V6): a same-plan retry after a 429 (nothing
68
+ // written) does not consume the limits a second time.
69
+ 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));
71
+ return {
72
+ hour: sent.filter((e) => at - e.at < HOUR_MS).length,
73
+ day: sent.length,
74
+ opHour: sent.filter((e) => e.op === op && at - e.at < HOUR_MS).length,
75
+ };
76
+ },
77
+ // A lingering `sending` (the vendor write ran but its outcome was never recorded) cools down too (F8).
78
+ coolingDown: (targetKey, at) => {
79
+ const latest = new Map();
80
+ for (const e of scanJsonl(ledgerPath))
81
+ latest.set(e.idemKey, e);
82
+ return [...latest.values()].some((e) => (e.state === 'unknown' || e.state === 'sending') && e.targetKey === targetKey && at - e.at < COOLDOWN_MS);
83
+ },
84
+ };
85
+ }
86
+ //# sourceMappingURL=ledger.js.map