@aiwg/cli 2026.10.14 → 2026.10.16

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 (210) hide show
  1. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md +13 -0
  2. package/agentic/code/addons/aiwg-utils/rules/anti-laziness.md +118 -0
  3. package/agentic/code/providers/pi/aiwg-bridge.ts +45 -7
  4. package/dist/src/artifacts/citation-parser.js +7 -6
  5. package/dist/src/artifacts/corpus-tools/citation-densify.js +4 -2
  6. package/dist/src/artifacts/corpus-tools/cli.js +37 -0
  7. package/dist/src/artifacts/corpus-tools/discovery-log.js +27 -25
  8. package/dist/src/artifacts/corpus-tools/expand-cli.js +90 -0
  9. package/dist/src/artifacts/corpus-tools/expand-dates.js +107 -0
  10. package/dist/src/artifacts/corpus-tools/expand-queue.js +41 -0
  11. package/dist/src/artifacts/corpus-tools/expand-review.js +104 -0
  12. package/dist/src/artifacts/corpus-tools/expand-state.js +56 -0
  13. package/dist/src/artifacts/corpus-tools/expand.js +124 -0
  14. package/dist/src/artifacts/corpus-tools/induction-audit.js +7 -6
  15. package/dist/src/artifacts/corpus-tools/integrity-scan.js +3 -3
  16. package/dist/src/artifacts/corpus-tools/radar-shared.js +7 -9
  17. package/dist/src/artifacts/corpus-tools/ref-files.js +11 -0
  18. package/dist/src/artifacts/corpus-tools/resolve-cli.js +99 -0
  19. package/dist/src/artifacts/corpus-tools/resolve-corpus.js +41 -0
  20. package/dist/src/artifacts/corpus-tools/resolve.js +119 -0
  21. package/dist/src/artifacts/corpus-tools/retrieval-lab.js +2 -1
  22. package/dist/src/artifacts/corpus-tools/sidecar-lint.js +4 -4
  23. package/dist/src/artifacts/corpus-tools/sidecar-repair.js +2 -1
  24. package/dist/src/artifacts/corpus-views/ref-parser.js +3 -17
  25. package/dist/src/artifacts/graph-query.js +5 -3
  26. package/dist/src/artifacts/hybrid-query.js +11 -2
  27. package/dist/src/artifacts/index-refresh.js +2 -0
  28. package/dist/src/cli/handlers/daemon.js +17 -1
  29. package/dist/src/cli/handlers/doctor-args.js +45 -0
  30. package/dist/src/cli/handlers/doctor-help.js +8 -3
  31. package/dist/src/cli/handlers/index.js +2 -2
  32. package/dist/src/cli/handlers/models-resource-sample.js +10 -0
  33. package/dist/src/cli/handlers/models.js +3 -2
  34. package/dist/src/cli/handlers/regenerate.js +8 -16
  35. package/dist/src/cli/handlers/sessions.js +7 -7
  36. package/dist/src/cli/handlers/subcommands.js +8 -0
  37. package/dist/src/cli/handlers/update.js +157 -0
  38. package/dist/src/cli/handlers/use.js +14 -4
  39. package/dist/src/cli/handlers/utilities.js +3 -586
  40. package/dist/src/cli/handlers/utility-doctor.js +412 -0
  41. package/dist/src/cli/services/deployment-verification.js +0 -1
  42. package/dist/src/config/aiwg-config.js +2 -1
  43. package/dist/src/config/authorization-cli.js +7 -3
  44. package/dist/src/config/dispatch-thresholds-runtime.d.mts +3 -2
  45. package/dist/src/config/dispatch-thresholds-runtime.mjs +17 -7
  46. package/dist/src/config/framework-aliases.js +12 -0
  47. package/dist/src/config/host-resource-report.d.mts +19 -0
  48. package/dist/src/config/host-resource-report.mjs +80 -0
  49. package/dist/src/config/host-resource-runtime.d.mts +34 -0
  50. package/dist/src/config/host-resource-runtime.mjs +293 -0
  51. package/dist/src/config/installed-selection.js +22 -0
  52. package/dist/src/config/worker-context.js +33 -4
  53. package/dist/src/config/worker-invocation-marker.d.mts +1 -0
  54. package/dist/src/config/worker-invocation-marker.mjs +2 -0
  55. package/dist/src/decision/heldout/access.js +74 -0
  56. package/dist/src/decision/heldout/calibration.js +1 -0
  57. package/dist/src/decision/heldout/collector.js +9 -2
  58. package/dist/src/effects/verifiers/file.js +22 -5
  59. package/dist/src/extensions/claude-attribution.js +82 -0
  60. package/dist/src/extensions/claude-hooks-installer.js +115 -69
  61. package/dist/src/extensions/commands/daemon.js +109 -0
  62. package/dist/src/extensions/commands/definitions.js +5 -89
  63. package/dist/src/features/catalog.js +1 -1
  64. package/dist/src/gates/evaluate.js +2 -2
  65. package/dist/src/gates/heldout.js +52 -0
  66. package/dist/src/gates/index.js +2 -1
  67. package/dist/src/lint/check-patterns.js +163 -0
  68. package/dist/src/lint/checks.js +268 -0
  69. package/dist/src/lint/reference-resolution.js +54 -0
  70. package/dist/src/lint/runner.js +3 -465
  71. package/dist/src/mcp/helpers.mjs +11 -1
  72. package/dist/src/memory/project-registry.js +44 -4
  73. package/dist/src/models/worker-installation-store.mjs +228 -0
  74. package/dist/src/models/worker-installation.mjs +7 -162
  75. package/dist/src/models/worker-plan.js +36 -5
  76. package/dist/src/models/wrapper-deployment.js +25 -12
  77. package/dist/src/models/wrapper-enforcement.js +47 -7
  78. package/dist/src/network-analysis/research.js +2 -1
  79. package/dist/src/policy/hitl-check.js +14 -4
  80. package/dist/src/policy/hitl-consume.js +54 -0
  81. package/dist/src/policy/hitl-receipt.js +2 -0
  82. package/dist/src/policy/hitl.js +11 -3
  83. package/dist/src/providers/provider-context-contracts.js +162 -0
  84. package/dist/src/providers/provider-definition-schema.js +136 -0
  85. package/dist/src/providers/provider-definitions.js +8 -1298
  86. package/dist/src/providers/provider-seeds-1.js +360 -0
  87. package/dist/src/providers/provider-seeds-2.js +387 -0
  88. package/dist/src/providers/provider-seeds-3.js +262 -0
  89. package/dist/src/research/clients/arxiv.js +14 -34
  90. package/dist/src/research/clients/base.js +53 -26
  91. package/dist/src/research/clients/crossref.js +9 -1
  92. package/dist/src/research/clients/semantic-scholar.js +73 -44
  93. package/dist/src/research/identity.js +117 -0
  94. package/dist/src/research/index.js +1 -0
  95. package/dist/src/research/query-cli.js +3 -87
  96. package/dist/src/research/query-options.js +87 -0
  97. package/dist/src/research/reference-match.js +135 -0
  98. package/dist/src/research/services/acquisition.js +9 -7
  99. package/dist/src/research/services/citation.js +5 -2
  100. package/dist/src/research/types.js +2 -0
  101. package/dist/src/rules/core-startup.d.mts +2 -0
  102. package/dist/src/rules/core-startup.mjs +31 -0
  103. package/dist/src/serve/mission-conductor.js +48 -4
  104. package/dist/src/sessions/adapters/grok-build-native.js +23 -0
  105. package/dist/src/sessions/adapters/grok-build.js +14 -7
  106. package/dist/src/sessions/workspace-discovery.js +5 -5
  107. package/dist/src/smiths/context-pipeline/agents-md.js +34 -0
  108. package/dist/src/smiths/context-pipeline/aiwg-md.js +19 -46
  109. package/dist/src/smiths/context-pipeline/bridge-ownership.js +50 -0
  110. package/dist/src/smiths/context-pipeline/claude-hook.js +1 -1
  111. package/dist/src/smiths/context-pipeline/code-regions.js +28 -0
  112. package/dist/src/smiths/context-pipeline/finalization.js +81 -51
  113. package/dist/src/smiths/context-pipeline/generator.js +49 -114
  114. package/dist/src/smiths/context-pipeline/managed-hook.js +11 -1
  115. package/dist/src/smiths/context-pipeline/muse-bridge.js +2 -2
  116. package/dist/src/smiths/context-pipeline/provider-policy.js +6 -12
  117. package/dist/src/smiths/context-pipeline/workspace-audit.js +299 -0
  118. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +148 -0
  119. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +111 -0
  120. package/dist/src/smiths/context-pipeline/workspace-context.js +8 -1373
  121. package/dist/src/smiths/context-pipeline/workspace-doctor.js +192 -0
  122. package/dist/src/smiths/context-pipeline/workspace-document.js +201 -0
  123. package/dist/src/smiths/context-pipeline/workspace-extraction.js +205 -0
  124. package/dist/src/smiths/context-pipeline/workspace-migration.js +250 -0
  125. package/package.json +13 -2
  126. package/schemas/decision/D29Study.v10.schema.json +65 -0
  127. package/tools/agents/deploy-agents.mjs +12 -123
  128. package/tools/agents/providers/antigravity.mjs +1 -1
  129. package/tools/agents/providers/claude-post-deploy.mjs +12 -1
  130. package/tools/agents/providers/context-write.mjs +16 -0
  131. package/tools/agents/providers/grok-build.mjs +8 -5
  132. package/tools/agents/providers/hermes-skill-lifecycle.mjs +144 -0
  133. package/tools/agents/providers/hermes-startup.mjs +209 -0
  134. package/tools/agents/providers/hermes.mjs +9 -359
  135. package/tools/agents/providers/model-wrapper.mjs +5 -1
  136. package/tools/agents/providers/muse.mjs +3 -3
  137. package/tools/agents/providers/pi.mjs +4 -2
  138. package/tools/agents/providers/rule-delivery-surface.mjs +332 -0
  139. package/tools/agents/providers/rule-delivery.mjs +20 -1346
  140. package/tools/agents/providers/rule-deployment-commit.mjs +144 -0
  141. package/tools/agents/providers/rule-deployment-prepare.mjs +452 -0
  142. package/tools/agents/providers/rule-deployment-state.mjs +300 -0
  143. package/tools/agents/providers/rule-presentation.mjs +13 -4
  144. package/tools/agents/providers/rule-projection.mjs +119 -0
  145. package/tools/agents/providers/rule-startup.mjs +70 -0
  146. package/tools/agents/providers/stale-artifact-prune.mjs +128 -0
  147. package/tools/agents/providers/warp.mjs +2 -2
  148. package/tools/agents/providers/windsurf.mjs +11 -57
  149. package/tools/daemon/README.md +511 -0
  150. package/tools/daemon/adapters/base-adapter.mjs +84 -0
  151. package/tools/daemon/adapters/webhook-adapter.mjs +107 -0
  152. package/tools/daemon/agent-supervisor.mjs +299 -0
  153. package/tools/daemon/automation-engine.mjs +310 -0
  154. package/tools/daemon/autonomous-engine.mjs +346 -0
  155. package/tools/daemon/behavior-loader.mjs +316 -0
  156. package/tools/daemon/behavior.mjs +174 -0
  157. package/tools/daemon/concierge/intent-router.mjs +401 -0
  158. package/tools/daemon/concierge/orchestrator.mjs +272 -0
  159. package/tools/daemon/concierge/response-translator.mjs +462 -0
  160. package/tools/daemon/config.mjs +377 -0
  161. package/tools/daemon/cron-scheduler.mjs +178 -0
  162. package/tools/daemon/daemon-main.mjs +1169 -0
  163. package/tools/daemon/event-router.mjs +84 -0
  164. package/tools/daemon/file-watcher.mjs +383 -0
  165. package/tools/daemon/index.mjs +1181 -0
  166. package/tools/daemon/init-profile.mjs +124 -0
  167. package/tools/daemon/ipc-client.mjs +197 -0
  168. package/tools/daemon/ipc-ops-handlers.mjs +236 -0
  169. package/tools/daemon/ipc-server.mjs +275 -0
  170. package/tools/daemon/maintenance-owner.mjs +79 -0
  171. package/tools/daemon/memory-manager.mjs +386 -0
  172. package/tools/daemon/message-router.mjs +194 -0
  173. package/tools/daemon/provider-watcher.mjs +585 -0
  174. package/tools/daemon/pty-adapter.mjs +420 -0
  175. package/tools/daemon/repl-chat.mjs +359 -0
  176. package/tools/daemon/resource-bounds.mjs +88 -0
  177. package/tools/daemon/sandbox-transport.mjs +295 -0
  178. package/tools/daemon/scheduled-task-runner.mjs +535 -0
  179. package/tools/daemon/task-store.mjs +450 -0
  180. package/tools/daemon/tmux-manager.mjs +324 -0
  181. package/tools/daemon/update-policy.mjs +517 -0
  182. package/tools/daemon/web-server.mjs +399 -0
  183. package/tools/daemon/web-ui/index.html +585 -0
  184. package/tools/daemon/web-ui/styles.css +156 -0
  185. package/tools/docker/Dockerfile.daemon +35 -0
  186. package/tools/docker/container-manager.mjs +291 -0
  187. package/tools/messaging/adapter-registry.mjs +230 -0
  188. package/tools/messaging/adapters/base.mjs +326 -0
  189. package/tools/messaging/adapters/discord.mjs +462 -0
  190. package/tools/messaging/adapters/slack.mjs +402 -0
  191. package/tools/messaging/adapters/telegram.mjs +552 -0
  192. package/tools/messaging/chat-handler.mjs +297 -0
  193. package/tools/messaging/command-router.mjs +269 -0
  194. package/tools/messaging/event-bus.mjs +199 -0
  195. package/tools/messaging/index.mjs +456 -0
  196. package/tools/messaging/message-formatter.mjs +320 -0
  197. package/tools/messaging/room-manager.mjs +277 -0
  198. package/tools/messaging/types.mjs +94 -0
  199. package/tools/plugin/plugin-links.mjs +3 -0
  200. package/tools/providers/pi-bridge-policy.mjs +4 -0
  201. package/tools/ralph-external/daemon-supervisor.mjs +394 -0
  202. package/tools/ralph-external/lib/behavior-registry.mjs +270 -0
  203. package/tools/ralph-external/lib/worker-invocation-processes.mjs +3 -2
  204. package/tools/ralph-external/lib/worker-isolation-args.mjs +217 -0
  205. package/tools/ralph-external/lib/worker-isolation-status.mjs +19 -0
  206. package/tools/ralph-external/lib/worker-isolation.mjs +11 -237
  207. package/tools/ralph-external/lib/worker-overflow.mjs +10 -2
  208. package/tools/ralph-external/lib/worker-unit-cleanup.mjs +72 -0
  209. package/tools/ralph-external/session-launcher.mjs +7 -7
  210. package/tools/scripts/resource-preflight.mjs +3 -242
@@ -0,0 +1,84 @@
1
+ import { EventEmitter } from 'events';
2
+
3
+ export class EventRouter extends EventEmitter {
4
+ constructor() {
5
+ super();
6
+ this.eventHistory = [];
7
+ this.deadLetterQueue = [];
8
+ this.maxRetries = 3;
9
+ }
10
+
11
+ route(event) {
12
+ this.record(event);
13
+ this.emit('event', event);
14
+ }
15
+
16
+ record(event) {
17
+ this.eventHistory.push({
18
+ ...event,
19
+ timestamp: new Date().toISOString()
20
+ });
21
+
22
+ if (this.eventHistory.length > 1000) {
23
+ this.eventHistory = this.eventHistory.slice(-1000);
24
+ }
25
+ }
26
+
27
+ // Watch delivery is awaited by FileWatcher so a busy owner cannot lose a
28
+ // subsequent change. Legacy route() remains synchronous EventEmitter fan-out.
29
+ async deliver(event) {
30
+ this.record(event);
31
+ try {
32
+ for (const listener of this.rawListeners('event')) await listener.call(this, event);
33
+ } catch (error) {
34
+ this.handleFailedEvent(event, error);
35
+ throw error;
36
+ }
37
+ }
38
+
39
+ handleFailedEvent(event, error, attemptCount = 0) {
40
+ // Scheduled owners and watcher builds share the operator recovery path.
41
+ // Replaying through the transient DLQ would bypass the owning authority.
42
+ if (event.source === 'watch' ||
43
+ (event.source === 'schedule' && event.payload?.kind && event.payload.kind !== 'agent.prompt')) {
44
+ if (!this.emit('schedule-recovery-required', { event, error })) throw error;
45
+ return;
46
+ }
47
+ if (attemptCount >= this.maxRetries) {
48
+ this.deadLetterQueue.push({
49
+ event,
50
+ error: error.message,
51
+ attempts: attemptCount,
52
+ timestamp: new Date().toISOString()
53
+ });
54
+
55
+ if (this.deadLetterQueue.length > 100) {
56
+ this.deadLetterQueue = this.deadLetterQueue.slice(-100);
57
+ }
58
+
59
+ this.emit('event-failed', { event, error });
60
+ } else {
61
+ setTimeout(() => {
62
+ this.handleFailedEvent(event, error, attemptCount + 1);
63
+ }, Math.pow(2, attemptCount) * 1000);
64
+ }
65
+ }
66
+
67
+ getEventHistory(limit = 50) {
68
+ return this.eventHistory.slice(-limit);
69
+ }
70
+
71
+ getDeadLetterQueue() {
72
+ return [...this.deadLetterQueue];
73
+ }
74
+
75
+ clearHistory() {
76
+ this.eventHistory = [];
77
+ }
78
+
79
+ clearDeadLetterQueue() {
80
+ this.deadLetterQueue = [];
81
+ }
82
+ }
83
+
84
+ export default EventRouter;
@@ -0,0 +1,383 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { createHash } from 'node:crypto';
4
+ import { EventEmitter } from 'events';
5
+
6
+ const inside = (root, candidate) => {
7
+ const relative = path.relative(root, candidate);
8
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));
9
+ };
10
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
11
+ // Filesystem timestamps are coarse (often a few ms, up to seconds on network or
12
+ // overlay filesystems). A same-size rewrite inside one timestamp tick keeps the
13
+ // whole stat signature, so files modified this recently are "racy" (as in git's
14
+ // racy-clean check): their contents are hashed once, and compared on the next
15
+ // scan even when the stat signature is unchanged. Stable files are never read.
16
+ const RACY_WINDOW_MS = 2000;
17
+
18
+ export class FileWatcher extends EventEmitter {
19
+ // Timers use the ambient clock (injectable by fake timers); filesystem and
20
+ // delivery seams keep recovery tests independent of native watch reliability.
21
+ constructor(config, debounceMs = config.debounce_ms ?? 500, { filesystem = fs, watch, deliver, maxHandles = null } = {}) {
22
+ super();
23
+ this.config = config;
24
+ this.debounceMs = debounceMs;
25
+ this.fs = filesystem;
26
+ this.watch = watch || ((...args) => this.fs.watch(...args));
27
+ this.deliver = deliver;
28
+ // Watch-handle cap (B6 resource bounds): roots beyond the cap stay on
29
+ // polling per the B3 reconciliation contract instead of failing.
30
+ this.maxHandles = maxHandles ?? config.max_handles ?? Infinity;
31
+ this.watchers = [];
32
+ this.timers = new Map();
33
+ this.pending = new Map();
34
+ this.roots = [];
35
+ this.eventsReceived = 0;
36
+ this.started = false;
37
+ this.stopped = false;
38
+ this.busy = false;
39
+ this.blocked = false;
40
+ this.reconcilePending = false;
41
+ this.pendingRoots = new Set();
42
+ this.generation = 0;
43
+ }
44
+
45
+ start() {
46
+ if (!this.config.enabled || this.started) return;
47
+ this.started = true;
48
+ this.stopped = false;
49
+ this.blocked = false;
50
+ this.reconcilePending = false;
51
+ this.pendingRoots.clear();
52
+ this.generation++;
53
+ this.roots = this.config.paths.map(config => ({ config, path: path.resolve(config.path),
54
+ state: new Map(), hashes: new Map(), available: false, polling: config.polling ?? this.config.polling ?? false,
55
+ watcher: null, identity: null, incompletePaths: [] }));
56
+ this.reconcile();
57
+ // Recovery probing remains enabled even if routine reconciliation is off.
58
+ this.pollTimer = setInterval(() => {
59
+ const roots = this.roots.filter(root => root.polling || !root.available || (!root.watcher && !this.covered(root)));
60
+ if (roots.length) this.reconcile(roots);
61
+ }, this.config.poll_interval_ms ?? 5000);
62
+ this.pollTimer.unref?.();
63
+ const interval = this.config.reconcile_interval_ms ?? 60000;
64
+ if (interval > 0) {
65
+ this.reconcileTimer = setInterval(() => this.reconcile(), interval);
66
+ this.reconcileTimer.unref?.();
67
+ }
68
+ }
69
+
70
+ covered(root) {
71
+ return this.roots.some(other => other !== root && other.watcher && inside(other.path, root.path));
72
+ }
73
+
74
+ watchPath(watchConfig) {
75
+ const root = this.roots.find(item => item.config === watchConfig);
76
+ if (!this.fs.existsSync(watchConfig.path)) {
77
+ console.warn(`Watch path does not exist: ${watchConfig.path}`);
78
+ return null;
79
+ }
80
+ const watcher = this.watch(watchConfig.path, { recursive: true }, () => {
81
+ // Every event, including overflow or a missing filename, is only a hint.
82
+ // Scan all logical roots so nested roots retain their own filter policy.
83
+ this.requestReconcile();
84
+ });
85
+ watcher.on?.('error', error => {
86
+ if (this.stopped) return;
87
+ if (root) this.closeWatch(root);
88
+ this.watchFailed(root, error);
89
+ this.requestReconcile();
90
+ });
91
+ return watcher;
92
+ }
93
+
94
+ watchFailed(root, error) {
95
+ if (root && ['ENOSPC', 'EMFILE', 'ERR_FEATURE_UNAVAILABLE_ON_PLATFORM'].includes(error.code)) {
96
+ root.polling = true;
97
+ }
98
+ console.error(`Failed to watch ${root?.config.path ?? 'root'}; reconciling${root?.polling ? ' by polling' : ''}:`, error.message);
99
+ this.emit('watch-unavailable', { path: root?.path, polling: root?.polling ?? false, error });
100
+ }
101
+
102
+ closeWatch(root) {
103
+ root.watcher?.close();
104
+ this.watchers = this.watchers.filter(watcher => watcher !== root.watcher);
105
+ root.watcher = null;
106
+ }
107
+
108
+ requestReconcile() {
109
+ this.reconcilePending = true;
110
+ for (const root of this.roots) this.pendingRoots.add(root);
111
+ if (this.busy || this.blocked || this.stopped) return;
112
+ clearTimeout(this.hintTimer);
113
+ // Batch hints across turns, with a shorter delay than the per-path debounce.
114
+ // Hold ready deliveries until these hints are reconciled so a following
115
+ // delete/atomic replacement cannot leave a stale create ready to deliver.
116
+ this.hintTimer = setTimeout(() => this.reconcile(), Math.min(this.debounceMs / 2, 100));
117
+ }
118
+
119
+ isIgnored(root, filepath) {
120
+ const relative = path.relative(root.path, filepath).split(path.sep).join('/');
121
+ const absolute = filepath.split(path.sep).join('/');
122
+ if (this.shouldIgnore(relative, root.config.ignore || []) ||
123
+ this.shouldIgnore(`${relative}/`, root.config.ignore || []) || this.shouldIgnore(absolute, [])) return true;
124
+ const generated = [
125
+ ...(this.config.generated_output_paths || []).map(output => path.resolve(output)),
126
+ ...(root.config.generated_output_paths || []).map(output => path.resolve(root.path, output))
127
+ ];
128
+ return generated.some(output => inside(output, filepath));
129
+ }
130
+
131
+ scan(root) {
132
+ const state = new Map();
133
+ const hashes = new Map();
134
+ const changed = new Set();
135
+ const incompletePaths = [];
136
+ const scanStart = Date.now();
137
+ const previousHashes = root.hashes ?? new Map();
138
+ const stat = this.fs.statSync(root.path);
139
+ const preserve = (filepath, error) => {
140
+ for (const [previous, signature] of root.state) {
141
+ if (inside(filepath, previous)) state.set(previous, signature);
142
+ }
143
+ for (const [previous, digest] of previousHashes) {
144
+ if (inside(filepath, previous)) hashes.set(previous, digest);
145
+ }
146
+ incompletePaths.push(filepath);
147
+ this.emit('scan-incomplete', { path: filepath, code: error.code, error });
148
+ };
149
+ const visit = directory => {
150
+ let entries;
151
+ try {
152
+ entries = this.fs.readdirSync(directory, { withFileTypes: true })
153
+ .sort((a, b) => compare(a.name, b.name));
154
+ } catch (error) {
155
+ if (directory === root.path) throw error;
156
+ preserve(directory, error);
157
+ return;
158
+ }
159
+ for (const entry of entries) {
160
+ const filepath = path.join(directory, entry.name);
161
+ if (this.isIgnored(root, filepath)) continue;
162
+ if (entry.isDirectory()) visit(filepath);
163
+ else if (entry.isFile() && (!(root.config.extensions?.length) || this.hasExtension(entry.name, root.config.extensions))) {
164
+ try {
165
+ const { size, mtimeMs, ctimeMs, ino } = this.fs.statSync(filepath);
166
+ // ctime detects writes with restored mtime; ino detects atomic saves.
167
+ const signature = `${size}:${mtimeMs}:${ctimeMs}:${ino}`;
168
+ state.set(filepath, signature);
169
+ const racy = Math.max(mtimeMs, ctimeMs) >= scanStart - RACY_WINDOW_MS;
170
+ const recheck = previousHashes.has(filepath) && root.state.get(filepath) === signature;
171
+ if (racy || recheck) {
172
+ const digest = this.contentDigest(filepath);
173
+ if (digest !== null) {
174
+ if (racy) hashes.set(filepath, digest);
175
+ if (recheck && digest !== previousHashes.get(filepath)) changed.add(filepath);
176
+ }
177
+ }
178
+ } catch (error) { preserve(filepath, error); }
179
+ }
180
+ // Symlinks are not followed: no loops or traversal outside a root.
181
+ }
182
+ };
183
+ visit(root.path);
184
+ return { state, hashes, changed, identity: `${stat.dev}:${stat.ino}`, incompletePaths };
185
+ }
186
+
187
+ // Unreadable racy files fall back to the stat signature alone.
188
+ contentDigest(filepath) {
189
+ try { return createHash('sha256').update(this.fs.readFileSync(filepath)).digest('hex'); }
190
+ catch { return null; }
191
+ }
192
+
193
+ reconcile(roots = this.roots) {
194
+ if (this.stopped) return;
195
+ if (this.busy || this.blocked) {
196
+ this.reconcilePending = true;
197
+ for (const root of roots) this.pendingRoots.add(root);
198
+ return;
199
+ }
200
+ roots = new Set([...roots, ...this.pendingRoots]);
201
+ this.pendingRoots.clear();
202
+ clearTimeout(this.hintTimer);
203
+ this.hintTimer = null;
204
+ this.reconcilePending = false;
205
+ // Build one union before diffing: overlapping policies cannot duplicate a
206
+ // path or turn another available root's file into a deletion.
207
+ const changes = new Map();
208
+ for (const root of roots) {
209
+ let next;
210
+ try { next = this.scan(root); }
211
+ catch (error) {
212
+ // Only failures at the root make it unavailable. Descendant failures
213
+ // retain just that subtree in scan(), allowing siblings to converge.
214
+ if (root.available) this.emit('root-unavailable', { path: root.path, error });
215
+ root.available = false;
216
+ this.closeWatch(root);
217
+ continue;
218
+ }
219
+ root.available = true;
220
+ root.incompletePaths = next.incompletePaths ?? [];
221
+ if (root.identity !== next.identity) this.closeWatch(root);
222
+ root.identity = next.identity;
223
+ const paths = new Set([...root.state.keys(), ...next.state.keys()]);
224
+ for (const filepath of paths) {
225
+ const before = root.state.get(filepath);
226
+ const after = next.state.get(filepath);
227
+ if (before === after && !next.changed?.has(filepath)) continue;
228
+ let type = before === undefined ? 'create' : after === undefined ? 'delete' : 'modify';
229
+ // A modify-only subscription still needs startup/restart catch-up.
230
+ if (type === 'create' && root.config.events?.includes('modify') && !root.config.events.includes('create')) type = 'modify';
231
+ if (!root.config.events || root.config.events.includes(type)) changes.set(filepath, type);
232
+ }
233
+ root.state = next.state;
234
+ root.hashes = next.hashes ?? new Map();
235
+ }
236
+ // Attach shallowest first; logical nested roots still get independent scans.
237
+ for (const root of [...this.roots].sort((a, b) => a.path.length - b.path.length || compare(a.path, b.path))) {
238
+ if (!root.available || root.polling || root.watcher || this.covered(root)) continue;
239
+ if (this.watchers.length >= this.maxHandles) {
240
+ root.polling = true;
241
+ this.emit('watch-unavailable', { path: root.path, polling: true,
242
+ error: Object.assign(new Error(`Watch-handle cap reached (${this.maxHandles}); polling instead`), { code: 'WATCH_CAP' }) });
243
+ continue;
244
+ }
245
+ try {
246
+ root.watcher = this.watchPath(root.config);
247
+ if (root.watcher) this.watchers.push(root.watcher);
248
+ } catch (error) { this.watchFailed(root, error); }
249
+ }
250
+ // A returning ancestor replaces any native watches attached to its children.
251
+ for (const root of this.roots) if (root.watcher && this.roots.some(other =>
252
+ other !== root && other.watcher && other.path !== root.path && inside(other.path, root.path))) this.closeWatch(root);
253
+ for (const [filepath, type] of [...changes].sort(([a], [b]) => compare(a, b))) {
254
+ if (type === 'delete' && this.roots.some(root => root.state.has(filepath) &&
255
+ (!root.available || root.incompletePaths.some(directory => inside(directory, filepath))))) continue;
256
+ this.handleRawEvent(type, filepath);
257
+ }
258
+ void this.drain();
259
+ }
260
+
261
+ handleRawEvent(eventType, filepath) {
262
+ const previous = this.pending.get(filepath);
263
+ const first = previous?.type;
264
+ let type = eventType;
265
+ if (first === 'create' && eventType === 'delete') type = null;
266
+ else if (first === 'create') type = 'create';
267
+ else if (first === 'delete' && eventType === 'create') type = 'modify';
268
+ clearTimeout(this.timers.get(filepath));
269
+ this.timers.delete(filepath);
270
+ if (type === null) { this.pending.delete(filepath); return; }
271
+ this.pending.set(filepath, { type, ready: false });
272
+ this.timers.set(filepath, setTimeout(() => {
273
+ this.timers.delete(filepath);
274
+ const item = this.pending.get(filepath);
275
+ if (item) item.ready = true;
276
+ void this.drain();
277
+ }, this.debounceMs));
278
+ }
279
+
280
+ async drain() {
281
+ if (this.busy || this.blocked || this.stopped || this.hintTimer) return;
282
+ this.busy = true;
283
+ const generation = this.generation;
284
+ try {
285
+ while (!this.stopped && generation === this.generation && !this.blocked) {
286
+ const entry = [...this.pending].find(([filepath, item]) => item.ready &&
287
+ !this.roots.some(root => !root.available && inside(root.path, filepath)));
288
+ if (!entry) break;
289
+ const [filepath, item] = entry;
290
+ this.pending.delete(filepath);
291
+ const event = { source: 'watch', type: `file.${item.type}`,
292
+ payload: { path: filepath, event_type: item.type } };
293
+ try {
294
+ if (this.deliver) await this.deliver(event);
295
+ else {
296
+ // Await consumers in registration order, including once listeners.
297
+ for (const listener of this.rawListeners('event')) {
298
+ const result = listener.call(this, event);
299
+ if (result?.then) await result;
300
+ }
301
+ }
302
+ if (this.stopped || generation !== this.generation) break;
303
+ this.eventsReceived++;
304
+ } catch (error) {
305
+ if (this.stopped || generation !== this.generation) break;
306
+ // An unknown build outcome requires inspection, never timer retries.
307
+ this.pending.set(filepath, this.pending.get(filepath) || item);
308
+ this.blocked = true;
309
+ this.reconcilePending = true;
310
+ for (const root of this.roots) this.pendingRoots.add(root);
311
+ this.emit('delivery-failed', { event, error });
312
+ }
313
+ }
314
+ } finally {
315
+ if (generation === this.generation) {
316
+ this.busy = false;
317
+ if (this.reconcilePending && !this.blocked && !this.stopped) this.reconcile([...this.pendingRoots]);
318
+ }
319
+ }
320
+ }
321
+
322
+ // Explicit operator acknowledgement; no independent retry/backoff authority.
323
+ resume() {
324
+ this.blocked = false;
325
+ this.reconcile();
326
+ void this.drain();
327
+ }
328
+
329
+ shouldIgnore(filename, ignorePatterns) {
330
+ for (const pattern of ignorePatterns) {
331
+ if (pattern.includes('*')) {
332
+ const regex = new RegExp(pattern.split('*').map(part => part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('.*'));
333
+ if (regex.test(filename)) return true;
334
+ } else if (filename.includes(pattern)) return true;
335
+ }
336
+ return filename.includes('node_modules') || filename.includes('.git') ||
337
+ filename.includes('.aiwg/working') || filename.includes('.aiwg/daemon');
338
+ }
339
+
340
+ hasExtension(filename, extensions) {
341
+ return extensions.some(ext => filename.endsWith(ext));
342
+ }
343
+
344
+ normalizeEventType(eventType, filepath) {
345
+ if (eventType === 'rename') return this.fs.existsSync(filepath) ? 'create' : 'delete';
346
+ return eventType === 'change' ? 'modify' : eventType;
347
+ }
348
+
349
+ stop() {
350
+ this.stopped = true;
351
+ this.started = false;
352
+ this.generation++;
353
+ this.busy = false;
354
+ for (const watcher of this.watchers) watcher?.close();
355
+ this.watchers = [];
356
+ clearTimeout(this.hintTimer);
357
+ this.hintTimer = null;
358
+ clearInterval(this.pollTimer);
359
+ clearInterval(this.reconcileTimer);
360
+ for (const timer of this.timers.values()) clearTimeout(timer);
361
+ this.timers.clear();
362
+ this.pending.clear();
363
+ this.pendingRoots.clear();
364
+ }
365
+
366
+ getStats() {
367
+ return {
368
+ enabled: this.config.enabled,
369
+ max_handles: Number.isFinite(this.maxHandles) ? this.maxHandles : null,
370
+ watch_handles: this.watchers.length,
371
+ paths: this.config.paths.map(p => p.path),
372
+ events_received: this.eventsReceived,
373
+ unavailable_roots: this.roots.filter(root => !root.available).map(root => root.path),
374
+ polling_roots: this.roots.filter(root => root.polling).map(root => root.path),
375
+ scan_incomplete_roots: this.roots.filter(root => root.incompletePaths.length).map(root => root.path),
376
+ pending_changes: this.pending.size,
377
+ reconciliation_pending: this.reconcilePending,
378
+ recovery_required: this.blocked
379
+ };
380
+ }
381
+ }
382
+
383
+ export default FileWatcher;