@animus-ui/next-plugin 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- import { t as __require } from "./chunk-y_GBKt04.mjs";
2
- import { a as getSharedExternalDirs, c as setAnalysisPromise, d as setSharedEngine, f as setSharedExternalDirs, i as getSharedCss, l as setManifestJson, m as setSharedSystemProps, n as getAnalysisPromise, o as getSharedExternalEntries, p as setSharedExternalEntries, s as resetAnalysisPromise, t as engineApi, u as setSharedCss } from "./singleton-BKALu7Mk.mjs";
3
- import { DEFAULT_EXTENSIONS, assembleStylesheet, assertNoRetiredEngineSelection, buildPathAliasesJson, buildSystemPropsModule, clearEngineCache, collectExternalPackageSources, contentHash, discoverFiles, enforceExternalTokenContracts, extractSystemFilePackages, findAssetSpecifiers, findPackageRoot, formatRustTimingWaterfall, loadSystemConfig, mergeExternalKeyframes, postProcessCss, preprocessMdx, readTsconfigAliasPairs, resolveAssetFile, resolveLightningTargets, runProjectAnalysis, serializeStaticCss, staleDistIncludesMessage, substituteAssetPlaceholders, toWatchKeys, unresolvableIncludesMessage } from "@animus-ui/extract/pipeline";
4
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, statSync, unlinkSync, watch, writeFileSync } from "fs";
5
- import { basename, dirname, extname, join, relative, resolve, sep } from "path";
1
+ import { S as __require, _ as replacementEpochPath, a as REPLACEMENT_EPOCH_ARTIFACT, b as stylesPath, c as SYSTEM_PROPS_ARTIFACT, f as envelopeCssArtifact, g as readJsonEnvelope, h as readCssEnvelope, i as MANIFEST_ARTIFACT, l as analysisCommitPath, n as ANALYSIS_INPUTS_ARTIFACT, o as SESSION_ASSETS_DIR, p as envelopeJsonArtifact, r as ANALYSIS_STATUS_ARTIFACT, s as STYLES_ARTIFACT, t as ANALYSIS_COMMIT_ARTIFACT, v as sessionArtifactDir, x as systemPropsPath, y as sessionsRootDir } from "./session-paths-DfYIPDcM.mjs";
2
+ import { C as setSharedExternalEntries, S as setSharedExternalDirs, T as setWatchTransaction, _ as setOwningWatchSession, b as setSharedCss, d as getSharedExternalEntries, f as getWatchTransaction, g as setManifestJson, h as setAnalyzedHashes, l as getSharedCss, m as setAnalysisPromise, n as engineApi, o as getOwningWatchSession, p as resetAnalysisPromise, r as getAnalysisPromise, s as getReplacementEpoch, t as claimProcessSessionId, u as getSharedExternalDirs, v as setReplacementEpoch, w as setSharedSystemProps, x as setSharedEngine, y as setSessionArtifactDir } from "./singleton-BjSsGjsg.mjs";
3
+ import { DEFAULT_EXTENSIONS, assembleStylesheet, assertNoErrorDiagnostics, assertNoRetiredEngineSelection, buildPathAliasesJson, buildSystemPropsModule, clearEngineCache, collectExternalPackageSources, contentHash, createSourceIdentity, discoverFiles, enforceExternalTokenContracts, excludeCollectedPackages, extractSystemFilePackages, findAssetSpecifiers, findPackageRoot, firstOwners, formatRustTimingWaterfall, hashReplacementPlans, isExcludedPackageRelativePath, isPathWithinRoot, loadSystemConfig, mergeExternalKeyframes, postProcessCss, preprocessMdx, readTsconfigAliasPairs, resolveAssetFile, resolveLightningTargets, runProjectAnalysis, serializeStaticCss, sharesVolumeRoot, snapshotFilePlans, staleDistIncludesMessage, substituteAssetPlaceholders, toWatchKeys, unresolvableIncludesMessage, walkPackageSources } from "@animus-ui/extract/pipeline";
4
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync } from "fs";
5
+ import { basename, dirname, extname, join, relative, resolve } from "path";
6
6
  import { fileURLToPath } from "url";
7
7
  //#region src/resolve-packages.ts
8
8
  /**
@@ -94,6 +94,21 @@ function logBuildTimings(bt, rustTiming, log, verbose) {
94
94
  * alias harvesting must skip.
95
95
  */
96
96
  const ANIMUS_CSS_MODULE_ID = ".animus/styles.css";
97
+ /** Retention window for sibling session directories (design D2). */
98
+ const SESSION_DIR_MAX_AGE_MS = 1440 * 60 * 1e3;
99
+ /** Watchdog added to the debounce ceiling for status deadlines (D3). */
100
+ const STATUS_WATCHDOG_MS = 2e3;
101
+ /** Flat legacy `.animus/` artifacts removed at session start — unreachable
102
+ * by session-scoped loaders and no longer written by anyone. */
103
+ const LEGACY_FLAT_ARTIFACTS = [
104
+ MANIFEST_ARTIFACT,
105
+ ANALYSIS_INPUTS_ARTIFACT,
106
+ STYLES_ARTIFACT,
107
+ SYSTEM_PROPS_ARTIFACT,
108
+ REPLACEMENT_EPOCH_ARTIFACT,
109
+ ANALYSIS_COMMIT_ARTIFACT,
110
+ ANALYSIS_STATUS_ARTIFACT
111
+ ];
97
112
  /** Default path fragments excluded from source discovery (full + watch). */
98
113
  const DEFAULT_EXCLUDE = [
99
114
  "node_modules",
@@ -128,15 +143,18 @@ var ExtractionSession = class {
128
143
  /** Physical asset files registered with the host watcher. */
129
144
  assetDependencyPaths = /* @__PURE__ */ new Set();
130
145
  assetDependencyKeys = /* @__PURE__ */ new Set();
131
- /** When set (Turbopack orchestration), every analysis also persists
132
- * `.animus/analysis-inputs.json` so isolated loader workers can hydrate.
133
- * Webpack mode leaves this off — its loader shares the process. */
134
- persistAnalysisInputs = false;
135
146
  /** Emitter identity override for the system-props module id. Webpack mode
136
147
  * (null) injects the absolute `.animus/system-props.js` path, resolved by
137
148
  * NormalModuleReplacement; Turbopack rejects absolute-path imports, so
138
149
  * its driver sets the virtual id that `resolveAlias` maps to disk. */
139
150
  systemPropsModuleId = null;
151
+ /** Whether the analysis-inputs hydration corpus is serialized + written.
152
+ * False (webpack mode): the loader shares the pipeline process and reads
153
+ * the manifest from memory — the corpus is never persisted. True is set
154
+ * by the Turbopack orchestration driver, whose isolated loader workers
155
+ * replay it (spec: next-turbopack-integration, "Manifest disk artifact" /
156
+ * "Webpack mode skips the hydration corpus"). */
157
+ persistAnalysisInputs = false;
140
158
  /** Absolute directory prefixes for external DS packages (loader allowlisting). */
141
159
  externalPackageDirs = [];
142
160
  /** Absolute package dir → owning specifier (cross-source correlation). */
@@ -145,6 +163,45 @@ var ExtractionSession = class {
145
163
  externalFileOwners = {};
146
164
  /** External package specifier → absolute source entry path. */
147
165
  externalSourceEntries = /* @__PURE__ */ new Map();
166
+ /** SourceId derivation authority for the current generation (openspec:
167
+ * external-source-watch-ingestion, design D2) — canonical roots
168
+ * realpath'd once per full pipeline; alias→SourceId associations
169
+ * recorded while files exist so deletion resolves through the cache. */
170
+ sourceIdentity = null;
171
+ /** Canonical admitted external root → declared specifiers (set-valued
172
+ * ownership, design D2; duplicate specifiers resolving to one canonical
173
+ * root share it). Engine watch wiring and tests read this. */
174
+ externalRootOwners = /* @__PURE__ */ new Map();
175
+ /** Canonical external root → the extension set its collection walk used
176
+ * (widened for dist-only roots); rewalks and classification share it. */
177
+ externalRootExtensions = /* @__PURE__ */ new Map();
178
+ /** Canonical admitted external watch roots — the engine-side watch
179
+ * surface (webpack contextDependencies / Turbopack watchers). */
180
+ externalWatchRoots = [];
181
+ /** Canonical external root → (raw sourceKey → {raw content hash, recorded
182
+ * abs spelling}): the previous-generation inventory a dirty-root rewalk
183
+ * diffs against (design D3). Raw hashes — MDX preprocessing never skews
184
+ * the diff; the recorded abs path is a registered deletion alias, so a
185
+ * reconstructed deletion always resolves through cached identity. */
186
+ externalInventory = /* @__PURE__ */ new Map();
187
+ /** Sticky diagnostics (design D5/D7): stable key → message, re-surfaced
188
+ * on every full pipeline until the underlying condition clears. */
189
+ stickyDiagnostics = /* @__PURE__ */ new Map();
190
+ /** Volume-membership predicate for the cross-volume gate (design D5).
191
+ * Injected seam: the shared predicate only discriminates on Windows
192
+ * (win32 semantics are unit-tested via path.win32), so runtime tests
193
+ * drive the gate through this. */
194
+ sharesProjectVolume = sharesVolumeRoot;
195
+ /** Orchestrator seams (openspec: external-source-watch-ingestion, design
196
+ * D4). `onExternalRootResolved` fires per volume-admitted external root
197
+ * DURING collection — after resolution, BEFORE that root's sources are
198
+ * walked — so a watching host can open its handle with no blind gap
199
+ * between scan and watch. `onExternalRootsCommitted` fires once after a
200
+ * successful full-pipeline publication with the complete admitted
201
+ * canonical root set (the host's promote/replay/close-old phase; a
202
+ * failed pipeline never fires it, so the host rolls back). */
203
+ onExternalRootResolved = null;
204
+ onExternalRootsCommitted = null;
148
205
  options;
149
206
  staticCssJson;
150
207
  system = null;
@@ -158,15 +215,49 @@ var ExtractionSession = class {
158
215
  /** Loader-reported dependency paths for bundler watch registration. */
159
216
  systemDependencyPaths = [];
160
217
  systemDependencyHashes = /* @__PURE__ */ new Map();
161
- lastCssHash = null;
162
218
  lastSystemPropsHash = null;
163
- lastManifestHash = null;
164
- lastAnalysisInputsHash = null;
219
+ /** Per-payload write guards: payloadHash gates rewrites (byte-identical
220
+ * payloads leave disk untouched); diskHash is the hash of the CURRENT
221
+ * disk bytes (envelope included) recorded in the analysis-commit. null =
222
+ * not yet seeded (first publication reads the artifact's envelope so a
223
+ * same-session restart never rewrites byte-identical artifacts). */
224
+ artifactRecords = {
225
+ manifest: null,
226
+ inputs: null,
227
+ styles: null
228
+ };
229
+ /** Last written analysis-commit; null = seeded from disk on first use. */
230
+ lastCommit = null;
231
+ /** Session identity — claimed once per PROCESS (one Next invocation),
232
+ * adopted by every subsequent session instance so all compilers share
233
+ * one artifact tree (design D2: `next dev`/`next build` co-writing are
234
+ * separate processes and therefore separate sessions). */
235
+ sessionId = claimProcessSessionId();
236
+ /** Epoch value of the last published analysis; null = not yet known
237
+ * (seeded from the session dir's artifact on first publication so a
238
+ * same-session restart with unchanged plans never rewrites bytes). */
239
+ lastEpochValue = null;
240
+ /** Watcher debounce ceiling feeding status deadlines (design D3). */
241
+ debounceCeilingMs = 75;
242
+ /** Test seam: observes every session-artifact write (name, content)
243
+ * post-rename — write ORDER is part of the transaction contract. */
244
+ onArtifactWrite = null;
245
+ /** Status attempt bookkeeping (design D3). */
246
+ statusAttemptId = 0;
247
+ statusAttemptOpen = false;
248
+ /** Debounce-window observations pending analysis (sourceKey → hash). */
249
+ debouncePending = /* @__PURE__ */ new Map();
250
+ /** Session-start hygiene (pruning + legacy cleanup) runs once. */
251
+ sessionStartHygieneDone = false;
165
252
  lcssTargets = null;
166
253
  constructor(options) {
167
254
  this.options = options;
168
255
  this.staticCssJson = serializeStaticCss(options.staticCss);
169
256
  }
257
+ /** This session's artifact directory. Requires `rootDir` to be set. */
258
+ get sessionDir() {
259
+ return sessionArtifactDir(this.rootDir, this.sessionId);
260
+ }
170
261
  get verbose() {
171
262
  return this.options.verbose === true || process.env.ANIMUS_DEBUG === "1" || process.env.ANIMUS_DEBUG === "true";
172
263
  }
@@ -182,24 +273,87 @@ var ExtractionSession = class {
182
273
  elapsed(t) {
183
274
  return this.verbose ? Math.round(performance.now() - t) : 0;
184
275
  }
276
+ /** Lazily-computed scan config (options are constructor-fixed, so the
277
+ * derivation is stable for the session's lifetime). */
278
+ scanConfigMemo = null;
185
279
  /** Resolve the scan configuration from options — the single source of the
186
280
  * exclude/extension policy shared by the full and incremental pipelines. */
187
281
  resolveScanConfig() {
188
- const extensionsSet = new Set(this.options.extensions ?? DEFAULT_EXTENSIONS);
189
- return {
190
- excludePatterns: this.options.exclude ?? DEFAULT_EXCLUDE,
191
- extensionsSet,
192
- shouldHandleMdx: extensionsSet.has(".mdx")
193
- };
282
+ if (this.scanConfigMemo === null) {
283
+ const extensionsSet = new Set(this.options.extensions ?? DEFAULT_EXTENSIONS);
284
+ this.scanConfigMemo = {
285
+ excludePatterns: this.options.exclude ?? DEFAULT_EXCLUDE,
286
+ extensionsSet,
287
+ shouldHandleMdx: extensionsSet.has(".mdx")
288
+ };
289
+ }
290
+ return this.scanConfigMemo;
291
+ }
292
+ /**
293
+ * Watch entry point: one single-flight analysis transaction per event
294
+ * batch (openspec: next-webpack-served-transform-coherence, design D3).
295
+ * The first entering session runs the transaction; every concurrent
296
+ * entry — same session re-entered, or another compiler's session
297
+ * (client/server/RSC each hold their own instance) — joins the in-flight
298
+ * promise, so no compiler proceeds against a generation older than the
299
+ * one the transaction publishes. A rejected transaction rejects every
300
+ * joiner; the gate always clears.
301
+ */
302
+ async handleWatchUpdate(changes) {
303
+ const inflight = getWatchTransaction();
304
+ if (inflight) {
305
+ await inflight;
306
+ return;
307
+ }
308
+ if (!this.system) {
309
+ const owner = getOwningWatchSession();
310
+ const hasBatch = (changes.modifiedFiles?.size ?? 0) > 0 || (changes.removedFiles?.size ?? 0) > 0;
311
+ if (owner && owner !== this && hasBatch) await owner.ingestForwardedBatch(changes);
312
+ return;
313
+ }
314
+ const transaction = this.processWatchUpdate(changes);
315
+ setWatchTransaction(transaction);
316
+ try {
317
+ await transaction;
318
+ } finally {
319
+ setWatchTransaction(null);
320
+ }
321
+ }
322
+ /**
323
+ * Owner-side entry for a batch observed by a NON-OWNING compiler's
324
+ * watcher. Serializes behind any in-flight transaction, then runs the
325
+ * forwarded batch as its own transaction — never drops it (a forwarded
326
+ * batch has no other delivery; content-hash diffing makes an
327
+ * already-covered batch a cheap no-op).
328
+ */
329
+ async ingestForwardedBatch(changes) {
330
+ if (!this.system) return;
331
+ for (;;) {
332
+ const inflight = getWatchTransaction();
333
+ if (!inflight) break;
334
+ await inflight;
335
+ }
336
+ const transaction = this.processWatchUpdate(changes);
337
+ setWatchTransaction(transaction);
338
+ try {
339
+ await transaction;
340
+ } finally {
341
+ setWatchTransaction(null);
342
+ }
194
343
  }
195
344
  /**
196
345
  * Incremental watch pass: geological reset when the system file changed,
197
346
  * otherwise content-hash diffing restricted to the watcher's change sets
198
347
  * (falling back to a full discovery walk when no sets are provided).
199
348
  */
200
- async handleWatchUpdate(changes) {
201
- if (!this.system) return;
349
+ async processWatchUpdate(changes) {
202
350
  const rootDir = this.rootDir;
351
+ try {
352
+ changes = this.reconcileExternalRoots(changes);
353
+ } catch (err) {
354
+ this.warn(`external root reconciliation failed: ${String(err)}`);
355
+ }
356
+ const changed = [...changes.modifiedFiles ?? [], ...changes.removedFiles ?? []];
203
357
  let assetChanged = false;
204
358
  try {
205
359
  let systemHit;
@@ -213,16 +367,16 @@ var ExtractionSession = class {
213
367
  break;
214
368
  }
215
369
  }
216
- else systemHit = [...changes.modifiedFiles ?? [], ...changes.removedFiles ?? []].find((path) => toWatchKeys(path).some((key) => this.systemDependencyKeys.has(key)));
370
+ else systemHit = changed.find((path) => toWatchKeys(path).some((key) => this.systemDependencyKeys.has(key)));
217
371
  if (systemHit) {
218
372
  this.log(`geological reset: system dependency changed (${relative(rootDir, systemHit)})`);
219
373
  this.resetForHmr();
220
- const promise = this.runFullPipeline();
374
+ const promise = this.runFullPipeline(this.pendingFromBatch(changes));
221
375
  setAnalysisPromise(promise);
222
376
  await promise;
223
377
  return;
224
378
  }
225
- if ([...changes.modifiedFiles ?? [], ...changes.removedFiles ?? []].some((path) => toWatchKeys(path).some((key) => this.assetDependencyKeys.has(key)))) {
379
+ if (changed.some((path) => toWatchKeys(path).some((key) => this.assetDependencyKeys.has(key)))) {
226
380
  this.assetCopyCache.clear();
227
381
  assetChanged = true;
228
382
  }
@@ -230,53 +384,122 @@ var ExtractionSession = class {
230
384
  this.warn(`HMR geological-reset check failed: ${String(err)}`);
231
385
  }
232
386
  const { excludePatterns, extensionsSet, shouldHandleMdx } = this.resolveScanConfig();
387
+ const priorCacheEntries = /* @__PURE__ */ new Map();
388
+ const recordPrior = (key) => {
389
+ if (!priorCacheEntries.has(key)) priorCacheEntries.set(key, this.fileCache.get(key) ?? null);
390
+ };
391
+ const inventoryUpdates = [];
392
+ const ownerRemovals = [];
233
393
  let removedAny = false;
234
394
  if (changes.removedFiles) for (const removedPath of changes.removedFiles) {
235
- const rel = relative(rootDir, removedPath);
236
- if (this.fileCache.delete(rel) || this.fileCache.delete(rel + ".tsx")) removedAny = true;
395
+ let key;
396
+ let owningRoot = null;
397
+ if (isPathWithinRoot(rootDir, removedPath)) key = relative(rootDir, removedPath);
398
+ else {
399
+ const resolved = this.sourceIdentity?.resolveDeletedSourceId(removedPath);
400
+ if (!resolved) continue;
401
+ key = resolved.sourceKey;
402
+ owningRoot = resolved.owningRoot;
403
+ }
404
+ recordPrior(key);
405
+ recordPrior(key + ".tsx");
406
+ if (this.fileCache.delete(key) || this.fileCache.delete(key + ".tsx")) {
407
+ removedAny = true;
408
+ if (owningRoot) {
409
+ inventoryUpdates.push({
410
+ root: owningRoot,
411
+ key,
412
+ hash: null,
413
+ abs: removedPath
414
+ });
415
+ ownerRemovals.push(key, key + ".tsx");
416
+ }
417
+ }
237
418
  }
238
- let files;
419
+ let targets;
239
420
  if (changes.modifiedFiles) {
240
- files = [];
421
+ targets = [];
241
422
  for (const modifiedPath of changes.modifiedFiles) {
242
- if (!extensionsSet.has(extname(modifiedPath))) continue;
243
- const rel = relative(rootDir, modifiedPath);
244
- if (rel.startsWith("..")) continue;
245
- if (excludePatterns.some((pattern) => modifiedPath.includes(pattern) || rel.includes(pattern))) continue;
246
- files.push(modifiedPath);
423
+ const classified = this.classifyWatchPath(modifiedPath, {
424
+ excludePatterns,
425
+ extensionsSet
426
+ });
427
+ if (classified) targets.push({
428
+ abs: modifiedPath,
429
+ ...classified
430
+ });
247
431
  }
248
- } else files = discoverFiles(rootDir, rootDir, excludePatterns, extensionsSet);
432
+ } else targets = discoverFiles(rootDir, rootDir, excludePatterns, extensionsSet).map((abs) => ({
433
+ abs,
434
+ key: relative(rootDir, abs),
435
+ owningRoot: null
436
+ }));
249
437
  const changedPaths = [];
250
- for (const filePath of files) {
251
- let relPath = relative(rootDir, filePath);
438
+ for (const target of targets) {
439
+ let relPath = target.key;
252
440
  let source;
253
441
  try {
254
- source = readFileSync(filePath, "utf-8");
442
+ source = readFileSync(target.abs, "utf-8");
255
443
  } catch {
256
444
  continue;
257
445
  }
258
- if (shouldHandleMdx && extname(filePath) === ".mdx") {
446
+ const rawHash = contentHash(source);
447
+ if (shouldHandleMdx && extname(target.abs) === ".mdx") {
259
448
  const processed = await this.preprocessMdxEntry(source, relPath, { warn: false });
260
449
  if (!processed) continue;
261
450
  source = processed.source;
262
451
  relPath = processed.relPath;
263
452
  }
264
453
  const cached = this.fileCache.get(relPath);
265
- const hash = contentHash(source);
454
+ const hash = relPath === target.key ? rawHash : contentHash(source);
266
455
  if (!cached || cached.hash !== hash) {
267
456
  changedPaths.push(relPath);
457
+ recordPrior(relPath);
268
458
  this.fileCache.set(relPath, {
269
459
  hash,
270
460
  source
271
461
  });
462
+ if (target.owningRoot) {
463
+ const owner = this.externalRootOwners.get(target.owningRoot)?.values().next().value;
464
+ if (owner !== void 0) this.externalFileOwners[relPath] ??= owner;
465
+ inventoryUpdates.push({
466
+ root: target.owningRoot,
467
+ key: target.key,
468
+ hash: rawHash,
469
+ abs: target.abs
470
+ });
471
+ }
272
472
  }
273
473
  }
274
474
  if (changedPaths.length > 0 || removedAny || assetChanged) {
275
475
  const fileEntries = this.buildFileEntriesFromCache();
476
+ const pending = changedPaths.map((rel) => [rel, this.fileCache.get(rel).hash]);
276
477
  resetAnalysisPromise();
277
- const promise = this.runIncrementalPipeline(fileEntries);
478
+ const promise = this.runIncrementalPipeline(fileEntries, pending);
278
479
  setAnalysisPromise(promise);
279
- await promise;
480
+ try {
481
+ await promise;
482
+ } catch (err) {
483
+ for (const [key, prior] of priorCacheEntries) if (prior === null) this.fileCache.delete(key);
484
+ else this.fileCache.set(key, prior);
485
+ throw err;
486
+ }
487
+ for (const update of inventoryUpdates) {
488
+ let inventory = this.externalInventory.get(update.root);
489
+ if (!inventory) {
490
+ inventory = /* @__PURE__ */ new Map();
491
+ this.externalInventory.set(update.root, inventory);
492
+ }
493
+ if (update.hash === null) inventory.delete(update.key);
494
+ else inventory.set(update.key, {
495
+ hash: update.hash,
496
+ abs: update.abs
497
+ });
498
+ }
499
+ for (const key of ownerRemovals) delete this.externalFileOwners[key];
500
+ } else if (this.statusAttemptOpen) {
501
+ this.debouncePending.clear();
502
+ this.writeAnalysisStatus("idle", []);
280
503
  }
281
504
  }
282
505
  /**
@@ -307,9 +530,11 @@ var ExtractionSession = class {
307
530
  relPath: relPath + ".tsx"
308
531
  };
309
532
  }
310
- async runFullPipeline() {
533
+ async runFullPipeline(pending = []) {
311
534
  const pipelineStart = this.now();
312
535
  const bt = {};
536
+ this.runSessionStartHygiene();
537
+ setSessionArtifactDir(this.sessionDir);
313
538
  clearEngineCache(engineApi);
314
539
  const rootDir = this.rootDir;
315
540
  const resolvedSystemPath = resolve(rootDir, this.options.system);
@@ -373,6 +598,7 @@ var ExtractionSession = class {
373
598
  t = this.now();
374
599
  const packageNames = extractSystemFilePackages(resolvedSystemPath);
375
600
  const preResolved = resolvePackagesByName(rootDir, packageNames);
601
+ const rawExternalFiles = /* @__PURE__ */ new Map();
376
602
  const collected = await collectExternalPackageSources({
377
603
  specifiers: packageNames,
378
604
  resolveSpecifier: (name) => preResolved[name] ? resolve(rootDir, preResolved[name]) : null,
@@ -380,6 +606,7 @@ var ExtractionSession = class {
380
606
  extensionsSet,
381
607
  hasEntry: (relPath) => fileEntries.some((e) => e.path === relPath),
382
608
  preprocessFile: async (source, relPath, absPath) => {
609
+ rawExternalFiles.set(absPath, contentHash(source));
383
610
  if (shouldHandleMdx && extname(absPath) === ".mdx") return this.preprocessMdxEntry(source, relPath, {
384
611
  warn: true,
385
612
  missingDepFlag
@@ -389,7 +616,16 @@ var ExtractionSession = class {
389
616
  relPath
390
617
  };
391
618
  },
392
- onUnreadable: (relPath, err) => this.warn(`skipped unreadable package file ${relPath}: ${String(err)}`)
619
+ onUnreadable: (relPath, err) => this.warn(`skipped unreadable package file ${relPath}: ${String(err)}`),
620
+ onPackageResolved: (_specifier, packageDir) => {
621
+ if (!this.onExternalRootResolved) return;
622
+ if (!this.sharesProjectVolume(rootDir, packageDir)) return;
623
+ let canonical = packageDir;
624
+ try {
625
+ canonical = realpathSync(packageDir);
626
+ } catch {}
627
+ this.onExternalRootResolved(canonical);
628
+ }
393
629
  });
394
630
  for (const record of collected.outcomes) if (record.outcome === "empty") this.warn(`include '${record.specifier}' resolved but discovered no component sources`);
395
631
  const unresolvableMessage = unresolvableIncludesMessage(collected.outcomes);
@@ -402,12 +638,54 @@ var ExtractionSession = class {
402
638
  if (this.options.strict) throw new Error(staleDistMessage);
403
639
  this.warn(staleDistMessage);
404
640
  }
405
- const packageMap = collected.packageMap;
641
+ const rejectedSpecifiers = /* @__PURE__ */ new Set();
642
+ const crossVolumeDetails = [];
643
+ for (const [dir, specifiers] of Object.entries(collected.dirOwnerSets)) {
644
+ if (this.sharesProjectVolume(rootDir, dir)) continue;
645
+ for (const specifier of specifiers) rejectedSpecifiers.add(specifier);
646
+ crossVolumeDetails.push(`${specifiers.join(", ")} → ${dir}`);
647
+ }
648
+ this.stickyDiagnostics.delete("cross-volume");
649
+ if (rejectedSpecifiers.size > 0) {
650
+ const message = `ANIMUS_EXTERNAL_CROSS_VOLUME_UNSUPPORTED: external package source root(s) on a different volume than the project root (${rootDir}): ${crossVolumeDetails.join("; ")} — cross-volume workspace sources are unsupported; the package(s) are excluded from extraction and watching`;
651
+ if (this.options.strict) throw new Error(`[animus-next] ${message}`);
652
+ this.stickyDiagnostics.set("cross-volume", message);
653
+ }
654
+ for (const message of this.stickyDiagnostics.values()) this.warn(message);
655
+ const admitted = excludeCollectedPackages(collected, rejectedSpecifiers, rootDir);
656
+ const identity = createSourceIdentity(rootDir);
657
+ this.externalRootOwners = /* @__PURE__ */ new Map();
658
+ this.externalRootExtensions = /* @__PURE__ */ new Map();
659
+ for (const [dir, specifiers] of Object.entries(admitted.dirOwnerSets)) {
660
+ const canonical = identity.registerExternalRoot(dir);
661
+ const owners = this.externalRootOwners.get(canonical) ?? /* @__PURE__ */ new Set();
662
+ for (const specifier of specifiers) owners.add(specifier);
663
+ this.externalRootOwners.set(canonical, owners);
664
+ const exts = admitted.dirExtensions[dir];
665
+ if (exts) this.externalRootExtensions.set(canonical, new Set(exts));
666
+ }
667
+ this.sourceIdentity = identity;
668
+ this.externalWatchRoots = identity.externalRoots();
669
+ this.externalInventory = /* @__PURE__ */ new Map();
670
+ for (const [absPath, rawHash] of rawExternalFiles) {
671
+ const resolved = identity.resolveSourceId(absPath);
672
+ if (!resolved?.owningRoot) continue;
673
+ let inventory = this.externalInventory.get(resolved.owningRoot);
674
+ if (!inventory) {
675
+ inventory = /* @__PURE__ */ new Map();
676
+ this.externalInventory.set(resolved.owningRoot, inventory);
677
+ }
678
+ inventory.set(resolved.sourceKey, {
679
+ hash: rawHash,
680
+ abs: absPath
681
+ });
682
+ }
683
+ const packageMap = admitted.packageMap;
406
684
  this.lastPackageMap = packageMap;
407
- this.externalDirOwners = collected.dirOwners;
408
- this.externalFileOwners = collected.fileOwners;
409
- this.externalSourceEntries = collected.sourceEntries;
410
- for (const entry of collected.entries) {
685
+ this.externalDirOwners = firstOwners(admitted.dirOwnerSets);
686
+ this.externalFileOwners = admitted.fileOwners;
687
+ this.externalSourceEntries = admitted.sourceEntries;
688
+ for (const entry of admitted.entries) {
411
689
  const hash = contentHash(entry.source);
412
690
  this.fileCache.set(entry.path, {
413
691
  hash,
@@ -419,30 +697,160 @@ var ExtractionSession = class {
419
697
  hash
420
698
  });
421
699
  }
422
- this.externalPackageDirs = collected.packageDirs;
423
- setSharedExternalDirs(collected.packageDirs);
424
- setSharedExternalEntries(collected.sourceEntries);
425
- if (this.system && collected.sourceEntries.size > 0) {
700
+ this.externalPackageDirs = admitted.packageDirs;
701
+ setSharedExternalDirs(admitted.packageDirs);
702
+ setSharedExternalEntries(admitted.sourceEntries);
703
+ if (this.system && admitted.keyframesScanEntries.size > 0) {
426
704
  const api = engineApi();
427
- const merge = mergeExternalKeyframes((entry, root) => api.scanKeyframesExports(entry, root), this.system.keyframesJson, collected.sourceEntries.values(), this.rootDir);
705
+ const merge = mergeExternalKeyframes((entry, root) => api.scanKeyframesExports(entry, root), this.system.keyframesJson, admitted.keyframesScanEntries.values(), this.rootDir);
428
706
  this.system.keyframesJson = merge.keyframesJson;
429
707
  this.externalKeyframesDiagnostics = merge.diagnostics;
430
- }
708
+ } else this.externalKeyframesDiagnostics = [];
431
709
  bt.packageResolve = this.elapsed(t);
432
- await this.analyzeAndEmit(fileEntries, packageMap, false, bt, pipelineStart);
710
+ const universe = new Set(fileEntries.map((entry) => entry.path));
711
+ for (const key of [...this.fileCache.keys()]) if (!universe.has(key)) this.fileCache.delete(key);
712
+ await this.analyzeAndEmit(fileEntries, packageMap, false, bt, pipelineStart, pending);
713
+ this.onExternalRootsCommitted?.(this.externalWatchRoots);
714
+ setOwningWatchSession(this);
433
715
  }
434
716
  /**
435
- * Reset analysis state for HMR geological reset.
717
+ * Reset analysis state for HMR geological reset. Payload write guards go
718
+ * back to null so the next publication reseeds them from the disk
719
+ * envelopes — a byte-identical post-reset artifact is still not
720
+ * rewritten.
436
721
  */
437
722
  resetForHmr() {
438
723
  resetAnalysisPromise();
439
- this.lastCssHash = null;
724
+ this.artifactRecords = {
725
+ manifest: null,
726
+ inputs: null,
727
+ styles: null
728
+ };
440
729
  this.lastSystemPropsHash = null;
441
- this.lastManifestHash = null;
442
- this.lastAnalysisInputsHash = null;
443
730
  clearEngineCache(engineApi);
444
731
  }
445
732
  /**
733
+ * The (sourceKey, observedSourceHash) pairs of a watch batch — cheap
734
+ * evidence for the status file's pending set on the geological-reset
735
+ * path, where the batch's component edits ride along with the system
736
+ * edit (design D3: loaders wait only on observed inputs).
737
+ */
738
+ pendingFromBatch(changes) {
739
+ const { excludePatterns, extensionsSet } = this.resolveScanConfig();
740
+ const pending = [];
741
+ for (const path of changes.modifiedFiles ?? []) {
742
+ const classified = this.classifyWatchPath(path, {
743
+ excludePatterns,
744
+ extensionsSet
745
+ });
746
+ if (!classified) continue;
747
+ try {
748
+ pending.push([classified.key, contentHash(readFileSync(path, "utf-8"))]);
749
+ } catch {}
750
+ }
751
+ return pending;
752
+ }
753
+ /**
754
+ * Root-dirty inventory reconciliation (design D3): partition the
755
+ * watcher's change sets into explicit FILE events and external ROOT hits
756
+ * (a reported path that IS an admitted root, or a directory inside one),
757
+ * rewalk each dirty root through the shared discovery policy, diff the
758
+ * SourceId+raw-hash inventory against the previous generation, and merge
759
+ * the reconstructed created/edited/deleted deltas with the explicit
760
+ * events (identity-level dedup happens downstream at the cache gate).
761
+ * Deletion falls out of the inventory diff — webpack may report only the
762
+ * directory (probe-proven).
763
+ */
764
+ reconcileExternalRoots(changes) {
765
+ const identity = this.sourceIdentity;
766
+ if (!identity) return changes;
767
+ if (!changes.modifiedFiles && !changes.removedFiles) return changes;
768
+ if (this.externalWatchRoots.length === 0) return changes;
769
+ const { extensionsSet } = this.resolveScanConfig();
770
+ const dirtyRoots = /* @__PURE__ */ new Set();
771
+ const modified = /* @__PURE__ */ new Set();
772
+ const removed = /* @__PURE__ */ new Set();
773
+ const rootHitFor = (path) => {
774
+ const containing = identity.containingExternalRoot(path);
775
+ if (!containing) return null;
776
+ try {
777
+ return statSync(path).isDirectory() ? containing : null;
778
+ } catch {
779
+ return identity.resolveDeletedSourceId(path) ? null : containing;
780
+ }
781
+ };
782
+ for (const path of changes.modifiedFiles ?? []) {
783
+ const root = rootHitFor(path);
784
+ if (root) dirtyRoots.add(root);
785
+ else modified.add(path);
786
+ }
787
+ for (const path of changes.removedFiles ?? []) {
788
+ const root = rootHitFor(path);
789
+ if (root) dirtyRoots.add(root);
790
+ else removed.add(path);
791
+ }
792
+ for (const root of dirtyRoots) {
793
+ const previous = this.externalInventory.get(root) ?? /* @__PURE__ */ new Map();
794
+ const seen = /* @__PURE__ */ new Set();
795
+ const walked = walkPackageSources(root, this.externalRootExtensions.get(root) ?? extensionsSet);
796
+ if (walked.length === 0 && previous.size > 0) this.warn(`external root rewalk found no files under ${root} while its inventory holds ${previous.size} — reconciling as full deletion`);
797
+ for (const abs of walked) {
798
+ const resolved = identity.resolveSourceId(abs);
799
+ if (!resolved || resolved.owningRoot !== root) continue;
800
+ seen.add(resolved.sourceKey);
801
+ let rawHash;
802
+ try {
803
+ rawHash = contentHash(readFileSync(abs, "utf-8"));
804
+ } catch {
805
+ continue;
806
+ }
807
+ if (previous.get(resolved.sourceKey)?.hash !== rawHash) modified.add(abs);
808
+ }
809
+ for (const [key, entry] of previous) if (!seen.has(key)) removed.add(entry.abs);
810
+ }
811
+ return {
812
+ modifiedFiles: modified,
813
+ removedFiles: removed
814
+ };
815
+ }
816
+ /**
817
+ * Route one watcher-reported path (design D1/D2): a project-root member
818
+ * (lexical containment — existing local semantics preserved; consumer
819
+ * exclude patterns apply) or an admitted external member (identity
820
+ * resolution with symlink-escape rejection; package-relative excludes
821
+ * mirror the collection walk's filters — guardrail G1, one policy).
822
+ * Returns null for dropped paths.
823
+ */
824
+ classifyWatchPath(absPath, scan) {
825
+ const ext = extname(absPath);
826
+ const rootDir = this.rootDir;
827
+ if (isPathWithinRoot(rootDir, absPath)) {
828
+ if (!scan.extensionsSet.has(ext)) return null;
829
+ const rel = relative(rootDir, absPath);
830
+ if (scan.excludePatterns.some((pattern) => absPath.includes(pattern) || rel.includes(pattern))) return null;
831
+ return {
832
+ key: rel,
833
+ owningRoot: null
834
+ };
835
+ }
836
+ const resolved = this.sourceIdentity?.resolveSourceId(absPath);
837
+ if (!resolved) return null;
838
+ if (resolved.owningRoot === null) {
839
+ if (!scan.extensionsSet.has(ext)) return null;
840
+ if (scan.excludePatterns.some((pattern) => resolved.sourceKey.includes(pattern))) return null;
841
+ return {
842
+ key: resolved.sourceKey,
843
+ owningRoot: null
844
+ };
845
+ }
846
+ if (!(this.externalRootExtensions.get(resolved.owningRoot) ?? scan.extensionsSet).has(ext)) return null;
847
+ if (isExcludedPackageRelativePath(resolved.pathInRoot)) return null;
848
+ return {
849
+ key: resolved.sourceKey,
850
+ owningRoot: resolved.owningRoot
851
+ };
852
+ }
853
+ /**
446
854
  * Build file entries from cache: every cached file rides with full source.
447
855
  * The v2 engine has NO Rust-side cache (arch-extract-v2-spine: uncached
448
856
  * re-analysis beats a cache-hit path), so it must always receive full sources
@@ -461,10 +869,10 @@ var ExtractionSession = class {
461
869
  * Run incremental pipeline with cache-aware file entries.
462
870
  * Reuses system config from the last full pipeline run.
463
871
  */
464
- async runIncrementalPipeline(fileEntries) {
872
+ async runIncrementalPipeline(fileEntries, pending = []) {
465
873
  const bt = {};
466
874
  const pipelineStart = this.now();
467
- await this.analyzeAndEmit(fileEntries, this.lastPackageMap, true, bt, pipelineStart);
875
+ await this.analyzeAndEmit(fileEntries, this.lastPackageMap, true, bt, pipelineStart, pending);
468
876
  }
469
877
  /**
470
878
  * Shared analysis + emit core for both pipelines — the single call site
@@ -482,27 +890,49 @@ var ExtractionSession = class {
482
890
  * - `true` (HMR): skips the report log, and guards the system-props.js
483
891
  * write by lastSystemPropsHash.
484
892
  *
485
- * The styles.css write guard (lastCssHash) is identical on both paths.
893
+ * The disk artifacts land under the session directory in transaction
894
+ * order (design D1): manifest → analysis-inputs (Turbopack orchestration
895
+ * only) → styles.css → system-props → analysis-commit →
896
+ * replacements-epoch (last, only when moved). The analysis-status file walks starting → analyzing →
897
+ * committing → idle around the attempt, landing in `failed` (with the
898
+ * diagnostic) on any throw (design D3).
486
899
  */
487
- async analyzeAndEmit(fileEntries, packageMap, devMode, bt, pipelineStart) {
900
+ async analyzeAndEmit(fileEntries, packageMap, devMode, bt, pipelineStart, pending = []) {
901
+ this.beginStatusAttempt();
902
+ this.debouncePending.clear();
903
+ this.writeAnalysisStatus("starting", pending);
904
+ try {
905
+ await this.analyzeAndEmitAttempt(fileEntries, packageMap, devMode, bt, pipelineStart, pending);
906
+ this.writeAnalysisStatus("idle", []);
907
+ } catch (err) {
908
+ this.writeAnalysisStatus("failed", pending, String(err));
909
+ throw err;
910
+ }
911
+ }
912
+ async analyzeAndEmitAttempt(fileEntries, packageMap, devMode, bt, pipelineStart, pending) {
488
913
  const system = this.system;
489
- const result = runProjectAnalysis(engineApi, {
914
+ const analysisOptions = {
490
915
  fileEntries,
491
916
  packageMap,
492
917
  system,
493
918
  emitter: {
494
919
  runtimeImport: "@animus-ui/system/runtime",
495
920
  cssModuleId: ANIMUS_CSS_MODULE_ID,
496
- systemPropsModuleId: this.systemPropsModuleId ?? join(this.rootDir, ".animus", "system-props.js")
921
+ systemPropsModuleId: this.systemPropsModuleId ?? systemPropsPath(this.sessionDir)
497
922
  },
498
923
  pathAliasesJson: this.pathAliasesJson,
499
924
  staticCssJson: this.staticCssJson,
500
925
  externalDirs: this.externalPackageDirs.map((dir) => relative(this.rootDir, dir)),
501
- devMode,
926
+ devMode
927
+ };
928
+ this.writeAnalysisStatus("analyzing", pending);
929
+ const result = runProjectAnalysis(engineApi, {
930
+ ...analysisOptions,
502
931
  warn: (message) => this.warn(message),
503
932
  strict: this.options.strict,
504
933
  extraDiagnostics: this.externalKeyframesDiagnostics
505
934
  });
935
+ assertNoErrorDiagnostics(result.manifest?.diagnostics);
506
936
  enforceExternalTokenContracts({
507
937
  diagnostics: result.manifest?.diagnostics,
508
938
  fileOwners: this.externalFileOwners,
@@ -539,80 +969,310 @@ var ExtractionSession = class {
539
969
  })
540
970
  ].filter(Boolean).join("\n");
541
971
  setSharedCss(fullCss);
542
- const cssHash = contentHash(fullCss);
543
- if (cssHash !== this.lastCssHash) {
544
- this.writeAnimusFile("styles.css", fullCss);
545
- this.lastCssHash = cssHash;
546
- }
547
972
  const systemPropsContent = buildSystemPropsModule({
548
973
  systemPropMapJson: JSON.stringify(manifest?.system_prop_map ?? {}),
549
974
  groupRegistryJson: system.groupRegistryJson,
550
975
  dynamicProps: manifest?.dynamic_props ?? {}
551
976
  });
552
977
  setSharedSystemProps(systemPropsContent);
978
+ setManifestJson(result.manifestJson);
979
+ setAnalyzedHashes(new Map(fileEntries.map((entry) => [entry.path, entry.hash])));
980
+ this.writeAnalysisStatus("committing", pending);
981
+ const epoch = hashReplacementPlans(snapshotFilePlans(manifest), systemPropsContent);
982
+ if (this.lastCommit === null) this.lastCommit = this.seedCommitFromDisk();
983
+ const generation = (this.lastCommit?.generation ?? 0) + 1;
984
+ this.publishPayloadArtifact("manifest", MANIFEST_ARTIFACT, result.manifestJson, epoch, generation, envelopeJsonArtifact);
985
+ if (this.persistAnalysisInputs) this.publishPayloadArtifact("inputs", ANALYSIS_INPUTS_ARTIFACT, JSON.stringify({
986
+ analyzedHashes: Object.fromEntries(fileEntries.map((entry) => [entry.path, entry.hash])),
987
+ ...result.inputs
988
+ }), epoch, generation, envelopeJsonArtifact);
989
+ this.publishPayloadArtifact("styles", STYLES_ARTIFACT, fullCss, epoch, generation, envelopeCssArtifact);
553
990
  if (devMode) {
554
991
  const systemPropsHash = contentHash(systemPropsContent);
555
992
  if (systemPropsHash !== this.lastSystemPropsHash) {
556
- this.writeAnimusFile("system-props.js", systemPropsContent);
993
+ this.writeSessionArtifact(SYSTEM_PROPS_ARTIFACT, systemPropsContent);
557
994
  this.lastSystemPropsHash = systemPropsHash;
558
995
  }
559
- } else this.writeAnimusFile("system-props.js", systemPropsContent);
560
- setManifestJson(result.manifestJson);
561
- const manifestHash = contentHash(result.manifestJson);
562
- if (this.lastManifestHash === null) this.lastManifestHash = this.diskArtifactHash("manifest.json");
563
- if (manifestHash !== this.lastManifestHash) {
564
- this.writeAnimusFile("manifest.json", result.manifestJson);
565
- this.lastManifestHash = manifestHash;
996
+ } else this.writeSessionArtifact(SYSTEM_PROPS_ARTIFACT, systemPropsContent);
997
+ this.publishAnalysisCommit(epoch, generation);
998
+ this.publishReplacementEpoch(epoch);
999
+ bt.total = this.elapsed(pipelineStart);
1000
+ logBuildTimings(bt, manifest?.timing, (msg) => this.log(msg), this.verbose);
1001
+ }
1002
+ /** Open a status attempt (attemptId increments once per burst — a
1003
+ * debouncing pre-write and the analysis that follows share one id). */
1004
+ beginStatusAttempt() {
1005
+ if (!this.statusAttemptOpen) {
1006
+ this.statusAttemptId += 1;
1007
+ this.statusAttemptOpen = true;
566
1008
  }
567
- if (this.persistAnalysisInputs) {
568
- const inputsJson = JSON.stringify(result.inputs);
569
- const inputsHash = contentHash(inputsJson);
570
- if (this.lastAnalysisInputsHash === null) this.lastAnalysisInputsHash = this.diskArtifactHash("analysis-inputs.json");
571
- if (inputsHash !== this.lastAnalysisInputsHash) {
572
- this.writeAnimusFile("analysis-inputs.json", inputsJson);
573
- this.lastAnalysisInputsHash = inputsHash;
1009
+ }
1010
+ /** Write the session's analysis-status artifact (design D3). Terminal
1011
+ * states (idle/failed) close the attempt. */
1012
+ writeAnalysisStatus(state, pending, diagnostic) {
1013
+ const status = {
1014
+ schema: 1,
1015
+ sessionId: this.sessionId,
1016
+ attemptId: this.statusAttemptId,
1017
+ state,
1018
+ pending,
1019
+ deadlineAt: Date.now() + this.debounceCeilingMs + STATUS_WATCHDOG_MS,
1020
+ ...diagnostic !== void 0 ? { diagnostic } : {}
1021
+ };
1022
+ this.writeSessionArtifact(ANALYSIS_STATUS_ARTIFACT, JSON.stringify(status));
1023
+ if (state === "idle" || state === "failed") this.statusAttemptOpen = false;
1024
+ }
1025
+ /**
1026
+ * Orchestrator seam (Turbopack watcher): record watch events observed
1027
+ * during the debounce window so a loader running ahead of the analysis
1028
+ * has positive evidence to wait on (design D3 'debouncing'). Paths are
1029
+ * filtered by the scan config and hashed at observation time.
1030
+ */
1031
+ noteDebouncedWatchEvents(absPaths) {
1032
+ if (!this.rootDir) return;
1033
+ const additions = this.pendingFromBatch({ modifiedFiles: new Set(absPaths) });
1034
+ if (additions.length === 0) return;
1035
+ this.beginStatusAttempt();
1036
+ for (const [key, hash] of additions) this.debouncePending.set(key, hash);
1037
+ if (this.debounceStatusWriteScheduled) return;
1038
+ this.debounceStatusWriteScheduled = true;
1039
+ queueMicrotask(() => {
1040
+ this.debounceStatusWriteScheduled = false;
1041
+ if (this.debouncePending.size === 0) return;
1042
+ try {
1043
+ this.writeAnalysisStatus("debouncing", [...this.debouncePending.entries()]);
1044
+ } catch (err) {
1045
+ this.warn(`debounce status write failed: ${String(err)}`);
574
1046
  }
1047
+ });
1048
+ }
1049
+ /** One pending microtask flushes a burst of debounce observations. */
1050
+ debounceStatusWriteScheduled = false;
1051
+ /**
1052
+ * Write one payload artifact into the session directory, enveloped with
1053
+ * `{sessionId, generation, replacementEpoch, payloadHash}` and rewritten
1054
+ * only when the PAYLOAD bytes changed (byte-identical re-analyses leave
1055
+ * disk untouched — spec: "Unchanged manifest is not rewritten"). The
1056
+ * recorded diskHash (hash of the enveloped bytes) feeds the
1057
+ * analysis-commit.
1058
+ */
1059
+ publishPayloadArtifact(key, name, payload, epoch, generation, wrap) {
1060
+ const payloadHash = contentHash(payload);
1061
+ if (this.artifactRecords[key] === null) this.artifactRecords[key] = this.seedPayloadRecord(key, name);
1062
+ const record = this.artifactRecords[key];
1063
+ if (record !== null && record.payloadHash === payloadHash) return;
1064
+ const envelope = {
1065
+ sessionId: this.sessionId,
1066
+ generation,
1067
+ replacementEpoch: epoch,
1068
+ payloadHash
1069
+ };
1070
+ const bytes = wrap(payload, JSON.stringify(envelope));
1071
+ this.writeSessionArtifact(name, bytes);
1072
+ this.artifactRecords[key] = {
1073
+ payloadHash,
1074
+ diskHash: contentHash(bytes)
1075
+ };
1076
+ }
1077
+ /** Reconstruct a payload write guard from the on-disk artifact's envelope
1078
+ * (same-session restart: a byte-identical payload must not rewrite). */
1079
+ seedPayloadRecord(key, name) {
1080
+ let bytes;
1081
+ try {
1082
+ bytes = readFileSync(join(this.sessionDir, name), "utf-8");
1083
+ } catch {
1084
+ return null;
575
1085
  }
576
- bt.total = this.elapsed(pipelineStart);
577
- logBuildTimings(bt, manifest?.timing, (msg) => this.log(msg), this.verbose);
1086
+ let envelope;
1087
+ try {
1088
+ envelope = key === "styles" ? readCssEnvelope(bytes) : readJsonEnvelope(bytes);
1089
+ } catch {
1090
+ return null;
1091
+ }
1092
+ if (!envelope || typeof envelope.payloadHash !== "string") return null;
1093
+ return {
1094
+ payloadHash: envelope.payloadHash,
1095
+ diskHash: contentHash(bytes)
1096
+ };
1097
+ }
1098
+ /** Last analysis-commit persisted in this session's directory, or null. */
1099
+ seedCommitFromDisk() {
1100
+ try {
1101
+ const parsed = JSON.parse(readFileSync(analysisCommitPath(this.sessionDir), "utf-8"));
1102
+ return parsed.schema === 1 && parsed.sessionId === this.sessionId && typeof parsed.generation === "number" ? parsed : null;
1103
+ } catch {
1104
+ return null;
1105
+ }
1106
+ }
1107
+ /**
1108
+ * Publish the analysis-commit — the transaction identity (design D1).
1109
+ * Written AFTER every payload and BEFORE the epoch; skipped entirely when
1110
+ * the payload set (disk hashes) and epoch are unchanged, so a no-op
1111
+ * re-analysis neither re-keys loader-worker hydration nor burns a
1112
+ * generation.
1113
+ */
1114
+ publishAnalysisCommit(epoch, generation) {
1115
+ const manifestHash = this.artifactRecords.manifest?.diskHash ?? "";
1116
+ const inputsHash = this.persistAnalysisInputs ? this.artifactRecords.inputs?.diskHash ?? "" : void 0;
1117
+ const stylesHash = this.artifactRecords.styles?.diskHash ?? "";
1118
+ const prev = this.lastCommit;
1119
+ if (prev !== null && prev.manifestHash === manifestHash && prev.inputsHash === inputsHash && prev.stylesHash === stylesHash && prev.replacementEpoch === epoch) return;
1120
+ const commit = {
1121
+ schema: 1,
1122
+ sessionId: this.sessionId,
1123
+ generation,
1124
+ replacementEpoch: epoch,
1125
+ manifestHash,
1126
+ ...inputsHash !== void 0 ? { inputsHash } : {},
1127
+ stylesHash
1128
+ };
1129
+ this.writeSessionArtifact(ANALYSIS_COMMIT_ARTIFACT, JSON.stringify(commit));
1130
+ this.lastCommit = commit;
1131
+ }
1132
+ /**
1133
+ * Publish the canonical replacement epoch: maintain the session-scoped
1134
+ * disk witness `{schema, sessionId, epoch}`, rewritten ONLY when the
1135
+ * epoch VALUE changes so style-only analyses and same-session restarts
1136
+ * leave bytes and mtime untouched, then expose the value through the
1137
+ * singleton for the plugin's needBuild fan-out and the loader's catch-up
1138
+ * re-check. Every VALUE move also reconciles sibling sessions' epoch
1139
+ * artifacts (below) — the webpack cold-cache validity witness.
1140
+ */
1141
+ publishReplacementEpoch(epoch) {
1142
+ const onDisk = this.diskEpochValue();
1143
+ if (this.lastEpochValue === null) this.lastEpochValue = onDisk;
1144
+ if (epoch !== onDisk) this.writeSessionArtifact(REPLACEMENT_EPOCH_ARTIFACT, JSON.stringify({
1145
+ schema: 1,
1146
+ sessionId: this.sessionId,
1147
+ epoch
1148
+ }));
1149
+ if (epoch !== this.lastEpochValue) {
1150
+ this.lastEpochValue = epoch;
1151
+ this.reconcileSiblingEpochs(epoch);
1152
+ }
1153
+ setReplacementEpoch(epoch);
578
1154
  }
579
- /** Content hash of an existing `.animus/` artifact, or null when absent or
580
- * unreadable. Seeds a null write guard so a FRESH session never rewrites a
581
- * byte-identical artifact (spec: next-turbopack-integration — a rewrite
582
- * changes mtime/inode and needlessly re-keys Turbopack loader-worker
583
- * hydration). */
584
- diskArtifactHash(name) {
1155
+ /**
1156
+ * Sibling epoch reconciliation — the cross-session half of the webpack
1157
+ * persistent-cache witness (spec: dev-served-transform-coherence,
1158
+ * "Offline change invalidates restored modules"). Restored-module
1159
+ * snapshots reference the epoch artifact of the session that BUILT them;
1160
+ * with session-scoped trees that file would otherwise sit untouched
1161
+ * forever, keeping stale snapshots valid. Whenever this session's epoch
1162
+ * value moves, delete every sibling epoch artifact that disagrees (their
1163
+ * snapshots must invalidate — restore-on-demand then rebuilds from the
1164
+ * current generation) and leave agreeing siblings byte-untouched (warm
1165
+ * restores stay valid). Deleting a stale artifact is pruning, not a
1166
+ * foreign-session write; races with concurrent sessions are tolerated
1167
+ * (S14).
1168
+ */
1169
+ /** Sibling ids already reconciled away (artifact deleted or absent) —
1170
+ * nothing left to invalidate for them on later moves. */
1171
+ reconciledSiblingIds = /* @__PURE__ */ new Set();
1172
+ /** sessions-root listing memo, keyed by the root dir's mtime — a new or
1173
+ * pruned sibling DIRECTORY moves it; agreeing siblings stay listed. */
1174
+ siblingListing = null;
1175
+ reconcileSiblingEpochs(epoch) {
1176
+ const rootPath = sessionsRootDir(this.rootDir);
1177
+ let entries;
585
1178
  try {
586
- return contentHash(readFileSync(join(this.rootDir, ".animus", name), "utf-8"));
1179
+ const mtimeMs = statSync(rootPath).mtimeMs;
1180
+ if (this.siblingListing?.mtimeMs === mtimeMs) entries = this.siblingListing.entries;
1181
+ else {
1182
+ entries = readdirSync(rootPath);
1183
+ this.siblingListing = {
1184
+ mtimeMs,
1185
+ entries
1186
+ };
1187
+ }
1188
+ } catch {
1189
+ return;
1190
+ }
1191
+ for (const entry of entries) {
1192
+ if (entry === this.sessionId) continue;
1193
+ if (this.reconciledSiblingIds.has(entry)) continue;
1194
+ const siblingEpochPath = join(rootPath, entry, REPLACEMENT_EPOCH_ARTIFACT);
1195
+ try {
1196
+ if (JSON.parse(readFileSync(siblingEpochPath, "utf-8")).epoch === epoch) continue;
1197
+ } catch (err) {
1198
+ if (err?.code === "ENOENT") {
1199
+ this.reconciledSiblingIds.add(entry);
1200
+ continue;
1201
+ }
1202
+ }
1203
+ try {
1204
+ unlinkSync(siblingEpochPath);
1205
+ } catch {}
1206
+ this.reconciledSiblingIds.add(entry);
1207
+ }
1208
+ }
1209
+ /** Epoch value held by this session's on-disk artifact, or null when
1210
+ * absent, unreadable, or not the expected schema. */
1211
+ diskEpochValue() {
1212
+ try {
1213
+ const parsed = JSON.parse(readFileSync(replacementEpochPath(this.sessionDir), "utf-8"));
1214
+ return parsed.schema === 1 && typeof parsed.epoch === "string" ? parsed.epoch : null;
587
1215
  } catch {
588
1216
  return null;
589
1217
  }
590
1218
  }
591
- /** Ensure `.animus/` exists and write one generated artifact into it.
1219
+ /** Session-start hygiene (design D2): delete legacy flat artifacts
1220
+ * (unreachable by session-scoped loaders) and prune sibling session
1221
+ * directories older than the retention window — never the own dir,
1222
+ * tolerating races with concurrently-pruning sessions (S14). */
1223
+ runSessionStartHygiene() {
1224
+ if (this.sessionStartHygieneDone) return;
1225
+ this.sessionStartHygieneDone = true;
1226
+ const animusDir = join(this.rootDir, ".animus");
1227
+ for (const name of LEGACY_FLAT_ARTIFACTS) try {
1228
+ unlinkSync(join(animusDir, name));
1229
+ } catch {}
1230
+ let entries;
1231
+ try {
1232
+ entries = readdirSync(sessionsRootDir(this.rootDir));
1233
+ } catch {
1234
+ return;
1235
+ }
1236
+ const cutoff = Date.now() - SESSION_DIR_MAX_AGE_MS;
1237
+ for (const entry of entries) {
1238
+ if (entry === this.sessionId) continue;
1239
+ const dir = join(sessionsRootDir(this.rootDir), entry);
1240
+ try {
1241
+ if (statSync(dir).mtimeMs < cutoff) rmSync(dir, {
1242
+ recursive: true,
1243
+ force: true
1244
+ });
1245
+ } catch {}
1246
+ }
1247
+ }
1248
+ /** Ensure the session directory exists and write one artifact into it.
592
1249
  * Write-then-rename so cross-process readers (Turbopack loader workers)
593
1250
  * can never observe a torn half-written file. The tmp name carries the
594
1251
  * pid — Next dev evaluates the config in more than one process, and two
595
1252
  * sessions writing the same artifact must not race on one tmp path. */
596
- writeAnimusFile(name, content) {
597
- const dir = join(this.rootDir, ".animus");
598
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1253
+ writeSessionArtifact(name, content) {
1254
+ const dir = this.sessionDir;
1255
+ mkdirSync(dir, { recursive: true });
599
1256
  const tmpPath = join(dir, `.${name}.${process.pid}.tmp`);
600
1257
  writeFileSync(tmpPath, content);
601
1258
  renameSync(tmpPath, join(dir, name));
1259
+ this.onArtifactWrite?.(name, content);
602
1260
  }
603
1261
  /**
604
1262
  * asset() placeholder substitution (global-styles-system): resolve each
605
- * referenced specifier through Node resolution, copy the bytes into
606
- * `.animus/assets/` under a content-hashed name, and substitute a
607
- * RELATIVE url. `.animus/styles.css` is processed by Next's own CSS
608
- * pipeline (webpack and Turbopack alike), which applies its native asset
609
- * handling — publicPath and output hashing — to relative url()
610
- * references. Unsubstitutable specifiers warn and emit literally in
611
- * non-strict mode, fail the build under `strict: true`.
1263
+ * referenced specifier through Node resolution, copy the bytes into the
1264
+ * session directory's `assets/` under a content-hashed name, and
1265
+ * substitute a RELATIVE url — relative to the session-scoped styles.css,
1266
+ * which sits beside `assets/`, so the emitted `./assets/<file>` form is
1267
+ * unchanged. The stylesheet is processed by Next's own CSS pipeline
1268
+ * (webpack and Turbopack alike), which applies its native asset handling
1269
+ * — publicPath and output hashing — to relative url() references.
1270
+ * Unsubstitutable specifiers warn and emit literally in non-strict mode,
1271
+ * fail the build under `strict: true`.
612
1272
  */
613
1273
  substituteAssetReferences(globalCss, devMode) {
614
1274
  const specifiers = findAssetSpecifiers(globalCss);
615
- const assetsDir = join(this.rootDir, ".animus", "assets");
1275
+ const assetsDir = join(this.sessionDir, SESSION_ASSETS_DIR);
616
1276
  const expected = /* @__PURE__ */ new Set();
617
1277
  this.assetDependencyPaths.clear();
618
1278
  this.assetDependencyKeys.clear();
@@ -708,7 +1368,37 @@ function pruneStaleAssets(assetsDir, expected) {
708
1368
  }
709
1369
  }
710
1370
  //#endregion
1371
+ //#region src/loader-path.ts
1372
+ const __dirname$1 = dirname(fileURLToPath(import.meta.url));
1373
+ /**
1374
+ * The one loader-path derivation: first existing dist candidate under the
1375
+ * plugin dir, else the in-repo source fallback. Both loader resolvers below
1376
+ * are thin wrappers, so rule registration and any loader-chain predicate
1377
+ * can never drift (openspec: next-webpack-served-transform-coherence,
1378
+ * design D1).
1379
+ */
1380
+ function resolveLoaderPath(pluginDir, distCandidates, sourceFallback) {
1381
+ for (const candidate of distCandidates) {
1382
+ const distPath = resolve(pluginDir, candidate);
1383
+ if (existsSync(distPath)) return distPath;
1384
+ }
1385
+ return resolve(pluginDir, sourceFallback);
1386
+ }
1387
+ /**
1388
+ * This package's webpack loader path, shared by the rule registration
1389
+ * (with-animus) and the needBuild loader-chain predicate (plugin). Compiled
1390
+ * dist ships `loader.mjs` next to this module; running from source falls
1391
+ * back to the TypeScript loader.
1392
+ */
1393
+ function resolveAnimusLoaderPath() {
1394
+ return resolveLoaderPath(__dirname$1, ["loader.mjs"], "loader.ts");
1395
+ }
1396
+ //#endregion
711
1397
  //#region src/plugin.ts
1398
+ /** Loud unsupported-version failure (design D7): the coherence mechanism
1399
+ * cannot exist without the per-compilation needBuild hook, so a webpack
1400
+ * that lacks it fails immediately instead of serving stale transforms. */
1401
+ const UNSUPPORTED_WEBPACK_MESSAGE = "[animus-extract] Unsupported webpack: NormalModule.getCompilationHooks(compilation).needBuild is required for dev transform coherence and this webpack does not expose it. Use a Next.js version covered by the animus webpack gauntlet.";
712
1402
  const PLUGIN_NAME = "AnimusWebpackPlugin";
713
1403
  /**
714
1404
  * Webpack adapter for the extraction pipeline. All pipeline logic lives in
@@ -722,11 +1412,57 @@ var AnimusWebpackPlugin = class {
722
1412
  session;
723
1413
  initialized = false;
724
1414
  aliasesExtracted = false;
1415
+ /** Loader paths counting as "the animus loader" in a module's chain —
1416
+ * this package's own loader plus an optional harness override. */
1417
+ animusLoaderPaths;
1418
+ /** Epoch THIS compiler last proceeded with (set after every awaited
1419
+ * watchRun transaction — including joined ones). Null until the
1420
+ * initialization pipeline publishes. */
1421
+ lastBuiltEpoch = null;
1422
+ /** Armed by watchRun when the transaction moved the epoch; captured and
1423
+ * disarmed by the next compilation's needBuild wiring (design D1). */
1424
+ epochMovedForNextCompilation = false;
725
1425
  constructor(options) {
726
1426
  this.options = options;
727
1427
  assertNoRetiredEngineSelection(options.engine);
728
1428
  setSharedEngine(options.engine ?? "v2");
729
1429
  this.session = new ExtractionSession(options);
1430
+ this.animusLoaderPaths = new Set([resolveAnimusLoaderPath()]);
1431
+ if (options.loaderPath) this.animusLoaderPaths.add(options.loaderPath);
1432
+ }
1433
+ /** True when the module's loader chain contains the animus loader — the
1434
+ * needBuild fan-out predicate (design D1: no historical records; covers
1435
+ * restored persistent-cache modules and raw passthroughs alike). */
1436
+ moduleUsesAnimusLoader(module) {
1437
+ const loaders = module?.loaders;
1438
+ if (!Array.isArray(loaders)) return false;
1439
+ return loaders.some((entry) => typeof entry?.loader === "string" && this.animusLoaderPaths.has(entry.loader));
1440
+ }
1441
+ /** Append the exact epoch artifact path to `watchOptions.ignored`,
1442
+ * preserving the user's shape (design D2: the artifact participates in
1443
+ * module snapshots via addDependency but never triggers live watch
1444
+ * turns — no echo compilations). Session identity is process-claimed,
1445
+ * so every compiler's plugin instance derives the SAME session-scoped
1446
+ * path here regardless of which instance ends up owning the pipeline.
1447
+ * Derived from the ONE root (session.rootDir, set at config time by
1448
+ * with-animus); compiler.context is the fallback for bare-apply
1449
+ * harnesses — identical when compiler.context === cwd. */
1450
+ appendEpochWatchIgnore(compiler) {
1451
+ const options = compiler.options;
1452
+ if (!options) return;
1453
+ const epochPath = replacementEpochPath(sessionArtifactDir(this.session.rootDir ?? compiler.context, this.session.sessionId));
1454
+ options.watchOptions ??= {};
1455
+ const watchOptions = options.watchOptions;
1456
+ const ignored = watchOptions.ignored;
1457
+ if (ignored === void 0 || ignored === null) watchOptions.ignored = [epochPath];
1458
+ else if (Array.isArray(ignored)) {
1459
+ if (!ignored.includes(epochPath)) ignored.push(epochPath);
1460
+ } else if (typeof ignored === "string") watchOptions.ignored = [ignored, epochPath];
1461
+ else if (ignored instanceof RegExp) watchOptions.ignored = (path) => path === epochPath || ignored.test(path);
1462
+ else if (typeof ignored === "function") {
1463
+ const original = ignored;
1464
+ watchOptions.ignored = (path) => path === epochPath || Boolean(original(path));
1465
+ }
730
1466
  }
731
1467
  /** Extract path aliases from webpack's resolve.alias config. Runs once per
732
1468
  * plugin instance — the resolve config is immutable after apply. */
@@ -751,12 +1487,29 @@ var AnimusWebpackPlugin = class {
751
1487
  }
752
1488
  apply(compiler) {
753
1489
  if (compiler.options?.name === "edge-server") return;
1490
+ const NormalModule = compiler.webpack?.NormalModule;
1491
+ if (typeof NormalModule?.getCompilationHooks !== "function") throw new Error(UNSUPPORTED_WEBPACK_MESSAGE);
1492
+ this.appendEpochWatchIgnore(compiler);
1493
+ compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
1494
+ const epochMoved = this.epochMovedForNextCompilation;
1495
+ this.epochMovedForNextCompilation = false;
1496
+ const needBuild = NormalModule.getCompilationHooks(compilation).needBuild;
1497
+ if (typeof needBuild?.tapAsync !== "function") throw new Error(UNSUPPORTED_WEBPACK_MESSAGE);
1498
+ needBuild.tapAsync(PLUGIN_NAME, (module, _context, callback) => {
1499
+ if (epochMoved && this.moduleUsesAnimusLoader(module)) {
1500
+ callback(null, true);
1501
+ return;
1502
+ }
1503
+ callback();
1504
+ });
1505
+ });
754
1506
  compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
755
1507
  const registerSystemDependencies = () => {
756
1508
  for (const dep of this.session.systemDependencyPaths) if (existsSync(dep)) compilation.fileDependencies.add(dep);
757
1509
  else compilation.missingDependencies.add(dep);
758
1510
  for (const dep of this.session.assetDependencyPaths) if (existsSync(dep)) compilation.fileDependencies.add(dep);
759
1511
  else compilation.missingDependencies.add(dep);
1512
+ for (const root of this.session.externalWatchRoots) compilation.contextDependencies.add(root);
760
1513
  };
761
1514
  registerSystemDependencies();
762
1515
  const stage = compiler.webpack?.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL ?? -2e3;
@@ -768,7 +1521,7 @@ var AnimusWebpackPlugin = class {
768
1521
  registerSystemDependencies();
769
1522
  const css = getSharedCss();
770
1523
  if (!css || !RawSource) return;
771
- const cssPath = join(this.session.rootDir || compiler.context, ".animus", "styles.css");
1524
+ const cssPath = stylesPath(sessionArtifactDir(this.session.rootDir || compiler.context, this.session.sessionId));
772
1525
  if (compilation.getAsset(cssPath)) {
773
1526
  compilation.updateAsset(cssPath, new RawSource(css));
774
1527
  return;
@@ -777,7 +1530,7 @@ var AnimusWebpackPlugin = class {
777
1530
  });
778
1531
  });
779
1532
  compiler.hooks.run.tapPromise(PLUGIN_NAME, async (_compiler) => {
780
- this.session.rootDir = _compiler.context;
1533
+ this.adoptCompilerContext(_compiler);
781
1534
  this.extractAliases(_compiler);
782
1535
  const existing = getAnalysisPromise();
783
1536
  if (existing) {
@@ -789,25 +1542,27 @@ var AnimusWebpackPlugin = class {
789
1542
  await promise;
790
1543
  });
791
1544
  compiler.hooks.watchRun.tapPromise(PLUGIN_NAME, async (_compiler) => {
792
- this.session.rootDir = _compiler.context;
1545
+ this.adoptCompilerContext(_compiler);
793
1546
  this.extractAliases(_compiler);
794
1547
  if (!this.initialized) {
795
1548
  const existing = getAnalysisPromise();
796
- if (existing) {
797
- await existing;
798
- this.initialized = true;
799
- return;
1549
+ if (existing) await existing;
1550
+ else {
1551
+ const promise = this.session.runFullPipeline();
1552
+ setAnalysisPromise(promise);
1553
+ await promise;
800
1554
  }
801
- const promise = this.session.runFullPipeline();
802
- setAnalysisPromise(promise);
803
- await promise;
804
1555
  this.initialized = true;
1556
+ this.lastBuiltEpoch = getReplacementEpoch();
805
1557
  return;
806
1558
  }
807
1559
  await this.session.handleWatchUpdate({
808
1560
  modifiedFiles: _compiler.modifiedFiles,
809
1561
  removedFiles: _compiler.removedFiles
810
1562
  });
1563
+ const epoch = getReplacementEpoch();
1564
+ this.epochMovedForNextCompilation = this.lastBuiltEpoch !== null && epoch !== null && epoch !== this.lastBuiltEpoch;
1565
+ if (epoch !== null) this.lastBuiltEpoch = epoch;
811
1566
  });
812
1567
  }
813
1568
  /**
@@ -816,6 +1571,44 @@ var AnimusWebpackPlugin = class {
816
1571
  resetForHmr() {
817
1572
  this.session.resetForHmr();
818
1573
  }
1574
+ /** Session identity (process-claimed) — with-animus derives the
1575
+ * session-scoped alias/stub paths from it (design D2). */
1576
+ get sessionId() {
1577
+ return this.session.sessionId;
1578
+ }
1579
+ /** Set the project root at CONFIG time (with-animus) — the ONE root all
1580
+ * session-path derivations use. The compiler hooks ADOPT
1581
+ * compiler.context only when no root was published (bare-apply
1582
+ * harnesses); they never overwrite this. */
1583
+ setRootDir(rootDir) {
1584
+ this.session.rootDir = rootDir;
1585
+ }
1586
+ /** One warning per plugin instance for a context/root mismatch. */
1587
+ warnedRootDivergence = false;
1588
+ /** The run/watchRun taps' root handling: adopt compiler.context when no
1589
+ * config-time root exists; otherwise KEEP the configured root — every
1590
+ * frozen config-time derivation (stub path, css alias target,
1591
+ * virtual:animus/system-props target, watch-ignore) came from it, and a
1592
+ * silent overwrite re-keys sessionDir so the pipeline publishes
1593
+ * artifacts where none of those consumers look. A disagreement is
1594
+ * surfaced loudly instead (with-animus derives the root from Next's own
1595
+ * `dir`, which equals compiler.context in real Next runs — a mismatch
1596
+ * means a custom-webpack setup wired the plugin differently). */
1597
+ adoptCompilerContext(compiler) {
1598
+ const context = compiler.context;
1599
+ if (!this.session.rootDir) {
1600
+ this.session.rootDir = context;
1601
+ return;
1602
+ }
1603
+ if (context && this.session.rootDir !== context && !this.warnedRootDivergence) {
1604
+ this.warnedRootDivergence = true;
1605
+ console.warn(`[animus-extract] compiler.context (${context}) differs from the configured project root (${this.session.rootDir}); keeping the configured root — run next against the app directory (or align your custom webpack context) so both agree`);
1606
+ }
1607
+ }
1608
+ /** This session's artifact directory, derived from the one root. */
1609
+ get sessionDir() {
1610
+ return this.session.sessionDir;
1611
+ }
819
1612
  /** Expose options for the loader */
820
1613
  getOptions() {
821
1614
  return this.options;
@@ -854,25 +1647,35 @@ function resolveTurbopackMode(options, env = process.env) {
854
1647
  if (mode === "auto") return env.TURBOPACK !== void 0;
855
1648
  return false;
856
1649
  }
1650
+ /** rootDir-relative module request for an absolute path — always forward
1651
+ * slashes, even when path.relative produced Windows separators. */
1652
+ function rootRelativeRequest(rootDir, absPath) {
1653
+ return `./${relative(rootDir, absPath).replace(/\\/g, "/")}`;
1654
+ }
857
1655
  /**
858
1656
  * Build the `turbopack` config fragment: one glob-keyed loader rule
859
1657
  * (file-level allowlisting lives in the loader via manifest lookup — Next 15
860
1658
  * rules have no condition algebra) plus resolve aliases for the virtual
861
1659
  * system-props id, the emitter's stylesheet id, and each collected external
862
- * package specifier redirected to its source entry.
1660
+ * package specifier redirected to its source entry. Loader options carry
1661
+ * the session identity (design D2: an options-borne, JSON-serializable
1662
+ * Turbopack task input — restart-cold by construction), and the artifact
1663
+ * aliases point into the session-scoped tree.
863
1664
  */
864
1665
  function buildTurbopackConfig(args) {
865
- const { rootDir, loaderPath, options, externalSourceEntries } = args;
1666
+ const { rootDir, loaderPath, options, externalSourceEntries, sessionId, sessionDir } = args;
866
1667
  const loaderOptions = {
867
1668
  rootDir,
1669
+ sessionId,
1670
+ sessionDir,
868
1671
  ...options.strict !== void 0 ? { strict: options.strict } : {},
869
1672
  ...options.cssImportTarget !== void 0 ? { cssImportTarget: options.cssImportTarget } : {}
870
1673
  };
871
1674
  const resolveAlias = {
872
- [TURBOPACK_SYSTEM_PROPS_ID]: "./.animus/system-props.js",
873
- ".animus/styles.css": "./.animus/styles.css"
1675
+ [TURBOPACK_SYSTEM_PROPS_ID]: rootRelativeRequest(rootDir, join(sessionDir, SYSTEM_PROPS_ARTIFACT)),
1676
+ ".animus/styles.css": rootRelativeRequest(rootDir, join(sessionDir, STYLES_ARTIFACT))
874
1677
  };
875
- for (const [specifier, srcEntry] of externalSourceEntries) resolveAlias[specifier] = `./${relative(rootDir, srcEntry).replace(/\\/g, "/")}`;
1678
+ for (const [specifier, srcEntry] of externalSourceEntries) resolveAlias[specifier] = rootRelativeRequest(rootDir, srcEntry);
876
1679
  return {
877
1680
  rules: { [ANIMUS_TURBOPACK_RULE_GLOB]: { loaders: [{
878
1681
  loader: loaderPath,
@@ -889,11 +1692,7 @@ function buildTurbopackConfig(args) {
889
1692
  * not guaranteed.
890
1693
  */
891
1694
  function resolveTurbopackLoaderPath(pluginDir) {
892
- for (const candidate of ["turbopack-loader.cjs", "turbopack-loader.mjs"]) {
893
- const distPath = resolve(pluginDir, candidate);
894
- if (existsSync(distPath)) return distPath;
895
- }
896
- return resolve(pluginDir, "turbopack-loader.ts");
1695
+ return resolveLoaderPath(pluginDir, ["turbopack-loader.cjs", "turbopack-loader.mjs"], "turbopack-loader.ts");
897
1696
  }
898
1697
  //#endregion
899
1698
  //#region src/turbopack-orchestrator.ts
@@ -904,12 +1703,15 @@ function resolveTurbopackLoaderPath(pluginDir) {
904
1703
  * filesystem watcher — the bundler only ever sees the `.animus/` disk
905
1704
  * artifacts.
906
1705
  */
907
- /** Run the full pipeline with the Turbopack emitter identity: hydration
908
- * artifacts persisted, and the virtual system-props id (Turbopack rejects
909
- * the webpack path's absolute-path imports). */
1706
+ /** Run the full pipeline with the Turbopack emitter identity: the virtual
1707
+ * system-props id (Turbopack rejects the webpack path's absolute-path
1708
+ * imports). Turbopack orchestration persists the analysis-inputs
1709
+ * hydration corpus — its isolated loader workers replay it (spec:
1710
+ * next-turbopack-integration, "Manifest disk artifact"; webpack mode
1711
+ * skips the corpus). */
910
1712
  async function runTurbopackPipeline(session) {
911
- session.persistAnalysisInputs = true;
912
1713
  session.systemPropsModuleId = TURBOPACK_SYSTEM_PROPS_ID;
1714
+ session.persistAnalysisInputs = true;
913
1715
  await session.runFullPipeline();
914
1716
  }
915
1717
  const activeWatcherRoots = /* @__PURE__ */ new Set();
@@ -935,11 +1737,31 @@ const IGNORED_SEGMENTS = new Set([
935
1737
  function startTurbopackWatcher(session, rootDir, debounceMs = 75, watchFn = watch) {
936
1738
  if (activeWatcherRoots.has(rootDir)) return null;
937
1739
  activeWatcherRoots.add(rootDir);
1740
+ if (typeof session.noteDebouncedWatchEvents === "function") session.debounceCeilingMs = debounceMs;
938
1741
  const pendingPaths = /* @__PURE__ */ new Set();
939
1742
  const watchers = /* @__PURE__ */ new Map();
940
1743
  let timer = null;
941
1744
  let updateChain = Promise.resolve();
942
1745
  let closed = false;
1746
+ const externalWatchers = /* @__PURE__ */ new Map();
1747
+ let pendingOpened = /* @__PURE__ */ new Map();
1748
+ let capturedDuringSnapshot = [];
1749
+ const externalDiagnosticKey = (root) => `external-watch:${root}`;
1750
+ const failureReason = (err) => {
1751
+ const code = err?.code;
1752
+ if (code === "EMFILE" || code === "ENFILE" || code === "ENOSPC" || code === "EPERM") return `capacity(${code})`;
1753
+ if (/inotify|too many/i.test(String(err))) return "capacity";
1754
+ return code ?? "error";
1755
+ };
1756
+ const degradeExternalRoot = (root, err) => {
1757
+ externalWatchers.get(root)?.close();
1758
+ externalWatchers.delete(root);
1759
+ pendingOpened.get(root)?.close();
1760
+ pendingOpened.delete(root);
1761
+ const message = `ANIMUS_EXTERNAL_WATCH_UNAVAILABLE root=${relative(rootDir, root)} reason=${failureReason(err)} effect=changes in this workspace source may require restart`;
1762
+ session.stickyDiagnostics?.set(externalDiagnosticKey(root), message);
1763
+ console.warn(`[animus-extract] ${message}`);
1764
+ };
943
1765
  const flush = () => {
944
1766
  timer = null;
945
1767
  const modifiedFiles = /* @__PURE__ */ new Set();
@@ -951,8 +1773,15 @@ function startTurbopackWatcher(session, rootDir, debounceMs = 75, watchFn = watc
951
1773
  removedFiles
952
1774
  }).catch((err) => {
953
1775
  console.warn(`[animus-extract] Turbopack watch update failed: ${String(err)}`);
1776
+ }).then(() => {
1777
+ if (pendingOpened.size > 0 || capturedDuringSnapshot.length > 0) rollbackPendingExternal();
954
1778
  }));
955
1779
  };
1780
+ const rollbackPendingExternal = () => {
1781
+ for (const watcher of pendingOpened.values()) watcher.close();
1782
+ pendingOpened = /* @__PURE__ */ new Map();
1783
+ capturedDuringSnapshot = [];
1784
+ };
956
1785
  const closeAll = () => {
957
1786
  if (closed) return;
958
1787
  closed = true;
@@ -960,12 +1789,29 @@ function startTurbopackWatcher(session, rootDir, debounceMs = 75, watchFn = watc
960
1789
  timer = null;
961
1790
  for (const watcher of watchers.values()) watcher.close();
962
1791
  watchers.clear();
1792
+ for (const watcher of externalWatchers.values()) watcher.close();
1793
+ externalWatchers.clear();
1794
+ rollbackPendingExternal();
1795
+ session.onExternalRootResolved = null;
1796
+ session.onExternalRootsCommitted = null;
963
1797
  activeWatcherRoots.delete(rootDir);
964
1798
  };
965
1799
  const onWatcherError = (err) => {
966
1800
  closeAll();
967
1801
  console.warn(`[animus-extract] Turbopack dev watcher failed (${String(err)}); source edits require a dev-server restart`);
968
1802
  };
1803
+ const enqueuePath = (abs) => {
1804
+ pendingPaths.add(abs);
1805
+ try {
1806
+ session.noteDebouncedWatchEvents?.([abs]);
1807
+ } catch (err) {
1808
+ console.warn(`[animus-extract] Turbopack debounce status update failed: ${String(err)}`);
1809
+ }
1810
+ if (!timer) {
1811
+ timer = setTimeout(flush, debounceMs);
1812
+ timer.unref?.();
1813
+ }
1814
+ };
969
1815
  const onEvent = (baseDir, filename) => {
970
1816
  if (closed || !filename) return;
971
1817
  const rel = filename.toString();
@@ -974,10 +1820,47 @@ function startTurbopackWatcher(session, rootDir, debounceMs = 75, watchFn = watc
974
1820
  if (baseDir === rootDir && !watchers.has(abs)) try {
975
1821
  if (statSync(abs).isDirectory()) addWatcher(abs, true);
976
1822
  } catch {}
977
- pendingPaths.add(abs);
978
- if (!timer) {
979
- timer = setTimeout(flush, debounceMs);
980
- timer.unref?.();
1823
+ enqueuePath(abs);
1824
+ };
1825
+ /** External-root event path: fenced by watcher identity ({watcherRootId,
1826
+ * generation} — a handle that is neither current nor pending belongs to
1827
+ * a retired generation and its events are rejected), `filename == null`
1828
+ * marks the ROOT dirty for rediscovery, and events observed while the
1829
+ * root's generation is still snapshotting are buffered for replay. */
1830
+ const onExternalEvent = (root, self, filename) => {
1831
+ if (closed) return;
1832
+ const watcher = self();
1833
+ const active = watcher !== void 0 && externalWatchers.get(root) === watcher;
1834
+ const isPending = watcher !== void 0 && pendingOpened.get(root) === watcher;
1835
+ if (!active && !isPending) return;
1836
+ let abs;
1837
+ if (filename == null) abs = root;
1838
+ else {
1839
+ const rel = filename.toString();
1840
+ if (rel.split(/[\\/]/).some((segment) => IGNORED_SEGMENTS.has(segment))) return;
1841
+ abs = rel === "" ? root : join(root, rel);
1842
+ }
1843
+ if (isPending && !active) {
1844
+ capturedDuringSnapshot.push(abs);
1845
+ return;
1846
+ }
1847
+ enqueuePath(abs);
1848
+ };
1849
+ /** Open one external-root watcher into `into` (the committed set at
1850
+ * startup, the pending set during reset reconciliation). Failures
1851
+ * degrade ONLY this root (design D7); node_modules-resident roots are
1852
+ * documented unwatchable and never registered (guardrail G2). */
1853
+ const openExternalWatcher = (root, into) => {
1854
+ if (root.split(/[\\/]/).includes("node_modules")) return;
1855
+ try {
1856
+ let watcher;
1857
+ watcher = watchFn(root, { recursive: true }, (_event, filename) => onExternalEvent(root, () => watcher, filename));
1858
+ watcher.on("error", (err) => degradeExternalRoot(root, err));
1859
+ watcher.unref?.();
1860
+ into.set(root, watcher);
1861
+ session.stickyDiagnostics?.delete(externalDiagnosticKey(root));
1862
+ } catch (err) {
1863
+ degradeExternalRoot(root, err);
981
1864
  }
982
1865
  };
983
1866
  const addWatcher = (dir, recursive) => {
@@ -997,6 +1880,23 @@ function startTurbopackWatcher(session, rootDir, debounceMs = 75, watchFn = watc
997
1880
  console.warn(`[animus-extract] Turbopack dev watcher unavailable (${String(err)}); source edits require a dev-server restart`);
998
1881
  return null;
999
1882
  }
1883
+ for (const root of session.externalWatchRoots ?? []) openExternalWatcher(root, externalWatchers);
1884
+ session.onExternalRootResolved = (root) => {
1885
+ if (closed) return;
1886
+ if (externalWatchers.has(root) || pendingOpened.has(root)) return;
1887
+ openExternalWatcher(root, pendingOpened);
1888
+ };
1889
+ session.onExternalRootsCommitted = (roots) => {
1890
+ if (closed) return;
1891
+ const admitted = new Set(roots);
1892
+ for (const [root, watcher] of pendingOpened) externalWatchers.set(root, watcher);
1893
+ pendingOpened = /* @__PURE__ */ new Map();
1894
+ for (const [root, watcher] of [...externalWatchers]) if (!admitted.has(root)) {
1895
+ watcher.close();
1896
+ externalWatchers.delete(root);
1897
+ }
1898
+ for (const abs of capturedDuringSnapshot.splice(0)) enqueuePath(abs);
1899
+ };
1000
1900
  return { close: closeAll };
1001
1901
  }
1002
1902
  //#endregion
@@ -1026,10 +1926,12 @@ function withAnimus(options) {
1026
1926
  ...nextConfig,
1027
1927
  webpack(config, context) {
1028
1928
  if (typeof existingWebpack === "function") config = existingWebpack(config, context);
1029
- const rootDir = process.cwd();
1030
- const animusDir = join(rootDir, ".animus");
1031
- if (!existsSync(animusDir)) mkdirSync(animusDir, { recursive: true });
1032
- const stubCssPath = join(animusDir, "styles.css");
1929
+ const rootDir = typeof context.dir === "string" && context.dir.length > 0 ? context.dir : process.cwd();
1930
+ const plugin = new AnimusWebpackPlugin(options);
1931
+ plugin.setRootDir(rootDir);
1932
+ const sessionDir = plugin.sessionDir;
1933
+ if (!existsSync(sessionDir)) mkdirSync(sessionDir, { recursive: true });
1934
+ const stubCssPath = stylesPath(sessionDir);
1033
1935
  if (!existsSync(stubCssPath)) {
1034
1936
  const { declaration } = assembleStylesheet({
1035
1937
  layers: options.layers,
@@ -1048,28 +1950,26 @@ function withAnimus(options) {
1048
1950
  }
1049
1951
  } catch {}
1050
1952
  }
1051
- const plugin = new AnimusWebpackPlugin(options);
1052
- const isExternalPackageFile = (filePath) => plugin.getExternalPackageDirs().some((dir) => filePath.startsWith(dir + sep) || filePath === dir);
1953
+ const isExternalPackageFile = (filePath) => plugin.getExternalPackageDirs().some((dir) => isPathWithinRoot(dir, filePath));
1053
1954
  config.plugins = config.plugins || [];
1054
1955
  config.plugins.push(plugin);
1055
1956
  const { DefinePlugin } = context.webpack ?? {};
1056
1957
  if (typeof DefinePlugin === "function") config.plugins.push(new DefinePlugin({ __ANIMUS_DEV__: JSON.stringify(context.dev === true) }));
1057
1958
  config.resolve = config.resolve || {};
1058
1959
  config.resolve.alias = config.resolve.alias || {};
1059
- config.resolve.alias[ANIMUS_CSS_MODULE_ID] = join(rootDir, ".animus", "styles.css");
1060
- const systemPropsPath = join(rootDir, ".animus", "system-props.js");
1960
+ config.resolve.alias[ANIMUS_CSS_MODULE_ID] = stylesPath(sessionDir);
1961
+ const sessionSystemPropsPath = systemPropsPath(sessionDir);
1061
1962
  config.plugins.push({ apply(compiler) {
1062
1963
  compiler.hooks.normalModuleFactory.tap("AnimusVirtualResolve", (nmf) => {
1063
1964
  nmf.hooks.beforeResolve.tap("AnimusVirtualResolve", (resolveData) => {
1064
- if (resolveData.request === "virtual:animus/system-props") resolveData.request = systemPropsPath;
1065
- if (resolveData.request === "virtual:animus/styles.css") resolveData.request = join(rootDir, ".animus", "styles.css");
1965
+ if (resolveData.request === "virtual:animus/system-props") resolveData.request = sessionSystemPropsPath;
1966
+ if (resolveData.request === "virtual:animus/styles.css") resolveData.request = stylesPath(sessionDir);
1066
1967
  const srcEntry = plugin.getExternalSourceEntries().get(resolveData.request);
1067
1968
  if (srcEntry) resolveData.request = srcEntry;
1068
1969
  });
1069
1970
  });
1070
1971
  } });
1071
- const loaderPath = resolve(__dirname, "loader.mjs");
1072
- const actualLoaderPath = existsSync(loaderPath) ? loaderPath : resolve(__dirname, "loader.ts");
1972
+ const actualLoaderPath = resolveAnimusLoaderPath();
1073
1973
  config.module = config.module || {};
1074
1974
  config.module.rules = config.module.rules || [];
1075
1975
  config.module.rules.push({
@@ -1113,7 +2013,9 @@ async function wireTurbopack(nextConfig, options) {
1113
2013
  rootDir,
1114
2014
  loaderPath: resolveTurbopackLoaderPath(__dirname),
1115
2015
  options,
1116
- externalSourceEntries: session.externalSourceEntries
2016
+ externalSourceEntries: session.externalSourceEntries,
2017
+ sessionId: session.sessionId,
2018
+ sessionDir: session.sessionDir
1117
2019
  });
1118
2020
  const existing = nextConfig.turbopack ?? {};
1119
2021
  if (existing.rules && "*.{ts,tsx,js,jsx,mjs}" in existing.rules) throw new Error(`[animus-extract] turbopack.rules['${ANIMUS_TURBOPACK_RULE_GLOB}'] is already configured — remove the consumer rule or disable unstable_turbopack`);