@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.
@@ -13,13 +13,15 @@ import { resolveProductionBranch, } from "./releaseConfig.js";
13
13
  import { configureGithubVercelReleaseCredential, } from "./releaseCredentials.js";
14
14
  import { runGithubReleaseTrustCommand } from "./releaseTrustCommand.js";
15
15
  import { checkLocalDatabase, setupLocalDatabase } from "./localDb.js";
16
+ import { classifyManagedFile, classifyManagedTask, describeManagedFileDifference, hashManagedFileText, removeManagedFile, syncManagedFile, } from "./managedFiles.js";
17
+ import { legacyDbPgliteHarnessOutputs, legacyDbTaskValues, legacyJobsDirectRunnerOutputs, legacyJobsTaskValues, } from "./legacyManagedOutputs.js";
16
18
  import { BETTER_AUTH_API_KEY_HTTP_PATHS } from "../apiKeys/betterAuth.js";
17
19
  import { DEFAULT_API_KEY_AUDIT_RETENTION } from "../apiKeys/retention.js";
18
20
  import { checkProjectSkills, getProjectSkillStatus, LOOM_EXTERNAL_SKILLS_GITIGNORE_LINE, removeLegacyNextSkillLink, setProjectSkillDisabled, syncExternalProjectSkills, syncInstalledPackageSkills, } from "./projectSkills.js";
19
21
  import { resolveMigrationEnvironment, resolveMigrationEnvironmentFromEnvFile, verifyMigrationConnection, verifyMigrationConnectionFromEnvFile, } from "./migrationEnv.js";
20
22
  import { prepareVercelBuildEnvironment, verifyVercelBuildArtifact, } from "./vercelBuildEnv.js";
21
23
  import { parseVercelReleaseTimeout, prepareVercelProjectRelease, promoteVercelProjectRelease, } from "./vercelProjectRelease.js";
22
- import { detectProjectTooling, ensureTask, ensureTaskFollowup, ensureTaskPrerequisite, findTaskConflicts, formatTaskInvocation, getTaskCommand, mutateDenoLinks, mutatePackageJsonOverride, mutateProjectDependencies, parseJsonc, readDenoLinks, readProjectPackageMetadata, readTaskStore, taskInvokes, taskRunsBeforeCommand, } from "./projectTooling.js";
24
+ import { detectProjectTooling, ensureTask, ensureTaskFollowup, ensureTaskPrerequisite, findTaskConflicts, formatTaskInvocation, getTaskCommand, jsonValuesEqual, mutateDenoLinks, mutatePackageJsonOverride, mutateProjectDependencies, parseJsonc, patchJsonText, readDenoLinks, readProjectPackageMetadata, readTaskStore, taskInvokes, taskRunsBeforeCommand, } from "./projectTooling.js";
23
25
  import { withLocalDevLock, } from "./localDevLock.js";
24
26
  import { computeLoomSourceFingerprint, computePackageContentDigest, computePackageTreeSignature, findNewPeerVariantDuplicates, findPackageTreeDifference, formatLoomBuildStamp, getLockfileOverride, getLockfileRootImporterDependency, hasLoomBuildProvenance, LOOM_BUILD_STAMP_FILE, LOOM_PACKAGE_RELEVANT_PATHS, readLoomBuildStamp, } from "./localDevPackage.js";
25
27
  export const DEFAULT_LOOM_RANGE = "^1.0.0";
@@ -317,6 +319,62 @@ async function writeTextIfChanged(path, text) {
317
319
  await writeFile(path, text, "utf8");
318
320
  return true;
319
321
  }
322
+ /**
323
+ * Writes loom.json when its data changed, ignoring key order. An existing
324
+ * file is patched member by member, so the consumer's formatting and key
325
+ * order survive and a formatter such as Biome has nothing to change; only a
326
+ * new file is written whole.
327
+ */
328
+ async function writeManifestIfChanged(cwd, manifest) {
329
+ const path = join(cwd, "loom.json");
330
+ const currentText = await readTextIfExists(path);
331
+ if (currentText === null) {
332
+ await writeFile(path, stringifyJson(manifest), "utf8");
333
+ return true;
334
+ }
335
+ if (jsonValuesEqual(parseJson(currentText, "loom.json"), manifest)) {
336
+ return false;
337
+ }
338
+ await writeFile(path, patchJsonText(currentText, manifest), "utf8");
339
+ return true;
340
+ }
341
+ function recordedManagedFileHash(feature, relativePath) {
342
+ return feature?.managedFiles?.[relativePath];
343
+ }
344
+ /**
345
+ * Notes one managed-file sync in `records`: Loom's hash when the file now
346
+ * holds or matches Loom output, otherwise the previous record, so the file is
347
+ * recognised again if its local edits are reverted.
348
+ */
349
+ function recordManagedFileSync(records, feature, relativePath, result) {
350
+ const hash = result.hash ?? recordedManagedFileHash(feature, relativePath);
351
+ if (hash)
352
+ records[relativePath] = hash;
353
+ }
354
+ /**
355
+ * Reports a managed file Loom left alone because it has local edits, naming
356
+ * the file, the difference and how to resolve it.
357
+ */
358
+ function formatPreservedManagedFileNote(relativePath, difference, resolution) {
359
+ return `Preserved local edits in Loom-managed ${relativePath}${difference ? ` (${difference})` : ""}; Loom did not update it. ${resolution}`;
360
+ }
361
+ /**
362
+ * Replaces a feature's managed-file or managed-task record with what this
363
+ * sync manages, sorted so loom.json stays stable. Entries Loom no longer
364
+ * manages drop out.
365
+ */
366
+ function setManagedRecords(feature, key, records) {
367
+ const entries = Object.entries(records).sort(([left], [right]) => left.localeCompare(right));
368
+ if (entries.length) {
369
+ feature[key] = Object.fromEntries(entries);
370
+ }
371
+ else {
372
+ delete feature[key];
373
+ }
374
+ }
375
+ function setManagedFileRecords(feature, records) {
376
+ setManagedRecords(feature, "managedFiles", records);
377
+ }
320
378
  export async function defaultCommandRunner(command, args, options) {
321
379
  return await new Promise((resolvePromise) => {
322
380
  const inherit = options.stdio === "inherit" ||
@@ -505,7 +563,7 @@ function jobsScriptBypassesEnvRunner(scriptName, scriptCommand) {
505
563
  return (scriptName === "job" || scriptCommand.includes("jobDirect.ts")) &&
506
564
  !scriptUsesLoomEnvRunner(scriptCommand);
507
565
  }
508
- async function checkEnvRunnerAdoption(cwd, manifest) {
566
+ async function checkEnvRunnerAdoption(cwd, manifest, framework) {
509
567
  const issues = [];
510
568
  const suggestions = new Set();
511
569
  const activeDb = manifest.features.db?.status === "active";
@@ -522,23 +580,53 @@ async function checkEnvRunnerAdoption(cwd, manifest) {
522
580
  }
523
581
  const tooling = await getProjectTooling(cwd, manifest);
524
582
  const taskStore = await readTaskStore(cwd, tooling.tasks);
583
+ // `loom add` refreshes only tasks whose value is provably Loom's; an edited
584
+ // task has to be moved onto `loom env` by hand.
585
+ const loomTasks = new Map();
586
+ if (activeDb) {
587
+ const dbConfig = mergeDbConfig(framework, manifest.features.db.config);
588
+ for (const task of getDbManagedTasks(dbConfig, tooling)) {
589
+ loomTasks.set(task.name, [manifest.features.db, task]);
590
+ }
591
+ }
592
+ if (activeJobs) {
593
+ const jobsConfig = mergeJobsConfig(framework, manifest.features.jobs.config);
594
+ for (const task of getJobsManagedTasks(jobsConfig)) {
595
+ loomTasks.set(task.name, [manifest.features.jobs, task]);
596
+ }
597
+ }
598
+ const loomRefreshes = (name, definition) => {
599
+ const entry = loomTasks.get(name);
600
+ if (!entry)
601
+ return false;
602
+ const [feature, task] = entry;
603
+ return classifyManagedTask(definition, task.definition, {
604
+ knownValues: task.knownValues,
605
+ recordedHash: feature.managedTasks?.[name],
606
+ }).state !== "customized";
607
+ };
608
+ const handEditSuggestion = (name) => `Loom does not overwrite edited tasks: change ${name} in ${taskStore.config} to run its command through \`loom env -- <command>\`.`;
525
609
  for (const [scriptName, definition] of Object.entries(taskStore.definitions)) {
526
610
  const scriptCommand = getTaskCommand(definition);
527
611
  if (activeDb && dbScriptBypassesEnvRunner(scriptName, scriptCommand)) {
528
612
  issues.push(taskStore.config === "package.json"
529
613
  ? `DB package.json script bypasses the Loom env runner: ${scriptName}`
530
614
  : `DB task in ${taskStore.config} bypasses the Loom env runner: ${scriptName}`);
531
- suggestions.add(taskStore.config === "package.json"
532
- ? "Run `loom add db` to refresh DB package scripts."
533
- : "Run `loom add db` to refresh DB tasks.");
615
+ suggestions.add(!loomRefreshes(scriptName, definition)
616
+ ? handEditSuggestion(scriptName)
617
+ : taskStore.config === "package.json"
618
+ ? "Run `loom add db` to refresh DB package scripts."
619
+ : "Run `loom add db` to refresh DB tasks.");
534
620
  }
535
621
  if (activeJobs && jobsScriptBypassesEnvRunner(scriptName, scriptCommand)) {
536
622
  issues.push(taskStore.config === "package.json"
537
623
  ? `Jobs package.json script bypasses the Loom env runner: ${scriptName}`
538
624
  : `Jobs task in ${taskStore.config} bypasses the Loom env runner: ${scriptName}`);
539
- suggestions.add(taskStore.config === "package.json"
540
- ? "Run `loom add jobs` to refresh jobs package scripts."
541
- : "Run `loom add jobs` to refresh jobs tasks.");
625
+ suggestions.add(!loomRefreshes(scriptName, definition)
626
+ ? handEditSuggestion(scriptName)
627
+ : taskStore.config === "package.json"
628
+ ? "Run `loom add jobs` to refresh jobs package scripts."
629
+ : "Run `loom add jobs` to refresh jobs tasks.");
542
630
  }
543
631
  }
544
632
  return {
@@ -1072,25 +1160,89 @@ export function ensurePackageJsonDependency(packageJson, versionRange = DEFAULT_
1072
1160
  async function getProjectTooling(cwd, manifest) {
1073
1161
  return await detectProjectTooling(cwd, manifest.project?.tooling);
1074
1162
  }
1075
- async function ensureProjectTasks(cwd, manifest, tasks) {
1163
+ function formatTaskValue(definition) {
1164
+ return `\`${typeof definition === "string" ? definition : JSON.stringify(definition)}\``;
1165
+ }
1166
+ /** Shows a kept task's local value next to Loom's value. */
1167
+ function formatCustomizedTaskValues({ current, task }) {
1168
+ return `(local: ${formatTaskValue(current)}; Loom: ${formatTaskValue(task.definition)})`;
1169
+ }
1170
+ /**
1171
+ * Creates missing Loom-owned tasks and updates those whose value is provably
1172
+ * Loom's (recorded hash, current value or a known earlier value), through
1173
+ * localized edits of the config `project.tooling` records. Edited tasks are
1174
+ * left alone and returned so the caller can report them.
1175
+ */
1176
+ async function syncManagedTasks(cwd, manifest, feature, tasks) {
1076
1177
  const tooling = await getProjectTooling(cwd, manifest);
1077
1178
  const changedKeys = [];
1078
- for (const [name, definition] of Object.entries(tasks)) {
1079
- const result = await ensureTask(cwd, tooling.tasks, { definition, name });
1179
+ const customized = [];
1180
+ const records = {};
1181
+ for (const task of tasks) {
1182
+ const store = await readTaskStore(cwd, tooling.tasks);
1183
+ const current = store.definitions[task.name];
1184
+ const classification = classifyManagedTask(current, task.definition, {
1185
+ knownValues: task.knownValues,
1186
+ recordedHash: feature?.managedTasks?.[task.name],
1187
+ });
1188
+ if (classification.state === "customized") {
1189
+ customized.push({ current, task });
1190
+ const previous = feature?.managedTasks?.[task.name];
1191
+ if (previous)
1192
+ records[task.name] = previous;
1193
+ continue;
1194
+ }
1195
+ records[task.name] = classification.expectedHash;
1196
+ // A value that matches apart from whitespace keeps the app's spelling.
1197
+ if (classification.state === "current")
1198
+ continue;
1199
+ const result = await ensureTask(cwd, tooling.tasks, {
1200
+ definition: task.definition,
1201
+ name: task.name,
1202
+ });
1080
1203
  if (result.changed)
1081
- changedKeys.push(name);
1204
+ changedKeys.push(task.name);
1082
1205
  }
1083
- return { changedKeys, config: tooling.tasks.config, tooling };
1206
+ return { changedKeys, config: tooling.tasks.config, customized, records };
1084
1207
  }
1085
- async function checkProjectTasks(cwd, manifest, expected) {
1208
+ /**
1209
+ * Compares Loom-owned tasks with Loom's values without writing: `mismatches`
1210
+ * are missing tasks or unedited older Loom values that `loom add` updates;
1211
+ * `customized` tasks have edits Loom will not overwrite.
1212
+ */
1213
+ async function checkManagedTasks(cwd, manifest, feature, tasks) {
1086
1214
  const tooling = await getProjectTooling(cwd, manifest);
1087
1215
  const store = await readTaskStore(cwd, tooling.tasks);
1088
- return {
1089
- config: tooling.tasks.config,
1090
- mismatches: Object.entries(expected).flatMap(([name, command]) => getTaskCommand(store.definitions[name]) === command ? [] : [name]),
1091
- store,
1092
- tooling,
1093
- };
1216
+ const mismatches = [];
1217
+ const customized = [];
1218
+ for (const task of tasks) {
1219
+ const current = store.definitions[task.name];
1220
+ const { state } = classifyManagedTask(current, task.definition, {
1221
+ knownValues: task.knownValues,
1222
+ recordedHash: feature?.managedTasks?.[task.name],
1223
+ });
1224
+ if (state === "customized") {
1225
+ customized.push({ current, task });
1226
+ }
1227
+ else if (state !== "current") {
1228
+ mismatches.push(task.name);
1229
+ }
1230
+ }
1231
+ return { config: tooling.tasks.config, customized, mismatches, store };
1232
+ }
1233
+ /** Notes for Loom-owned tasks that `loom init` or `loom add` left alone. */
1234
+ function formatPreservedTaskNotes(sync, featureKey) {
1235
+ 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}\`.`);
1236
+ }
1237
+ /**
1238
+ * `loom check` warnings for Loom-owned tasks with local edits, naming each
1239
+ * task and showing both values.
1240
+ */
1241
+ function addCustomizedTaskWarnings(check, featureKey, warnings, suggestions) {
1242
+ for (const customized of check.customized) {
1243
+ warnings.push(`Loom-managed task ${customized.task.name} in ${check.config} has local edits that Loom will not overwrite ${formatCustomizedTaskValues(customized)}`);
1244
+ suggestions.add(`To restore Loom's value for an edited ${featureKey} task, delete the task and rerun \`loom add ${featureKey}\`.`);
1245
+ }
1094
1246
  }
1095
1247
  export function buildManifest(cwd, packageJson, framework, existingManifest, tooling) {
1096
1248
  return {
@@ -1436,6 +1588,14 @@ function getDbExpectedScripts(config, tooling) {
1436
1588
  "schema:gen": "loom db schema-gen",
1437
1589
  };
1438
1590
  }
1591
+ function getDbManagedTasks(config, tooling) {
1592
+ const legacy = legacyDbTaskValues(config.modules.drizzleConfig);
1593
+ return Object.entries(getDbExpectedScripts(config, tooling)).map(([name, definition]) => ({
1594
+ definition,
1595
+ knownValues: legacy[name] ?? [],
1596
+ name,
1597
+ }));
1598
+ }
1439
1599
  function mergeDbConfig(framework, featureConfig) {
1440
1600
  const defaults = getDbConfig(framework);
1441
1601
  return {
@@ -2268,7 +2428,7 @@ function plainYamlValue(value) {
2268
2428
  return trimmed.replace(/\s+#.*$/, "").trim();
2269
2429
  }
2270
2430
  /**
2271
- * Local (`file:`/`link:`) Loom entries of the pnpm-workspace.yaml
2431
+ * Local (`file:`/`link:`/`workspace:`) Loom entries of the pnpm-workspace.yaml
2272
2432
  * `overrides:` map outside Loom's managed block, such as one written by
2273
2433
  * hand. `line` is the entry's line in `text` once the managed block is
2274
2434
  * removed, or null in flow style, which Loom does not edit.
@@ -2283,7 +2443,7 @@ function getUnmanagedPnpmWorkspaceLoomOverrides(text) {
2283
2443
  return entries;
2284
2444
  const add = (key, value, line) => {
2285
2445
  const spec = plainYamlValue(value);
2286
- if (overrideKeyTargetsLoom(key) && /^(?:file|link):/.test(spec)) {
2446
+ if (overrideKeyTargetsLoom(key) && isLocalPackageSpec(spec)) {
2287
2447
  entries.push({ key, line, spec });
2288
2448
  }
2289
2449
  };
@@ -3094,6 +3254,15 @@ function compareParsedVersions(left, right) {
3094
3254
  }
3095
3255
  return left.prerelease.localeCompare(right.prerelease);
3096
3256
  }
3257
+ /**
3258
+ * Whether `version` is a newer release than the exact pin `pinned`. Pin
3259
+ * advice must never suggest moving an app back to an older Loom.
3260
+ */
3261
+ function isNewerLoomVersion(version, pinned) {
3262
+ const candidate = parseSemverTag(version);
3263
+ const pin = parseSemverTag(pinned);
3264
+ return !!candidate && !!pin && compareParsedVersions(candidate, pin) > 0;
3265
+ }
3097
3266
  async function findPublishedLoomPublicationForCommit(sourceRoot, sourceCommit, commandRunner, env, preferredSpec,
3098
3267
  /** Names the commit in refusals, such as "Loom commit abc, which built X,". */
3099
3268
  subject) {
@@ -3208,6 +3377,208 @@ export async function captureLoadedLocalLoomSignature(cwd, env) {
3208
3377
  function formatPnpmOverrideNotAppliedMessage(override, pnpmVersion) {
3209
3378
  return `pnpm did not apply the Loom local-dev override in ${formatPnpmOverrideLocation(override.location)}: pnpm-lock.yaml does not record ${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\`.`;
3210
3379
  }
3380
+ /** Whether deno.lock records a `links` entry for Loom. */
3381
+ async function denoLockLinksLoom(cwd) {
3382
+ const text = await readTextIfExists(join(cwd, "deno.lock"));
3383
+ if (!text)
3384
+ return false;
3385
+ let lock;
3386
+ try {
3387
+ lock = JSON.parse(text);
3388
+ }
3389
+ catch {
3390
+ // Unreadable: assume it may record one.
3391
+ return true;
3392
+ }
3393
+ const linkKeys = (scope) => scope && typeof scope === "object" &&
3394
+ scope.links &&
3395
+ typeof scope.links === "object"
3396
+ ? Object.keys(scope.links)
3397
+ : [];
3398
+ const members = lock.workspace?.members &&
3399
+ typeof lock.workspace.members === "object"
3400
+ ? Object.values(lock.workspace.members)
3401
+ : [];
3402
+ return [lock.workspace, ...members].flatMap(linkKeys).some((key) => key === LOOM_DEPENDENCY || key.startsWith(`npm:${LOOM_DEPENDENCY}@`) ||
3403
+ key.startsWith(`${LOOM_DEPENDENCY}@`));
3404
+ }
3405
+ /**
3406
+ * Every Deno `links` entry that is, or may be, Loom's: its package is named
3407
+ * Loom, or its package is gone. A dangling entry may be Loom's whatever
3408
+ * identifies it (the path dev state recorded, a Loom link in deno.lock, or
3409
+ * nothing at all): node_modules can still hold what Deno copied from it,
3410
+ * and a broken link cannot ship anyway.
3411
+ */
3412
+ async function findLoomDenoLinks(cwd, denoConfig) {
3413
+ const links = [];
3414
+ for (const link of await readDenoLinks(cwd, denoConfig)) {
3415
+ const path = resolve(cwd, link);
3416
+ const dangling = !await exists(join(path, "package.json"));
3417
+ if (dangling || await findLocalLoomDenoLink(cwd, [link])) {
3418
+ links.push({ dangling, link, path });
3419
+ }
3420
+ }
3421
+ return links;
3422
+ }
3423
+ /**
3424
+ * Local Loom overrides and links in the project's config: Loom overrides
3425
+ * with a local (`file:`/`link:`/`workspace:`) spec under any selector, in
3426
+ * package.json maps or pnpm-workspace.yaml (managed or hand-written), a local
3427
+ * Loom catalog entry, and Deno links to Loom, dangling ones included. Each
3428
+ * is described for messages.
3429
+ */
3430
+ async function findLocalLoomLinks(cwd) {
3431
+ const manifest = await readManifestIfExists(cwd);
3432
+ const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
3433
+ const packageJson = await readPackageJsonIfExists(cwd) ?? {};
3434
+ const workspaceText = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
3435
+ const links = [];
3436
+ // Reported by the catalog check itself; still local Loom in use.
3437
+ const catalogLinks = [];
3438
+ for (const { field, location } of PACKAGE_JSON_OVERRIDE_LOCATIONS) {
3439
+ for (const [key, spec] of Object.entries(getPackageJsonOverrideMap(packageJson, field))) {
3440
+ if (overrideKeyTargetsLoom(key) && typeof spec === "string" &&
3441
+ isLocalPackageSpec(spec)) {
3442
+ links.push(`${formatPnpmOverrideLocation(location)}: ${spec}`);
3443
+ }
3444
+ }
3445
+ }
3446
+ const managedSpec = getManagedDevOverrideSpec(workspaceText);
3447
+ if (managedSpec)
3448
+ links.push(`pnpm-workspace.yaml: ${managedSpec}`);
3449
+ for (const { key, spec } of getUnmanagedPnpmWorkspaceLoomOverrides(workspaceText)) {
3450
+ links.push(`pnpm-workspace.yaml overrides ${key}: ${spec}`);
3451
+ }
3452
+ const dependency = await resolveLoomDependencySpec(cwd, packageJson);
3453
+ if (dependency.catalogName && dependency.effective &&
3454
+ isLocalPackageSpec(dependency.effective)) {
3455
+ catalogLinks.push(`pnpm-workspace.yaml catalog ${dependency.catalogName}: ${dependency.effective}`);
3456
+ }
3457
+ if (usesDenoTooling(tooling)) {
3458
+ const denoConfig = await getDenoConfigForLinks(cwd, tooling);
3459
+ for (const { dangling, link } of await findLoomDenoLinks(cwd, denoConfig)) {
3460
+ links.push(`${denoConfig} links: ${link}${dangling ? " (its package is gone; it may be Loom's)" : ""}`);
3461
+ }
3462
+ }
3463
+ return {
3464
+ catalogLinks,
3465
+ denoMode: usesDenoTooling(tooling),
3466
+ links,
3467
+ packageJson,
3468
+ };
3469
+ }
3470
+ /**
3471
+ * The published Loom version a Deno project's node_modules copy came from,
3472
+ * when deno.lock proves it: the lock records no Loom link, resolves the
3473
+ * project's `npm:@gadicc/loom@<pin>` specifier to a version installed from
3474
+ * the registry (its npm entry carries an integrity hash, which a linked
3475
+ * package's entry lacks), and node_modules holds that version. Null
3476
+ * otherwise, including without a deno.lock.
3477
+ */
3478
+ async function findInstalledDenoRegistryLoomVersion(cwd, packageJson) {
3479
+ const text = await readTextIfExists(join(cwd, "deno.lock"));
3480
+ if (!text || await denoLockLinksLoom(cwd))
3481
+ return null;
3482
+ let lock;
3483
+ try {
3484
+ lock = JSON.parse(text);
3485
+ }
3486
+ catch {
3487
+ return null;
3488
+ }
3489
+ const manifest = await readManifestIfExists(cwd);
3490
+ const tooling = await detectProjectTooling(cwd, manifest?.project?.tooling);
3491
+ const denoConfig = await getDenoConfigForLinks(cwd, tooling);
3492
+ const imports = parseJsonc(await readTextIfExists(join(cwd, denoConfig)) ?? "{}", denoConfig).imports ?? {};
3493
+ const pinned = [
3494
+ imports[LOOM_DEPENDENCY],
3495
+ packageJson.dependencies?.[LOOM_DEPENDENCY] &&
3496
+ `npm:${LOOM_DEPENDENCY}@${packageJson.dependencies[LOOM_DEPENDENCY]}`,
3497
+ ].find((spec) => typeof spec === "string" && spec.startsWith(`npm:${LOOM_DEPENDENCY}@`) &&
3498
+ lock.specifiers?.[spec] !== undefined);
3499
+ const resolved = pinned ? lock.specifiers[pinned] : undefined;
3500
+ if (!resolved)
3501
+ return null;
3502
+ const entry = lock.npm?.[`${LOOM_DEPENDENCY}@${resolved}`];
3503
+ if (typeof entry?.integrity !== "string")
3504
+ return null;
3505
+ const version = resolved.replace(/_.*$/, "");
3506
+ return await readPackageVersion(join(cwd, "node_modules", LOOM_DEPENDENCY)) ===
3507
+ version
3508
+ ? version
3509
+ : null;
3510
+ }
3511
+ /**
3512
+ * Why this project may still run local Loom code; empty only when it
3513
+ * provably does not. One predicate decides this for `loom dev published`
3514
+ * (whether to drop the sync record) and `loom check` (whether that record
3515
+ * is stale):
3516
+ * - any local Loom override, catalog entry or Deno link
3517
+ * ({@link findLocalLoomLinks});
3518
+ * - pnpm-lock.yaml resolving Loom locally, or deno.lock recording a Loom link;
3519
+ * - an installed node_modules/@gadicc/loom that is not provably the
3520
+ * published package: for pnpm, unless it is pnpm's registry store entry
3521
+ * ({@link findInstalledRegistryLoomVersion}); for Deno, any copy, since a
3522
+ * copied link looks like a registry install. A missing one is not
3523
+ * installed.
3524
+ * Errors while finding out count as in use. Loom reads overrides,
3525
+ * lockfiles and node_modules from this directory only, so a member of an
3526
+ * enclosing pnpm workspace, whose root holds them, always counts as in use.
3527
+ */
3528
+ async function findLocalLoomUse(cwd) {
3529
+ try {
3530
+ const { catalogLinks, denoMode, links, packageJson } = await findLocalLoomLinks(cwd);
3531
+ const uses = [...links, ...catalogLinks].map((reason) => ({
3532
+ kind: "link",
3533
+ reason,
3534
+ }));
3535
+ if (!denoMode && !await exists(join(cwd, "pnpm-workspace.yaml"))) {
3536
+ for (let parent = dirname(resolve(cwd)); parent !== dirname(parent); parent = dirname(parent)) {
3537
+ if (await exists(join(parent, "pnpm-workspace.yaml"))) {
3538
+ uses.push({
3539
+ kind: "workspace",
3540
+ reason: `this project is in the pnpm workspace at ${parent}, whose overrides and lockfile Loom does not read`,
3541
+ });
3542
+ break;
3543
+ }
3544
+ }
3545
+ }
3546
+ const lockfileText = await readTextIfExists(join(cwd, "pnpm-lock.yaml"));
3547
+ const lockfileResolution = lockfileText
3548
+ ? getLocalLoomLockfileResolution(lockfileText)
3549
+ : null;
3550
+ if (lockfileResolution) {
3551
+ uses.push({
3552
+ kind: "lockfile",
3553
+ reason: `pnpm-lock.yaml resolves Loom to ${lockfileResolution}`,
3554
+ });
3555
+ }
3556
+ if (await denoLockLinksLoom(cwd)) {
3557
+ uses.push({
3558
+ kind: "lockfile",
3559
+ reason: "deno.lock records a link for Loom",
3560
+ });
3561
+ }
3562
+ if (await exists(join(cwd, "node_modules", LOOM_DEPENDENCY, "package.json"))) {
3563
+ const proven = denoMode
3564
+ ? await findInstalledDenoRegistryLoomVersion(cwd, packageJson)
3565
+ : await findInstalledRegistryLoomVersion(cwd, lockfileText, (await readLocalDevState(cwd))?.localPackagePath);
3566
+ if (!proven) {
3567
+ uses.push({
3568
+ kind: "installed",
3569
+ reason: "node_modules/@gadicc/loom is not provably the published package",
3570
+ });
3571
+ }
3572
+ }
3573
+ return uses;
3574
+ }
3575
+ catch (error) {
3576
+ return [{
3577
+ kind: "error",
3578
+ reason: `Loom could not tell whether local Loom is in use: ${error.message}`,
3579
+ }];
3580
+ }
3581
+ }
3211
3582
  /** The project's active local Loom link, read from its current files. */
3212
3583
  async function detectLocalDevLink(cwd) {
3213
3584
  const manifest = await readManifestIfExists(cwd);
@@ -3607,7 +3978,7 @@ async function findInstalledRegistryLoomVersion(cwd, lockfileText, localBuild) {
3607
3978
  entry.startsWith(`${registryEntry}(`))) {
3608
3979
  return null;
3609
3980
  }
3610
- if (await exists(join(localBuild, "package.json")) &&
3981
+ if (localBuild && await exists(join(localBuild, "package.json")) &&
3611
3982
  await findInstalledLocalLoomDifference(cwd, localBuild) === null) {
3612
3983
  return null;
3613
3984
  }
@@ -3630,16 +4001,9 @@ async function collectLocalLoomTargets(cwd, project) {
3630
4001
  };
3631
4002
  const denoLinks = [];
3632
4003
  if (project.denoConfig) {
3633
- const recorded = await readLocalDevState(cwd);
3634
- const recordedPath = recorded?.localPackagePath
3635
- ? resolve(cwd, recorded.localPackagePath)
3636
- : null;
3637
- for (const link of await readDenoLinks(cwd, project.denoConfig)) {
3638
- const path = resolve(cwd, link);
3639
- if (await findLocalLoomDenoLink(cwd, [link]) || path === recordedPath) {
3640
- denoLinks.push(link);
3641
- await add(path, `${project.denoConfig} links ${link}`);
3642
- }
4004
+ for (const { link, path } of await findLoomDenoLinks(cwd, project.denoConfig)) {
4005
+ denoLinks.push(link);
4006
+ await add(path, `${project.denoConfig} links ${link}`);
3643
4007
  }
3644
4008
  return { denoLinks, targets: [...targets.values()] };
3645
4009
  }
@@ -3648,6 +4012,9 @@ async function collectLocalLoomTargets(cwd, project) {
3648
4012
  await add(localSpecToPath(cwd, workspaceSpec), "the pnpm-workspace.yaml override");
3649
4013
  }
3650
4014
  for (const { key, spec } of getUnmanagedPnpmWorkspaceLoomOverrides(project.workspaceText)) {
4015
+ if (spec.startsWith("workspace:")) {
4016
+ 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 ${LOOM_DEPENDENCY} instead.`);
4017
+ }
3651
4018
  await add(localSpecToPath(cwd, spec), `the pnpm-workspace.yaml overrides entry for ${key}`);
3652
4019
  }
3653
4020
  for (const { location, spec } of getPackageJsonLocalLoomOverrides(project.packageJson)) {
@@ -3677,7 +4044,9 @@ async function proveLocalLoomBuildPublished(cwd, target, options) {
3677
4044
  const lockfileOnly = target.sources.every((source) => source === "pnpm-lock.yaml");
3678
4045
  throw new Error(`${path}, which ${target.sources.join(" and ")} point${target.sources.length === 1 ? "s" : ""} at, holds no built Loom package. ${lockfileOnly
3679
4046
  ? "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`"
3680
- : "Restore that Loom checkout and run `loom dev sync`, or link another with `loom dev local`"}, ${rerun}.`);
4047
+ : options.denoConfig
4048
+ ? `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\``
4049
+ : "Restore that Loom checkout and run `loom dev sync`, or link another with `loom dev local`"}, ${rerun}.`);
3681
4050
  }
3682
4051
  const stamp = await readLoomBuildStamp(path);
3683
4052
  if (stamp?.legacyBuildFingerprint && !hasLoomBuildProvenance(stamp)) {
@@ -3800,8 +4169,17 @@ async function usePublishedDevPackageLocked(cwd, options) {
3800
4169
  lockfileText,
3801
4170
  preferredSpec: publishedSpec,
3802
4171
  });
3803
- publishedSpec = proof.publication.version;
3804
4172
  notes.push(proof.note);
4173
+ // Never move an exact pin back: a checkout without the newest tags names
4174
+ // the oldest release it knows that covers the build, and a newer pin
4175
+ // (Loom releases only from main) covers it too.
4176
+ if (isExactSemverVersion(publishedSpec) &&
4177
+ isNewerLoomVersion(publishedSpec, proof.publication.version)) {
4178
+ notes.push(`The pinned ${LOOM_DEPENDENCY}@${publishedSpec} is newer than ${proof.publication.version}, so the pin stays at ${publishedSpec}.`);
4179
+ }
4180
+ else {
4181
+ publishedSpec = proof.publication.version;
4182
+ }
3805
4183
  }
3806
4184
  const changedFiles = [];
3807
4185
  let catalogChanged = false;
@@ -3905,6 +4283,14 @@ async function usePublishedDevPackageLocked(cwd, options) {
3905
4283
  }
3906
4284
  }
3907
4285
  }
4286
+ // Once nothing local can be in use, the sync record describes code the app
4287
+ // no longer runs; kept, `loom check` would go on checking a commit in a
4288
+ // checkout that may since be gone. Until then (typically until the
4289
+ // `pnpm install` this command asks for), it stays. Created-map flags were
4290
+ // cleared above.
4291
+ if ((await findLocalLoomUse(cwd)).length === 0) {
4292
+ await rm(join(cwd, LOOM_LOCAL_DEV_STATE_RELATIVE_PATH), { force: true });
4293
+ }
3908
4294
  return {
3909
4295
  changedFiles,
3910
4296
  notes,
@@ -4213,17 +4599,15 @@ async function checkManagedLocalDevOverride(cwd, production, commandRunner, env)
4213
4599
  // The main project tooling check reports invalid configuration separately.
4214
4600
  }
4215
4601
  const workspaceText = await readTextIfExists(join(cwd, "pnpm-workspace.yaml"));
4216
- const packageJson = denoLink ? null : await readPackageJsonIfExists(cwd);
4217
- const workspaceSpec = getManagedDevOverrideSpec(workspaceText);
4218
- // Any local spec for Loom in a package.json override map is a local-dev
4219
- // link, whoever wrote it and whatever selector it uses, and must not ship.
4220
- const packageJsonOverride = packageJson
4221
- ? PACKAGE_JSON_OVERRIDE_LOCATIONS.flatMap(({ field, location }) => Object.entries(getPackageJsonOverrideMap(packageJson, field)).flatMap(([key, spec]) => overrideKeyTargetsLoom(key) && typeof spec === "string" &&
4222
- isLocalPackageSpec(spec)
4223
- ? [`${formatPnpmOverrideLocation(location)}: ${spec}`]
4224
- : []))[0]
4225
- : undefined;
4226
- if (!workspaceSpec && !packageJsonOverride && !denoLink) {
4602
+ const denoMode = denoConfig !== null;
4603
+ const packageJson = denoMode ? null : await readPackageJsonIfExists(cwd);
4604
+ // Any local spec for Loom in an override map, whoever wrote it and
4605
+ // whatever selector it uses, is a local-dev link and must not ship; so is
4606
+ // a Deno link to Loom, even one whose package is gone. The same finder
4607
+ // decides whether a sync record is stale. A local catalog entry has its
4608
+ // own, clearer issue.
4609
+ const links = await findLocalLoomLinks(cwd).then((found) => found.links, () => []);
4610
+ if (!links.length && !denoLink) {
4227
4611
  return {
4228
4612
  issues: [],
4229
4613
  suggestions: [],
@@ -4232,10 +4616,8 @@ async function checkManagedLocalDevOverride(cwd, production, commandRunner, env)
4232
4616
  }
4233
4617
  const location = denoLink
4234
4618
  ? `${denoConfig} links: ${denoLink.link}`
4235
- : workspaceSpec
4236
- ? `pnpm-workspace.yaml: ${workspaceSpec}`
4237
- : packageJsonOverride;
4238
- const restore = denoLink
4619
+ : links[0];
4620
+ const restore = denoMode
4239
4621
  ? "Run `loom dev published`, then run `deno install` before committing or shipping a published build."
4240
4622
  : "Run `loom dev published`, then run `pnpm install` (or the command it prints) before committing or shipping a published build.";
4241
4623
  const warnings = [];
@@ -4358,10 +4740,46 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
4358
4740
  addReleaseCheckMessage(issues, warnings, production, `pnpm-lock.yaml resolves @gadicc/loom to a local package: ${localLockfileResolution}`);
4359
4741
  suggestions.add("Run `loom dev published`, then refresh the lockfile with the published @gadicc/loom version before production build.");
4360
4742
  }
4361
- if (devState?.sourceCommit) {
4743
+ // The sync record only matters while the app can still run local Loom
4744
+ // code. Without a link, an override or a local lockfile resolution, the
4745
+ // app runs a published Loom, and the record (perhaps naming a checkout
4746
+ // that is gone) is stale.
4747
+ const localLoomUses = await findLocalLoomUse(cwd);
4748
+ const localLoomInUse = localLoomUses.length > 0;
4749
+ // Only an installed copy Loom cannot prove published, with no link or
4750
+ // lockfile pointing at local Loom, is too weak to fail a release by
4751
+ // itself: the record's findings stay warnings then.
4752
+ const recordGatesRelease = production &&
4753
+ localLoomUses.some((use) => use.kind !== "installed");
4754
+ if (devState?.sourceCommit && !localLoomInUse) {
4755
+ const shortCommit = devState.sourceCommit.slice(0, 12);
4756
+ warnings.push(`${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.`);
4757
+ // The app may still rely on what that sync contained: advise, never
4758
+ // fail, when a newer release covers it than the app pins. A checkout
4759
+ // that is gone is not looked up at all.
4760
+ if (devState.sourceRoot && !devState.sourceDirty &&
4761
+ dependency && isExactSemverVersion(dependency) &&
4762
+ await exists(devState.sourceRoot)) {
4763
+ const publication = await resolveLoomCommitPublication(devState.sourceRoot, devState.sourceCommit, options.commandRunner, options.env, dependency);
4764
+ if (publication.status === "published" &&
4765
+ isNewerLoomVersion(publication.version, dependency)) {
4766
+ warnings.push(`This app was last synced against Loom commit ${shortCommit}; ${publication.reason === "package-equivalent"
4767
+ ? `package-relevant files match ${LOOM_DEPENDENCY}@${publication.version}`
4768
+ : `it is published as ${LOOM_DEPENDENCY}@${publication.version}`}, but ${pinLocation} is pinned to ${dependency}.`);
4769
+ suggestions.add(pinSuggestion(publication.version));
4770
+ }
4771
+ }
4772
+ }
4773
+ else if (devState?.sourceCommit && devState.sourceRoot &&
4774
+ !devState.sourceDirty && !await exists(devState.sourceRoot)) {
4775
+ // A deleted checkout is not evidence of unpublished code; the active
4776
+ // link or lockfile already fails the release check on its own.
4777
+ 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.`);
4778
+ }
4779
+ else if (devState?.sourceCommit) {
4362
4780
  const shortCommit = devState.sourceCommit.slice(0, 12);
4363
4781
  if (devState.sourceDirty) {
4364
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit} with a dirty source tree.`);
4782
+ addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit} with a dirty source tree.`);
4365
4783
  suggestions.add("Commit or discard the Loom changes, rerun `loom dev sync`, and publish Loom if the app depends on those changes.");
4366
4784
  }
4367
4785
  else if (!devState.sourceRoot) {
@@ -4371,21 +4789,29 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
4371
4789
  const publication = await resolveLoomCommitPublication(devState.sourceRoot, devState.sourceCommit, options.commandRunner, options.env, isExactSemverVersion(dependency ?? "") ? dependency : undefined);
4372
4790
  switch (publication.status) {
4373
4791
  case "not-on-origin-main":
4374
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}, which is not reachable from origin/main.`);
4792
+ addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit}, which is not reachable from origin/main.`);
4375
4793
  suggestions.add("Push or merge the Loom changes, fetch origin/main, publish Loom if needed, then rerun `loom dev published`.");
4376
4794
  break;
4377
4795
  case "no-release-tag":
4378
- 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.`);
4796
+ 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.`);
4379
4797
  suggestions.add("Publish Loom first, fetch tags, then rerun `loom dev published`.");
4380
4798
  break;
4381
- case "published":
4382
- if (dependency && isExactSemverVersion(dependency) &&
4383
- dependency !== publication.version) {
4799
+ case "published": {
4800
+ // Advice only ever moves the pin forward. A checkout without the
4801
+ // newest tags reports the oldest release it knows that contains
4802
+ // the commit; an exact pin newer than that covers it too.
4803
+ const pinCovers = !!dependency &&
4804
+ isExactSemverVersion(dependency) &&
4805
+ !isNewerLoomVersion(publication.version, dependency);
4806
+ const coveringVersion = pinCovers && dependency
4807
+ ? dependency
4808
+ : publication.version;
4809
+ if (dependency && isExactSemverVersion(dependency) && !pinCovers) {
4384
4810
  const publicationDescription = publication.reason ===
4385
4811
  "package-equivalent"
4386
4812
  ? `package-relevant files match ${LOOM_DEPENDENCY}@${publication.version}`
4387
4813
  : `it is published as ${LOOM_DEPENDENCY}@${publication.version}`;
4388
- addReleaseCheckMessage(issues, warnings, production, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${pinLocation} is pinned to ${dependency}.`);
4814
+ addReleaseCheckMessage(issues, warnings, recordGatesRelease, `This app was last synced against Loom commit ${shortCommit}; ${publicationDescription}, but ${pinLocation} is pinned to ${dependency}.`);
4389
4815
  suggestions.add(pnpmOverrideActive
4390
4816
  ? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
4391
4817
  : pinSuggestion(publication.version));
@@ -4395,16 +4821,20 @@ async function checkLoomReleaseState(cwd, packageJson, options) {
4395
4821
  "package-equivalent"
4396
4822
  ? `has no package-relevant changes after ${publication.tag}, so ${LOOM_DEPENDENCY}@${publication.version} covers it`
4397
4823
  : `is published as ${LOOM_DEPENDENCY}@${publication.version}`;
4398
- warnings.push(`The synced Loom commit ${shortCommit} ${publicationDescription}; refresh the lockfile away from ${localLockfileResolution}.`);
4824
+ const newerPin = coveringVersion !== publication.version
4825
+ ? ` (the pinned ${coveringVersion} is newer)`
4826
+ : "";
4827
+ warnings.push(`The synced Loom commit ${shortCommit} ${publicationDescription}${newerPin}; refresh the lockfile away from ${localLockfileResolution}.`);
4399
4828
  suggestions.add(pnpmOverrideActive
4400
4829
  ? "Run `loom dev published`, which pins the covering version, then run `pnpm install`."
4401
- : catalogName && dependency === publication.version
4830
+ : catalogName && dependency === coveringVersion
4402
4831
  // pnpm keeps a local resolution while the catalog version
4403
4832
  // it was linked under is unchanged.
4404
4833
  ? "Restore pnpm-lock.yaml from git and run `pnpm install`."
4405
- : pinSuggestion(publication.version));
4834
+ : pinSuggestion(coveringVersion));
4406
4835
  }
4407
4836
  break;
4837
+ }
4408
4838
  }
4409
4839
  }
4410
4840
  }
@@ -5483,9 +5913,16 @@ function getJobsExpectedScripts(config) {
5483
5913
  job: `TSX_TSCONFIG=./${JOBS_SCRIPTS_TSCONFIG_PATH} loom env -- node --conditions=react-server --import tsx ${config.directRunner.scriptPath}`,
5484
5914
  };
5485
5915
  }
5486
- function jobsDirectRunnerTemplate(config, framework) {
5916
+ function getJobsManagedTasks(config) {
5917
+ const legacy = legacyJobsTaskValues(JOBS_SCRIPTS_TSCONFIG_PATH, config.directRunner.scriptPath);
5918
+ return Object.entries(getJobsExpectedScripts(config)).map(([name, definition]) => ({ definition, knownValues: legacy[name] ?? [], name }));
5919
+ }
5920
+ function getJobsDirectRunnerCatalogImportPath(config, framework) {
5487
5921
  const jobsRoot = framework.srcDir ? "src/jobs" : "jobs";
5488
- const catalogImportPath = toRelativeImportPath(config.directRunner.scriptPath, `${jobsRoot}/index.ts`);
5922
+ return toRelativeImportPath(config.directRunner.scriptPath, `${jobsRoot}/index.ts`);
5923
+ }
5924
+ function jobsDirectRunnerTemplate(config, framework) {
5925
+ const catalogImportPath = getJobsDirectRunnerCatalogImportPath(config, framework);
5489
5926
  return `import {
5490
5927
  createJobCatalogFromSource,
5491
5928
  createJobExecution,
@@ -5615,24 +6052,64 @@ function jobsThinRouteTemplate(source) {
5615
6052
  export const maxDuration = ${DEFAULT_JOBS_MAX_DURATION_SECONDS};
5616
6053
  `;
5617
6054
  }
5618
- function jobsStaticRouteTemplate(config, moduleSpecifier, maxDuration) {
5619
- if (!config.staticRoutes) {
5620
- throw new Error("Static jobs route config is required");
5621
- }
6055
+ function renderJobsStaticRoute(values) {
5622
6056
  return `${LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER}
5623
6057
  // Generated by \`loom add jobs\` from loom.json. Do not edit directly.
5624
6058
 
5625
- import { ${config.staticRoutes.handlerFactoryExport} } from "${toAliasImportPath(config.modules.routeModule)}";
5626
- import * as job from "${moduleSpecifier}";
6059
+ import { ${values.handlerFactoryExport} } from "${values.routeModuleSpecifier}";
6060
+ import * as job from "${values.moduleSpecifier}";
5627
6061
 
5628
6062
  // Next.js route segment config must be a direct, statically analyzable export.
5629
- export const maxDuration = ${maxDuration};
6063
+ export const maxDuration = ${values.maxDuration};
5630
6064
 
5631
- const handler = ${config.staticRoutes.handlerFactoryExport}(job);
6065
+ const handler = ${values.handlerFactoryExport}(job);
5632
6066
 
5633
6067
  export { handler as GET, handler as POST };
5634
6068
  `;
5635
6069
  }
6070
+ function jobsStaticRouteTemplate(config, moduleSpecifier, maxDuration) {
6071
+ if (!config.staticRoutes) {
6072
+ throw new Error("Static jobs route config is required");
6073
+ }
6074
+ return renderJobsStaticRoute({
6075
+ handlerFactoryExport: config.staticRoutes.handlerFactoryExport,
6076
+ maxDuration,
6077
+ moduleSpecifier,
6078
+ routeModuleSpecifier: toAliasImportPath(config.modules.routeModule),
6079
+ });
6080
+ }
6081
+ /**
6082
+ * Whether a marked static job route is exactly Loom's template for the
6083
+ * configured handler factory and route module, with any job module and
6084
+ * `maxDuration`. Those two values come from loom.json, so such a route is
6085
+ * stale Loom output that Loom may update or remove. A different factory or
6086
+ * route module (an audited wrapper, say), or any other edit, makes the file
6087
+ * the app's. This only covers routes from before Loom recorded their hashes.
6088
+ */
6089
+ function isLoomJobsStaticRoute(text, config) {
6090
+ if (!config.staticRoutes)
6091
+ return false;
6092
+ if (!text.startsWith(LOOM_MANAGED_STATIC_JOB_ROUTE_MARKER))
6093
+ return false;
6094
+ const job = text.match(/import\s*\*\s*as\s+job\s+from\s*["']([^"']+)["']/);
6095
+ const maxDuration = text.match(/export\s+const\s+maxDuration\s*=\s*(\d+)/);
6096
+ if (!job || !maxDuration)
6097
+ return false;
6098
+ return hashManagedFileText(text) ===
6099
+ hashManagedFileText(renderJobsStaticRoute({
6100
+ handlerFactoryExport: config.staticRoutes.handlerFactoryExport,
6101
+ maxDuration: Number(maxDuration[1]),
6102
+ moduleSpecifier: job[1],
6103
+ routeModuleSpecifier: toAliasImportPath(config.modules.routeModule),
6104
+ }));
6105
+ }
6106
+ function jobsStaticRouteProof(config, feature, relativePath) {
6107
+ return {
6108
+ isLoomOutput: (text) => isLoomJobsStaticRoute(text, config),
6109
+ recordedHash: recordedManagedFileHash(feature, relativePath),
6110
+ };
6111
+ }
6112
+ 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.`;
5636
6113
  function assertPositiveJobsMaxDuration(value, label) {
5637
6114
  if (!Number.isInteger(value) || value <= 0) {
5638
6115
  throw new Error(`${label} must be a positive integer`);
@@ -5700,11 +6177,12 @@ async function findManagedJobsStaticRoutePaths(cwd, config) {
5700
6177
  }
5701
6178
  return managedPaths;
5702
6179
  }
5703
- async function syncJobsStaticRoutes(cwd, config) {
6180
+ async function syncJobsStaticRoutes(cwd, config, feature) {
5704
6181
  const changedFiles = [];
5705
6182
  const notes = [];
6183
+ const records = {};
5706
6184
  if (!config.staticRoutes)
5707
- return { changedFiles, notes };
6185
+ return { changedFiles, notes, records };
5708
6186
  const plans = getJobsStaticRoutePlans(cwd, config);
5709
6187
  const expectedPaths = new Set(plans.map((plan) => plan.path));
5710
6188
  for (const plan of plans) {
@@ -5714,21 +6192,33 @@ async function syncJobsStaticRoutes(cwd, config) {
5714
6192
  notes.push(`Preserved unmanaged jobs static route file: ${plan.relativePath}`);
5715
6193
  continue;
5716
6194
  }
5717
- if (await writeTextIfChanged(plan.path, plan.text)) {
6195
+ const result = await syncManagedFile(plan.path, plan.text, jobsStaticRouteProof(config, feature, plan.relativePath));
6196
+ recordManagedFileSync(records, feature, plan.relativePath, result);
6197
+ if (result.state === "created" || result.state === "updated") {
5718
6198
  changedFiles.push(plan.relativePath);
5719
6199
  }
6200
+ else if (result.state === "customized") {
6201
+ notes.push(formatPreservedManagedFileNote(plan.relativePath, result.difference, JOBS_STATIC_ROUTE_EDIT_RESOLUTION));
6202
+ }
5720
6203
  }
5721
6204
  for (const routePath of await findManagedJobsStaticRoutePaths(cwd, config)) {
5722
6205
  if (expectedPaths.has(routePath))
5723
6206
  continue;
5724
- await rm(routePath);
6207
+ const relativePath = relative(cwd, routePath).replaceAll("\\", "/");
6208
+ const removal = await removeManagedFile(routePath, jobsStaticRouteProof(config, feature, relativePath));
6209
+ if (removal === "customized") {
6210
+ 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.`);
6211
+ continue;
6212
+ }
6213
+ if (removal !== "removed")
6214
+ continue;
5725
6215
  const routeDirectory = dirname(routePath);
5726
6216
  if ((await readdir(routeDirectory)).length === 0) {
5727
6217
  await rm(routeDirectory, { recursive: true });
5728
6218
  }
5729
- changedFiles.push(relative(cwd, routePath).replaceAll("\\", "/"));
6219
+ changedFiles.push(relativePath);
5730
6220
  }
5731
- return { changedFiles, notes };
6221
+ return { changedFiles, notes, records };
5732
6222
  }
5733
6223
  function pwaSerwistConfigTemplate(config) {
5734
6224
  return `import { serwist } from "@serwist/next/config";
@@ -5783,6 +6273,7 @@ function pwaLifecyclePropLines(config) {
5783
6273
  : ` updateCheckIntervalMs={${formatTsNumberLiteral(config.updateCheckIntervalMs)}}`,
5784
6274
  ].filter((line) => line !== null);
5785
6275
  }
6276
+ 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`.";
5786
6277
  function pwaClientProviderTemplate(config) {
5787
6278
  const lifecyclePropLines = pwaLifecyclePropLines(config);
5788
6279
  const headlessLifecycle = lifecyclePropLines.length
@@ -5907,6 +6398,57 @@ afterAll(closeMemoryPglite);
5907
6398
  export const { client, db, tableLoader } = harness;
5908
6399
  `;
5909
6400
  }
6401
+ function getDbManagedFiles(config, testRunner, tooling) {
6402
+ const schemaImportPath = toRelativeImportPath(config.modules.pgliteHarnessModule, join(config.dirs.schemaDir, "index.ts"));
6403
+ return [
6404
+ {
6405
+ knownOutputs: [],
6406
+ mismatch: "DB neon module does not match the Loom-managed wrapper",
6407
+ relativePath: config.modules.neonModule,
6408
+ text: dbNeonTemplate(),
6409
+ },
6410
+ {
6411
+ knownOutputs: [],
6412
+ mismatch: "DB neonFull module does not match the Loom-managed wrapper",
6413
+ relativePath: config.modules.neonFullModule,
6414
+ text: dbNeonFullTemplate(),
6415
+ },
6416
+ {
6417
+ knownOutputs: [],
6418
+ mismatch: "Drizzle config does not match the Loom-managed wrapper",
6419
+ relativePath: config.modules.drizzleConfig,
6420
+ text: dbDrizzleConfigTemplate(config),
6421
+ },
6422
+ {
6423
+ knownOutputs: [
6424
+ // With Deno tasks the harness follows whether the `test` task runs
6425
+ // vitest, which can change, so either runner's harness may be what
6426
+ // Loom wrote. Other runners only ever got the vitest harness.
6427
+ ...(tooling.tasks.runner === "deno"
6428
+ ? [
6429
+ dbPgliteHarnessTemplate(config, testRunner === "deno" ? "vitest" : "deno"),
6430
+ ]
6431
+ : []),
6432
+ ...legacyDbPgliteHarnessOutputs(schemaImportPath, config.dirs.fixtureDir),
6433
+ ],
6434
+ mismatch: "PGlite test harness does not match the Loom-managed wrapper",
6435
+ relativePath: config.modules.pgliteHarnessModule,
6436
+ text: dbPgliteHarnessTemplate(config, testRunner),
6437
+ },
6438
+ {
6439
+ knownOutputs: [],
6440
+ mismatch: "DB scripts tsconfig does not match the Loom-managed template",
6441
+ relativePath: config.modules.scriptsTsconfig,
6442
+ text: dbScriptsTsconfigTemplate(),
6443
+ },
6444
+ {
6445
+ knownOutputs: [],
6446
+ mismatch: "Valibot refinements common module does not match the Loom-managed wrapper",
6447
+ relativePath: config.modules.refinementsCommonModule,
6448
+ text: dbRefinementsCommonTemplate(),
6449
+ },
6450
+ ];
6451
+ }
5910
6452
  async function getDbTestRunner(cwd, tooling) {
5911
6453
  if (tooling.tasks.runner !== "deno")
5912
6454
  return "vitest";
@@ -6224,6 +6766,29 @@ function isGeneratedFilesStorageStub(text) {
6224
6766
  "storageNotConfigured();",
6225
6767
  ].every((part) => text.includes(part));
6226
6768
  }
6769
+ /**
6770
+ * Installs the S3 storage adapter in place of the generated not-configured
6771
+ * stub, but only while the stub is exactly Loom's scaffold: an edited stub is
6772
+ * the app's and stays.
6773
+ */
6774
+ async function replaceFilesStorageStub(storagePath, relativePath) {
6775
+ const stub = filesStorageTemplate();
6776
+ const result = await syncManagedFile(storagePath, filesS3StorageTemplate(), {
6777
+ knownOutputs: [stub],
6778
+ });
6779
+ if (result.state !== "customized") {
6780
+ return {
6781
+ changed: result.state === "created" || result.state === "updated",
6782
+ note: null,
6783
+ };
6784
+ }
6785
+ // The edits that matter are the app's changes to Loom's stub.
6786
+ const currentText = await readTextIfExists(storagePath) ?? "";
6787
+ return {
6788
+ changed: false,
6789
+ note: formatPreservedManagedFileNote(relativePath, 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."),
6790
+ };
6791
+ }
6227
6792
  function filesRouteTemplate(config) {
6228
6793
  return `import { createFilesRouteHandlers } from "@gadicc/loom/next/files";
6229
6794
  import {
@@ -6830,14 +7395,88 @@ function buildValibotBarrelText(generatedNames, refinementNames) {
6830
7395
  ? `export * from "./refinements/${name}";`
6831
7396
  : `export * from "./generated/${name}";`).join("\n")}\n`;
6832
7397
  }
6833
- async function syncValibotBarrel(cwd, config) {
7398
+ const VALIBOT_BARREL_LINE = /^export\s*\*\s*from\s*["']\.\/(generated|refinements)\/([^"']+)["']\s*;?$/;
7399
+ async function directoryHasModule(directory, name) {
7400
+ try {
7401
+ return (await readdir(directory)).some((entry) => entry === name || stripModuleExtension(entry) === name);
7402
+ }
7403
+ catch (error) {
7404
+ if (isNodeErrorCode(error, "ENOENT"))
7405
+ return false;
7406
+ throw error;
7407
+ }
7408
+ }
7409
+ /**
7410
+ * Whether a valibot barrel holds only export lines Loom generates, so it can
7411
+ * be rebuilt without losing a hand-written export. Loom exports each `.ts`
7412
+ * module of the generated and refinement directories except `index` and
7413
+ * `_`-prefixed ones, once each, and a refinement replaces the generated
7414
+ * module of the same name. So a `./generated/<name>` line beside a
7415
+ * `./refinements/<name>` line was added by hand, while one without it is
7416
+ * what Loom wrote before that refinement existed. A line for a module that
7417
+ * no longer exists is stale Loom output; a line for another module that does
7418
+ * exist was added by hand.
7419
+ */
7420
+ async function isLoomValibotBarrel(cwd, config, text, generatedNames, refinementNames) {
7421
+ const lines = [];
7422
+ const seen = new Set();
7423
+ for (const line of normalizeText(text).split("\n")) {
7424
+ const trimmed = line.trim();
7425
+ if (!trimmed)
7426
+ continue;
7427
+ const match = trimmed.match(VALIBOT_BARREL_LINE);
7428
+ if (!match)
7429
+ return false;
7430
+ const [, kind, name] = match;
7431
+ if (name === "index" || name.startsWith("_") || name.includes("/")) {
7432
+ return false;
7433
+ }
7434
+ const key = `${kind}/${name}`;
7435
+ if (seen.has(key))
7436
+ return false;
7437
+ seen.add(key);
7438
+ lines.push({ kind, name });
7439
+ }
7440
+ for (const { kind, name } of lines) {
7441
+ if (kind === "refinements" && refinementNames.includes(name))
7442
+ continue;
7443
+ if (kind === "generated" && generatedNames.includes(name)) {
7444
+ if (refinementNames.includes(name) && seen.has(`refinements/${name}`)) {
7445
+ return false;
7446
+ }
7447
+ continue;
7448
+ }
7449
+ const directory = kind === "generated"
7450
+ ? config.dirs.valibotGeneratedDir
7451
+ : config.dirs.valibotRefinementsDir;
7452
+ if (await directoryHasModule(join(cwd, directory), name))
7453
+ return false;
7454
+ }
7455
+ return true;
7456
+ }
7457
+ async function readValibotBarrelState(cwd, config) {
6834
7458
  const generatedNames = await readTsModuleNames(join(cwd, config.dirs.valibotGeneratedDir));
6835
7459
  const refinementNames = await readTsModuleNames(join(cwd, config.dirs.valibotRefinementsDir));
6836
- const text = buildValibotBarrelText(generatedNames, refinementNames);
6837
- if (!text) {
6838
- return false;
7460
+ const proof = {
7461
+ isLoomOutput: (text) => isLoomValibotBarrel(cwd, config, text, generatedNames, refinementNames),
7462
+ };
7463
+ return {
7464
+ proof,
7465
+ text: buildValibotBarrelText(generatedNames, refinementNames),
7466
+ };
7467
+ }
7468
+ async function syncValibotBarrel(cwd, config) {
7469
+ const barrel = await readValibotBarrelState(cwd, config);
7470
+ if (!barrel.text) {
7471
+ return { changed: false, note: null };
6839
7472
  }
6840
- return await writeTextIfChanged(join(cwd, config.modules.valibotBarrelModule), text);
7473
+ const result = await syncManagedFile(join(cwd, config.modules.valibotBarrelModule), barrel.text, barrel.proof);
7474
+ return {
7475
+ changed: result.state === "created" || result.state === "updated",
7476
+ note: result.state === "customized"
7477
+ ? 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.")
7478
+ : null,
7479
+ };
6841
7480
  }
6842
7481
  function getLatestManagedSchemaConfig(schema) {
6843
7482
  const latest = {
@@ -7062,8 +7701,7 @@ export async function syncDbSchemas(cwd) {
7062
7701
  (!mailFeature || mailFeature.status !== "active")) {
7063
7702
  notes.push("No active Loom-managed DB schemas are configured.");
7064
7703
  }
7065
- const manifestPath = join(cwd, "loom.json");
7066
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
7704
+ if (await writeManifestIfChanged(cwd, manifest)) {
7067
7705
  changedFiles.push("loom.json");
7068
7706
  }
7069
7707
  if (changedFiles.length) {
@@ -7093,8 +7731,7 @@ export async function configureFilesIdGeneration(cwd, idGeneration) {
7093
7731
  const config = getFilesConfig(framework, dbConfig, filesFeature.config);
7094
7732
  config.schema.idGeneration = idGeneration;
7095
7733
  filesFeature.config = config;
7096
- const nextText = stringifyJson(manifest);
7097
- const changedFiles = await writeTextIfChanged(manifestPath, nextText)
7734
+ const changedFiles = await writeManifestIfChanged(cwd, manifest)
7098
7735
  ? ["loom.json"]
7099
7736
  : [];
7100
7737
  return {
@@ -7773,9 +8410,12 @@ export async function setupLocalFiles(cwd, options = {}) {
7773
8410
  notes.push(`Run ${tooling.dependencies.manager} install to update the dependency lockfile.`);
7774
8411
  }
7775
8412
  if (!storageText || isGeneratedFilesStorageStub(storageText)) {
7776
- if (await writeTextIfChanged(storagePath, filesS3StorageTemplate())) {
8413
+ const storageUpdate = await replaceFilesStorageStub(storagePath, config.modules.storageModule);
8414
+ if (storageUpdate.changed) {
7777
8415
  changedFiles.push(config.modules.storageModule);
7778
8416
  }
8417
+ if (storageUpdate.note)
8418
+ notes.push(storageUpdate.note);
7779
8419
  }
7780
8420
  config.storage.adapter = "s3";
7781
8421
  if (config.storage.provider) {
@@ -7786,7 +8426,7 @@ export async function setupLocalFiles(cwd, options = {}) {
7786
8426
  };
7787
8427
  }
7788
8428
  feature.config = config;
7789
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
8429
+ if (await writeManifestIfChanged(cwd, manifest)) {
7790
8430
  changedFiles.push("loom.json");
7791
8431
  }
7792
8432
  return {
@@ -8038,7 +8678,7 @@ export async function setupCloudflareR2(cwd, options = {}) {
8038
8678
  };
8039
8679
  feature.config = config;
8040
8680
  manifest.features.files = feature;
8041
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
8681
+ if (await writeManifestIfChanged(cwd, manifest)) {
8042
8682
  changedFiles.push("loom.json");
8043
8683
  }
8044
8684
  for (const bucket of new Set(Object.values(buckets))) {
@@ -8068,9 +8708,12 @@ export async function setupCloudflareR2(cwd, options = {}) {
8068
8708
  const storagePath = join(cwd, config.modules.storageModule);
8069
8709
  const storageText = await readTextIfExists(storagePath);
8070
8710
  if (!storageText || isGeneratedFilesStorageStub(storageText)) {
8071
- if (await writeTextIfChanged(storagePath, filesS3StorageTemplate())) {
8711
+ const storageUpdate = await replaceFilesStorageStub(storagePath, config.modules.storageModule);
8712
+ if (storageUpdate.changed) {
8072
8713
  changedFiles.push(config.modules.storageModule);
8073
8714
  }
8715
+ if (storageUpdate.note)
8716
+ notes.push(storageUpdate.note);
8074
8717
  }
8075
8718
  else if (!storageText.includes("@gadicc/loom/files/s3")) {
8076
8719
  notes.push(`Preserved customized storage module ${config.modules.storageModule}; wire it to the canonical FILES_S3_* variables manually.`);
@@ -8163,7 +8806,7 @@ export async function setupCloudflareR2(cwd, options = {}) {
8163
8806
  catch (error) {
8164
8807
  config.storage.provider.connectionStatus = "partial";
8165
8808
  feature.config = config;
8166
- await writeTextIfChanged(manifestPath, stringifyJson(manifest));
8809
+ await writeManifestIfChanged(cwd, manifest);
8167
8810
  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.`);
8168
8811
  }
8169
8812
  const secretsConfigured = FILES_R2_ENVIRONMENTS.every((environment) => ["FILES_S3_ACCESS_KEY_ID", "FILES_S3_SECRET_ACCESS_KEY"].every((name) => hasExactEnvName(envListings.get(environment) ?? "", name)));
@@ -8173,7 +8816,7 @@ export async function setupCloudflareR2(cwd, options = {}) {
8173
8816
  ? "configured"
8174
8817
  : "credentials-required";
8175
8818
  feature.config = config;
8176
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
8819
+ if (await writeManifestIfChanged(cwd, manifest)) {
8177
8820
  if (!changedFiles.includes("loom.json"))
8178
8821
  changedFiles.push("loom.json");
8179
8822
  }
@@ -9298,7 +9941,7 @@ export async function setupVercelNeon(cwd, options = {}) {
9298
9941
  recordNeonProviderConfig(feature, framework, resourceName, "connected", undefined, options.region);
9299
9942
  manifest.features.db = feature;
9300
9943
  const changedFiles = [];
9301
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
9944
+ if (await writeManifestIfChanged(cwd, manifest)) {
9302
9945
  changedFiles.push("loom.json");
9303
9946
  }
9304
9947
  return {
@@ -9317,7 +9960,7 @@ export async function setupVercelNeon(cwd, options = {}) {
9317
9960
  recordNeonProviderConfig(feature, framework, resourceName, "provisioned", undefined, options.region);
9318
9961
  manifest.features.db = feature;
9319
9962
  const changedFiles = [];
9320
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
9963
+ if (await writeManifestIfChanged(cwd, manifest)) {
9321
9964
  changedFiles.push("loom.json");
9322
9965
  }
9323
9966
  return {
@@ -9347,7 +9990,7 @@ export async function setupVercelNeon(cwd, options = {}) {
9347
9990
  recordNeonProviderConfig(feature, framework, resourceName, result.code === 0 ? "connected" : "provisioned", provisionSuccess?.dashboardUrl, options.region);
9348
9991
  manifest.features.db = feature;
9349
9992
  const changedFiles = [];
9350
- if (await writeTextIfChanged(manifestPath, stringifyJson(manifest))) {
9993
+ if (await writeManifestIfChanged(cwd, manifest)) {
9351
9994
  changedFiles.push("loom.json");
9352
9995
  }
9353
9996
  const notes = result.code === 0
@@ -9480,7 +10123,9 @@ async function applyJobsFeature(cwd, framework, manifest, activate) {
9480
10123
  dependencies: JOBS_DEFAULT_DEPENDENCIES,
9481
10124
  devDependencies: JOBS_DEFAULT_DEV_DEPENDENCIES,
9482
10125
  });
9483
- const scriptsUpdate = await ensureProjectTasks(cwd, manifest, getJobsExpectedScripts(config));
10126
+ const scriptsUpdate = await syncManagedTasks(cwd, manifest, currentFeature, getJobsManagedTasks(config));
10127
+ setManagedRecords(feature, "managedTasks", scriptsUpdate.records);
10128
+ notes.push(...formatPreservedTaskNotes(scriptsUpdate, "jobs"));
9484
10129
  if (dependencyUpdate.changed)
9485
10130
  changedFiles.push(dependencyUpdate.config);
9486
10131
  if (scriptsUpdate.changedKeys.length)
@@ -9535,9 +10180,18 @@ async function applyJobsFeature(cwd, framework, manifest, activate) {
9535
10180
  if (relativePath === config.directRunner.scriptPath &&
9536
10181
  currentText !== null &&
9537
10182
  isLegacyLoomJobsDirectRunner(currentText)) {
9538
- if (await writeTextIfChanged(path, text)) {
10183
+ // Replace a dotenv-era runner only when it is exactly what an older
10184
+ // Loom wrote; an edited one keeps its app code.
10185
+ const legacyRunners = legacyJobsDirectRunnerOutputs(getJobsDirectRunnerCatalogImportPath(config, framework));
10186
+ const result = await syncManagedFile(path, text, {
10187
+ knownOutputs: legacyRunners,
10188
+ });
10189
+ if (result.state === "updated") {
9539
10190
  changedFiles.push(relativePath);
9540
10191
  }
10192
+ else if (result.state === "customized") {
10193
+ notes.push(`Preserved local edits in the dotenv-based jobs direct runner ${relativePath} (${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.`);
10194
+ }
9541
10195
  continue;
9542
10196
  }
9543
10197
  const scaffoldState = await scaffoldTextFile(path, text);
@@ -9549,9 +10203,10 @@ async function applyJobsFeature(cwd, framework, manifest, activate) {
9549
10203
  notes.push(`Preserved existing jobs scaffold file: ${relativePath}`);
9550
10204
  }
9551
10205
  }
9552
- const staticRouteSync = await syncJobsStaticRoutes(cwd, config);
10206
+ const staticRouteSync = await syncJobsStaticRoutes(cwd, config, currentFeature);
9553
10207
  changedFiles.push(...staticRouteSync.changedFiles);
9554
10208
  notes.push(...staticRouteSync.notes);
10209
+ setManagedFileRecords(feature, staticRouteSync.records);
9555
10210
  const jobsRoot = framework.srcDir ? "src/jobs" : "jobs";
9556
10211
  const catalogPath = join(cwd, jobsRoot, "index.ts");
9557
10212
  const metaCatalogPath = join(cwd, jobsRoot, "indexWithMetaOnly.ts");
@@ -9591,7 +10246,9 @@ async function applyDbFeature(cwd, framework, manifest, activate) {
9591
10246
  devDependencies: DB_DEFAULT_DEV_DEPENDENCIES,
9592
10247
  remove: DB_MOVED_DEPENDENCIES,
9593
10248
  });
9594
- const scriptsUpdate = await ensureProjectTasks(cwd, manifest, getDbExpectedScripts(config, tooling));
10249
+ const scriptsUpdate = await syncManagedTasks(cwd, manifest, currentFeature, getDbManagedTasks(config, tooling));
10250
+ setManagedRecords(feature, "managedTasks", scriptsUpdate.records);
10251
+ notes.push(...formatPreservedTaskNotes(scriptsUpdate, "db"));
9595
10252
  const testRunner = await getDbTestRunner(cwd, tooling);
9596
10253
  if (dependencyUpdate.changed)
9597
10254
  changedFiles.push(dependencyUpdate.config);
@@ -9606,26 +10263,21 @@ async function applyDbFeature(cwd, framework, manifest, activate) {
9606
10263
  if (dependencyUpdate.removedKeys.length) {
9607
10264
  notes.push(`Removed consumer-managed DB generator dependencies now owned by Loom: ${dependencyUpdate.removedKeys.join(", ")}`);
9608
10265
  }
9609
- const managedFiles = [
9610
- [config.modules.neonModule, dbNeonTemplate()],
9611
- [config.modules.neonFullModule, dbNeonFullTemplate()],
9612
- [config.modules.drizzleConfig, dbDrizzleConfigTemplate(config)],
9613
- [
9614
- config.modules.pgliteHarnessModule,
9615
- dbPgliteHarnessTemplate(config, testRunner),
9616
- ],
9617
- [config.modules.scriptsTsconfig, dbScriptsTsconfigTemplate()],
9618
- [
9619
- config.modules.refinementsCommonModule,
9620
- dbRefinementsCommonTemplate(),
9621
- ],
9622
- ];
9623
- for (const [relativePath, text] of managedFiles) {
9624
- const path = join(cwd, relativePath);
9625
- if (await writeTextIfChanged(path, text)) {
9626
- changedFiles.push(relativePath);
10266
+ const managedFileRecords = {};
10267
+ for (const managedFile of getDbManagedFiles(config, testRunner, tooling)) {
10268
+ const result = await syncManagedFile(join(cwd, managedFile.relativePath), managedFile.text, {
10269
+ knownOutputs: managedFile.knownOutputs,
10270
+ recordedHash: recordedManagedFileHash(currentFeature, managedFile.relativePath),
10271
+ });
10272
+ recordManagedFileSync(managedFileRecords, currentFeature, managedFile.relativePath, result);
10273
+ if (result.state === "created" || result.state === "updated") {
10274
+ changedFiles.push(managedFile.relativePath);
10275
+ }
10276
+ else if (result.state === "customized") {
10277
+ 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."));
9627
10278
  }
9628
10279
  }
10280
+ setManagedFileRecords(feature, managedFileRecords);
9629
10281
  const scaffoldFiles = [
9630
10282
  [config.modules.fixtureDumpScript, dbFixturesScriptTemplate(config)],
9631
10283
  [join(config.dirs.fixtureDir, ".gitkeep"), ""],
@@ -9641,9 +10293,12 @@ async function applyDbFeature(cwd, framework, manifest, activate) {
9641
10293
  notes.push(`Preserved existing DB scaffold file: ${relativePath}`);
9642
10294
  }
9643
10295
  }
9644
- if (await syncValibotBarrel(cwd, config)) {
10296
+ const barrelSync = await syncValibotBarrel(cwd, config);
10297
+ if (barrelSync.changed) {
9645
10298
  changedFiles.push(config.modules.valibotBarrelModule);
9646
10299
  }
10300
+ if (barrelSync.note)
10301
+ notes.push(barrelSync.note);
9647
10302
  const schemaIndexPath = join(cwd, config.dirs.schemaDir, "index.ts");
9648
10303
  if (!await exists(schemaIndexPath)) {
9649
10304
  notes.push(`Missing ${config.dirs.schemaDir}/index.ts. Add your app-local Drizzle schema barrel there so Loom-managed DB helpers can import it.`);
@@ -9952,6 +10607,26 @@ function linguiCliCommand(tooling) {
9952
10607
  return "yarn lingui";
9953
10608
  }
9954
10609
  }
10610
+ function getLinguiManagedTasks(config, tooling) {
10611
+ // Lingui tasks have followed the recorded dependency manager since the
10612
+ // feature was added, so there is no earlier value to accept.
10613
+ const executable = linguiCliCommand(tooling);
10614
+ return [
10615
+ {
10616
+ definition: `${executable} extract --clean`,
10617
+ knownValues: [],
10618
+ name: config.tasks.extract,
10619
+ },
10620
+ {
10621
+ definition: `${executable} compile`,
10622
+ knownValues: [],
10623
+ name: config.tasks.compile,
10624
+ },
10625
+ ];
10626
+ }
10627
+ const PWA_MANAGED_TASKS = [
10628
+ { definition: PWA_BUILD_SCRIPT, knownValues: [], name: "pwa:build" },
10629
+ ];
9955
10630
  function linguiConfigTemplate(framework) {
9956
10631
  const sourceRoot = framework.srcDir ? "src/" : "";
9957
10632
  return `import { formatter } from "@lingui/format-po";
@@ -10101,19 +10776,10 @@ async function applyLinguiFeature(cwd, framework, manifest, activate) {
10101
10776
  else if (activate && configState === "preserved") {
10102
10777
  notes.push(`Preserved existing Lingui config: ${config.configFile}`);
10103
10778
  }
10104
- const taskChanges = [];
10105
- const executable = linguiCliCommand(tooling);
10106
- for (const [name, command] of [
10107
- [config.tasks.extract, `${executable} extract --clean`],
10108
- [config.tasks.compile, `${executable} compile`],
10109
- ]) {
10110
- const result = await ensureTask(cwd, tooling.tasks, {
10111
- definition: command,
10112
- name,
10113
- });
10114
- if (result.changed)
10115
- taskChanges.push(name);
10116
- }
10779
+ const linguiTasks = await syncManagedTasks(cwd, manifest, currentFeature, getLinguiManagedTasks(config, tooling));
10780
+ setManagedRecords(feature, "managedTasks", linguiTasks.records);
10781
+ const taskChanges = [...linguiTasks.changedKeys];
10782
+ notes.push(...formatPreservedTaskNotes(linguiTasks, "lingui"));
10117
10783
  let taskStore = await readTaskStore(cwd, tooling.tasks);
10118
10784
  if (!getTaskCommand(taskStore.definitions[config.tasks.build])) {
10119
10785
  const result = await ensureTask(cwd, tooling.tasks, {
@@ -10143,9 +10809,15 @@ async function applyLinguiFeature(cwd, framework, manifest, activate) {
10143
10809
  const poDeclarations = await findSourceFilesMatching(cwd, /declare\s+module\s+["']\*\.po["']/);
10144
10810
  if (!poDeclarations.length) {
10145
10811
  const declarationPath = `${framework.srcDir ? "src/" : ""}lingui.d.ts`;
10146
- if (await writeTextIfChanged(join(cwd, declarationPath), linguiPoDeclarationTemplate())) {
10812
+ // Loom's declaration file always declares `*.po`, so an existing file
10813
+ // without one is the app's own and is never replaced.
10814
+ const declarationState = await scaffoldTextFile(join(cwd, declarationPath), linguiPoDeclarationTemplate());
10815
+ if (declarationState === "created") {
10147
10816
  changedFiles.push(declarationPath);
10148
10817
  }
10818
+ else if (declarationState === "preserved") {
10819
+ 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.`);
10820
+ }
10149
10821
  }
10150
10822
  }
10151
10823
  if (framework.kind === "nextjs") {
@@ -10197,12 +10869,10 @@ async function applyPwaFeature(cwd, framework, manifest, activate) {
10197
10869
  if (dependencyUpdate.changed)
10198
10870
  changedFiles.push(dependencyUpdate.config);
10199
10871
  const scriptsChanged = [];
10200
- const pwaTask = await ensureTask(cwd, tooling.tasks, {
10201
- definition: PWA_BUILD_SCRIPT,
10202
- name: "pwa:build",
10203
- });
10204
- if (pwaTask.changed)
10205
- scriptsChanged.push("pwa:build");
10872
+ const pwaTasks = await syncManagedTasks(cwd, manifest, currentFeature, PWA_MANAGED_TASKS);
10873
+ setManagedRecords(feature, "managedTasks", pwaTasks.records);
10874
+ scriptsChanged.push(...pwaTasks.changedKeys);
10875
+ notes.push(...formatPreservedTaskNotes(pwaTasks, "pwa"));
10206
10876
  const taskStore = await readTaskStore(cwd, tooling.tasks);
10207
10877
  const buildCommand = getTaskCommand(taskStore.definitions.build);
10208
10878
  if (!buildCommand) {
@@ -10247,14 +10917,27 @@ async function applyPwaFeature(cwd, framework, manifest, activate) {
10247
10917
  notes.push(`Preserved existing PWA service worker file: ${config.modules.serviceWorkerModule}`);
10248
10918
  }
10249
10919
  const clientProviderPath = join(cwd, config.modules.clientProviderModule);
10250
- const clientProviderExisted = await exists(clientProviderPath);
10920
+ const managedFileRecords = {};
10251
10921
  if (config.provider.managed) {
10252
- if (await writeTextIfChanged(clientProviderPath, pwaClientProviderTemplate(config))) {
10922
+ // `loom add pwa` may refresh the recorded adapter, so the provider the
10923
+ // previous configuration rendered is also Loom's output.
10924
+ const previousConfig = currentConfig
10925
+ ? await getPwaConfig(cwd, framework, packageJson, currentConfig, false)
10926
+ : config;
10927
+ const result = await syncManagedFile(clientProviderPath, pwaClientProviderTemplate(config), {
10928
+ knownOutputs: [pwaClientProviderTemplate(previousConfig)],
10929
+ recordedHash: recordedManagedFileHash(currentFeature, config.modules.clientProviderModule),
10930
+ });
10931
+ recordManagedFileSync(managedFileRecords, currentFeature, config.modules.clientProviderModule, result);
10932
+ if (result.state === "created" || result.state === "updated") {
10253
10933
  changedFiles.push(config.modules.clientProviderModule);
10254
10934
  }
10255
- if (!clientProviderExisted) {
10935
+ if (result.state === "created") {
10256
10936
  notes.push(`Scaffolded ${config.modules.clientProviderModule}. Wrap the app's root layout or provider tree with LoomPwaProvider to register the service worker.`);
10257
10937
  }
10938
+ else if (result.state === "customized") {
10939
+ notes.push(formatPreservedManagedFileNote(config.modules.clientProviderModule, result.difference, PWA_CUSTOMIZED_PROVIDER_RESOLUTION));
10940
+ }
10258
10941
  }
10259
10942
  else {
10260
10943
  const clientProviderState = await scaffoldTextFile(clientProviderPath, pwaClientProviderTemplate(config));
@@ -10265,6 +10948,7 @@ async function applyPwaFeature(cwd, framework, manifest, activate) {
10265
10948
  notes.push(`Preserved existing PWA client provider file: ${config.modules.clientProviderModule}`);
10266
10949
  }
10267
10950
  }
10951
+ setManagedFileRecords(feature, managedFileRecords);
10268
10952
  if (config.confirmAdapter === "mui") {
10269
10953
  notes.push("Detected @mui/material; PWA update prompts should use @gadicc/loom/mui/confirm.");
10270
10954
  }
@@ -10285,14 +10969,14 @@ async function checkJobsFeature(cwd, framework, manifest) {
10285
10969
  return { issues, suggestions: [], warnings: [] };
10286
10970
  }
10287
10971
  const config = mergeJobsConfig(framework, feature.config);
10288
- const expectedScripts = getJobsExpectedScripts(config);
10289
- const taskCheck = await checkProjectTasks(cwd, manifest, expectedScripts);
10972
+ const taskCheck = await checkManagedTasks(cwd, manifest, feature, getJobsManagedTasks(config));
10290
10973
  for (const taskName of taskCheck.mismatches) {
10291
10974
  issues.push(taskCheck.config === "package.json"
10292
10975
  ? `Jobs package.json script does not match Loom defaults: ${taskName}`
10293
10976
  : `Jobs task in ${taskCheck.config} does not match Loom defaults: ${taskName}`);
10294
10977
  suggestions.add("Run `loom add jobs`.");
10295
10978
  }
10979
+ addCustomizedTaskWarnings(taskCheck, "jobs", warnings, suggestions);
10296
10980
  const requiredFiles = [
10297
10981
  JOBS_SCRIPTS_TSCONFIG_PATH,
10298
10982
  config.directRunner?.scriptPath,
@@ -10343,8 +11027,14 @@ async function checkJobsFeature(cwd, framework, manifest) {
10343
11027
  const plans = getJobsStaticRoutePlans(cwd, config);
10344
11028
  const expectedPaths = new Set(plans.map((plan) => plan.path));
10345
11029
  for (const plan of plans) {
10346
- const currentText = await readTextIfExists(plan.path);
10347
- if (normalizeText(currentText ?? "") !== normalizeText(plan.text)) {
11030
+ const classification = await classifyManagedFile(await readTextIfExists(plan.path), plan.text, jobsStaticRouteProof(config, feature, plan.relativePath));
11031
+ if (classification.state === "current")
11032
+ continue;
11033
+ if (classification.state === "customized") {
11034
+ issues.push(`Jobs static route does not match loom manifest config: ${plan.relativePath} (${classification.difference})`);
11035
+ suggestions.add(`Loom does not overwrite edited or app-owned static job routes. ${JOBS_STATIC_ROUTE_EDIT_RESOLUTION}`);
11036
+ }
11037
+ else {
10348
11038
  issues.push(`Jobs static route does not match loom manifest config: ${plan.relativePath}`);
10349
11039
  suggestions.add("Run `loom add jobs` to sync static job routes.");
10350
11040
  }
@@ -10352,8 +11042,12 @@ async function checkJobsFeature(cwd, framework, manifest) {
10352
11042
  for (const routePath of await findManagedJobsStaticRoutePaths(cwd, config)) {
10353
11043
  if (expectedPaths.has(routePath))
10354
11044
  continue;
10355
- issues.push(`Managed jobs static route is not declared in loom.json: ${relative(cwd, routePath).replaceAll("\\", "/")}`);
10356
- suggestions.add("Run `loom add jobs` to sync static job routes.");
11045
+ const relativePath = relative(cwd, routePath).replaceAll("\\", "/");
11046
+ issues.push(`Managed jobs static route is not declared in loom.json: ${relativePath}`);
11047
+ const routeState = await classifyManagedFile(await readTextIfExists(routePath), "", jobsStaticRouteProof(config, feature, relativePath));
11048
+ suggestions.add(routeState.state === "loom-output"
11049
+ ? "Run `loom add jobs` to sync static job routes."
11050
+ : `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.`);
10357
11051
  }
10358
11052
  const routeModuleText = await readTextIfExists(join(cwd, config.modules.routeModule));
10359
11053
  if (routeModuleText &&
@@ -10496,7 +11190,6 @@ async function checkDbFeature(cwd, framework, manifest, options) {
10496
11190
  const { packageJson } = await readProjectPackageJson(cwd);
10497
11191
  const tooling = await getProjectTooling(cwd, manifest);
10498
11192
  const testRunner = await getDbTestRunner(cwd, tooling);
10499
- const expectedScripts = getDbExpectedScripts(config, tooling);
10500
11193
  const migrationFlowCheck = await checkDbProductionMigrationFlow(cwd, options.production ?? false, productionBranch);
10501
11194
  issues.push(...migrationFlowCheck.issues);
10502
11195
  warnings.push(...migrationFlowCheck.warnings);
@@ -10528,13 +11221,14 @@ async function checkDbFeature(cwd, framework, manifest, options) {
10528
11221
  suggestions.add(`Run loom add db to rewrite ${tooling.dependencies.config}.`);
10529
11222
  }
10530
11223
  }
10531
- const taskCheck = await checkProjectTasks(cwd, manifest, expectedScripts);
11224
+ const taskCheck = await checkManagedTasks(cwd, manifest, feature, getDbManagedTasks(config, tooling));
10532
11225
  for (const taskName of taskCheck.mismatches) {
10533
11226
  issues.push(taskCheck.config === "package.json"
10534
11227
  ? `DB package.json script does not match Loom defaults: ${taskName}`
10535
11228
  : `DB task in ${taskCheck.config} does not match Loom defaults: ${taskName}`);
10536
11229
  suggestions.add("Run `loom add db`.");
10537
11230
  }
11231
+ addCustomizedTaskWarnings(taskCheck, "db", warnings, suggestions);
10538
11232
  const requiredFiles = [
10539
11233
  config.modules.neonModule,
10540
11234
  config.modules.neonFullModule,
@@ -10551,44 +11245,22 @@ async function checkDbFeature(cwd, framework, manifest, options) {
10551
11245
  suggestions.add("Run `loom add db`.");
10552
11246
  }
10553
11247
  }
10554
- const exactManagedFileChecks = [
10555
- [
10556
- config.modules.neonModule,
10557
- dbNeonTemplate(),
10558
- "DB neon module does not match the Loom-managed wrapper",
10559
- ],
10560
- [
10561
- config.modules.neonFullModule,
10562
- dbNeonFullTemplate(),
10563
- "DB neonFull module does not match the Loom-managed wrapper",
10564
- ],
10565
- [
10566
- config.modules.drizzleConfig,
10567
- dbDrizzleConfigTemplate(config),
10568
- "Drizzle config does not match the Loom-managed wrapper",
10569
- ],
10570
- [
10571
- config.modules.pgliteHarnessModule,
10572
- dbPgliteHarnessTemplate(config, testRunner),
10573
- "PGlite test harness does not match the Loom-managed wrapper",
10574
- ],
10575
- [
10576
- config.modules.scriptsTsconfig,
10577
- dbScriptsTsconfigTemplate(),
10578
- "DB scripts tsconfig does not match the Loom-managed template",
10579
- ],
10580
- [
10581
- config.modules.refinementsCommonModule,
10582
- dbRefinementsCommonTemplate(),
10583
- "Valibot refinements common module does not match the Loom-managed wrapper",
10584
- ],
10585
- ];
10586
- for (const [relativePath, expectedText, message] of exactManagedFileChecks) {
10587
- const currentText = await readTextIfExists(join(cwd, relativePath));
11248
+ for (const managedFile of getDbManagedFiles(config, testRunner, tooling)) {
11249
+ const currentText = await readTextIfExists(join(cwd, managedFile.relativePath));
10588
11250
  if (!currentText)
10589
11251
  continue;
10590
- if (normalizeText(currentText) !== normalizeText(expectedText)) {
10591
- issues.push(`${message}: ${relativePath}`);
11252
+ const classification = await classifyManagedFile(currentText, managedFile.text, {
11253
+ knownOutputs: managedFile.knownOutputs,
11254
+ recordedHash: recordedManagedFileHash(feature, managedFile.relativePath),
11255
+ });
11256
+ if (classification.state === "current")
11257
+ continue;
11258
+ if (classification.state === "customized") {
11259
+ issues.push(`${managedFile.mismatch}: ${managedFile.relativePath} (${classification.difference})`);
11260
+ 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.");
11261
+ }
11262
+ else {
11263
+ issues.push(`${managedFile.mismatch}: ${managedFile.relativePath}`);
10592
11264
  suggestions.add("Run `loom add db` to restore the Loom-managed DB wrappers.");
10593
11265
  }
10594
11266
  }
@@ -10619,20 +11291,24 @@ async function checkDbFeature(cwd, framework, manifest, options) {
10619
11291
  }
10620
11292
  }
10621
11293
  }
10622
- const generatedNames = await readTsModuleNames(join(cwd, config.dirs.valibotGeneratedDir));
10623
- const refinementNames = await readTsModuleNames(join(cwd, config.dirs.valibotRefinementsDir));
10624
- const expectedBarrelText = buildValibotBarrelText(generatedNames, refinementNames);
11294
+ const barrel = await readValibotBarrelState(cwd, config);
11295
+ const expectedBarrelText = barrel.text;
10625
11296
  const barrelPath = join(cwd, config.modules.valibotBarrelModule);
10626
11297
  const barrelText = await readTextIfExists(barrelPath);
10627
11298
  if (expectedBarrelText) {
10628
- if (!barrelText) {
11299
+ const classification = await classifyManagedFile(barrelText, expectedBarrelText, barrel.proof);
11300
+ if (classification.state === "missing") {
10629
11301
  issues.push(`Valibot barrel is missing while generated/refinement modules exist: ${config.modules.valibotBarrelModule}`);
10630
11302
  suggestions.add("Run `loom db schema-gen` to refresh generated validation exports.");
10631
11303
  }
10632
- else if (normalizeText(barrelText) !== normalizeText(expectedBarrelText)) {
11304
+ else if (classification.state === "loom-output") {
10633
11305
  issues.push(`Valibot barrel does not match the generated/refinement modules: ${config.modules.valibotBarrelModule}`);
10634
11306
  suggestions.add("Run `loom db schema-gen` to rebuild the generated validation exports and barrel.");
10635
11307
  }
11308
+ else if (classification.state === "customized") {
11309
+ issues.push(`Valibot barrel does not match the generated/refinement modules: ${config.modules.valibotBarrelModule} (${classification.difference})`);
11310
+ 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.`);
11311
+ }
10636
11312
  }
10637
11313
  else if (barrelText) {
10638
11314
  warnings.push(`Valibot barrel exists but no generated/refinement modules were discovered: ${config.modules.valibotBarrelModule}`);
@@ -12359,6 +13035,8 @@ async function checkLinguiFeature(cwd, framework, manifest, options) {
12359
13035
  issues.push(`Lingui config is missing: ${config.configFile}`);
12360
13036
  suggestions.add("Run `loom add lingui`.");
12361
13037
  }
13038
+ // Missing or broken tasks are issues below; edited working ones only warn.
13039
+ addCustomizedTaskWarnings(await checkManagedTasks(cwd, manifest, feature, getLinguiManagedTasks(config, tooling)), "lingui", warnings, suggestions);
12362
13040
  const taskStore = await readTaskStore(cwd, tooling.tasks);
12363
13041
  if (!linguiTaskRuns(getTaskCommand(taskStore.definitions[config.tasks.extract]), "extract")) {
12364
13042
  issues.push(`Lingui extraction task is missing or invalid in ${tooling.tasks.config}: ${config.tasks.extract}`);
@@ -12480,6 +13158,9 @@ async function checkPwaFeature(cwd, framework, manifest) {
12480
13158
  suggestions.add("Run `loom add pwa`.");
12481
13159
  }
12482
13160
  }
13161
+ // A missing or broken pwa:build is an issue below; an edited working one
13162
+ // only warns.
13163
+ addCustomizedTaskWarnings(await checkManagedTasks(cwd, manifest, feature, PWA_MANAGED_TASKS), "pwa", warnings, suggestions);
12483
13164
  const taskStore = await readTaskStore(cwd, tooling.tasks);
12484
13165
  if (!scriptRunsSerwistBuild(getTaskCommand(taskStore.definitions["pwa:build"]))) {
12485
13166
  issues.push(`PWA task in ${tooling.tasks.config} does not build Serwist: pwa:build`);
@@ -12571,6 +13252,15 @@ async function checkPwaFeature(cwd, framework, manifest) {
12571
13252
  }
12572
13253
  const clientProviderText = await readTextIfExists(join(cwd, config.modules.clientProviderModule));
12573
13254
  if (clientProviderText) {
13255
+ if (config.provider.managed) {
13256
+ const classification = await classifyManagedFile(clientProviderText, pwaClientProviderTemplate(config), {
13257
+ recordedHash: recordedManagedFileHash(feature, config.modules.clientProviderModule),
13258
+ });
13259
+ if (classification.state === "customized") {
13260
+ warnings.push(`PWA client provider is recorded as Loom-managed but has local edits that Loom will not overwrite: ${config.modules.clientProviderModule} (${classification.difference})`);
13261
+ suggestions.add(`PWA client provider ${config.modules.clientProviderModule}: ${PWA_CUSTOMIZED_PROVIDER_RESOLUTION}`);
13262
+ }
13263
+ }
12574
13264
  if (!await isPwaClientProviderMounted(cwd, framework, config)) {
12575
13265
  issues.push(`PWA client provider is not mounted by the app root provider tree: ${config.modules.clientProviderModule}`);
12576
13266
  suggestions.add("Wrap the app root layout or existing client provider with LoomPwaProvider.");
@@ -12767,11 +13457,9 @@ export async function initProject(cwd, versionRange) {
12767
13457
  notes.push(...packageSkillInit.notes);
12768
13458
  if (await ensureExternalSkillsGitignore(cwd))
12769
13459
  changedFiles.push(".gitignore");
12770
- const manifestText = stringifyJson(manifest);
12771
- const manifestChanged = !existingManifest ||
12772
- JSON.stringify(existingManifest) !== JSON.stringify(manifest);
12773
- if (manifestChanged) {
12774
- await writeFile(loomManifestPath, manifestText, "utf8");
13460
+ // The new manifest shares the existing features object, which the feature
13461
+ // hooks update in place, so compare with the file on disk.
13462
+ if (await writeManifestIfChanged(cwd, manifest)) {
12775
13463
  changedFiles.push("loom.json");
12776
13464
  }
12777
13465
  return {
@@ -12797,8 +13485,7 @@ export async function addFeature(cwd, featureKey, versionRange) {
12797
13485
  ...skillSync.changedFiles,
12798
13486
  ];
12799
13487
  const notes = [...base.notes, ...result.notes, ...skillSync.notes];
12800
- const manifestPath = join(cwd, "loom.json");
12801
- if (await writeTextIfChanged(manifestPath, stringifyJson(base.manifest))) {
13488
+ if (await writeManifestIfChanged(cwd, base.manifest)) {
12802
13489
  changedFiles.push("loom.json");
12803
13490
  }
12804
13491
  return {
@@ -12856,7 +13543,7 @@ export async function integrateApiKeysJobs(cwd, permission, allowQueryParam = fa
12856
13543
  };
12857
13544
  feature.config = config;
12858
13545
  manifest.features["api-keys"] = feature;
12859
- const changed = await writeTextIfChanged(manifestPath, stringifyJson(manifest));
13546
+ const changed = await writeManifestIfChanged(cwd, manifest);
12860
13547
  return {
12861
13548
  changedFiles: changed ? ["loom.json"] : [],
12862
13549
  notes: [
@@ -12894,7 +13581,7 @@ export async function configureApiKeyRetention(cwd, enabled, overrides = {}) {
12894
13581
  };
12895
13582
  feature.config = config;
12896
13583
  manifest.features["api-keys"] = feature;
12897
- const changed = await writeTextIfChanged(manifestPath, stringifyJson(manifest));
13584
+ const changed = await writeManifestIfChanged(cwd, manifest);
12898
13585
  return {
12899
13586
  changedFiles: changed ? ["loom.json"] : [],
12900
13587
  notes: enabled
@@ -13038,7 +13725,7 @@ export async function checkProject(cwd, env = process.env, options = {}) {
13038
13725
  for (const suggestion of agentsCheck.suggestions) {
13039
13726
  suggestions.add(suggestion);
13040
13727
  }
13041
- const envRunnerCheck = await checkEnvRunnerAdoption(cwd, manifest);
13728
+ const envRunnerCheck = await checkEnvRunnerAdoption(cwd, manifest, framework);
13042
13729
  for (const issue of envRunnerCheck.issues) {
13043
13730
  issues.push(issue);
13044
13731
  }
@@ -14111,9 +14798,12 @@ async function runDbSchemaGen(cwd, forwardedArgs, io) {
14111
14798
  io.out("Biome is not installed; generated Valibot files were left unformatted.");
14112
14799
  }
14113
14800
  }
14114
- if (await syncValibotBarrel(cwd, config)) {
14801
+ const barrelSync = await syncValibotBarrel(cwd, config);
14802
+ if (barrelSync.changed) {
14115
14803
  io.out(`Updated ${config.modules.valibotBarrelModule}.`);
14116
14804
  }
14805
+ if (barrelSync.note)
14806
+ io.out(`Note: ${barrelSync.note}`);
14117
14807
  return 0;
14118
14808
  }
14119
14809
  async function runDbFixtures(cwd, forwardedArgs) {