@gadicc/loom 1.35.0 → 1.35.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -86,6 +86,8 @@ const releaseConfig_js_1 = require("./releaseConfig.js");
86
86
  const releaseCredentials_js_1 = require("./releaseCredentials.js");
87
87
  const releaseTrustCommand_js_1 = require("./releaseTrustCommand.js");
88
88
  const localDb_js_1 = require("./localDb.js");
89
+ const managedFiles_js_1 = require("./managedFiles.js");
90
+ const legacyManagedOutputs_js_1 = require("./legacyManagedOutputs.js");
89
91
  const betterAuth_js_1 = require("../apiKeys/betterAuth.js");
90
92
  const retention_js_1 = require("../apiKeys/retention.js");
91
93
  const projectSkills_js_1 = require("./projectSkills.js");
@@ -390,6 +392,62 @@ async function writeTextIfChanged(path, text) {
390
392
  await (0, promises_1.writeFile)(path, text, "utf8");
391
393
  return true;
392
394
  }
395
+ /**
396
+ * Writes loom.json when its data changed, ignoring key order. An existing
397
+ * file is patched member by member, so the consumer's formatting and key
398
+ * order survive and a formatter such as Biome has nothing to change; only a
399
+ * new file is written whole.
400
+ */
401
+ async function writeManifestIfChanged(cwd, manifest) {
402
+ const path = (0, node_path_1.join)(cwd, "loom.json");
403
+ const currentText = await readTextIfExists(path);
404
+ if (currentText === null) {
405
+ await (0, promises_1.writeFile)(path, stringifyJson(manifest), "utf8");
406
+ return true;
407
+ }
408
+ if ((0, projectTooling_js_1.jsonValuesEqual)(parseJson(currentText, "loom.json"), manifest)) {
409
+ return false;
410
+ }
411
+ await (0, promises_1.writeFile)(path, (0, projectTooling_js_1.patchJsonText)(currentText, manifest), "utf8");
412
+ return true;
413
+ }
414
+ function recordedManagedFileHash(feature, relativePath) {
415
+ return feature?.managedFiles?.[relativePath];
416
+ }
417
+ /**
418
+ * Notes one managed-file sync in `records`: Loom's hash when the file now
419
+ * holds or matches Loom output, otherwise the previous record, so the file is
420
+ * recognised again if its local edits are reverted.
421
+ */
422
+ function recordManagedFileSync(records, feature, relativePath, result) {
423
+ const hash = result.hash ?? recordedManagedFileHash(feature, relativePath);
424
+ if (hash)
425
+ records[relativePath] = hash;
426
+ }
427
+ /**
428
+ * Reports a managed file Loom left alone because it has local edits, naming
429
+ * the file, the difference and how to resolve it.
430
+ */
431
+ function formatPreservedManagedFileNote(relativePath, difference, resolution) {
432
+ return `Preserved local edits in Loom-managed ${relativePath}${difference ? ` (${difference})` : ""}; Loom did not update it. ${resolution}`;
433
+ }
434
+ /**
435
+ * Replaces a feature's managed-file or managed-task record with what this
436
+ * sync manages, sorted so loom.json stays stable. Entries Loom no longer
437
+ * manages drop out.
438
+ */
439
+ function setManagedRecords(feature, key, records) {
440
+ const entries = Object.entries(records).sort(([left], [right]) => left.localeCompare(right));
441
+ if (entries.length) {
442
+ feature[key] = Object.fromEntries(entries);
443
+ }
444
+ else {
445
+ delete feature[key];
446
+ }
447
+ }
448
+ function setManagedFileRecords(feature, records) {
449
+ setManagedRecords(feature, "managedFiles", records);
450
+ }
393
451
  async function defaultCommandRunner(command, args, options) {
394
452
  return await new Promise((resolvePromise) => {
395
453
  const inherit = options.stdio === "inherit" ||
@@ -578,7 +636,7 @@ function jobsScriptBypassesEnvRunner(scriptName, scriptCommand) {
578
636
  return (scriptName === "job" || scriptCommand.includes("jobDirect.ts")) &&
579
637
  !scriptUsesLoomEnvRunner(scriptCommand);
580
638
  }
581
- async function checkEnvRunnerAdoption(cwd, manifest) {
639
+ async function checkEnvRunnerAdoption(cwd, manifest, framework) {
582
640
  const issues = [];
583
641
  const suggestions = new Set();
584
642
  const activeDb = manifest.features.db?.status === "active";
@@ -595,23 +653,53 @@ async function checkEnvRunnerAdoption(cwd, manifest) {
595
653
  }
596
654
  const tooling = await getProjectTooling(cwd, manifest);
597
655
  const taskStore = await (0, projectTooling_js_1.readTaskStore)(cwd, tooling.tasks);
656
+ // `loom add` refreshes only tasks whose value is provably Loom's; an edited
657
+ // task has to be moved onto `loom env` by hand.
658
+ const loomTasks = new Map();
659
+ if (activeDb) {
660
+ const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
661
+ for (const task of getDbManagedTasks(dbConfig, tooling)) {
662
+ loomTasks.set(task.name, [manifest.features.db, task]);
663
+ }
664
+ }
665
+ if (activeJobs) {
666
+ const jobsConfig = mergeJobsConfig(framework, manifest.features.jobs.config);
667
+ for (const task of getJobsManagedTasks(jobsConfig)) {
668
+ loomTasks.set(task.name, [manifest.features.jobs, task]);
669
+ }
670
+ }
671
+ const loomRefreshes = (name, definition) => {
672
+ const entry = loomTasks.get(name);
673
+ if (!entry)
674
+ return false;
675
+ const [feature, task] = entry;
676
+ return (0, managedFiles_js_1.classifyManagedTask)(definition, task.definition, {
677
+ knownValues: task.knownValues,
678
+ recordedHash: feature.managedTasks?.[name],
679
+ }).state !== "customized";
680
+ };
681
+ const handEditSuggestion = (name) => `Loom does not overwrite edited tasks: change ${name} in ${taskStore.config} to run its command through \`loom env -- <command>\`.`;
598
682
  for (const [scriptName, definition] of Object.entries(taskStore.definitions)) {
599
683
  const scriptCommand = (0, projectTooling_js_1.getTaskCommand)(definition);
600
684
  if (activeDb && dbScriptBypassesEnvRunner(scriptName, scriptCommand)) {
601
685
  issues.push(taskStore.config === "package.json"
602
686
  ? `DB package.json script bypasses the Loom env runner: ${scriptName}`
603
687
  : `DB task in ${taskStore.config} bypasses the Loom env runner: ${scriptName}`);
604
- suggestions.add(taskStore.config === "package.json"
605
- ? "Run `loom add db` to refresh DB package scripts."
606
- : "Run `loom add db` to refresh DB tasks.");
688
+ suggestions.add(!loomRefreshes(scriptName, definition)
689
+ ? handEditSuggestion(scriptName)
690
+ : taskStore.config === "package.json"
691
+ ? "Run `loom add db` to refresh DB package scripts."
692
+ : "Run `loom add db` to refresh DB tasks.");
607
693
  }
608
694
  if (activeJobs && jobsScriptBypassesEnvRunner(scriptName, scriptCommand)) {
609
695
  issues.push(taskStore.config === "package.json"
610
696
  ? `Jobs package.json script bypasses the Loom env runner: ${scriptName}`
611
697
  : `Jobs task in ${taskStore.config} bypasses the Loom env runner: ${scriptName}`);
612
- suggestions.add(taskStore.config === "package.json"
613
- ? "Run `loom add jobs` to refresh jobs package scripts."
614
- : "Run `loom add jobs` to refresh jobs tasks.");
698
+ suggestions.add(!loomRefreshes(scriptName, definition)
699
+ ? handEditSuggestion(scriptName)
700
+ : taskStore.config === "package.json"
701
+ ? "Run `loom add jobs` to refresh jobs package scripts."
702
+ : "Run `loom add jobs` to refresh jobs tasks.");
615
703
  }
616
704
  }
617
705
  return {
@@ -1145,25 +1233,89 @@ function ensurePackageJsonDependency(packageJson, versionRange = exports.DEFAULT
1145
1233
  async function getProjectTooling(cwd, manifest) {
1146
1234
  return await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest.project?.tooling);
1147
1235
  }
1148
- async function ensureProjectTasks(cwd, manifest, tasks) {
1236
+ function formatTaskValue(definition) {
1237
+ return `\`${typeof definition === "string" ? definition : JSON.stringify(definition)}\``;
1238
+ }
1239
+ /** Shows a kept task's local value next to Loom's value. */
1240
+ function formatCustomizedTaskValues({ current, task }) {
1241
+ return `(local: ${formatTaskValue(current)}; Loom: ${formatTaskValue(task.definition)})`;
1242
+ }
1243
+ /**
1244
+ * Creates missing Loom-owned tasks and updates those whose value is provably
1245
+ * Loom's (recorded hash, current value or a known earlier value), through
1246
+ * localized edits of the config `project.tooling` records. Edited tasks are
1247
+ * left alone and returned so the caller can report them.
1248
+ */
1249
+ async function syncManagedTasks(cwd, manifest, feature, tasks) {
1149
1250
  const tooling = await getProjectTooling(cwd, manifest);
1150
1251
  const changedKeys = [];
1151
- for (const [name, definition] of Object.entries(tasks)) {
1152
- const result = await (0, projectTooling_js_1.ensureTask)(cwd, tooling.tasks, { definition, name });
1252
+ const customized = [];
1253
+ const records = {};
1254
+ for (const task of tasks) {
1255
+ const store = await (0, projectTooling_js_1.readTaskStore)(cwd, tooling.tasks);
1256
+ const current = store.definitions[task.name];
1257
+ const classification = (0, managedFiles_js_1.classifyManagedTask)(current, task.definition, {
1258
+ knownValues: task.knownValues,
1259
+ recordedHash: feature?.managedTasks?.[task.name],
1260
+ });
1261
+ if (classification.state === "customized") {
1262
+ customized.push({ current, task });
1263
+ const previous = feature?.managedTasks?.[task.name];
1264
+ if (previous)
1265
+ records[task.name] = previous;
1266
+ continue;
1267
+ }
1268
+ records[task.name] = classification.expectedHash;
1269
+ // A value that matches apart from whitespace keeps the app's spelling.
1270
+ if (classification.state === "current")
1271
+ continue;
1272
+ const result = await (0, projectTooling_js_1.ensureTask)(cwd, tooling.tasks, {
1273
+ definition: task.definition,
1274
+ name: task.name,
1275
+ });
1153
1276
  if (result.changed)
1154
- changedKeys.push(name);
1277
+ changedKeys.push(task.name);
1155
1278
  }
1156
- return { changedKeys, config: tooling.tasks.config, tooling };
1279
+ return { changedKeys, config: tooling.tasks.config, customized, records };
1157
1280
  }
1158
- async function checkProjectTasks(cwd, manifest, expected) {
1281
+ /**
1282
+ * Compares Loom-owned tasks with Loom's values without writing: `mismatches`
1283
+ * are missing tasks or unedited older Loom values that `loom add` updates;
1284
+ * `customized` tasks have edits Loom will not overwrite.
1285
+ */
1286
+ async function checkManagedTasks(cwd, manifest, feature, tasks) {
1159
1287
  const tooling = await getProjectTooling(cwd, manifest);
1160
1288
  const store = await (0, projectTooling_js_1.readTaskStore)(cwd, tooling.tasks);
1161
- return {
1162
- config: tooling.tasks.config,
1163
- mismatches: Object.entries(expected).flatMap(([name, command]) => (0, projectTooling_js_1.getTaskCommand)(store.definitions[name]) === command ? [] : [name]),
1164
- store,
1165
- tooling,
1166
- };
1289
+ const mismatches = [];
1290
+ const customized = [];
1291
+ for (const task of tasks) {
1292
+ const current = store.definitions[task.name];
1293
+ const { state } = (0, managedFiles_js_1.classifyManagedTask)(current, task.definition, {
1294
+ knownValues: task.knownValues,
1295
+ recordedHash: feature?.managedTasks?.[task.name],
1296
+ });
1297
+ if (state === "customized") {
1298
+ customized.push({ current, task });
1299
+ }
1300
+ else if (state !== "current") {
1301
+ mismatches.push(task.name);
1302
+ }
1303
+ }
1304
+ return { config: tooling.tasks.config, customized, mismatches, store };
1305
+ }
1306
+ /** Notes for Loom-owned tasks that `loom init` or `loom add` left alone. */
1307
+ function formatPreservedTaskNotes(sync, featureKey) {
1308
+ return sync.customized.map((customized) => `Preserved local edits in Loom-managed task ${customized.task.name} in ${sync.config} ${formatCustomizedTaskValues(customized)}; Loom did not update it. To restore Loom's value, delete the task and rerun \`loom add ${featureKey}\`.`);
1309
+ }
1310
+ /**
1311
+ * `loom check` warnings for Loom-owned tasks with local edits, naming each
1312
+ * task and showing both values.
1313
+ */
1314
+ function addCustomizedTaskWarnings(check, featureKey, warnings, suggestions) {
1315
+ for (const customized of check.customized) {
1316
+ warnings.push(`Loom-managed task ${customized.task.name} in ${check.config} has local edits that Loom will not overwrite ${formatCustomizedTaskValues(customized)}`);
1317
+ suggestions.add(`To restore Loom's value for an edited ${featureKey} task, delete the task and rerun \`loom add ${featureKey}\`.`);
1318
+ }
1167
1319
  }
1168
1320
  function buildManifest(cwd, packageJson, framework, existingManifest, tooling) {
1169
1321
  return {
@@ -1509,6 +1661,14 @@ function getDbExpectedScripts(config, tooling) {
1509
1661
  "schema:gen": "loom db schema-gen",
1510
1662
  };
1511
1663
  }
1664
+ function getDbManagedTasks(config, tooling) {
1665
+ const legacy = (0, legacyManagedOutputs_js_1.legacyDbTaskValues)(config.modules.drizzleConfig);
1666
+ return Object.entries(getDbExpectedScripts(config, tooling)).map(([name, definition]) => ({
1667
+ definition,
1668
+ knownValues: legacy[name] ?? [],
1669
+ name,
1670
+ }));
1671
+ }
1512
1672
  function mergeDbConfig(framework, featureConfig) {
1513
1673
  const defaults = getDbConfig(framework);
1514
1674
  return {
@@ -2341,7 +2501,7 @@ function plainYamlValue(value) {
2341
2501
  return trimmed.replace(/\s+#.*$/, "").trim();
2342
2502
  }
2343
2503
  /**
2344
- * Local (`file:`/`link:`) Loom entries of the pnpm-workspace.yaml
2504
+ * Local (`file:`/`link:`/`workspace:`) Loom entries of the pnpm-workspace.yaml
2345
2505
  * `overrides:` map outside Loom's managed block, such as one written by
2346
2506
  * hand. `line` is the entry's line in `text` once the managed block is
2347
2507
  * removed, or null in flow style, which Loom does not edit.
@@ -2356,7 +2516,7 @@ function getUnmanagedPnpmWorkspaceLoomOverrides(text) {
2356
2516
  return entries;
2357
2517
  const add = (key, value, line) => {
2358
2518
  const spec = plainYamlValue(value);
2359
- if (overrideKeyTargetsLoom(key) && /^(?:file|link):/.test(spec)) {
2519
+ if (overrideKeyTargetsLoom(key) && isLocalPackageSpec(spec)) {
2360
2520
  entries.push({ key, line, spec });
2361
2521
  }
2362
2522
  };
@@ -3167,6 +3327,15 @@ function compareParsedVersions(left, right) {
3167
3327
  }
3168
3328
  return left.prerelease.localeCompare(right.prerelease);
3169
3329
  }
3330
+ /**
3331
+ * Whether `version` is a newer release than the exact pin `pinned`. Pin
3332
+ * advice must never suggest moving an app back to an older Loom.
3333
+ */
3334
+ function isNewerLoomVersion(version, pinned) {
3335
+ const candidate = parseSemverTag(version);
3336
+ const pin = parseSemverTag(pinned);
3337
+ return !!candidate && !!pin && compareParsedVersions(candidate, pin) > 0;
3338
+ }
3170
3339
  async function findPublishedLoomPublicationForCommit(sourceRoot, sourceCommit, commandRunner, env, preferredSpec,
3171
3340
  /** Names the commit in refusals, such as "Loom commit abc, which built X,". */
3172
3341
  subject) {
@@ -3281,6 +3450,208 @@ async function captureLoadedLocalLoomSignature(cwd, env) {
3281
3450
  function formatPnpmOverrideNotAppliedMessage(override, pnpmVersion) {
3282
3451
  return `pnpm did not apply the Loom local-dev override in ${formatPnpmOverrideLocation(override.location)}: pnpm-lock.yaml does not record ${exports.LOOM_DEPENDENCY}: ${override.spec} under overrides, so this app still resolves the published package. Loom placed it for ${pnpmVersion ? `pnpm ${pnpmVersion}` : "an unknown pnpm version"}: pnpm before 10.5.1 reads overrides only from package.json, pnpm 10.5.1 and later 10.x read pnpm-workspace.yaml overrides only while package.json has none, and pnpm 11 reads only pnpm-workspace.yaml. Make sure package.json packageManager names the pnpm version you run, then rerun \`loom dev sync\`.`;
3283
3452
  }
3453
+ /** Whether deno.lock records a `links` entry for Loom. */
3454
+ async function denoLockLinksLoom(cwd) {
3455
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, "deno.lock"));
3456
+ if (!text)
3457
+ return false;
3458
+ let lock;
3459
+ try {
3460
+ lock = JSON.parse(text);
3461
+ }
3462
+ catch {
3463
+ // Unreadable: assume it may record one.
3464
+ return true;
3465
+ }
3466
+ const linkKeys = (scope) => scope && typeof scope === "object" &&
3467
+ scope.links &&
3468
+ typeof scope.links === "object"
3469
+ ? Object.keys(scope.links)
3470
+ : [];
3471
+ const members = lock.workspace?.members &&
3472
+ typeof lock.workspace.members === "object"
3473
+ ? Object.values(lock.workspace.members)
3474
+ : [];
3475
+ return [lock.workspace, ...members].flatMap(linkKeys).some((key) => key === exports.LOOM_DEPENDENCY || key.startsWith(`npm:${exports.LOOM_DEPENDENCY}@`) ||
3476
+ key.startsWith(`${exports.LOOM_DEPENDENCY}@`));
3477
+ }
3478
+ /**
3479
+ * Every Deno `links` entry that is, or may be, Loom's: its package is named
3480
+ * Loom, or its package is gone. A dangling entry may be Loom's whatever
3481
+ * identifies it (the path dev state recorded, a Loom link in deno.lock, or
3482
+ * nothing at all): node_modules can still hold what Deno copied from it,
3483
+ * and a broken link cannot ship anyway.
3484
+ */
3485
+ async function findLoomDenoLinks(cwd, denoConfig) {
3486
+ const links = [];
3487
+ for (const link of await (0, projectTooling_js_1.readDenoLinks)(cwd, denoConfig)) {
3488
+ const path = (0, node_path_1.resolve)(cwd, link);
3489
+ const dangling = !await exists((0, node_path_1.join)(path, "package.json"));
3490
+ if (dangling || await findLocalLoomDenoLink(cwd, [link])) {
3491
+ links.push({ dangling, link, path });
3492
+ }
3493
+ }
3494
+ return links;
3495
+ }
3496
+ /**
3497
+ * Local Loom overrides and links in the project's config: Loom overrides
3498
+ * with a local (`file:`/`link:`/`workspace:`) spec under any selector, in
3499
+ * package.json maps or pnpm-workspace.yaml (managed or hand-written), a local
3500
+ * Loom catalog entry, and Deno links to Loom, dangling ones included. Each
3501
+ * is described for messages.
3502
+ */
3503
+ async function findLocalLoomLinks(cwd) {
3504
+ const manifest = await readManifestIfExists(cwd);
3505
+ const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
3506
+ const packageJson = await readPackageJsonIfExists(cwd) ?? {};
3507
+ const workspaceText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
3508
+ const links = [];
3509
+ // Reported by the catalog check itself; still local Loom in use.
3510
+ const catalogLinks = [];
3511
+ for (const { field, location } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
3512
+ for (const [key, spec] of Object.entries(getPackageJsonOverrideMap(packageJson, field))) {
3513
+ if (overrideKeyTargetsLoom(key) && typeof spec === "string" &&
3514
+ isLocalPackageSpec(spec)) {
3515
+ links.push(`${formatPnpmOverrideLocation(location)}: ${spec}`);
3516
+ }
3517
+ }
3518
+ }
3519
+ const managedSpec = getManagedDevOverrideSpec(workspaceText);
3520
+ if (managedSpec)
3521
+ links.push(`pnpm-workspace.yaml: ${managedSpec}`);
3522
+ for (const { key, spec } of getUnmanagedPnpmWorkspaceLoomOverrides(workspaceText)) {
3523
+ links.push(`pnpm-workspace.yaml overrides ${key}: ${spec}`);
3524
+ }
3525
+ const dependency = await resolveLoomDependencySpec(cwd, packageJson);
3526
+ if (dependency.catalogName && dependency.effective &&
3527
+ isLocalPackageSpec(dependency.effective)) {
3528
+ catalogLinks.push(`pnpm-workspace.yaml catalog ${dependency.catalogName}: ${dependency.effective}`);
3529
+ }
3530
+ if (usesDenoTooling(tooling)) {
3531
+ const denoConfig = await getDenoConfigForLinks(cwd, tooling);
3532
+ for (const { dangling, link } of await findLoomDenoLinks(cwd, denoConfig)) {
3533
+ links.push(`${denoConfig} links: ${link}${dangling ? " (its package is gone; it may be Loom's)" : ""}`);
3534
+ }
3535
+ }
3536
+ return {
3537
+ catalogLinks,
3538
+ denoMode: usesDenoTooling(tooling),
3539
+ links,
3540
+ packageJson,
3541
+ };
3542
+ }
3543
+ /**
3544
+ * The published Loom version a Deno project's node_modules copy came from,
3545
+ * when deno.lock proves it: the lock records no Loom link, resolves the
3546
+ * project's `npm:@gadicc/loom@<pin>` specifier to a version installed from
3547
+ * the registry (its npm entry carries an integrity hash, which a linked
3548
+ * package's entry lacks), and node_modules holds that version. Null
3549
+ * otherwise, including without a deno.lock.
3550
+ */
3551
+ async function findInstalledDenoRegistryLoomVersion(cwd, packageJson) {
3552
+ const text = await readTextIfExists((0, node_path_1.join)(cwd, "deno.lock"));
3553
+ if (!text || await denoLockLinksLoom(cwd))
3554
+ return null;
3555
+ let lock;
3556
+ try {
3557
+ lock = JSON.parse(text);
3558
+ }
3559
+ catch {
3560
+ return null;
3561
+ }
3562
+ const manifest = await readManifestIfExists(cwd);
3563
+ const tooling = await (0, projectTooling_js_1.detectProjectTooling)(cwd, manifest?.project?.tooling);
3564
+ const denoConfig = await getDenoConfigForLinks(cwd, tooling);
3565
+ const imports = (0, projectTooling_js_1.parseJsonc)(await readTextIfExists((0, node_path_1.join)(cwd, denoConfig)) ?? "{}", denoConfig).imports ?? {};
3566
+ const pinned = [
3567
+ imports[exports.LOOM_DEPENDENCY],
3568
+ packageJson.dependencies?.[exports.LOOM_DEPENDENCY] &&
3569
+ `npm:${exports.LOOM_DEPENDENCY}@${packageJson.dependencies[exports.LOOM_DEPENDENCY]}`,
3570
+ ].find((spec) => typeof spec === "string" && spec.startsWith(`npm:${exports.LOOM_DEPENDENCY}@`) &&
3571
+ lock.specifiers?.[spec] !== undefined);
3572
+ const resolved = pinned ? lock.specifiers[pinned] : undefined;
3573
+ if (!resolved)
3574
+ return null;
3575
+ const entry = lock.npm?.[`${exports.LOOM_DEPENDENCY}@${resolved}`];
3576
+ if (typeof entry?.integrity !== "string")
3577
+ return null;
3578
+ const version = resolved.replace(/_.*$/, "");
3579
+ return await readPackageVersion((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY)) ===
3580
+ version
3581
+ ? version
3582
+ : null;
3583
+ }
3584
+ /**
3585
+ * Why this project may still run local Loom code; empty only when it
3586
+ * provably does not. One predicate decides this for `loom dev published`
3587
+ * (whether to drop the sync record) and `loom check` (whether that record
3588
+ * is stale):
3589
+ * - any local Loom override, catalog entry or Deno link
3590
+ * ({@link findLocalLoomLinks});
3591
+ * - pnpm-lock.yaml resolving Loom locally, or deno.lock recording a Loom link;
3592
+ * - an installed node_modules/@gadicc/loom that is not provably the
3593
+ * published package: for pnpm, unless it is pnpm's registry store entry
3594
+ * ({@link findInstalledRegistryLoomVersion}); for Deno, any copy, since a
3595
+ * copied link looks like a registry install. A missing one is not
3596
+ * installed.
3597
+ * Errors while finding out count as in use. Loom reads overrides,
3598
+ * lockfiles and node_modules from this directory only, so a member of an
3599
+ * enclosing pnpm workspace, whose root holds them, always counts as in use.
3600
+ */
3601
+ async function findLocalLoomUse(cwd) {
3602
+ try {
3603
+ const { catalogLinks, denoMode, links, packageJson } = await findLocalLoomLinks(cwd);
3604
+ const uses = [...links, ...catalogLinks].map((reason) => ({
3605
+ kind: "link",
3606
+ reason,
3607
+ }));
3608
+ if (!denoMode && !await exists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"))) {
3609
+ for (let parent = (0, node_path_1.dirname)((0, node_path_1.resolve)(cwd)); parent !== (0, node_path_1.dirname)(parent); parent = (0, node_path_1.dirname)(parent)) {
3610
+ if (await exists((0, node_path_1.join)(parent, "pnpm-workspace.yaml"))) {
3611
+ uses.push({
3612
+ kind: "workspace",
3613
+ reason: `this project is in the pnpm workspace at ${parent}, whose overrides and lockfile Loom does not read`,
3614
+ });
3615
+ break;
3616
+ }
3617
+ }
3618
+ }
3619
+ const lockfileText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-lock.yaml"));
3620
+ const lockfileResolution = lockfileText
3621
+ ? getLocalLoomLockfileResolution(lockfileText)
3622
+ : null;
3623
+ if (lockfileResolution) {
3624
+ uses.push({
3625
+ kind: "lockfile",
3626
+ reason: `pnpm-lock.yaml resolves Loom to ${lockfileResolution}`,
3627
+ });
3628
+ }
3629
+ if (await denoLockLinksLoom(cwd)) {
3630
+ uses.push({
3631
+ kind: "lockfile",
3632
+ reason: "deno.lock records a link for Loom",
3633
+ });
3634
+ }
3635
+ if (await exists((0, node_path_1.join)(cwd, "node_modules", exports.LOOM_DEPENDENCY, "package.json"))) {
3636
+ const proven = denoMode
3637
+ ? await findInstalledDenoRegistryLoomVersion(cwd, packageJson)
3638
+ : await findInstalledRegistryLoomVersion(cwd, lockfileText, (await readLocalDevState(cwd))?.localPackagePath);
3639
+ if (!proven) {
3640
+ uses.push({
3641
+ kind: "installed",
3642
+ reason: "node_modules/@gadicc/loom is not provably the published package",
3643
+ });
3644
+ }
3645
+ }
3646
+ return uses;
3647
+ }
3648
+ catch (error) {
3649
+ return [{
3650
+ kind: "error",
3651
+ reason: `Loom could not tell whether local Loom is in use: ${error.message}`,
3652
+ }];
3653
+ }
3654
+ }
3284
3655
  /** The project's active local Loom link, read from its current files. */
3285
3656
  async function detectLocalDevLink(cwd) {
3286
3657
  const manifest = await readManifestIfExists(cwd);
@@ -3680,7 +4051,7 @@ async function findInstalledRegistryLoomVersion(cwd, lockfileText, localBuild) {
3680
4051
  entry.startsWith(`${registryEntry}(`))) {
3681
4052
  return null;
3682
4053
  }
3683
- if (await exists((0, node_path_1.join)(localBuild, "package.json")) &&
4054
+ if (localBuild && await exists((0, node_path_1.join)(localBuild, "package.json")) &&
3684
4055
  await findInstalledLocalLoomDifference(cwd, localBuild) === null) {
3685
4056
  return null;
3686
4057
  }
@@ -3703,16 +4074,9 @@ async function collectLocalLoomTargets(cwd, project) {
3703
4074
  };
3704
4075
  const denoLinks = [];
3705
4076
  if (project.denoConfig) {
3706
- const recorded = await readLocalDevState(cwd);
3707
- const recordedPath = recorded?.localPackagePath
3708
- ? (0, node_path_1.resolve)(cwd, recorded.localPackagePath)
3709
- : null;
3710
- for (const link of await (0, projectTooling_js_1.readDenoLinks)(cwd, project.denoConfig)) {
3711
- const path = (0, node_path_1.resolve)(cwd, link);
3712
- if (await findLocalLoomDenoLink(cwd, [link]) || path === recordedPath) {
3713
- denoLinks.push(link);
3714
- await add(path, `${project.denoConfig} links ${link}`);
3715
- }
4077
+ for (const { link, path } of await findLoomDenoLinks(cwd, project.denoConfig)) {
4078
+ denoLinks.push(link);
4079
+ await add(path, `${project.denoConfig} links ${link}`);
3716
4080
  }
3717
4081
  return { denoLinks, targets: [...targets.values()] };
3718
4082
  }
@@ -3721,6 +4085,9 @@ async function collectLocalLoomTargets(cwd, project) {
3721
4085
  await add(localSpecToPath(cwd, workspaceSpec), "the pnpm-workspace.yaml override");
3722
4086
  }
3723
4087
  for (const { key, spec } of getUnmanagedPnpmWorkspaceLoomOverrides(project.workspaceText)) {
4088
+ if (spec.startsWith("workspace:")) {
4089
+ throw new Error(`pnpm-workspace.yaml overrides ${key} with ${spec}, a workspace package Loom cannot trace to a build, so it cannot prove that the installed Loom is published. Remove that override and install a published ${exports.LOOM_DEPENDENCY} instead.`);
4090
+ }
3724
4091
  await add(localSpecToPath(cwd, spec), `the pnpm-workspace.yaml overrides entry for ${key}`);
3725
4092
  }
3726
4093
  for (const { location, spec } of getPackageJsonLocalLoomOverrides(project.packageJson)) {
@@ -3750,7 +4117,9 @@ async function proveLocalLoomBuildPublished(cwd, target, options) {
3750
4117
  const lockfileOnly = target.sources.every((source) => source === "pnpm-lock.yaml");
3751
4118
  throw new Error(`${path}, which ${target.sources.join(" and ")} point${target.sources.length === 1 ? "s" : ""} at, holds no built Loom package. ${lockfileOnly
3752
4119
  ? "If the app does not need that build, restore pnpm-lock.yaml from git and run `pnpm install`; otherwise restore that Loom checkout, link it with `loom dev local` and run `loom dev sync`"
3753
- : "Restore that Loom checkout and run `loom dev sync`, or link another with `loom dev local`"}, ${rerun}.`);
4120
+ : options.denoConfig
4121
+ ? `Restore that Loom checkout and run \`loom dev sync\`, or link another with \`loom dev local\`; if the app does not need that build, remove the link from ${options.denoConfig} yourself and run \`deno install\``
4122
+ : "Restore that Loom checkout and run `loom dev sync`, or link another with `loom dev local`"}, ${rerun}.`);
3754
4123
  }
3755
4124
  const stamp = await (0, localDevPackage_js_1.readLoomBuildStamp)(path);
3756
4125
  if (stamp?.legacyBuildFingerprint && !(0, localDevPackage_js_1.hasLoomBuildProvenance)(stamp)) {
@@ -3873,8 +4242,17 @@ async function usePublishedDevPackageLocked(cwd, options) {
3873
4242
  lockfileText,
3874
4243
  preferredSpec: publishedSpec,
3875
4244
  });
3876
- publishedSpec = proof.publication.version;
3877
4245
  notes.push(proof.note);
4246
+ // Never move an exact pin back: a checkout without the newest tags names
4247
+ // the oldest release it knows that covers the build, and a newer pin
4248
+ // (Loom releases only from main) covers it too.
4249
+ if (isExactSemverVersion(publishedSpec) &&
4250
+ isNewerLoomVersion(publishedSpec, proof.publication.version)) {
4251
+ notes.push(`The pinned ${exports.LOOM_DEPENDENCY}@${publishedSpec} is newer than ${proof.publication.version}, so the pin stays at ${publishedSpec}.`);
4252
+ }
4253
+ else {
4254
+ publishedSpec = proof.publication.version;
4255
+ }
3878
4256
  }
3879
4257
  const changedFiles = [];
3880
4258
  let catalogChanged = false;
@@ -3978,6 +4356,14 @@ async function usePublishedDevPackageLocked(cwd, options) {
3978
4356
  }
3979
4357
  }
3980
4358
  }
4359
+ // Once nothing local can be in use, the sync record describes code the app
4360
+ // no longer runs; kept, `loom check` would go on checking a commit in a
4361
+ // checkout that may since be gone. Until then (typically until the
4362
+ // `pnpm install` this command asks for), it stays. Created-map flags were
4363
+ // cleared above.
4364
+ if ((await findLocalLoomUse(cwd)).length === 0) {
4365
+ await (0, promises_1.rm)((0, node_path_1.join)(cwd, exports.LOOM_LOCAL_DEV_STATE_RELATIVE_PATH), { force: true });
4366
+ }
3981
4367
  return {
3982
4368
  changedFiles,
3983
4369
  notes,
@@ -4286,17 +4672,15 @@ async function checkManagedLocalDevOverride(cwd, production, commandRunner, env)
4286
4672
  // The main project tooling check reports invalid configuration separately.
4287
4673
  }
4288
4674
  const workspaceText = await readTextIfExists((0, node_path_1.join)(cwd, "pnpm-workspace.yaml"));
4289
- const packageJson = denoLink ? null : await readPackageJsonIfExists(cwd);
4290
- const workspaceSpec = getManagedDevOverrideSpec(workspaceText);
4291
- // Any local spec for Loom in a package.json override map is a local-dev
4292
- // link, whoever wrote it and whatever selector it uses, and must not ship.
4293
- const packageJsonOverride = packageJson
4294
- ? PACKAGE_JSON_OVERRIDE_LOCATIONS.flatMap(({ field, location }) => Object.entries(getPackageJsonOverrideMap(packageJson, field)).flatMap(([key, spec]) => overrideKeyTargetsLoom(key) && typeof spec === "string" &&
4295
- isLocalPackageSpec(spec)
4296
- ? [`${formatPnpmOverrideLocation(location)}: ${spec}`]
4297
- : []))[0]
4298
- : undefined;
4299
- if (!workspaceSpec && !packageJsonOverride && !denoLink) {
4675
+ const denoMode = denoConfig !== null;
4676
+ const packageJson = denoMode ? null : await readPackageJsonIfExists(cwd);
4677
+ // Any local spec for Loom in an override map, whoever wrote it and
4678
+ // whatever selector it uses, is a local-dev link and must not ship; so is
4679
+ // a Deno link to Loom, even one whose package is gone. The same finder
4680
+ // decides whether a sync record is stale. A local catalog entry has its
4681
+ // own, clearer issue.
4682
+ const links = await findLocalLoomLinks(cwd).then((found) => found.links, () => []);
4683
+ if (!links.length && !denoLink) {
4300
4684
  return {
4301
4685
  issues: [],
4302
4686
  suggestions: [],
@@ -4305,10 +4689,8 @@ async function checkManagedLocalDevOverride(cwd, production, commandRunner, env)
4305
4689
  }
4306
4690
  const location = denoLink
4307
4691
  ? `${denoConfig} links: ${denoLink.link}`
4308
- : workspaceSpec
4309
- ? `pnpm-workspace.yaml: ${workspaceSpec}`
4310
- : packageJsonOverride;
4311
- const restore = denoLink
4692
+ : links[0];
4693
+ const restore = denoMode
4312
4694
  ? "Run `loom dev published`, then run `deno install` before committing or shipping a published build."
4313
4695
  : "Run `loom dev published`, then run `pnpm install` (or the command it prints) before committing or shipping a published build.";
4314
4696
  const warnings = [];
@@ -4431,10 +4813,46 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
4431
4813
  addReleaseCheckMessage(issues, warnings, production, `pnpm-lock.yaml resolves @gadicc/loom to a local package: ${localLockfileResolution}`);
4432
4814
  suggestions.add("Run `loom dev published`, then refresh the lockfile with the published @gadicc/loom version before production build.");
4433
4815
  }
4434
- if (devState?.sourceCommit) {
4816
+ // The sync record only matters while the app can still run local Loom
4817
+ // code. Without a link, an override or a local lockfile resolution, the
4818
+ // app runs a published Loom, and the record (perhaps naming a checkout
4819
+ // that is gone) is stale.
4820
+ const localLoomUses = await findLocalLoomUse(cwd);
4821
+ const localLoomInUse = localLoomUses.length > 0;
4822
+ // Only an installed copy Loom cannot prove published, with no link or
4823
+ // lockfile pointing at local Loom, is too weak to fail a release by
4824
+ // itself: the record's findings stay warnings then.
4825
+ const recordGatesRelease = production &&
4826
+ localLoomUses.some((use) => use.kind !== "installed");
4827
+ if (devState?.sourceCommit && !localLoomInUse) {
4828
+ const shortCommit = devState.sourceCommit.slice(0, 12);
4829
+ warnings.push(`${exports.LOOM_LOCAL_DEV_STATE_RELATIVE_PATH} still records a local Loom sync at commit ${shortCommit}, but no local Loom is linked, locked or installed any more, so it is stale and can be deleted.`);
4830
+ // The app may still rely on what that sync contained: advise, never
4831
+ // fail, when a newer release covers it than the app pins. A checkout
4832
+ // that is gone is not looked up at all.
4833
+ if (devState.sourceRoot && !devState.sourceDirty &&
4834
+ dependency && isExactSemverVersion(dependency) &&
4835
+ await exists(devState.sourceRoot)) {
4836
+ const publication = await resolveLoomCommitPublication(devState.sourceRoot, devState.sourceCommit, options.commandRunner, options.env, dependency);
4837
+ if (publication.status === "published" &&
4838
+ isNewerLoomVersion(publication.version, dependency)) {
4839
+ warnings.push(`This app was last synced against Loom commit ${shortCommit}; ${publication.reason === "package-equivalent"
4840
+ ? `package-relevant files match ${exports.LOOM_DEPENDENCY}@${publication.version}`
4841
+ : `it is published as ${exports.LOOM_DEPENDENCY}@${publication.version}`}, but ${pinLocation} is pinned to ${dependency}.`);
4842
+ suggestions.add(pinSuggestion(publication.version));
4843
+ }
4844
+ }
4845
+ }
4846
+ else if (devState?.sourceCommit && devState.sourceRoot &&
4847
+ !devState.sourceDirty && !await exists(devState.sourceRoot)) {
4848
+ // A deleted checkout is not evidence of unpublished code; the active
4849
+ // link or lockfile already fails the release check on its own.
4850
+ warnings.push(`This app was last synced against Loom commit ${devState.sourceCommit.slice(0, 12)} in ${devState.sourceRoot}, which no longer exists, so Loom cannot check that commit.`);
4851
+ }
4852
+ else if (devState?.sourceCommit) {
4435
4853
  const shortCommit = devState.sourceCommit.slice(0, 12);
4436
4854
  if (devState.sourceDirty) {
4437
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit} with a dirty source tree.`);
4855
+ addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit} with a dirty source tree.`);
4438
4856
  suggestions.add("Commit or discard the Loom changes, rerun `loom dev sync`, and publish Loom if the app depends on those changes.");
4439
4857
  }
4440
4858
  else if (!devState.sourceRoot) {
@@ -4444,21 +4862,29 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
4444
4862
  const publication = await resolveLoomCommitPublication(devState.sourceRoot, devState.sourceCommit, options.commandRunner, options.env, isExactSemverVersion(dependency ?? "") ? dependency : undefined);
4445
4863
  switch (publication.status) {
4446
4864
  case "not-on-origin-main":
4447
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}, which is not reachable from origin/main.`);
4865
+ addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit}, which is not reachable from origin/main.`);
4448
4866
  suggestions.add("Push or merge the Loom changes, fetch origin/main, publish Loom if needed, then rerun `loom dev published`.");
4449
4867
  break;
4450
4868
  case "no-release-tag":
4451
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}, but no published Loom version contains that commit or matches its package-relevant files.`);
4869
+ addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit}, but no published Loom version contains that commit or matches its package-relevant files.`);
4452
4870
  suggestions.add("Publish Loom first, fetch tags, then rerun `loom dev published`.");
4453
4871
  break;
4454
- case "published":
4455
- if (dependency && isExactSemverVersion(dependency) &&
4456
- dependency !== publication.version) {
4872
+ case "published": {
4873
+ // Advice only ever moves the pin forward. A checkout without the
4874
+ // newest tags reports the oldest release it knows that contains
4875
+ // the commit; an exact pin newer than that covers it too.
4876
+ const pinCovers = !!dependency &&
4877
+ isExactSemverVersion(dependency) &&
4878
+ !isNewerLoomVersion(publication.version, dependency);
4879
+ const coveringVersion = pinCovers && dependency
4880
+ ? dependency
4881
+ : publication.version;
4882
+ if (dependency && isExactSemverVersion(dependency) && !pinCovers) {
4457
4883
  const publicationDescription = publication.reason ===
4458
4884
  "package-equivalent"
4459
4885
  ? `package-relevant files match ${exports.LOOM_DEPENDENCY}@${publication.version}`
4460
4886
  : `it is published as ${exports.LOOM_DEPENDENCY}@${publication.version}`;
4461
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${pinLocation} is pinned to ${dependency}.`);
4887
+ addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${pinLocation} is pinned to ${dependency}.`);
4462
4888
  suggestions.add(pnpmOverrideActive
4463
4889
  ? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
4464
4890
  : pinSuggestion(publication.version));
@@ -4468,16 +4894,20 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
4468
4894
  "package-equivalent"
4469
4895
  ? `has no package-relevant changes after ${publication.tag}, so ${exports.LOOM_DEPENDENCY}@${publication.version} covers it`
4470
4896
  : `is published as ${exports.LOOM_DEPENDENCY}@${publication.version}`;
4471
- warnings.push(`The synced Loom commit ${shortCommit} ${publicationDescription}; refresh the lockfile away from ${localLockfileResolution}.`);
4897
+ const newerPin = coveringVersion !== publication.version
4898
+ ? ` (the pinned ${coveringVersion} is newer)`
4899
+ : "";
4900
+ warnings.push(`The synced Loom commit ${shortCommit} ${publicationDescription}${newerPin}; refresh the lockfile away from ${localLockfileResolution}.`);
4472
4901
  suggestions.add(pnpmOverrideActive
4473
4902
  ? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
4474
- : catalogName && dependency === publication.version
4903
+ : catalogName && dependency === coveringVersion
4475
4904
  // pnpm keeps a local resolution while the catalog version
4476
4905
  // it was linked under is unchanged.
4477
4906
  ? "Restore pnpm-lock.yaml from git and run `pnpm install`."
4478
- : pinSuggestion(publication.version));
4907
+ : pinSuggestion(coveringVersion));
4479
4908
  }
4480
4909
  break;
4910
+ }
4481
4911
  }
4482
4912
  }
4483
4913
  }
@@ -5556,9 +5986,16 @@ function getJobsExpectedScripts(config) {
5556
5986
  job: `TSX_TSCONFIG=./${JOBS_SCRIPTS_TSCONFIG_PATH} loom env -- node --conditions=react-server --import tsx ${config.directRunner.scriptPath}`,
5557
5987
  };
5558
5988
  }
5559
- function jobsDirectRunnerTemplate(config, framework) {
5989
+ function getJobsManagedTasks(config) {
5990
+ const legacy = (0, legacyManagedOutputs_js_1.legacyJobsTaskValues)(JOBS_SCRIPTS_TSCONFIG_PATH, config.directRunner.scriptPath);
5991
+ return Object.entries(getJobsExpectedScripts(config)).map(([name, definition]) => ({ definition, knownValues: legacy[name] ?? [], name }));
5992
+ }
5993
+ function getJobsDirectRunnerCatalogImportPath(config, framework) {
5560
5994
  const jobsRoot = framework.srcDir ? "src/jobs" : "jobs";
5561
- const catalogImportPath = toRelativeImportPath(config.directRunner.scriptPath, `${jobsRoot}/index.ts`);
5995
+ return toRelativeImportPath(config.directRunner.scriptPath, `${jobsRoot}/index.ts`);
5996
+ }
5997
+ function jobsDirectRunnerTemplate(config, framework) {
5998
+ const catalogImportPath = getJobsDirectRunnerCatalogImportPath(config, framework);
5562
5999
  return `import {
5563
6000
  createJobCatalogFromSource,
5564
6001
  createJobExecution,
@@ -5688,24 +6125,64 @@ function jobsThinRouteTemplate(source) {
5688
6125
  export const maxDuration = ${DEFAULT_JOBS_MAX_DURATION_SECONDS};
5689
6126
  `;
5690
6127
  }
5691
- function jobsStaticRouteTemplate(config, moduleSpecifier, maxDuration) {
5692
- if (!config.staticRoutes) {
5693
- throw new Error("Static jobs route config is required");
5694
- }
6128
+ function renderJobsStaticRoute(values) {
5695
6129
  return `${LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER}
5696
6130
  // Generated by \`loom add jobs\` from loom.json. Do not edit directly.
5697
6131
 
5698
- import { ${config.staticRoutes.handlerFactoryExport} } from "${toAliasImportPath(config.modules.routeModule)}";
5699
- import * as job from "${moduleSpecifier}";
6132
+ import { ${values.handlerFactoryExport} } from "${values.routeModuleSpecifier}";
6133
+ import * as job from "${values.moduleSpecifier}";
5700
6134
 
5701
6135
  // Next.js route segment config must be a direct, statically analyzable export.
5702
- export const maxDuration = ${maxDuration};
6136
+ export const maxDuration = ${values.maxDuration};
5703
6137
 
5704
- const handler = ${config.staticRoutes.handlerFactoryExport}(job);
6138
+ const handler = ${values.handlerFactoryExport}(job);
5705
6139
 
5706
6140
  export { handler as GET, handler as POST };
5707
6141
  `;
5708
6142
  }
6143
+ function jobsStaticRouteTemplate(config, moduleSpecifier, maxDuration) {
6144
+ if (!config.staticRoutes) {
6145
+ throw new Error("Static jobs route config is required");
6146
+ }
6147
+ return renderJobsStaticRoute({
6148
+ handlerFactoryExport: config.staticRoutes.handlerFactoryExport,
6149
+ maxDuration,
6150
+ moduleSpecifier,
6151
+ routeModuleSpecifier: toAliasImportPath(config.modules.routeModule),
6152
+ });
6153
+ }
6154
+ /**
6155
+ * Whether a marked static job route is exactly Loom's template for the
6156
+ * configured handler factory and route module, with any job module and
6157
+ * `maxDuration`. Those two values come from loom.json, so such a route is
6158
+ * stale Loom output that Loom may update or remove. A different factory or
6159
+ * route module (an audited wrapper, say), or any other edit, makes the file
6160
+ * the app's. This only covers routes from before Loom recorded their hashes.
6161
+ */
6162
+ function isLoomJobsStaticRoute(text, config) {
6163
+ if (!config.staticRoutes)
6164
+ return false;
6165
+ if (!text.startsWith(LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER))
6166
+ return false;
6167
+ const job = text.match(/import\s*\*\s*as\s+job\s+from\s*["']([^"']+)["']/);
6168
+ const maxDuration = text.match(/export\s+const\s+maxDuration\s*=\s*(\d+)/);
6169
+ if (!job || !maxDuration)
6170
+ return false;
6171
+ return (0, managedFiles_js_1.hashManagedFileText)(text) ===
6172
+ (0, managedFiles_js_1.hashManagedFileText)(renderJobsStaticRoute({
6173
+ handlerFactoryExport: config.staticRoutes.handlerFactoryExport,
6174
+ maxDuration: Number(maxDuration[1]),
6175
+ moduleSpecifier: job[1],
6176
+ routeModuleSpecifier: toAliasImportPath(config.modules.routeModule),
6177
+ }));
6178
+ }
6179
+ function jobsStaticRouteProof(config, feature, relativePath) {
6180
+ return {
6181
+ isLoomOutput: (text) => isLoomJobsStaticRoute(text, config),
6182
+ recordedHash: recordedManagedFileHash(feature, relativePath),
6183
+ };
6184
+ }
6185
+ const JOBS_STATIC_ROUTE_EDIT_RESOLUTION = `Move app-specific route code out of the generated file, then delete it and rerun \`loom add jobs\`; or remove its \`${LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER}\` marker line to keep it as an app-owned route.`;
5709
6186
  function assertPositiveJobsMaxDuration(value, label) {
5710
6187
  if (!Number.isInteger(value) || value <= 0) {
5711
6188
  throw new Error(`${label} must be a positive integer`);
@@ -5773,11 +6250,12 @@ async function findManagedJobsStaticRoutePaths(cwd, config) {
5773
6250
  }
5774
6251
  return managedPaths;
5775
6252
  }
5776
- async function syncJobsStaticRoutes(cwd, config) {
6253
+ async function syncJobsStaticRoutes(cwd, config, feature) {
5777
6254
  const changedFiles = [];
5778
6255
  const notes = [];
6256
+ const records = {};
5779
6257
  if (!config.staticRoutes)
5780
- return { changedFiles, notes };
6258
+ return { changedFiles, notes, records };
5781
6259
  const plans = getJobsStaticRoutePlans(cwd, config);
5782
6260
  const expectedPaths = new Set(plans.map((plan) => plan.path));
5783
6261
  for (const plan of plans) {
@@ -5787,21 +6265,33 @@ async function syncJobsStaticRoutes(cwd, config) {
5787
6265
  notes.push(`Preserved unmanaged jobs static route file: ${plan.relativePath}`);
5788
6266
  continue;
5789
6267
  }
5790
- if (await writeTextIfChanged(plan.path, plan.text)) {
6268
+ const result = await (0, managedFiles_js_1.syncManagedFile)(plan.path, plan.text, jobsStaticRouteProof(config, feature, plan.relativePath));
6269
+ recordManagedFileSync(records, feature, plan.relativePath, result);
6270
+ if (result.state === "created" || result.state === "updated") {
5791
6271
  changedFiles.push(plan.relativePath);
5792
6272
  }
6273
+ else if (result.state === "customized") {
6274
+ notes.push(formatPreservedManagedFileNote(plan.relativePath, result.difference, JOBS_STATIC_ROUTE_EDIT_RESOLUTION));
6275
+ }
5793
6276
  }
5794
6277
  for (const routePath of await findManagedJobsStaticRoutePaths(cwd, config)) {
5795
6278
  if (expectedPaths.has(routePath))
5796
6279
  continue;
5797
- await (0, promises_1.rm)(routePath);
6280
+ const relativePath = (0, node_path_1.relative)(cwd, routePath).replaceAll("\\", "/");
6281
+ const removal = await (0, managedFiles_js_1.removeManagedFile)(routePath, jobsStaticRouteProof(config, feature, relativePath));
6282
+ if (removal === "customized") {
6283
+ notes.push(`Preserved local edits in ${relativePath}, a generated jobs static route that loom.json no longer declares. Delete it yourself if the job is gone, or remove its \`${LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER}\` marker line to keep it as an app-owned route.`);
6284
+ continue;
6285
+ }
6286
+ if (removal !== "removed")
6287
+ continue;
5798
6288
  const routeDirectory = (0, node_path_1.dirname)(routePath);
5799
6289
  if ((await (0, promises_1.readdir)(routeDirectory)).length === 0) {
5800
6290
  await (0, promises_1.rm)(routeDirectory, { recursive: true });
5801
6291
  }
5802
- changedFiles.push((0, node_path_1.relative)(cwd, routePath).replaceAll("\\", "/"));
6292
+ changedFiles.push(relativePath);
5803
6293
  }
5804
- return { changedFiles, notes };
6294
+ return { changedFiles, notes, records };
5805
6295
  }
5806
6296
  function pwaSerwistConfigTemplate(config) {
5807
6297
  return `import { serwist } from "@serwist/next/config";
@@ -5856,6 +6346,7 @@ function pwaLifecyclePropLines(config) {
5856
6346
  : ` updateCheckIntervalMs={${formatTsNumberLiteral(config.updateCheckIntervalMs)}}`,
5857
6347
  ].filter((line) => line !== null);
5858
6348
  }
6349
+ const PWA_CUSTOMIZED_PROVIDER_RESOLUTION = "To keep it app-owned, set `features.pwa.config.provider.managed` to `false` in loom.json (`loom check` still validates its PWA wiring); to restore Loom's provider, delete it and rerun `loom init`.";
5859
6350
  function pwaClientProviderTemplate(config) {
5860
6351
  const lifecyclePropLines = pwaLifecyclePropLines(config);
5861
6352
  const headlessLifecycle = lifecyclePropLines.length
@@ -5980,6 +6471,57 @@ afterAll(closeMemoryPglite);
5980
6471
  export const { client, db, tableLoader } = harness;
5981
6472
  `;
5982
6473
  }
6474
+ function getDbManagedFiles(config, testRunner, tooling) {
6475
+ const schemaImportPath = toRelativeImportPath(config.modules.pgliteHarnessModule, (0, node_path_1.join)(config.dirs.schemaDir, "index.ts"));
6476
+ return [
6477
+ {
6478
+ knownOutputs: [],
6479
+ mismatch: "DB neon module does not match the Loom-managed wrapper",
6480
+ relativePath: config.modules.neonModule,
6481
+ text: dbNeonTemplate(),
6482
+ },
6483
+ {
6484
+ knownOutputs: [],
6485
+ mismatch: "DB neonFull module does not match the Loom-managed wrapper",
6486
+ relativePath: config.modules.neonFullModule,
6487
+ text: dbNeonFullTemplate(),
6488
+ },
6489
+ {
6490
+ knownOutputs: [],
6491
+ mismatch: "Drizzle config does not match the Loom-managed wrapper",
6492
+ relativePath: config.modules.drizzleConfig,
6493
+ text: dbDrizzleConfigTemplate(config),
6494
+ },
6495
+ {
6496
+ knownOutputs: [
6497
+ // With Deno tasks the harness follows whether the `test` task runs
6498
+ // vitest, which can change, so either runner's harness may be what
6499
+ // Loom wrote. Other runners only ever got the vitest harness.
6500
+ ...(tooling.tasks.runner === "deno"
6501
+ ? [
6502
+ dbPgliteHarnessTemplate(config, testRunner === "deno" ? "vitest" : "deno"),
6503
+ ]
6504
+ : []),
6505
+ ...(0, legacyManagedOutputs_js_1.legacyDbPgliteHarnessOutputs)(schemaImportPath, config.dirs.fixtureDir),
6506
+ ],
6507
+ mismatch: "PGlite test harness does not match the Loom-managed wrapper",
6508
+ relativePath: config.modules.pgliteHarnessModule,
6509
+ text: dbPgliteHarnessTemplate(config, testRunner),
6510
+ },
6511
+ {
6512
+ knownOutputs: [],
6513
+ mismatch: "DB scripts tsconfig does not match the Loom-managed template",
6514
+ relativePath: config.modules.scriptsTsconfig,
6515
+ text: dbScriptsTsconfigTemplate(),
6516
+ },
6517
+ {
6518
+ knownOutputs: [],
6519
+ mismatch: "Valibot refinements common module does not match the Loom-managed wrapper",
6520
+ relativePath: config.modules.refinementsCommonModule,
6521
+ text: dbRefinementsCommonTemplate(),
6522
+ },
6523
+ ];
6524
+ }
5983
6525
  async function getDbTestRunner(cwd, tooling) {
5984
6526
  if (tooling.tasks.runner !== "deno")
5985
6527
  return "vitest";
@@ -6297,6 +6839,29 @@ function isGeneratedFilesStorageStub(text) {
6297
6839
  "storageNotConfigured();",
6298
6840
  ].every((part) => text.includes(part));
6299
6841
  }
6842
+ /**
6843
+ * Installs the S3 storage adapter in place of the generated not-configured
6844
+ * stub, but only while the stub is exactly Loom's scaffold: an edited stub is
6845
+ * the app's and stays.
6846
+ */
6847
+ async function replaceFilesStorageStub(storagePath, relativePath) {
6848
+ const stub = filesStorageTemplate();
6849
+ const result = await (0, managedFiles_js_1.syncManagedFile)(storagePath, filesS3StorageTemplate(), {
6850
+ knownOutputs: [stub],
6851
+ });
6852
+ if (result.state !== "customized") {
6853
+ return {
6854
+ changed: result.state === "created" || result.state === "updated",
6855
+ note: null,
6856
+ };
6857
+ }
6858
+ // The edits that matter are the app's changes to Loom's stub.
6859
+ const currentText = await readTextIfExists(storagePath) ?? "";
6860
+ return {
6861
+ changed: false,
6862
+ note: formatPreservedManagedFileNote(relativePath, (0, managedFiles_js_1.describeManagedFileDifference)(currentText, stub), "Wire it to the canonical FILES_S3_* variables yourself, or delete it and rerun this command to install Loom's S3 storage adapter."),
6863
+ };
6864
+ }
6300
6865
  function filesRouteTemplate(config) {
6301
6866
  return `import { createFilesRouteHandlers } from "@gadicc/loom/next/files";
6302
6867
  import {
@@ -6903,14 +7468,88 @@ function buildValibotBarrelText(generatedNames, refinementNames) {
6903
7468
  ? `export * from "./refinements/${name}";`
6904
7469
  : `export * from "./generated/${name}";`).join("\n")}\n`;
6905
7470
  }
6906
- async function syncValibotBarrel(cwd, config) {
7471
+ const VALIBOT_BARREL_LINE = /^export\s*\*\s*from\s*["']\.\/(generated|refinements)\/([^"']+)["']\s*;?$/;
7472
+ async function directoryHasModule(directory, name) {
7473
+ try {
7474
+ return (await (0, promises_1.readdir)(directory)).some((entry) => entry === name || stripModuleExtension(entry) === name);
7475
+ }
7476
+ catch (error) {
7477
+ if (isNodeErrorCode(error, "ENOENT"))
7478
+ return false;
7479
+ throw error;
7480
+ }
7481
+ }
7482
+ /**
7483
+ * Whether a valibot barrel holds only export lines Loom generates, so it can
7484
+ * be rebuilt without losing a hand-written export. Loom exports each `.ts`
7485
+ * module of the generated and refinement directories except `index` and
7486
+ * `_`-prefixed ones, once each, and a refinement replaces the generated
7487
+ * module of the same name. So a `./generated/<name>` line beside a
7488
+ * `./refinements/<name>` line was added by hand, while one without it is
7489
+ * what Loom wrote before that refinement existed. A line for a module that
7490
+ * no longer exists is stale Loom output; a line for another module that does
7491
+ * exist was added by hand.
7492
+ */
7493
+ async function isLoomValibotBarrel(cwd, config, text, generatedNames, refinementNames) {
7494
+ const lines = [];
7495
+ const seen = new Set();
7496
+ for (const line of normalizeText(text).split("\n")) {
7497
+ const trimmed = line.trim();
7498
+ if (!trimmed)
7499
+ continue;
7500
+ const match = trimmed.match(VALIBOT_BARREL_LINE);
7501
+ if (!match)
7502
+ return false;
7503
+ const [, kind, name] = match;
7504
+ if (name === "index" || name.startsWith("_") || name.includes("/")) {
7505
+ return false;
7506
+ }
7507
+ const key = `${kind}/${name}`;
7508
+ if (seen.has(key))
7509
+ return false;
7510
+ seen.add(key);
7511
+ lines.push({ kind, name });
7512
+ }
7513
+ for (const { kind, name } of lines) {
7514
+ if (kind === "refinements" && refinementNames.includes(name))
7515
+ continue;
7516
+ if (kind === "generated" && generatedNames.includes(name)) {
7517
+ if (refinementNames.includes(name) && seen.has(`refinements/${name}`)) {
7518
+ return false;
7519
+ }
7520
+ continue;
7521
+ }
7522
+ const directory = kind === "generated"
7523
+ ? config.dirs.valibotGeneratedDir
7524
+ : config.dirs.valibotRefinementsDir;
7525
+ if (await directoryHasModule((0, node_path_1.join)(cwd, directory), name))
7526
+ return false;
7527
+ }
7528
+ return true;
7529
+ }
7530
+ async function readValibotBarrelState(cwd, config) {
6907
7531
  const generatedNames = await readTsModuleNames((0, node_path_1.join)(cwd, config.dirs.valibotGeneratedDir));
6908
7532
  const refinementNames = await readTsModuleNames((0, node_path_1.join)(cwd, config.dirs.valibotRefinementsDir));
6909
- const text = buildValibotBarrelText(generatedNames, refinementNames);
6910
- if (!text) {
6911
- return false;
7533
+ const proof = {
7534
+ isLoomOutput: (text) => isLoomValibotBarrel(cwd, config, text, generatedNames, refinementNames),
7535
+ };
7536
+ return {
7537
+ proof,
7538
+ text: buildValibotBarrelText(generatedNames, refinementNames),
7539
+ };
7540
+ }
7541
+ async function syncValibotBarrel(cwd, config) {
7542
+ const barrel = await readValibotBarrelState(cwd, config);
7543
+ if (!barrel.text) {
7544
+ return { changed: false, note: null };
6912
7545
  }
6913
- return await writeTextIfChanged((0, node_path_1.join)(cwd, config.modules.valibotBarrelModule), text);
7546
+ const result = await (0, managedFiles_js_1.syncManagedFile)((0, node_path_1.join)(cwd, config.modules.valibotBarrelModule), barrel.text, barrel.proof);
7547
+ return {
7548
+ changed: result.state === "created" || result.state === "updated",
7549
+ note: result.state === "customized"
7550
+ ? formatPreservedManagedFileNote(config.modules.valibotBarrelModule, result.difference, "Keep only `export * from` lines for the generated and refinement modules there, or add the missing exports by hand.")
7551
+ : null,
7552
+ };
6914
7553
  }
6915
7554
  function getLatestManagedSchemaConfig(schema) {
6916
7555
  const latest = {
@@ -7135,8 +7774,7 @@ async function syncDbSchemas(cwd) {
7135
7774
  (!mailFeature || mailFeature.status !== "active")) {
7136
7775
  notes.push("No active Loom-managed DB schemas are configured.");
7137
7776
  }
7138
- const manifestPath = (0, node_path_1.join)(cwd, "loom.json");
7139
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
7777
+ if (await writeManifestIfChanged(cwd, manifest)) {
7140
7778
  changedFiles.push("loom.json");
7141
7779
  }
7142
7780
  if (changedFiles.length) {
@@ -7166,8 +7804,7 @@ async function configureFilesIdGeneration(cwd, idGeneration) {
7166
7804
  const config = getFilesConfig(framework, dbConfig, filesFeature.config);
7167
7805
  config.schema.idGeneration = idGeneration;
7168
7806
  filesFeature.config = config;
7169
- const nextText = stringifyJson(manifest);
7170
- const changedFiles = await writeTextIfChanged(manifestPath, nextText)
7807
+ const changedFiles = await writeManifestIfChanged(cwd, manifest)
7171
7808
  ? ["loom.json"]
7172
7809
  : [];
7173
7810
  return {
@@ -7846,9 +8483,12 @@ async function setupLocalFiles(cwd, options = {}) {
7846
8483
  notes.push(`Run ${tooling.dependencies.manager} install to update the dependency lockfile.`);
7847
8484
  }
7848
8485
  if (!storageText || isGeneratedFilesStorageStub(storageText)) {
7849
- if (await writeTextIfChanged(storagePath, filesS3StorageTemplate())) {
8486
+ const storageUpdate = await replaceFilesStorageStub(storagePath, config.modules.storageModule);
8487
+ if (storageUpdate.changed) {
7850
8488
  changedFiles.push(config.modules.storageModule);
7851
8489
  }
8490
+ if (storageUpdate.note)
8491
+ notes.push(storageUpdate.note);
7852
8492
  }
7853
8493
  config.storage.adapter = "s3";
7854
8494
  if (config.storage.provider) {
@@ -7859,7 +8499,7 @@ async function setupLocalFiles(cwd, options = {}) {
7859
8499
  };
7860
8500
  }
7861
8501
  feature.config = config;
7862
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
8502
+ if (await writeManifestIfChanged(cwd, manifest)) {
7863
8503
  changedFiles.push("loom.json");
7864
8504
  }
7865
8505
  return {
@@ -8111,7 +8751,7 @@ async function setupCloudflareR2(cwd, options = {}) {
8111
8751
  };
8112
8752
  feature.config = config;
8113
8753
  manifest.features.files = feature;
8114
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
8754
+ if (await writeManifestIfChanged(cwd, manifest)) {
8115
8755
  changedFiles.push("loom.json");
8116
8756
  }
8117
8757
  for (const bucket of new Set(Object.values(buckets))) {
@@ -8141,9 +8781,12 @@ async function setupCloudflareR2(cwd, options = {}) {
8141
8781
  const storagePath = (0, node_path_1.join)(cwd, config.modules.storageModule);
8142
8782
  const storageText = await readTextIfExists(storagePath);
8143
8783
  if (!storageText || isGeneratedFilesStorageStub(storageText)) {
8144
- if (await writeTextIfChanged(storagePath, filesS3StorageTemplate())) {
8784
+ const storageUpdate = await replaceFilesStorageStub(storagePath, config.modules.storageModule);
8785
+ if (storageUpdate.changed) {
8145
8786
  changedFiles.push(config.modules.storageModule);
8146
8787
  }
8788
+ if (storageUpdate.note)
8789
+ notes.push(storageUpdate.note);
8147
8790
  }
8148
8791
  else if (!storageText.includes("@gadicc/loom/files/s3")) {
8149
8792
  notes.push(`Preserved customized storage module ${config.modules.storageModule}; wire it to the canonical FILES_S3_* variables manually.`);
@@ -8236,7 +8879,7 @@ async function setupCloudflareR2(cwd, options = {}) {
8236
8879
  catch (error) {
8237
8880
  config.storage.provider.connectionStatus = "partial";
8238
8881
  feature.config = config;
8239
- await writeTextIfChanged(manifestPath, stringifyJson(manifest));
8882
+ await writeManifestIfChanged(cwd, manifest);
8240
8883
  throw new Error(`R2 buckets are ready, but Vercel configuration is incomplete: ${error instanceof Error ? error.message : String(error)} Rerun \`loom files r2 setup\`; Loom will reuse the existing buckets.`);
8241
8884
  }
8242
8885
  const secretsConfigured = FILES_R2_ENVIRONMENTS.every((environment) => ["FILES_S3_ACCESS_KEY_ID", "FILES_S3_SECRET_ACCESS_KEY"].every((name) => hasExactEnvName(envListings.get(environment) ?? "", name)));
@@ -8246,7 +8889,7 @@ async function setupCloudflareR2(cwd, options = {}) {
8246
8889
  ? "configured"
8247
8890
  : "credentials-required";
8248
8891
  feature.config = config;
8249
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
8892
+ if (await writeManifestIfChanged(cwd, manifest)) {
8250
8893
  if (!changedFiles.includes("loom.json"))
8251
8894
  changedFiles.push("loom.json");
8252
8895
  }
@@ -9371,7 +10014,7 @@ async function setupVercelNeon(cwd, options = {}) {
9371
10014
  recordNeonProviderConfig(feature, framework, resourceName, "connected", undefined, options.region);
9372
10015
  manifest.features.db = feature;
9373
10016
  const changedFiles = [];
9374
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
10017
+ if (await writeManifestIfChanged(cwd, manifest)) {
9375
10018
  changedFiles.push("loom.json");
9376
10019
  }
9377
10020
  return {
@@ -9390,7 +10033,7 @@ async function setupVercelNeon(cwd, options = {}) {
9390
10033
  recordNeonProviderConfig(feature, framework, resourceName, "provisioned", undefined, options.region);
9391
10034
  manifest.features.db = feature;
9392
10035
  const changedFiles = [];
9393
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
10036
+ if (await writeManifestIfChanged(cwd, manifest)) {
9394
10037
  changedFiles.push("loom.json");
9395
10038
  }
9396
10039
  return {
@@ -9420,7 +10063,7 @@ async function setupVercelNeon(cwd, options = {}) {
9420
10063
  recordNeonProviderConfig(feature, framework, resourceName, result.code === 0 ? "connected" : "provisioned", provisionSuccess?.dashboardUrl, options.region);
9421
10064
  manifest.features.db = feature;
9422
10065
  const changedFiles = [];
9423
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
10066
+ if (await writeManifestIfChanged(cwd, manifest)) {
9424
10067
  changedFiles.push("loom.json");
9425
10068
  }
9426
10069
  const notes = result.code === 0
@@ -9553,7 +10196,9 @@ async function applyJobsFeature(cwd, framework, manifest, activate) {
9553
10196
  dependencies: JOBS_DEFAULT_DEPENDENCIES,
9554
10197
  devDependencies: JOBS_DEFAULT_DEV_DEPENDENCIES,
9555
10198
  });
9556
- const scriptsUpdate = await ensureProjectTasks(cwd, manifest, getJobsExpectedScripts(config));
10199
+ const scriptsUpdate = await syncManagedTasks(cwd, manifest, currentFeature, getJobsManagedTasks(config));
10200
+ setManagedRecords(feature, "managedTasks", scriptsUpdate.records);
10201
+ notes.push(...formatPreservedTaskNotes(scriptsUpdate, "jobs"));
9557
10202
  if (dependencyUpdate.changed)
9558
10203
  changedFiles.push(dependencyUpdate.config);
9559
10204
  if (scriptsUpdate.changedKeys.length)
@@ -9608,9 +10253,18 @@ async function applyJobsFeature(cwd, framework, manifest, activate) {
9608
10253
  if (relativePath === config.directRunner.scriptPath &&
9609
10254
  currentText !== null &&
9610
10255
  isLegacyLoomJobsDirectRunner(currentText)) {
9611
- if (await writeTextIfChanged(path, text)) {
10256
+ // Replace a dotenv-era runner only when it is exactly what an older
10257
+ // Loom wrote; an edited one keeps its app code.
10258
+ const legacyRunners = (0, legacyManagedOutputs_js_1.legacyJobsDirectRunnerOutputs)(getJobsDirectRunnerCatalogImportPath(config, framework));
10259
+ const result = await (0, managedFiles_js_1.syncManagedFile)(path, text, {
10260
+ knownOutputs: legacyRunners,
10261
+ });
10262
+ if (result.state === "updated") {
9612
10263
  changedFiles.push(relativePath);
9613
10264
  }
10265
+ else if (result.state === "customized") {
10266
+ notes.push(`Preserved local edits in the dotenv-based jobs direct runner ${relativePath} (${(0, managedFiles_js_1.describeManagedFileDifference)(currentText, legacyRunners)}); Loom did not replace it. Remove its dotenv import and \`dotenv.config(...)\` call and run it through \`loom env\`, or delete it and rerun \`loom add jobs\` to restore Loom's runner.`);
10267
+ }
9614
10268
  continue;
9615
10269
  }
9616
10270
  const scaffoldState = await scaffoldTextFile(path, text);
@@ -9622,9 +10276,10 @@ async function applyJobsFeature(cwd, framework, manifest, activate) {
9622
10276
  notes.push(`Preserved existing jobs scaffold file: ${relativePath}`);
9623
10277
  }
9624
10278
  }
9625
- const staticRouteSync = await syncJobsStaticRoutes(cwd, config);
10279
+ const staticRouteSync = await syncJobsStaticRoutes(cwd, config, currentFeature);
9626
10280
  changedFiles.push(...staticRouteSync.changedFiles);
9627
10281
  notes.push(...staticRouteSync.notes);
10282
+ setManagedFileRecords(feature, staticRouteSync.records);
9628
10283
  const jobsRoot = framework.srcDir ? "src/jobs" : "jobs";
9629
10284
  const catalogPath = (0, node_path_1.join)(cwd, jobsRoot, "index.ts");
9630
10285
  const metaCatalogPath = (0, node_path_1.join)(cwd, jobsRoot, "indexWithMetaOnly.ts");
@@ -9664,7 +10319,9 @@ async function applyDbFeature(cwd, framework, manifest, activate) {
9664
10319
  devDependencies: DB_DEFAULT_DEV_DEPENDENCIES,
9665
10320
  remove: DB_MOVED_DEPENDENCIES,
9666
10321
  });
9667
- const scriptsUpdate = await ensureProjectTasks(cwd, manifest, getDbExpectedScripts(config, tooling));
10322
+ const scriptsUpdate = await syncManagedTasks(cwd, manifest, currentFeature, getDbManagedTasks(config, tooling));
10323
+ setManagedRecords(feature, "managedTasks", scriptsUpdate.records);
10324
+ notes.push(...formatPreservedTaskNotes(scriptsUpdate, "db"));
9668
10325
  const testRunner = await getDbTestRunner(cwd, tooling);
9669
10326
  if (dependencyUpdate.changed)
9670
10327
  changedFiles.push(dependencyUpdate.config);
@@ -9679,26 +10336,21 @@ async function applyDbFeature(cwd, framework, manifest, activate) {
9679
10336
  if (dependencyUpdate.removedKeys.length) {
9680
10337
  notes.push(`Removed consumer-managed DB generator dependencies now owned by Loom: ${dependencyUpdate.removedKeys.join(", ")}`);
9681
10338
  }
9682
- const managedFiles = [
9683
- [config.modules.neonModule, dbNeonTemplate()],
9684
- [config.modules.neonFullModule, dbNeonFullTemplate()],
9685
- [config.modules.drizzleConfig, dbDrizzleConfigTemplate(config)],
9686
- [
9687
- config.modules.pgliteHarnessModule,
9688
- dbPgliteHarnessTemplate(config, testRunner),
9689
- ],
9690
- [config.modules.scriptsTsconfig, dbScriptsTsconfigTemplate()],
9691
- [
9692
- config.modules.refinementsCommonModule,
9693
- dbRefinementsCommonTemplate(),
9694
- ],
9695
- ];
9696
- for (const [relativePath, text] of managedFiles) {
9697
- const path = (0, node_path_1.join)(cwd, relativePath);
9698
- if (await writeTextIfChanged(path, text)) {
9699
- changedFiles.push(relativePath);
10339
+ const managedFileRecords = {};
10340
+ for (const managedFile of getDbManagedFiles(config, testRunner, tooling)) {
10341
+ const result = await (0, managedFiles_js_1.syncManagedFile)((0, node_path_1.join)(cwd, managedFile.relativePath), managedFile.text, {
10342
+ knownOutputs: managedFile.knownOutputs,
10343
+ recordedHash: recordedManagedFileHash(currentFeature, managedFile.relativePath),
10344
+ });
10345
+ recordManagedFileSync(managedFileRecords, currentFeature, managedFile.relativePath, result);
10346
+ if (result.state === "created" || result.state === "updated") {
10347
+ changedFiles.push(managedFile.relativePath);
10348
+ }
10349
+ else if (result.state === "customized") {
10350
+ notes.push(formatPreservedManagedFileNote(managedFile.relativePath, result.difference, "Move app-specific code to a separate module, then delete the file and rerun `loom add db` to restore the Loom wrapper."));
9700
10351
  }
9701
10352
  }
10353
+ setManagedFileRecords(feature, managedFileRecords);
9702
10354
  const scaffoldFiles = [
9703
10355
  [config.modules.fixtureDumpScript, dbFixturesScriptTemplate(config)],
9704
10356
  [(0, node_path_1.join)(config.dirs.fixtureDir, ".gitkeep"), ""],
@@ -9714,9 +10366,12 @@ async function applyDbFeature(cwd, framework, manifest, activate) {
9714
10366
  notes.push(`Preserved existing DB scaffold file: ${relativePath}`);
9715
10367
  }
9716
10368
  }
9717
- if (await syncValibotBarrel(cwd, config)) {
10369
+ const barrelSync = await syncValibotBarrel(cwd, config);
10370
+ if (barrelSync.changed) {
9718
10371
  changedFiles.push(config.modules.valibotBarrelModule);
9719
10372
  }
10373
+ if (barrelSync.note)
10374
+ notes.push(barrelSync.note);
9720
10375
  const schemaIndexPath = (0, node_path_1.join)(cwd, config.dirs.schemaDir, "index.ts");
9721
10376
  if (!await exists(schemaIndexPath)) {
9722
10377
  notes.push(`Missing ${config.dirs.schemaDir}/index.ts. Add your app-local Drizzle schema barrel there so Loom-managed DB helpers can import it.`);
@@ -10025,6 +10680,26 @@ function linguiCliCommand(tooling) {
10025
10680
  return "yarn lingui";
10026
10681
  }
10027
10682
  }
10683
+ function getLinguiManagedTasks(config, tooling) {
10684
+ // Lingui tasks have followed the recorded dependency manager since the
10685
+ // feature was added, so there is no earlier value to accept.
10686
+ const executable = linguiCliCommand(tooling);
10687
+ return [
10688
+ {
10689
+ definition: `${executable} extract --clean`,
10690
+ knownValues: [],
10691
+ name: config.tasks.extract,
10692
+ },
10693
+ {
10694
+ definition: `${executable} compile`,
10695
+ knownValues: [],
10696
+ name: config.tasks.compile,
10697
+ },
10698
+ ];
10699
+ }
10700
+ const PWA_MANAGED_TASKS = [
10701
+ { definition: PWA_BUILD_SCRIPT, knownValues: [], name: "pwa:build" },
10702
+ ];
10028
10703
  function linguiConfigTemplate(framework) {
10029
10704
  const sourceRoot = framework.srcDir ? "src/" : "";
10030
10705
  return `import { formatter } from "@lingui/format-po";
@@ -10174,19 +10849,10 @@ async function applyLinguiFeature(cwd, framework, manifest, activate) {
10174
10849
  else if (activate && configState === "preserved") {
10175
10850
  notes.push(`Preserved existing Lingui config: ${config.configFile}`);
10176
10851
  }
10177
- const taskChanges = [];
10178
- const executable = linguiCliCommand(tooling);
10179
- for (const [name, command] of [
10180
- [config.tasks.extract, `${executable} extract --clean`],
10181
- [config.tasks.compile, `${executable} compile`],
10182
- ]) {
10183
- const result = await (0, projectTooling_js_1.ensureTask)(cwd, tooling.tasks, {
10184
- definition: command,
10185
- name,
10186
- });
10187
- if (result.changed)
10188
- taskChanges.push(name);
10189
- }
10852
+ const linguiTasks = await syncManagedTasks(cwd, manifest, currentFeature, getLinguiManagedTasks(config, tooling));
10853
+ setManagedRecords(feature, "managedTasks", linguiTasks.records);
10854
+ const taskChanges = [...linguiTasks.changedKeys];
10855
+ notes.push(...formatPreservedTaskNotes(linguiTasks, "lingui"));
10190
10856
  let taskStore = await (0, projectTooling_js_1.readTaskStore)(cwd, tooling.tasks);
10191
10857
  if (!(0, projectTooling_js_1.getTaskCommand)(taskStore.definitions[config.tasks.build])) {
10192
10858
  const result = await (0, projectTooling_js_1.ensureTask)(cwd, tooling.tasks, {
@@ -10216,9 +10882,15 @@ async function applyLinguiFeature(cwd, framework, manifest, activate) {
10216
10882
  const poDeclarations = await findSourceFilesMatching(cwd, /declare\s+module\s+["']\*\.po["']/);
10217
10883
  if (!poDeclarations.length) {
10218
10884
  const declarationPath = `${framework.srcDir ? "src/" : ""}lingui.d.ts`;
10219
- if (await writeTextIfChanged((0, node_path_1.join)(cwd, declarationPath), linguiPoDeclarationTemplate())) {
10885
+ // Loom's declaration file always declares `*.po`, so an existing file
10886
+ // without one is the app's own and is never replaced.
10887
+ const declarationState = await scaffoldTextFile((0, node_path_1.join)(cwd, declarationPath), linguiPoDeclarationTemplate());
10888
+ if (declarationState === "created") {
10220
10889
  changedFiles.push(declarationPath);
10221
10890
  }
10891
+ else if (declarationState === "preserved") {
10892
+ notes.push(`Preserved existing ${declarationPath}, which does not declare \`*.po\` modules; add \`declare module "*.po"\` there or in another declaration file for the Lingui loader.`);
10893
+ }
10222
10894
  }
10223
10895
  }
10224
10896
  if (framework.kind === "nextjs") {
@@ -10270,12 +10942,10 @@ async function applyPwaFeature(cwd, framework, manifest, activate) {
10270
10942
  if (dependencyUpdate.changed)
10271
10943
  changedFiles.push(dependencyUpdate.config);
10272
10944
  const scriptsChanged = [];
10273
- const pwaTask = await (0, projectTooling_js_1.ensureTask)(cwd, tooling.tasks, {
10274
- definition: PWA_BUILD_SCRIPT,
10275
- name: "pwa:build",
10276
- });
10277
- if (pwaTask.changed)
10278
- scriptsChanged.push("pwa:build");
10945
+ const pwaTasks = await syncManagedTasks(cwd, manifest, currentFeature, PWA_MANAGED_TASKS);
10946
+ setManagedRecords(feature, "managedTasks", pwaTasks.records);
10947
+ scriptsChanged.push(...pwaTasks.changedKeys);
10948
+ notes.push(...formatPreservedTaskNotes(pwaTasks, "pwa"));
10279
10949
  const taskStore = await (0, projectTooling_js_1.readTaskStore)(cwd, tooling.tasks);
10280
10950
  const buildCommand = (0, projectTooling_js_1.getTaskCommand)(taskStore.definitions.build);
10281
10951
  if (!buildCommand) {
@@ -10320,14 +10990,27 @@ async function applyPwaFeature(cwd, framework, manifest, activate) {
10320
10990
  notes.push(`Preserved existing PWA service worker file: ${config.modules.serviceWorkerModule}`);
10321
10991
  }
10322
10992
  const clientProviderPath = (0, node_path_1.join)(cwd, config.modules.clientProviderModule);
10323
- const clientProviderExisted = await exists(clientProviderPath);
10993
+ const managedFileRecords = {};
10324
10994
  if (config.provider.managed) {
10325
- if (await writeTextIfChanged(clientProviderPath, pwaClientProviderTemplate(config))) {
10995
+ // `loom add pwa` may refresh the recorded adapter, so the provider the
10996
+ // previous configuration rendered is also Loom's output.
10997
+ const previousConfig = currentConfig
10998
+ ? await getPwaConfig(cwd, framework, packageJson, currentConfig, false)
10999
+ : config;
11000
+ const result = await (0, managedFiles_js_1.syncManagedFile)(clientProviderPath, pwaClientProviderTemplate(config), {
11001
+ knownOutputs: [pwaClientProviderTemplate(previousConfig)],
11002
+ recordedHash: recordedManagedFileHash(currentFeature, config.modules.clientProviderModule),
11003
+ });
11004
+ recordManagedFileSync(managedFileRecords, currentFeature, config.modules.clientProviderModule, result);
11005
+ if (result.state === "created" || result.state === "updated") {
10326
11006
  changedFiles.push(config.modules.clientProviderModule);
10327
11007
  }
10328
- if (!clientProviderExisted) {
11008
+ if (result.state === "created") {
10329
11009
  notes.push(`Scaffolded ${config.modules.clientProviderModule}. Wrap the app's root layout or provider tree with LoomPwaProvider to register the service worker.`);
10330
11010
  }
11011
+ else if (result.state === "customized") {
11012
+ notes.push(formatPreservedManagedFileNote(config.modules.clientProviderModule, result.difference, PWA_CUSTOMIZED_PROVIDER_RESOLUTION));
11013
+ }
10331
11014
  }
10332
11015
  else {
10333
11016
  const clientProviderState = await scaffoldTextFile(clientProviderPath, pwaClientProviderTemplate(config));
@@ -10338,6 +11021,7 @@ async function applyPwaFeature(cwd, framework, manifest, activate) {
10338
11021
  notes.push(`Preserved existing PWA client provider file: ${config.modules.clientProviderModule}`);
10339
11022
  }
10340
11023
  }
11024
+ setManagedFileRecords(feature, managedFileRecords);
10341
11025
  if (config.confirmAdapter === "mui") {
10342
11026
  notes.push("Detected @mui/material; PWA update prompts should use @gadicc/loom/mui/confirm.");
10343
11027
  }
@@ -10358,14 +11042,14 @@ async function checkJobsFeature(cwd, framework, manifest) {
10358
11042
  return { issues, suggestions: [], warnings: [] };
10359
11043
  }
10360
11044
  const config = mergeJobsConfig(framework, feature.config);
10361
- const expectedScripts = getJobsExpectedScripts(config);
10362
- const taskCheck = await checkProjectTasks(cwd, manifest, expectedScripts);
11045
+ const taskCheck = await checkManagedTasks(cwd, manifest, feature, getJobsManagedTasks(config));
10363
11046
  for (const taskName of taskCheck.mismatches) {
10364
11047
  issues.push(taskCheck.config === "package.json"
10365
11048
  ? `Jobs package.json script does not match Loom defaults: ${taskName}`
10366
11049
  : `Jobs task in ${taskCheck.config} does not match Loom defaults: ${taskName}`);
10367
11050
  suggestions.add("Run `loom add jobs`.");
10368
11051
  }
11052
+ addCustomizedTaskWarnings(taskCheck, "jobs", warnings, suggestions);
10369
11053
  const requiredFiles = [
10370
11054
  JOBS_SCRIPTS_TSCONFIG_PATH,
10371
11055
  config.directRunner?.scriptPath,
@@ -10416,8 +11100,14 @@ async function checkJobsFeature(cwd, framework, manifest) {
10416
11100
  const plans = getJobsStaticRoutePlans(cwd, config);
10417
11101
  const expectedPaths = new Set(plans.map((plan) => plan.path));
10418
11102
  for (const plan of plans) {
10419
- const currentText = await readTextIfExists(plan.path);
10420
- if (normalizeText(currentText ?? "") !== normalizeText(plan.text)) {
11103
+ const classification = await (0, managedFiles_js_1.classifyManagedFile)(await readTextIfExists(plan.path), plan.text, jobsStaticRouteProof(config, feature, plan.relativePath));
11104
+ if (classification.state === "current")
11105
+ continue;
11106
+ if (classification.state === "customized") {
11107
+ issues.push(`Jobs static route does not match loom manifest config: ${plan.relativePath} (${classification.difference})`);
11108
+ suggestions.add(`Loom does not overwrite edited or app-owned static job routes. ${JOBS_STATIC_ROUTE_EDIT_RESOLUTION}`);
11109
+ }
11110
+ else {
10421
11111
  issues.push(`Jobs static route does not match loom manifest config: ${plan.relativePath}`);
10422
11112
  suggestions.add("Run `loom add jobs` to sync static job routes.");
10423
11113
  }
@@ -10425,8 +11115,12 @@ async function checkJobsFeature(cwd, framework, manifest) {
10425
11115
  for (const routePath of await findManagedJobsStaticRoutePaths(cwd, config)) {
10426
11116
  if (expectedPaths.has(routePath))
10427
11117
  continue;
10428
- issues.push(`Managed jobs static route is not declared in loom.json: ${(0, node_path_1.relative)(cwd, routePath).replaceAll("\\", "/")}`);
10429
- suggestions.add("Run `loom add jobs` to sync static job routes.");
11118
+ const relativePath = (0, node_path_1.relative)(cwd, routePath).replaceAll("\\", "/");
11119
+ issues.push(`Managed jobs static route is not declared in loom.json: ${relativePath}`);
11120
+ const routeState = await (0, managedFiles_js_1.classifyManagedFile)(await readTextIfExists(routePath), "", jobsStaticRouteProof(config, feature, relativePath));
11121
+ suggestions.add(routeState.state === "loom-output"
11122
+ ? "Run `loom add jobs` to sync static job routes."
11123
+ : `Loom does not delete edited static job routes: delete ${relativePath} yourself if the job is gone, or remove its \`${LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER}\` marker line to keep it.`);
10430
11124
  }
10431
11125
  const routeModuleText = await readTextIfExists((0, node_path_1.join)(cwd, config.modules.routeModule));
10432
11126
  if (routeModuleText &&
@@ -10569,7 +11263,6 @@ async function checkDbFeature(cwd, framework, manifest, options) {
10569
11263
  const { packageJson } = await readProjectPackageJson(cwd);
10570
11264
  const tooling = await getProjectTooling(cwd, manifest);
10571
11265
  const testRunner = await getDbTestRunner(cwd, tooling);
10572
- const expectedScripts = getDbExpectedScripts(config, tooling);
10573
11266
  const migrationFlowCheck = await checkDbProductionMigrationFlow(cwd, options.production ?? false, productionBranch);
10574
11267
  issues.push(...migrationFlowCheck.issues);
10575
11268
  warnings.push(...migrationFlowCheck.warnings);
@@ -10601,13 +11294,14 @@ async function checkDbFeature(cwd, framework, manifest, options) {
10601
11294
  suggestions.add(`Run loom add db to rewrite ${tooling.dependencies.config}.`);
10602
11295
  }
10603
11296
  }
10604
- const taskCheck = await checkProjectTasks(cwd, manifest, expectedScripts);
11297
+ const taskCheck = await checkManagedTasks(cwd, manifest, feature, getDbManagedTasks(config, tooling));
10605
11298
  for (const taskName of taskCheck.mismatches) {
10606
11299
  issues.push(taskCheck.config === "package.json"
10607
11300
  ? `DB package.json script does not match Loom defaults: ${taskName}`
10608
11301
  : `DB task in ${taskCheck.config} does not match Loom defaults: ${taskName}`);
10609
11302
  suggestions.add("Run `loom add db`.");
10610
11303
  }
11304
+ addCustomizedTaskWarnings(taskCheck, "db", warnings, suggestions);
10611
11305
  const requiredFiles = [
10612
11306
  config.modules.neonModule,
10613
11307
  config.modules.neonFullModule,
@@ -10624,44 +11318,22 @@ async function checkDbFeature(cwd, framework, manifest, options) {
10624
11318
  suggestions.add("Run `loom add db`.");
10625
11319
  }
10626
11320
  }
10627
- const exactManagedFileChecks = [
10628
- [
10629
- config.modules.neonModule,
10630
- dbNeonTemplate(),
10631
- "DB neon module does not match the Loom-managed wrapper",
10632
- ],
10633
- [
10634
- config.modules.neonFullModule,
10635
- dbNeonFullTemplate(),
10636
- "DB neonFull module does not match the Loom-managed wrapper",
10637
- ],
10638
- [
10639
- config.modules.drizzleConfig,
10640
- dbDrizzleConfigTemplate(config),
10641
- "Drizzle config does not match the Loom-managed wrapper",
10642
- ],
10643
- [
10644
- config.modules.pgliteHarnessModule,
10645
- dbPgliteHarnessTemplate(config, testRunner),
10646
- "PGlite test harness does not match the Loom-managed wrapper",
10647
- ],
10648
- [
10649
- config.modules.scriptsTsconfig,
10650
- dbScriptsTsconfigTemplate(),
10651
- "DB scripts tsconfig does not match the Loom-managed template",
10652
- ],
10653
- [
10654
- config.modules.refinementsCommonModule,
10655
- dbRefinementsCommonTemplate(),
10656
- "Valibot refinements common module does not match the Loom-managed wrapper",
10657
- ],
10658
- ];
10659
- for (const [relativePath, expectedText, message] of exactManagedFileChecks) {
10660
- const currentText = await readTextIfExists((0, node_path_1.join)(cwd, relativePath));
11321
+ for (const managedFile of getDbManagedFiles(config, testRunner, tooling)) {
11322
+ const currentText = await readTextIfExists((0, node_path_1.join)(cwd, managedFile.relativePath));
10661
11323
  if (!currentText)
10662
11324
  continue;
10663
- if (normalizeText(currentText) !== normalizeText(expectedText)) {
10664
- issues.push(`${message}: ${relativePath}`);
11325
+ const classification = await (0, managedFiles_js_1.classifyManagedFile)(currentText, managedFile.text, {
11326
+ knownOutputs: managedFile.knownOutputs,
11327
+ recordedHash: recordedManagedFileHash(feature, managedFile.relativePath),
11328
+ });
11329
+ if (classification.state === "current")
11330
+ continue;
11331
+ if (classification.state === "customized") {
11332
+ issues.push(`${managedFile.mismatch}: ${managedFile.relativePath} (${classification.difference})`);
11333
+ suggestions.add("Loom does not overwrite local edits in its DB wrappers: move app-specific code to a separate module, delete the edited wrapper, then run `loom add db` to restore it.");
11334
+ }
11335
+ else {
11336
+ issues.push(`${managedFile.mismatch}: ${managedFile.relativePath}`);
10665
11337
  suggestions.add("Run `loom add db` to restore the Loom-managed DB wrappers.");
10666
11338
  }
10667
11339
  }
@@ -10692,20 +11364,24 @@ async function checkDbFeature(cwd, framework, manifest, options) {
10692
11364
  }
10693
11365
  }
10694
11366
  }
10695
- const generatedNames = await readTsModuleNames((0, node_path_1.join)(cwd, config.dirs.valibotGeneratedDir));
10696
- const refinementNames = await readTsModuleNames((0, node_path_1.join)(cwd, config.dirs.valibotRefinementsDir));
10697
- const expectedBarrelText = buildValibotBarrelText(generatedNames, refinementNames);
11367
+ const barrel = await readValibotBarrelState(cwd, config);
11368
+ const expectedBarrelText = barrel.text;
10698
11369
  const barrelPath = (0, node_path_1.join)(cwd, config.modules.valibotBarrelModule);
10699
11370
  const barrelText = await readTextIfExists(barrelPath);
10700
11371
  if (expectedBarrelText) {
10701
- if (!barrelText) {
11372
+ const classification = await (0, managedFiles_js_1.classifyManagedFile)(barrelText, expectedBarrelText, barrel.proof);
11373
+ if (classification.state === "missing") {
10702
11374
  issues.push(`Valibot barrel is missing while generated/refinement modules exist: ${config.modules.valibotBarrelModule}`);
10703
11375
  suggestions.add("Run `loom db schema-gen` to refresh generated validation exports.");
10704
11376
  }
10705
- else if (normalizeText(barrelText) !== normalizeText(expectedBarrelText)) {
11377
+ else if (classification.state === "loom-output") {
10706
11378
  issues.push(`Valibot barrel does not match the generated/refinement modules: ${config.modules.valibotBarrelModule}`);
10707
11379
  suggestions.add("Run `loom db schema-gen` to rebuild the generated validation exports and barrel.");
10708
11380
  }
11381
+ else if (classification.state === "customized") {
11382
+ issues.push(`Valibot barrel does not match the generated/refinement modules: ${config.modules.valibotBarrelModule} (${classification.difference})`);
11383
+ suggestions.add(`Loom does not overwrite hand-written exports in ${config.modules.valibotBarrelModule}: keep only \`export * from\` lines for the generated and refinement modules there, or add the missing exports by hand.`);
11384
+ }
10709
11385
  }
10710
11386
  else if (barrelText) {
10711
11387
  warnings.push(`Valibot barrel exists but no generated/refinement modules were discovered: ${config.modules.valibotBarrelModule}`);
@@ -12432,6 +13108,8 @@ async function checkLinguiFeature(cwd, framework, manifest, options) {
12432
13108
  issues.push(`Lingui config is missing: ${config.configFile}`);
12433
13109
  suggestions.add("Run `loom add lingui`.");
12434
13110
  }
13111
+ // Missing or broken tasks are issues below; edited working ones only warn.
13112
+ addCustomizedTaskWarnings(await checkManagedTasks(cwd, manifest, feature, getLinguiManagedTasks(config, tooling)), "lingui", warnings, suggestions);
12435
13113
  const taskStore = await (0, projectTooling_js_1.readTaskStore)(cwd, tooling.tasks);
12436
13114
  if (!linguiTaskRuns((0, projectTooling_js_1.getTaskCommand)(taskStore.definitions[config.tasks.extract]), "extract")) {
12437
13115
  issues.push(`Lingui extraction task is missing or invalid in ${tooling.tasks.config}: ${config.tasks.extract}`);
@@ -12553,6 +13231,9 @@ async function checkPwaFeature(cwd, framework, manifest) {
12553
13231
  suggestions.add("Run `loom add pwa`.");
12554
13232
  }
12555
13233
  }
13234
+ // A missing or broken pwa:build is an issue below; an edited working one
13235
+ // only warns.
13236
+ addCustomizedTaskWarnings(await checkManagedTasks(cwd, manifest, feature, PWA_MANAGED_TASKS), "pwa", warnings, suggestions);
12556
13237
  const taskStore = await (0, projectTooling_js_1.readTaskStore)(cwd, tooling.tasks);
12557
13238
  if (!scriptRunsSerwistBuild((0, projectTooling_js_1.getTaskCommand)(taskStore.definitions["pwa:build"]))) {
12558
13239
  issues.push(`PWA task in ${tooling.tasks.config} does not build Serwist: pwa:build`);
@@ -12644,6 +13325,15 @@ async function checkPwaFeature(cwd, framework, manifest) {
12644
13325
  }
12645
13326
  const clientProviderText = await readTextIfExists((0, node_path_1.join)(cwd, config.modules.clientProviderModule));
12646
13327
  if (clientProviderText) {
13328
+ if (config.provider.managed) {
13329
+ const classification = await (0, managedFiles_js_1.classifyManagedFile)(clientProviderText, pwaClientProviderTemplate(config), {
13330
+ recordedHash: recordedManagedFileHash(feature, config.modules.clientProviderModule),
13331
+ });
13332
+ if (classification.state === "customized") {
13333
+ warnings.push(`PWA client provider is recorded as Loom-managed but has local edits that Loom will not overwrite: ${config.modules.clientProviderModule} (${classification.difference})`);
13334
+ suggestions.add(`PWA client provider ${config.modules.clientProviderModule}: ${PWA_CUSTOMIZED_PROVIDER_RESOLUTION}`);
13335
+ }
13336
+ }
12647
13337
  if (!await isPwaClientProviderMounted(cwd, framework, config)) {
12648
13338
  issues.push(`PWA client provider is not mounted by the app root provider tree: ${config.modules.clientProviderModule}`);
12649
13339
  suggestions.add("Wrap the app root layout or existing client provider with LoomPwaProvider.");
@@ -12840,11 +13530,9 @@ async function initProject(cwd, versionRange) {
12840
13530
  notes.push(...packageSkillInit.notes);
12841
13531
  if (await ensureExternalSkillsGitignore(cwd))
12842
13532
  changedFiles.push(".gitignore");
12843
- const manifestText = stringifyJson(manifest);
12844
- const manifestChanged = !existingManifest ||
12845
- JSON.stringify(existingManifest) !== JSON.stringify(manifest);
12846
- if (manifestChanged) {
12847
- await (0, promises_1.writeFile)(loomManifestPath, manifestText, "utf8");
13533
+ // The new manifest shares the existing features object, which the feature
13534
+ // hooks update in place, so compare with the file on disk.
13535
+ if (await writeManifestIfChanged(cwd, manifest)) {
12848
13536
  changedFiles.push("loom.json");
12849
13537
  }
12850
13538
  return {
@@ -12870,8 +13558,7 @@ async function addFeature(cwd, featureKey, versionRange) {
12870
13558
  ...skillSync.changedFiles,
12871
13559
  ];
12872
13560
  const notes = [...base.notes, ...result.notes, ...skillSync.notes];
12873
- const manifestPath = (0, node_path_1.join)(cwd, "loom.json");
12874
- if (await writeTextIfChanged(manifestPath, stringifyJson(base.manifest))) {
13561
+ if (await writeManifestIfChanged(cwd, base.manifest)) {
12875
13562
  changedFiles.push("loom.json");
12876
13563
  }
12877
13564
  return {
@@ -12929,7 +13616,7 @@ async function integrateApiKeysJobs(cwd, permission, allowQueryParam = false) {
12929
13616
  };
12930
13617
  feature.config = config;
12931
13618
  manifest.features["api-keys"] = feature;
12932
- const changed = await writeTextIfChanged(manifestPath, stringifyJson(manifest));
13619
+ const changed = await writeManifestIfChanged(cwd, manifest);
12933
13620
  return {
12934
13621
  changedFiles: changed ? ["loom.json"] : [],
12935
13622
  notes: [
@@ -12967,7 +13654,7 @@ async function configureApiKeyRetention(cwd, enabled, overrides = {}) {
12967
13654
  };
12968
13655
  feature.config = config;
12969
13656
  manifest.features["api-keys"] = feature;
12970
- const changed = await writeTextIfChanged(manifestPath, stringifyJson(manifest));
13657
+ const changed = await writeManifestIfChanged(cwd, manifest);
12971
13658
  return {
12972
13659
  changedFiles: changed ? ["loom.json"] : [],
12973
13660
  notes: enabled
@@ -13111,7 +13798,7 @@ async function checkProject(cwd, env = node_process_1.default.env, options = {})
13111
13798
  for (const suggestion of agentsCheck.suggestions) {
13112
13799
  suggestions.add(suggestion);
13113
13800
  }
13114
- const envRunnerCheck = await checkEnvRunnerAdoption(cwd, manifest);
13801
+ const envRunnerCheck = await checkEnvRunnerAdoption(cwd, manifest, framework);
13115
13802
  for (const issue of envRunnerCheck.issues) {
13116
13803
  issues.push(issue);
13117
13804
  }
@@ -14184,9 +14871,12 @@ async function runDbSchemaGen(cwd, forwardedArgs, io) {
14184
14871
  io.out("Biome is not installed; generated Valibot files were left unformatted.");
14185
14872
  }
14186
14873
  }
14187
- if (await syncValibotBarrel(cwd, config)) {
14874
+ const barrelSync = await syncValibotBarrel(cwd, config);
14875
+ if (barrelSync.changed) {
14188
14876
  io.out(`Updated ${config.modules.valibotBarrelModule}.`);
14189
14877
  }
14878
+ if (barrelSync.note)
14879
+ io.out(`Note: ${barrelSync.note}`);
14190
14880
  return 0;
14191
14881
  }
14192
14882
  async function runDbFixtures(cwd, forwardedArgs) {