@ariestools/toolchain 8.7.23 → 8.7.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/actions/deplint/engine.d.ts.map +1 -1
  2. package/dist/actions/deplint/fixer.d.ts.map +1 -1
  3. package/dist/actions/deplint/getExternalImportsFromFiles.d.ts +5 -1
  4. package/dist/actions/deplint/getExternalImportsFromFiles.d.ts.map +1 -1
  5. package/dist/actions/deplint/index.d.ts +1 -0
  6. package/dist/actions/deplint/index.d.ts.map +1 -1
  7. package/dist/actions/deplint/rules.d.ts.map +1 -1
  8. package/dist/actions/deplint/rulesDeprecatedRefType.d.ts +16 -0
  9. package/dist/actions/deplint/rulesDeprecatedRefType.d.ts.map +1 -0
  10. package/dist/actions/deplint/snapshot.d.ts +3 -1
  11. package/dist/actions/deplint/snapshot.d.ts.map +1 -1
  12. package/dist/actions/deplint/types.d.ts +16 -1
  13. package/dist/actions/deplint/types.d.ts.map +1 -1
  14. package/dist/actions/fix.d.ts.map +1 -1
  15. package/dist/actions/ruleCatalog.d.ts +1 -0
  16. package/dist/actions/ruleCatalog.d.ts.map +1 -1
  17. package/dist/actions/work/helpers.d.ts +21 -0
  18. package/dist/actions/work/helpers.d.ts.map +1 -0
  19. package/dist/actions/work/index.d.ts +29 -86
  20. package/dist/actions/work/index.d.ts.map +1 -1
  21. package/dist/actions/work/lifecycle.d.ts +41 -0
  22. package/dist/actions/work/lifecycle.d.ts.map +1 -0
  23. package/dist/actions/work/lint.d.ts +21 -0
  24. package/dist/actions/work/lint.d.ts.map +1 -0
  25. package/dist/actions/work/list.d.ts +30 -0
  26. package/dist/actions/work/list.d.ts.map +1 -0
  27. package/dist/actions/work/move.d.ts +21 -0
  28. package/dist/actions/work/move.d.ts.map +1 -0
  29. package/dist/actions/work/queue.d.ts +26 -0
  30. package/dist/actions/work/queue.d.ts.map +1 -0
  31. package/dist/actions/work/render.d.ts +10 -3
  32. package/dist/actions/work/render.d.ts.map +1 -1
  33. package/dist/actions/work/store.d.ts +5 -0
  34. package/dist/actions/work/store.d.ts.map +1 -1
  35. package/dist/actions/work/sync.d.ts +20 -0
  36. package/dist/actions/work/sync.d.ts.map +1 -1
  37. package/dist/actions/work/workspace.d.ts +46 -0
  38. package/dist/actions/work/workspace.d.ts.map +1 -0
  39. package/dist/bin/package/build.mjs +6 -0
  40. package/dist/bin/package/build.mjs.map +1 -1
  41. package/dist/bin/package/clean.mjs +6 -0
  42. package/dist/bin/package/clean.mjs.map +1 -1
  43. package/dist/bin/package/publint.mjs +6 -0
  44. package/dist/bin/package/publint.mjs.map +1 -1
  45. package/dist/bin/package/recompile.mjs +6 -0
  46. package/dist/bin/package/recompile.mjs.map +1 -1
  47. package/dist/bin/skills.mjs +220 -76
  48. package/dist/bin/skills.mjs.map +1 -1
  49. package/dist/bin/xy.mjs +2094 -1060
  50. package/dist/bin/xy.mjs.map +1 -1
  51. package/dist/lib/ruleCommandRegistry.d.ts +6 -0
  52. package/dist/lib/ruleCommandRegistry.d.ts.map +1 -1
  53. package/dist/xy/common/work/addCommand.d.ts.map +1 -1
  54. package/dist/xy/common/work/claimCommand.d.ts.map +1 -1
  55. package/dist/xy/common/work/doneCommand.d.ts.map +1 -1
  56. package/dist/xy/common/work/index.d.ts.map +1 -1
  57. package/dist/xy/common/work/initCommand.d.ts.map +1 -1
  58. package/dist/xy/common/work/lintCommand.d.ts +3 -0
  59. package/dist/xy/common/work/lintCommand.d.ts.map +1 -0
  60. package/dist/xy/common/work/listCommand.d.ts.map +1 -1
  61. package/dist/xy/common/work/moveCommand.d.ts +3 -0
  62. package/dist/xy/common/work/moveCommand.d.ts.map +1 -0
  63. package/dist/xy/common/work/nextCommand.d.ts.map +1 -1
  64. package/dist/xy/common/work/options.d.ts +8 -0
  65. package/dist/xy/common/work/options.d.ts.map +1 -1
  66. package/dist/xy/common/work/queueCommand.d.ts.map +1 -1
  67. package/dist/xy/common/work/showCommand.d.ts.map +1 -1
  68. package/dist/xy/common/work/syncCommand.d.ts.map +1 -1
  69. package/dist/xy/common/work/triageCommand.d.ts.map +1 -1
  70. package/dist/xy/common/work/updateCommand.d.ts.map +1 -1
  71. package/package.json +5 -5
package/dist/bin/xy.mjs CHANGED
@@ -12137,6 +12137,12 @@ const RULE_COMMANDS = {
12137
12137
  configKey: "skillsLint",
12138
12138
  includeInRoot: true,
12139
12139
  title: "Skills Lint Rules"
12140
+ },
12141
+ workLint: {
12142
+ command: "work lint",
12143
+ configKey: "workLint",
12144
+ includeInRoot: true,
12145
+ title: "Work Lint Rules"
12140
12146
  }
12141
12147
  };
12142
12148
  const DEPRECATED_CONFIG_KEY_ALIASES = {
@@ -29326,21 +29332,17 @@ function warnMissingExportTargets(name, location) {
29326
29332
  function hasShippedTsconfig(location) {
29327
29333
  return (readPackageJson$5(location)?.files)?.some((f) => f === "tsconfig.json" || f.includes("tsconfig")) ?? false;
29328
29334
  }
29329
- function getEffectiveRuntimeImportPaths({ distImportPaths, distTypeImportPaths, hasDist, hasRuntimeRoots, srcImportPaths, srcTypeImportPaths }) {
29335
+ function getEffectiveRuntimeImportPaths({ distImportPaths, distTypeImportPaths, hasDist, srcImportPaths, srcTypeImportPaths }) {
29330
29336
  if (hasDist) return {
29331
29337
  importPaths: distImportPaths,
29332
29338
  typeImportPaths: distTypeImportPaths
29333
29339
  };
29334
- if (!hasRuntimeRoots) return {
29335
- importPaths: {},
29336
- typeImportPaths: {}
29337
- };
29338
29340
  return {
29339
29341
  importPaths: excludeToolingConfigImports(srcImportPaths),
29340
29342
  typeImportPaths: excludeToolingConfigImports(srcTypeImportPaths)
29341
29343
  };
29342
29344
  }
29343
- function getExternalImportsFromFiles({ allFiles, distFiles, hasRuntimeRoots = true, location, name, tsconfigExtends = [], tsconfigPaths = [], tsconfigTypes = [] }) {
29345
+ function getExternalImportsFromFiles({ allFiles, distFiles, location, name, tsconfigExtends = [], tsconfigPaths = [], tsconfigTypes = [] }) {
29344
29346
  const srcImportPaths = {};
29345
29347
  const srcTypeImportPaths = {};
29346
29348
  for (const path of allFiles) {
@@ -29363,7 +29365,6 @@ function getExternalImportsFromFiles({ allFiles, distFiles, hasRuntimeRoots = tr
29363
29365
  distImportPaths,
29364
29366
  distTypeImportPaths,
29365
29367
  hasDist,
29366
- hasRuntimeRoots,
29367
29368
  srcImportPaths,
29368
29369
  srcTypeImportPaths
29369
29370
  });
@@ -30856,6 +30857,68 @@ function resolvePeerRangeFormOption(options) {
30856
30857
  return options.bound === void 0 ? "shorthand" : "broad";
30857
30858
  }
30858
30859
  //#endregion
30860
+ //#region src/actions/deplint/rulesDeprecatedRefType.ts
30861
+ /**
30862
+ * Convert a raw package entry that still uses deprecated `refType` into the
30863
+ * modern `placement` (+ historical `presence: "allowed"` vouching) shape.
30864
+ *
30865
+ * - `refType` alone → `placement: refType`, `presence: "allowed"` (unless
30866
+ * presence was already explicit)
30867
+ * - `placement` + `refType` → keep placement, drop refType, preserve
30868
+ * vouching by defaulting presence to `"allowed"` when unset (refType used
30869
+ * to imply allowed)
30870
+ * - Always drop `refType`
30871
+ */
30872
+ function migrateRefTypePackageConfig(config) {
30873
+ if (config.refType === void 0) return void 0;
30874
+ return {
30875
+ placement: config.placement ?? config.refType,
30876
+ presence: config.presence ?? "allowed",
30877
+ ...config.peerOptional !== void 0 && { peerOptional: config.peerOptional }
30878
+ };
30879
+ }
30880
+ const deprecatedRefTypeRule = {
30881
+ category: "workspace",
30882
+ id: "dep.package.deprecated-reftype",
30883
+ meta: {
30884
+ description: "Deprecated refType package config should be migrated to placement (+ presence)",
30885
+ fixable: ["config"],
30886
+ severity: "warning"
30887
+ },
30888
+ evaluate(context) {
30889
+ if (context.localConfigPath === void 0 || context.localPackageConfigs.size === 0) return;
30890
+ for (const [dependency, config] of context.localPackageConfigs) {
30891
+ if (config.refType === void 0) continue;
30892
+ const migrated = migrateRefTypePackageConfig(config);
30893
+ if (migrated === void 0) continue;
30894
+ const from = `refType: "${config.refType}"`;
30895
+ const toParts = [`placement: "${migrated.placement}"`, ...migrated.presence === void 0 ? [] : [`presence: "${migrated.presence}"`]];
30896
+ context.report({
30897
+ data: {
30898
+ configPath: context.localConfigPath,
30899
+ dependency,
30900
+ migrated,
30901
+ refType: config.refType
30902
+ },
30903
+ dependency,
30904
+ file: context.localConfigPath,
30905
+ message: `deprecated ${from} for ${dependency} — use ${toParts.join(", ")} instead (run \`xy deplint --fix\` to migrate)`
30906
+ });
30907
+ }
30908
+ },
30909
+ resolveFixes(diagnostic) {
30910
+ const data = diagnostic.data;
30911
+ if (!data) return [];
30912
+ return [{
30913
+ action: "set-package-config",
30914
+ config: data.migrated,
30915
+ configPath: data.configPath,
30916
+ dependency: data.dependency,
30917
+ detail: `migrated refType "${data.refType}" to placement for ${data.dependency}`
30918
+ }];
30919
+ }
30920
+ };
30921
+ //#endregion
30859
30922
  //#region src/actions/deplint/rulesDiagnostic.ts
30860
30923
  function isRuleFixable(rule) {
30861
30924
  return (rule.meta.fixable?.length ?? 0) > 0;
@@ -31383,11 +31446,14 @@ const unusedDependenciesRule = {
31383
31446
  },
31384
31447
  evaluate(context) {
31385
31448
  const findings = findUnusedDependencies(context.workspace.location, context.packageParams.dependencies, context.packageParams.devDependencies, context.sourceParams.externalDistImports, context.sourceParams.externalDistTypeImports, context.sourceParams.externalAllImports, context.unusedDependencyExclude);
31386
- for (const finding of findings) context.report({
31387
- data: finding,
31388
- dependency: finding.dep,
31389
- message: finding.kind === "move-to-dev" ? `dependency should be devDependency in package.json: ${finding.dep}${finding.reason != null && finding.reason.length > 0 ? ` (${finding.reason})` : ""}` : `Unused dependency in package.json: ${finding.dep}`
31390
- });
31449
+ for (const finding of findings) {
31450
+ if (context.isTerminalPackage && finding.kind === "move-to-dev") continue;
31451
+ context.report({
31452
+ data: finding,
31453
+ dependency: finding.dep,
31454
+ message: finding.kind === "move-to-dev" ? `dependency should be devDependency in package.json: ${finding.dep}${finding.reason != null && finding.reason.length > 0 ? ` (${finding.reason})` : ""}` : `Unused dependency in package.json: ${finding.dep}`
31455
+ });
31456
+ }
31391
31457
  },
31392
31458
  resolveFixes(diagnostic) {
31393
31459
  const data = diagnostic.data;
@@ -31813,6 +31879,7 @@ const builtInDeplintPlugin = {
31813
31879
  rules: [
31814
31880
  requiredPackagesRule,
31815
31881
  redundantPackagePlacementRule,
31882
+ deprecatedRefTypeRule,
31816
31883
  unlistedDependenciesRule,
31817
31884
  unusedDependenciesRule,
31818
31885
  misplacedDependenciesRule,
@@ -31986,6 +32053,7 @@ function buildWorkspaceContext(workspace, options = {}) {
31986
32053
  forcePeers: options.forcePeers ?? /* @__PURE__ */ new Set(),
31987
32054
  isTerminalPackage: packageClassification.isTerminalPackage,
31988
32055
  localConfigPath: options.localConfigPath,
32056
+ localPackageConfigs: options.localPackageConfigs ?? /* @__PURE__ */ new Map(),
31989
32057
  localPackagePolicies: options.localPackagePolicies ?? /* @__PURE__ */ new Map(),
31990
32058
  packageKind: packageClassification.kind,
31991
32059
  packageJsonPath,
@@ -32079,7 +32147,8 @@ async function loadWorkspaceEvaluationContext(workspace, options, workspaceNames
32079
32147
  const forcePeerOptional = /* @__PURE__ */ new Map();
32080
32148
  for (const [name, policy] of packageEntries) if (typeof policy.peerOptional === "boolean") forcePeerOptional.set(name, policy.peerOptional);
32081
32149
  const localConfigPath = findXyConfigFile(PATH.isAbsolute(workspace.location) ? workspace.location : PATH.resolve(INIT_CWD(), workspace.location));
32082
- const localPackagePolicies = localConfigPath === void 0 ? /* @__PURE__ */ new Map() : normalizeDeplintPackagePolicies(Object.fromEntries(readPackagesFromConfigFile(localConfigPath)));
32150
+ const localPackageConfigs = localConfigPath === void 0 ? /* @__PURE__ */ new Map() : readPackagesFromConfigFile(localConfigPath);
32151
+ const localPackagePolicies = localConfigPath === void 0 ? /* @__PURE__ */ new Map() : normalizeDeplintPackagePolicies(Object.fromEntries(localPackageConfigs));
32083
32152
  const rangeStyleOptions = rules.find((rule) => rule.id === "dep.peerDependencies.range-style")?.options ?? {};
32084
32153
  const peerRangeForm = resolvePeerRangeFormOption(rangeStyleOptions);
32085
32154
  const peerRangeBound = resolvePeerRangeBoundOption(rangeStyleOptions);
@@ -32101,6 +32170,7 @@ async function loadWorkspaceEvaluationContext(workspace, options, workspaceNames
32101
32170
  forcePeerWithDefault,
32102
32171
  forcePeers,
32103
32172
  localConfigPath,
32173
+ localPackageConfigs,
32104
32174
  localPackagePolicies,
32105
32175
  peerRangeBound,
32106
32176
  peerRangeForm,
@@ -32324,13 +32394,14 @@ var DeplintPackageEditor = class {
32324
32394
  //#endregion
32325
32395
  //#region src/actions/deplint/fixer.ts
32326
32396
  function isConfigFix(fix) {
32327
- return fix.action === "remove-package-config";
32397
+ return fix.action === "remove-package-config" || fix.action === "set-package-config";
32328
32398
  }
32329
32399
  function listConfigFixEntries(diagnostics) {
32330
32400
  return diagnostics.flatMap((diagnostic) => {
32331
32401
  return (diagnostic.fixes ?? []).flatMap((fix) => {
32332
32402
  if (!isConfigFix(fix)) return [];
32333
32403
  return [{
32404
+ config: fix.action === "set-package-config" ? fix.config : void 0,
32334
32405
  configPath: fix.configPath,
32335
32406
  dependency: fix.dependency,
32336
32407
  detail: fix.detail,
@@ -32350,23 +32421,19 @@ function groupByConfigDir(entries) {
32350
32421
  return byDir;
32351
32422
  }
32352
32423
  function applyConfigFixesForDir(dir, entries, cwd) {
32353
- const written = applyPackageEditsToConfigDir(dir, [...new Set(entries.map((entry) => entry.dependency))].map((dependency) => ({
32354
- config: void 0,
32355
- dependency
32424
+ const byDep = /* @__PURE__ */ new Map();
32425
+ for (const entry of entries) byDep.set(entry.dependency, entry);
32426
+ const uniqueEntries = byDep.values().toArray();
32427
+ const written = applyPackageEditsToConfigDir(dir, uniqueEntries.map((entry) => ({
32428
+ config: entry.config,
32429
+ dependency: entry.dependency
32356
32430
  })));
32357
32431
  if (written === void 0) return [];
32358
- const credited = /* @__PURE__ */ new Set();
32359
- const applied = [];
32360
- for (const entry of entries) {
32361
- if (credited.has(entry.dependency)) continue;
32362
- credited.add(entry.dependency);
32363
- applied.push({
32364
- dependency: entry.dependency,
32365
- detail: `${entry.detail} (${PATH.relative(cwd, written) || PATH.basename(written)})`,
32366
- workspace: entry.workspace
32367
- });
32368
- }
32369
- return applied;
32432
+ return uniqueEntries.map((entry) => ({
32433
+ dependency: entry.dependency,
32434
+ detail: `${entry.detail} (${PATH.relative(cwd, written) || PATH.basename(written)})`,
32435
+ workspace: entry.workspace
32436
+ }));
32370
32437
  }
32371
32438
  function applyConfigFixes(diagnostics) {
32372
32439
  const cwd = INIT_CWD();
@@ -41760,6 +41827,12 @@ const fix = async ({ jobs, pkg, verbose }) => {
41760
41827
  ...pkgOpts,
41761
41828
  "--fix",
41762
41829
  ...verboseOpts
41830
+ ]),
41831
+ pm.runXy([
41832
+ "lint",
41833
+ "lint",
41834
+ "--fix",
41835
+ ...verboseOpts
41763
41836
  ])
41764
41837
  ], false);
41765
41838
  };
@@ -51573,437 +51646,6 @@ const skillsLint = async (options = {}) => {
51573
51646
  return result;
51574
51647
  };
51575
51648
  //#endregion
51576
- //#region src/actions/ruleCatalog.ts
51577
- const REPO_LINT_RULES = [
51578
- [
51579
- "repo.root-private",
51580
- "Root package is private",
51581
- "error",
51582
- true
51583
- ],
51584
- [
51585
- "repo.no-private-publish-config",
51586
- "Private root has no publishConfig",
51587
- "error",
51588
- true
51589
- ],
51590
- [
51591
- "repo.packages-folder",
51592
- "Workspace packages live under packages/",
51593
- "error",
51594
- false
51595
- ],
51596
- [
51597
- "repo.spec-layout",
51598
- "Spec files live in spec/ folders",
51599
- "error",
51600
- false
51601
- ],
51602
- [
51603
- "repo.workspaces-field-placement",
51604
- "Workspace fields are declared in the package-manager-specific location",
51605
- "error",
51606
- true
51607
- ],
51608
- [
51609
- "repo.workspace-glob-coverage",
51610
- "Workspace globs cover every package",
51611
- "error",
51612
- false
51613
- ],
51614
- [
51615
- "repo.no-package-manager-in-workspaces",
51616
- "Only the root package declares packageManager",
51617
- "error",
51618
- true
51619
- ],
51620
- [
51621
- "repo.volta-only-root",
51622
- "Only the root package declares volta",
51623
- "error",
51624
- true
51625
- ],
51626
- [
51627
- "repo.engines-non-terminal",
51628
- "Only non-terminal packages declare engines",
51629
- "error",
51630
- true
51631
- ],
51632
- [
51633
- "repo.engines-lts",
51634
- "Engine and volta versions include latest LTS",
51635
- "error",
51636
- false
51637
- ],
51638
- [
51639
- "repo.version-consistency",
51640
- "Workspace versions are consistent",
51641
- "error",
51642
- true
51643
- ],
51644
- [
51645
- "repo.internal-dependency-ranges",
51646
- "Internal dependencies use the expected workspace/version protocol",
51647
- "error",
51648
- true
51649
- ],
51650
- [
51651
- "repo.internal-peer-ranges",
51652
- "Internal peerDependencies use publishable ranges",
51653
- "error",
51654
- true
51655
- ],
51656
- [
51657
- "repo.pnpm-release-age-excludes",
51658
- "pnpm minimumReleaseAgeExclude matches imported scopes",
51659
- "error",
51660
- true
51661
- ],
51662
- [
51663
- "repo.pnpm-minimum-release-age",
51664
- "pnpm minimumReleaseAge is configured",
51665
- "error",
51666
- true
51667
- ],
51668
- [
51669
- "repo.pnpm-no-overrides",
51670
- "pnpm dependency overrides are not configured",
51671
- "warn",
51672
- false
51673
- ]
51674
- ].map(([id, description, defaultLevel, fixable]) => ({
51675
- defaultLevel,
51676
- description,
51677
- fixable,
51678
- id
51679
- }));
51680
- const NON_FIXABLE_DEAD_RULES = /* @__PURE__ */ new Set([
51681
- "dead.repo.deprecated-export",
51682
- "dead.workspace.deprecated-export",
51683
- "dead.workspace.deprecated-unused-export"
51684
- ]);
51685
- function isDeadRuleFixable(ruleId) {
51686
- return !NON_FIXABLE_DEAD_RULES.has(ruleId);
51687
- }
51688
- function severityToLevel(severity, enabled = true) {
51689
- if (!enabled) return "off";
51690
- return severity === "error" ? "error" : "warn";
51691
- }
51692
- async function loadCommandConfig(commandName, pkg) {
51693
- if (pkg !== void 0 && pkg.length > 0) {
51694
- const workspace = getPackageManager().findWorkspace(pkg);
51695
- if (workspace === void 0) throw new Error(`Workspace not found: ${pkg}`);
51696
- return loadWorkspaceCommandConfig(workspace.location, commandName);
51697
- }
51698
- return loadWorkspaceCommandConfig(process.cwd(), commandName);
51699
- }
51700
- function staticCatalog(command, configKey, definitions, config) {
51701
- const ruleSettings = config?.rules ?? {};
51702
- const known = new Set(definitions.flatMap((rule) => [rule.id, ...rule.aliases ?? []]));
51703
- const unknown = Object.keys(ruleSettings).filter((id) => !known.has(id));
51704
- if (unknown.length > 0) throw new TypeError(`Unknown ${command} rule ${unknown.map((id) => `"${id}"`).join(", ")} in commands.${configKey}.rules`);
51705
- const resolveSetting = (rule) => {
51706
- if (ruleSettings[rule.id] !== void 0) return ruleSettings[rule.id];
51707
- const aliases = rule.aliases ?? [];
51708
- for (const alias of aliases) if (ruleSettings[alias] !== void 0) return ruleSettings[alias];
51709
- };
51710
- return definitions.map((rule) => ({
51711
- command,
51712
- defaultLevel: rule.defaultLevel,
51713
- description: rule.description,
51714
- fixable: rule.fixable === true,
51715
- id: rule.id,
51716
- level: parseRuleLevelSetting(ruleConfigPath(configKey, rule.id), resolveSetting(rule), rule.defaultLevel)
51717
- }));
51718
- }
51719
- function runtimeRuleCatalog(command, configKey, definitions, config) {
51720
- return staticCatalog(command, configKey, definitions, config);
51721
- }
51722
- function commandPrefix(prefix, rules) {
51723
- return rules.map((rule) => ({
51724
- ...rule,
51725
- command: `${prefix} ${rule.command}`
51726
- }));
51727
- }
51728
- async function getDeplintRuleCatalog(pkg) {
51729
- const config = await loadCommandConfig("deplint", pkg);
51730
- const rules = await loadDeplintRules(config);
51731
- const defaultRules = await loadDeplintRules(config === void 0 ? void 0 : {
51732
- ...config,
51733
- rules: void 0
51734
- });
51735
- const defaults = new Map(defaultRules.map((rule) => [rule.id, severityToLevel(rule.meta.severity, rule.enabled !== false)]));
51736
- return sortRules(rules.map((rule) => ({
51737
- command: RULE_COMMANDS.deplint.command,
51738
- defaultLevel: defaults.get(rule.id) ?? "warn",
51739
- description: rule.meta.description,
51740
- fixable: isRuleFixable(rule),
51741
- id: rule.id,
51742
- level: severityToLevel(rule.meta.severity, rule.enabled !== false)
51743
- })));
51744
- }
51745
- async function getDeadRuleCatalog(pkg, options) {
51746
- const config = await loadCommandConfig("dead", pkg);
51747
- const rules = loadDeadRules(config, { deprecated: options?.deprecated === true });
51748
- const defaultConfig = config === void 0 ? void 0 : {
51749
- ...config,
51750
- rules: void 0
51751
- };
51752
- const defaults = new Map(loadDeadRules(defaultConfig, { deprecated: options?.deprecated === true }).map((rule) => [rule.id, severityToLevel(rule.meta.severity, rule.enabled)]));
51753
- return sortRules(rules.map((rule) => ({
51754
- command: RULE_COMMANDS.dead.command,
51755
- defaultLevel: defaults.get(rule.id) ?? "warn",
51756
- description: rule.meta.description,
51757
- fixable: isDeadRuleFixable(rule.id),
51758
- id: rule.id,
51759
- level: severityToLevel(rule.meta.severity, rule.enabled)
51760
- })));
51761
- }
51762
- async function getPublintRuleCatalog(command = RULE_COMMANDS.publint.command, pkg) {
51763
- const levels = resolvePublintRuleLevels(await loadCommandConfig("publint", pkg));
51764
- return ALL_PUBLINT_CHECKS.map((check) => ({
51765
- command,
51766
- defaultLevel: defaultPublintLevel(check),
51767
- description: publintRuleDescription(check),
51768
- fixable: publintRuleFixable(check),
51769
- id: publintRuleId(check),
51770
- level: levels.get(check) ?? "warn"
51771
- }));
51772
- }
51773
- async function getApiExposureRuleCatalog(pkg) {
51774
- const config = normalizeApiExposureConfig(await loadCommandConfig("apiExposure", pkg));
51775
- const byId = new Map(config.rules.map((rule) => [rule.id, rule]));
51776
- return AEI_RULES.map((rule) => {
51777
- const resolved = byId.get(rule.id);
51778
- return {
51779
- command: RULE_COMMANDS.apiExposure.command,
51780
- defaultLevel: rule.defaultEnabled === false ? "off" : "warn",
51781
- description: rule.description,
51782
- fixable: false,
51783
- id: rule.id,
51784
- level: resolved?.level ?? "warn",
51785
- weight: resolved?.weight ?? rule.defaultWeight
51786
- };
51787
- });
51788
- }
51789
- async function getGitlintRuleCatalog() {
51790
- return runtimeRuleCatalog(RULE_COMMANDS.gitLint.command, RULE_COMMANDS.gitLint.configKey, GITLINT_RULES, await loadCommandConfig("gitLint"));
51791
- }
51792
- async function getPackmanRuleCatalog() {
51793
- return runtimeRuleCatalog(RULE_COMMANDS.packman.command, RULE_COMMANDS.packman.configKey, PACKMAN_RULES, await loadCommandConfig("packman"));
51794
- }
51795
- async function getRepoLintRuleCatalog() {
51796
- return staticCatalog(RULE_COMMANDS.repoLint.command, RULE_COMMANDS.repoLint.configKey, REPO_LINT_RULES, await loadCommandConfig("repoLint"));
51797
- }
51798
- async function getNodeLintRuleCatalog() {
51799
- return runtimeRuleCatalog(RULE_COMMANDS.nodeLint.command, RULE_COMMANDS.nodeLint.configKey, NODE_LINT_RULES, await loadCommandConfig("nodeLint"));
51800
- }
51801
- async function getLintlintRuleCatalog() {
51802
- return runtimeRuleCatalog(RULE_COMMANDS.lintLint.command, RULE_COMMANDS.lintLint.configKey, LINTLINT_RULES, await loadCommandConfig("lintLint"));
51803
- }
51804
- async function getSkillsLintRuleCatalog() {
51805
- return runtimeRuleCatalog(RULE_COMMANDS.skillsLint.command, RULE_COMMANDS.skillsLint.configKey, SKILLS_LINT_RULES, await loadCommandConfig("skillsLint"));
51806
- }
51807
- function parseEslintRuleLevel(setting) {
51808
- let current = setting;
51809
- while (Array.isArray(current) && current.length > 0) current = current[0];
51810
- if (current === "error" || current === 2) return "error";
51811
- if (current === "warn" || current === 1) return "warn";
51812
- return "off";
51813
- }
51814
- function mergeEslintRules(configs) {
51815
- const rules = /* @__PURE__ */ new Map();
51816
- for (const config of configs) {
51817
- if (config.rules === void 0) continue;
51818
- for (const [id, setting] of Object.entries(config.rules)) rules.set(id, setting);
51819
- }
51820
- return rules;
51821
- }
51822
- function eslintRuleDescription(rule) {
51823
- const description = rule?.meta?.docs?.description;
51824
- return typeof description === "string" && description.length > 0 ? description : void 0;
51825
- }
51826
- function eslintRuleFixable(rule) {
51827
- return rule?.meta?.fixable !== void 0;
51828
- }
51829
- function collectEslintRuleDescriptions(configs) {
51830
- const descriptions = /* @__PURE__ */ new Map();
51831
- for (const [id, rule] of builtinRules) {
51832
- const description = eslintRuleDescription(rule);
51833
- if (description !== void 0) descriptions.set(id, description);
51834
- }
51835
- for (const config of configs) {
51836
- const plugins = Object.entries(config.plugins ?? {});
51837
- for (const [pluginName, plugin] of plugins) {
51838
- const rules = Object.entries(plugin?.rules ?? {});
51839
- for (const [ruleName, rule] of rules) {
51840
- const description = eslintRuleDescription(rule);
51841
- if (description !== void 0) descriptions.set(`${pluginName}/${ruleName}`, description);
51842
- }
51843
- }
51844
- }
51845
- return descriptions;
51846
- }
51847
- function collectEslintRuleFixability(configs) {
51848
- const fixability = /* @__PURE__ */ new Map();
51849
- for (const [id, rule] of builtinRules) fixability.set(id, eslintRuleFixable(rule));
51850
- for (const config of configs) {
51851
- const plugins = Object.entries(config.plugins ?? {});
51852
- for (const [pluginName, plugin] of plugins) {
51853
- const rules = Object.entries(plugin?.rules ?? {});
51854
- for (const [ruleName, rule] of rules) fixability.set(`${pluginName}/${ruleName}`, eslintRuleFixable(rule));
51855
- }
51856
- }
51857
- return fixability;
51858
- }
51859
- async function getEslintRuleCatalog(command = RULE_COMMANDS.lint.command) {
51860
- const configPath = await findUp(["eslint.config.ts", "eslint.config.mjs"]);
51861
- if (configPath === void 0) return [];
51862
- const module = await import(pathToFileURL(configPath).href);
51863
- const configs = Array.isArray(module.default) ? module.default : [];
51864
- const rules = mergeEslintRules(configs);
51865
- const descriptions = collectEslintRuleDescriptions(configs);
51866
- const fixability = collectEslintRuleFixability(configs);
51867
- return rules.entries().map(([id, setting]) => ({
51868
- command,
51869
- defaultLevel: parseEslintRuleLevel(setting),
51870
- description: descriptions.get(id),
51871
- fixable: fixability.get(id) ?? false,
51872
- id,
51873
- level: parseEslintRuleLevel(setting),
51874
- source: configPath
51875
- })).toArray().toSorted((left, right) => left.id.localeCompare(right.id));
51876
- }
51877
- function getCycleRuleCatalog(depth = 25) {
51878
- return [{
51879
- command: RULE_COMMANDS.cycle.command,
51880
- defaultLevel: "warn",
51881
- description: `ESLint import cycle rule with maxDepth ${depth}`,
51882
- fixable: false,
51883
- id: "import-x/no-cycle",
51884
- level: "warn"
51885
- }];
51886
- }
51887
- async function loadDirectRuleCatalog() {
51888
- return sortRules([...(await Promise.all([
51889
- getApiExposureRuleCatalog(),
51890
- getCleanRuleCatalog(),
51891
- getDeadRuleCatalog(),
51892
- getDeplintRuleCatalog(),
51893
- getGitlintRuleCatalog(),
51894
- getPackmanRuleCatalog(),
51895
- getPublintRuleCatalog(),
51896
- getRepoLintRuleCatalog(),
51897
- getNodeLintRuleCatalog(),
51898
- getLintlintRuleCatalog(),
51899
- getSkillsLintRuleCatalog()
51900
- ])).flat(), ...getCycleRuleCatalog()]);
51901
- }
51902
- async function getCheckRuleCatalog() {
51903
- return sortRules(commandPrefix("check", (await Promise.all([
51904
- getGitlintRuleCatalog(),
51905
- getPackmanRuleCatalog(),
51906
- getPublintRuleCatalog(),
51907
- getRepoLintRuleCatalog(),
51908
- getLintlintRuleCatalog(),
51909
- getSkillsLintRuleCatalog()
51910
- ])).flat()));
51911
- }
51912
- async function getFixRuleCatalog() {
51913
- return sortRules(commandPrefix("fix", (await Promise.all([
51914
- getGitlintRuleCatalog(),
51915
- getDeplintRuleCatalog(),
51916
- getRepoLintRuleCatalog(),
51917
- getPublintRuleCatalog(),
51918
- getEslintRuleCatalog("lint")
51919
- ])).flat()));
51920
- }
51921
- async function getMasterRuleCatalog() {
51922
- return sortRules(await loadDirectRuleCatalog());
51923
- }
51924
- //#endregion
51925
- //#region src/actions/secure.ts
51926
- const secure = async ({ jobs = 16, pkg, verbose = false } = {}) => {
51927
- return await runSecurityAudit(getPackageManager(), {
51928
- concurrency: jobs,
51929
- pkg,
51930
- verbose
51931
- });
51932
- };
51933
- //#endregion
51934
- //#region src/actions/sitemap.ts
51935
- const sitemap = () => {
51936
- return runSteps("Sitemap", [["ts-node-script", "./scripts/sitemap.ts"]]);
51937
- };
51938
- //#endregion
51939
- //#region src/actions/skills/updo.ts
51940
- const SCOPE_FLAGS = /* @__PURE__ */ new Set([
51941
- "-g",
51942
- "--global",
51943
- "-p",
51944
- "--project"
51945
- ]);
51946
- const hasSkillsScopeFlag = (args) => args.some((a) => SCOPE_FLAGS.has(a));
51947
- const skillsUpdoArgs = (args) => {
51948
- return ["update", ...hasSkillsScopeFlag(args) ? args : ["-p", ...args]];
51949
- };
51950
- const skillsUpdo = (args) => {
51951
- return runSkills(skillsUpdoArgs(args));
51952
- };
51953
- //#endregion
51954
- //#region src/actions/sonar.ts
51955
- const sonar = () => {
51956
- return runSteps("Sonar", [["eslint", [
51957
- "-c",
51958
- "sonar.eslintrc",
51959
- "."
51960
- ]]]);
51961
- };
51962
- //#endregion
51963
- //#region src/actions/start.ts
51964
- const start = () => {
51965
- return runSteps("Start", [[getPackageManager().command, "react-scripts start"]]);
51966
- };
51967
- //#endregion
51968
- //#region src/actions/statics.ts
51969
- const DefaultDependencies = [
51970
- "axios",
51971
- "@xylabs/pixel",
51972
- "react",
51973
- "graphql",
51974
- "react-router",
51975
- "@mui/material",
51976
- "@mui/system"
51977
- ];
51978
- const statics = () => {
51979
- console.log(chalk.green("Check Required Static Dependencies"));
51980
- const staticsValue = ((parsedPackageJSON()?.xy)?.deps)?.statics;
51981
- const result = detectDuplicateDependencies(staticsValue, DefaultDependencies, false);
51982
- return isStrictMode() ? result : 0;
51983
- };
51984
- //#endregion
51985
- //#region src/actions/test.ts
51986
- const test = ({ target } = {}) => {
51987
- const pm = getPackageManager();
51988
- if (target != null && target.length > 0 && pm.findWorkspace(target)) return runSteps(`Test [${target}]`, [pm.runInWorkspace(target, "vitest", ["."])]);
51989
- return runSteps("Test", [["vitest", [target ?? "."]]]);
51990
- };
51991
- //#endregion
51992
- //#region src/actions/up.ts
51993
- const up = () => {
51994
- return runSteps("Up", [getPackageManager().outdated()]);
51995
- };
51996
- //#endregion
51997
- //#region src/actions/updo.ts
51998
- const updo = async ({ jobs, latest = false, next = false, risk = "green" } = {}) => {
51999
- return await runUpdo(getPackageManager(), {
52000
- jobs,
52001
- latest,
52002
- next,
52003
- risk
52004
- });
52005
- };
52006
- //#endregion
52007
51649
  //#region src/actions/work/id.ts
52008
51650
  const formatWorkDate = (date) => {
52009
51651
  return date.toISOString().slice(0, 10).replaceAll("-", "");
@@ -52247,6 +51889,12 @@ const readWorkConfig = (cwd = process.cwd()) => {
52247
51889
  const paths = ensureWorkStore(cwd);
52248
51890
  return validateWorkConfig(readJson(paths.configPath));
52249
51891
  };
51892
+ /** Read config when the store already exists; does not create it. */
51893
+ const tryReadWorkConfig = (cwd = process.cwd()) => {
51894
+ const fixed = fixedWorkRootPaths(cwd);
51895
+ if (!existsSync(fixed.configPath)) return void 0;
51896
+ return validateWorkConfig(readJson(fixed.configPath));
51897
+ };
52250
51898
  const workItemPath = (cwd, id) => {
52251
51899
  assertSafeWorkId(id);
52252
51900
  return PATH.resolve(workStorePaths(cwd, readWorkConfig(cwd)).itemsDir, `${id}.json`);
@@ -52264,6 +51912,17 @@ const readWorkItem = (cwd, id) => {
52264
51912
  if (!existsSync(filePath)) throw new Error(`Work item not found: ${id}`);
52265
51913
  return validateWorkItem(readJson(filePath));
52266
51914
  };
51915
+ const workItemExists = (cwd, id) => {
51916
+ assertSafeWorkId(id);
51917
+ const config = tryReadWorkConfig(cwd);
51918
+ if (config === void 0) return false;
51919
+ return existsSync(PATH.resolve(workStorePaths(cwd, config).itemsDir, `${id}.json`));
51920
+ };
51921
+ const deleteWorkItem = (cwd, id) => {
51922
+ const filePath = workItemPath(cwd, id);
51923
+ if (!existsSync(filePath)) throw new Error(`Work item not found: ${id}`);
51924
+ unlinkSync(filePath);
51925
+ };
52267
51926
  const listWorkItems = (cwd = process.cwd()) => {
52268
51927
  const paths = workStorePaths(cwd, readWorkConfig(cwd));
52269
51928
  return readdirSync(paths.itemsDir).filter((file) => file.endsWith(".json")).toSorted().map((file) => validateWorkItem(readJson(PATH.resolve(paths.itemsDir, file))));
@@ -52286,182 +51945,9 @@ const pathInsideRepo = (cwd, filePath) => {
52286
51945
  relativePath: relativePath.split(PATH.sep).join("/")
52287
51946
  };
52288
51947
  };
52289
- //#endregion
52290
- //#region src/actions/work/inline.ts
52291
- const markdownLikeExtensions = /* @__PURE__ */ new Set([
52292
- ".htm",
52293
- ".html",
52294
- ".md",
52295
- ".mdx"
52296
- ]);
52297
- const markerForFile = (filePath, marker, id) => {
52298
- const ext = PATH.extname(filePath).toLowerCase();
52299
- if (markdownLikeExtensions.has(ext)) return `<!-- ${marker}: ${id} -->`;
52300
- return `// ${marker}: ${id}`;
52301
- };
52302
- const insertInlineWorkMarker = ({ cwd, filePath, id, line, marker }) => {
52303
- const { absolutePath, relativePath } = pathInsideRepo(cwd, filePath);
52304
- if (!existsSync(absolutePath)) throw new Error(`Inline anchor file not found: ${relativePath}`);
52305
- const markerText = markerForFile(absolutePath, marker, id);
52306
- const original = readFileSync(absolutePath, "utf8");
52307
- if (original.includes(markerText)) return relativePath;
52308
- if (line === void 0) {
52309
- writeFileSync(absolutePath, `${original}${original.endsWith("\n") || original.length === 0 ? "" : "\n"}${markerText}\n`, "utf8");
52310
- return relativePath;
52311
- }
52312
- const lines = original.split("\n");
52313
- const index = Math.max(0, Math.min(line - 1, lines.length));
52314
- lines.splice(index, 0, markerText);
52315
- writeFileSync(absolutePath, lines.join("\n"), "utf8");
52316
- return relativePath;
52317
- };
52318
- //#endregion
52319
- //#region src/actions/work/priority.ts
52320
- const FIELD_SET = new Set(WORK_PRIORITY_FIELDS);
52321
- const TERM_PATTERN = /([+-]?)\s*(impact|urgency|effort|risk|confidence)/g;
52322
- const calculatePriorityScore = (priority, formula = DEFAULT_PRIORITY_FORMULA) => {
52323
- if (priority === void 0) return void 0;
52324
- let score = 0;
52325
- let cursor = 0;
52326
- for (const match of formula.matchAll(TERM_PATTERN)) {
52327
- const index = match.index ?? 0;
52328
- const skipped = formula.slice(cursor, index);
52329
- if (!/^[\s+]*$/.test(skipped)) throw new Error(`Unsupported priority formula: ${formula}`);
52330
- const operator = match[1] === "-" ? -1 : 1;
52331
- const field = match[2];
52332
- if (!FIELD_SET.has(field)) throw new Error(`Unknown priority field in formula: ${field}`);
52333
- score += operator * priority[field];
52334
- cursor = index + match[0].length;
52335
- }
52336
- if (!/^[\s+]*$/.test(formula.slice(cursor))) throw new Error(`Unsupported priority formula: ${formula}`);
52337
- return score;
52338
- };
52339
- const compareWorkItemsByPriority = (a, b, formula = DEFAULT_PRIORITY_FORMULA) => {
52340
- const aScore = calculatePriorityScore(a.priority, formula);
52341
- const bScore = calculatePriorityScore(b.priority, formula);
52342
- if (aScore !== void 0 && bScore !== void 0 && aScore !== bScore) return bScore - aScore;
52343
- if (aScore !== void 0 && bScore === void 0) return -1;
52344
- if (aScore === void 0 && bScore !== void 0) return 1;
52345
- return a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id);
52346
- };
52347
- const priorityFromPartial = (partial) => {
52348
- if (Object.values(partial).every((value) => value === void 0)) return void 0;
52349
- return {
52350
- confidence: partial.confidence ?? 3,
52351
- effort: partial.effort ?? 3,
52352
- impact: partial.impact ?? 3,
52353
- risk: partial.risk ?? 3,
52354
- urgency: partial.urgency ?? 3
52355
- };
52356
- };
52357
- //#endregion
52358
- //#region src/actions/work/render.ts
52359
- const maxWidth = (headerLabel, values, max = Infinity) => {
52360
- return Math.min(max, Math.max(headerLabel.length, ...values.map((value) => value.length)));
52361
- };
52362
- const resolveTableWidth = () => {
52363
- const columns = process.stdout.isTTY ? process.stdout.columns : void 0;
52364
- return Math.max(72, Math.min(columns ?? 120, 160) - 2);
52365
- };
52366
- const resolveWorkTableWidths = (rows) => {
52367
- const tableChromeWidth = 19;
52368
- const id = maxWidth("ID", rows.map((row) => row.id), 28);
52369
- const status = maxWidth("Status", rows.map((row) => row.status), 12);
52370
- const type = maxWidth("Type", rows.map((row) => row.type), 12);
52371
- const score = maxWidth("Score", rows.map((row) => row.score), 8);
52372
- const area = maxWidth("Area", rows.map((row) => row.area), 20);
52373
- const fixedWidth = tableChromeWidth + id + status + type + score + area;
52374
- const availableTitle = Math.max(20, resolveTableWidth() - fixedWidth);
52375
- const naturalTitle = maxWidth("Title", rows.map((row) => row.title), 72);
52376
- return {
52377
- area,
52378
- id,
52379
- score,
52380
- status,
52381
- title: Math.min(naturalTitle, availableTitle),
52382
- type
52383
- };
52384
- };
52385
- const workTableConfig = (widths) => ({
52386
- border: (0, import_src.getBorderCharacters)("norc"),
52387
- columnDefault: {
52388
- paddingLeft: 1,
52389
- paddingRight: 1,
52390
- wrapWord: true
52391
- },
52392
- columns: {
52393
- 0: { width: widths.id },
52394
- 1: { width: widths.status },
52395
- 2: { width: widths.type },
52396
- 3: {
52397
- alignment: "right",
52398
- width: widths.score
52399
- },
52400
- 4: { width: widths.area },
52401
- 5: { width: widths.title }
52402
- },
52403
- drawHorizontalLine: (index, size) => [
52404
- 0,
52405
- 1,
52406
- size
52407
- ].includes(index)
52408
- });
52409
- const toRow = (item, formula) => {
52410
- const score = calculatePriorityScore(item.priority, formula);
52411
- return {
52412
- area: item.area ?? "-",
52413
- id: item.id,
52414
- score: score === void 0 ? "-" : String(score),
52415
- status: item.status,
52416
- title: item.title,
52417
- type: item.type
52418
- };
52419
- };
52420
- const formatWorkTable = (items, formula) => {
52421
- const rows = items.map((item) => toRow(item, formula));
52422
- const widths = resolveWorkTableWidths(rows);
52423
- return (0, import_src.table)([[
52424
- chalk.gray.bold("ID"),
52425
- chalk.gray.bold("Status"),
52426
- chalk.gray.bold("Type"),
52427
- chalk.gray.bold("Score"),
52428
- chalk.gray.bold("Area"),
52429
- chalk.gray.bold("Title")
52430
- ], ...rows.map((row) => [
52431
- chalk.cyan(row.id),
52432
- chalk.white(row.status),
52433
- chalk.white(row.type),
52434
- chalk.gray(row.score),
52435
- chalk.gray(row.area),
52436
- chalk.white(row.title)
52437
- ])], workTableConfig(widths)).trimEnd();
52438
- };
52439
- const printWorkItemsTable = (items, formula) => {
52440
- if (isJsonMode()) return;
52441
- if (items.length === 0) {
52442
- xyLog("No work items");
52443
- return;
52444
- }
52445
- xyLog(formatWorkTable(items, formula));
52446
- };
52447
- const printWorkItemSummary = (item, score) => {
52448
- const scoreText = score === void 0 ? "-" : String(score);
52449
- xyLog(`${item.id}\t${item.status}\t${item.type}\t${scoreText}\t${item.title}`);
52450
- };
52451
- //#endregion
52452
- //#region src/actions/work/result.ts
52453
- const cleanResult = (data) => {
52454
- return {
52455
- envelope: {
52456
- data,
52457
- errorCount: 0,
52458
- warningCount: 0
52459
- },
52460
- exitCode: 0,
52461
- data
52462
- };
51948
+ const workStoreExists = (cwd = process.cwd()) => {
51949
+ return existsSync(fixedWorkRootPaths(cwd).configPath);
52463
51950
  };
52464
- const nowIso = (now = /* @__PURE__ */ new Date()) => now.toISOString();
52465
51951
  //#endregion
52466
51952
  //#region src/actions/work/github.ts
52467
51953
  /** Label applied to every GitHub issue created by `xy work`. */
@@ -52722,6 +52208,20 @@ const createGithubWorkBridge = (runner = defaultGithubWorkRunner) => {
52722
52208
  };
52723
52209
  const defaultGithubWorkBridge = createGithubWorkBridge();
52724
52210
  //#endregion
52211
+ //#region src/actions/work/result.ts
52212
+ const cleanResult = (data) => {
52213
+ return {
52214
+ envelope: {
52215
+ data,
52216
+ errorCount: 0,
52217
+ warningCount: 0
52218
+ },
52219
+ exitCode: 0,
52220
+ data
52221
+ };
52222
+ };
52223
+ const nowIso = (now = /* @__PURE__ */ new Date()) => now.toISOString();
52224
+ //#endregion
52725
52225
  //#region src/actions/work/sync.ts
52726
52226
  const resolveGithubBridge = (config, cwd, bridge = defaultGithubWorkBridge) => {
52727
52227
  if (!config.stores.github.enabled) return void 0;
@@ -52754,261 +52254,1808 @@ const emptySyncSummary = () => ({
52754
52254
  updatedGithub: [],
52755
52255
  updatedLocal: []
52756
52256
  });
52757
- const withGithubLink = (item, number, url, createdByXyWork) => {
52257
+ const withGithubLink$1 = (item, number, url, createdByXyWork) => {
52258
+ return {
52259
+ ...item,
52260
+ stores: {
52261
+ ...item.stores,
52262
+ github: {
52263
+ createdByXyWork,
52264
+ number,
52265
+ ...!createdByXyWork && { source: "github" },
52266
+ url
52267
+ }
52268
+ }
52269
+ };
52270
+ };
52271
+ const importGithubIssueLocally = (cwd, issue, now, preferredId) => {
52272
+ const base = normalizeGithubIssueToWorkItem(issue);
52273
+ const id = preferredId ?? base.id;
52274
+ const createdByXyWork = isXyWorkGithubIssue(issue);
52275
+ const open = githubIssueIsOpen(issue);
52276
+ const item = {
52277
+ ...base,
52278
+ completedAt: open ? void 0 : base.updatedAt || nowIso(now),
52279
+ id,
52280
+ status: open ? "open" : "done",
52281
+ stores: { github: {
52282
+ createdByXyWork,
52283
+ number: issue.number,
52284
+ ...!createdByXyWork && { source: "github" },
52285
+ url: issue.url
52286
+ } },
52287
+ updatedAt: nowIso(now)
52288
+ };
52289
+ writeWorkItem(cwd, item);
52290
+ return item;
52291
+ };
52292
+ const createMissingGithubIssues = (cwd, localItems, github, issuesByNumber, summary, now) => {
52293
+ for (const item of localItems) {
52294
+ if (readGithubStoreNumber(item.stores) !== void 0) continue;
52295
+ if (isTerminalWorkStatus(item.status)) continue;
52296
+ try {
52297
+ const ref = github.createIssue(cwd, item);
52298
+ const linked = {
52299
+ ...withGithubLink$1(item, ref.number, ref.url, true),
52300
+ updatedAt: nowIso(now)
52301
+ };
52302
+ writeWorkItem(cwd, linked);
52303
+ summary.createdGithub.push(`${item.id}→#${String(ref.number)}`);
52304
+ issuesByNumber.set(ref.number, {
52305
+ body: formatGithubWorkIssueBody(linked),
52306
+ createdAt: linked.createdAt,
52307
+ labels: ["xy-work"],
52308
+ number: ref.number,
52309
+ state: "OPEN",
52310
+ title: linked.title,
52311
+ updatedAt: linked.updatedAt,
52312
+ url: ref.url
52313
+ });
52314
+ } catch (error) {
52315
+ const message = error instanceof Error ? error.message : String(error);
52316
+ xyLog(`Sync create failed for ${item.id}: ${message}`);
52317
+ }
52318
+ }
52319
+ };
52320
+ const attachOrImportGithubIssues = (cwd, issuesByNumber, summary, now) => {
52321
+ const localItems = listWorkItems(cwd);
52322
+ const localById = new Map(localItems.map((item) => [item.id, item]));
52323
+ const linkedNumbers = linkedGithubNumbers(localItems);
52324
+ for (const issue of issuesByNumber.values()) {
52325
+ if (linkedNumbers.has(issue.number)) continue;
52326
+ const xyWorkId = isXyWorkGithubIssue(issue) ? parseXyWorkIdFromGithubBody(issue.body) : void 0;
52327
+ if (xyWorkId !== void 0 && localById.has(xyWorkId)) {
52328
+ const existing = localById.get(xyWorkId);
52329
+ if (existing === void 0) continue;
52330
+ if (readGithubStoreNumber(existing.stores) === void 0) {
52331
+ const linked = {
52332
+ ...withGithubLink$1(existing, issue.number, issue.url, true),
52333
+ updatedAt: nowIso(now)
52334
+ };
52335
+ writeWorkItem(cwd, linked);
52336
+ localById.set(xyWorkId, linked);
52337
+ linkedNumbers.add(issue.number);
52338
+ summary.updatedLocal.push(`${xyWorkId}↔#${String(issue.number)}`);
52339
+ }
52340
+ continue;
52341
+ }
52342
+ if (!githubIssueIsOpen(issue) && !isXyWorkGithubIssue(issue)) continue;
52343
+ const preferredId = xyWorkId;
52344
+ if (preferredId !== void 0 && localById.has(preferredId)) continue;
52345
+ try {
52346
+ const imported = importGithubIssueLocally(cwd, issue, now ?? /* @__PURE__ */ new Date(), preferredId);
52347
+ localById.set(imported.id, imported);
52348
+ linkedNumbers.add(issue.number);
52349
+ summary.importedLocal.push(`${imported.id}←#${String(issue.number)}`);
52350
+ } catch (error) {
52351
+ const message = error instanceof Error ? error.message : String(error);
52352
+ xyLog(`Sync import failed for GitHub #${String(issue.number)}: ${message}`);
52353
+ }
52354
+ }
52355
+ };
52356
+ const reconcileTitleDrift = (cwd, github, item, issue, number, summary, now) => {
52357
+ if (item.title === issue.title) return {
52358
+ localChanged: false,
52359
+ next: item
52360
+ };
52361
+ if (item.updatedAt.localeCompare(issue.updatedAt) >= 0) {
52362
+ github.updateIssue(cwd, number, {
52363
+ body: formatGithubWorkIssueBody(item),
52364
+ title: item.title
52365
+ });
52366
+ summary.updatedGithub.push(`${item.id}→#${String(number)}`);
52367
+ issue.title = item.title;
52368
+ issue.updatedAt = nowIso(now);
52369
+ return {
52370
+ localChanged: false,
52371
+ next: item
52372
+ };
52373
+ }
52374
+ return {
52375
+ localChanged: true,
52376
+ next: {
52377
+ ...item,
52378
+ title: issue.title,
52379
+ updatedAt: nowIso(now)
52380
+ }
52381
+ };
52382
+ };
52383
+ const ensureGithubStoreUrl = (item, issue, number) => {
52384
+ const url = readGithubStoreUrl(item.stores) ?? issue.url;
52385
+ if (readGithubStoreUrl(item.stores) === url) return {
52386
+ localChanged: false,
52387
+ next: item
52388
+ };
52389
+ const store = item.stores.github;
52390
+ const createdByXyWork = isXyWorkGithubIssue(issue) || typeof store === "object" && store !== null && store.createdByXyWork === true;
52391
+ return {
52392
+ localChanged: true,
52393
+ next: withGithubLink$1(item, number, url, createdByXyWork)
52394
+ };
52395
+ };
52396
+ const reconcileLinkedItem = (cwd, github, item, issue, number, summary, now) => {
52397
+ let next = item;
52398
+ let localChanged = false;
52399
+ const issueOpen = githubIssueIsOpen(issue);
52400
+ const localTerminal = isTerminalWorkStatus(item.status);
52401
+ if (localTerminal && issueOpen) {
52402
+ github.updateIssue(cwd, number, { state: "closed" });
52403
+ summary.closedGithub.push(`${item.id}→#${String(number)}`);
52404
+ issue.state = "CLOSED";
52405
+ } else if (!localTerminal && !issueOpen) {
52406
+ next = {
52407
+ ...next,
52408
+ completedAt: next.completedAt ?? issue.updatedAt,
52409
+ status: "done",
52410
+ updatedAt: nowIso(now),
52411
+ verification: [.../* @__PURE__ */ new Set([...next.verification, `synced closed from GitHub #${String(number)}`])]
52412
+ };
52413
+ localChanged = true;
52414
+ } else if (!localTerminal && issueOpen) {
52415
+ const titleResult = reconcileTitleDrift(cwd, github, next, issue, number, summary, now);
52416
+ next = titleResult.next;
52417
+ localChanged ||= titleResult.localChanged;
52418
+ }
52419
+ const urlResult = ensureGithubStoreUrl(next, issue, number);
52420
+ next = urlResult.next;
52421
+ localChanged ||= urlResult.localChanged;
52422
+ if (localChanged) {
52423
+ writeWorkItem(cwd, next);
52424
+ summary.updatedLocal.push(`${next.id}←#${String(number)}`);
52425
+ }
52426
+ };
52427
+ const reconcileLinkedPairs = (cwd, github, issuesByNumber, summary, now) => {
52428
+ for (const item of listWorkItems(cwd)) {
52429
+ const number = readGithubStoreNumber(item.stores);
52430
+ if (number === void 0) continue;
52431
+ const issue = issuesByNumber.get(number);
52432
+ if (issue === void 0) continue;
52433
+ try {
52434
+ reconcileLinkedItem(cwd, github, item, issue, number, summary, now);
52435
+ } catch (error) {
52436
+ const message = error instanceof Error ? error.message : String(error);
52437
+ xyLog(`Sync reconcile failed for ${item.id}/#${String(number)}: ${message}`);
52438
+ }
52439
+ }
52440
+ };
52441
+ const logSyncSummary = (summary) => {
52442
+ if (summary.createdGithub.length + summary.importedLocal.length + summary.updatedLocal.length + summary.updatedGithub.length + summary.closedGithub.length + summary.reopenedGithub.length === 0) {
52443
+ xyLog("GitHub sync: already in sync");
52444
+ return;
52445
+ }
52446
+ xyLog([
52447
+ "GitHub sync complete:",
52448
+ ` created GitHub: ${String(summary.createdGithub.length)}`,
52449
+ ` imported local: ${String(summary.importedLocal.length)}`,
52450
+ ` updated local: ${String(summary.updatedLocal.length)}`,
52451
+ ` updated GitHub: ${String(summary.updatedGithub.length)}`,
52452
+ ` closed GitHub: ${String(summary.closedGithub.length)}`
52453
+ ].join("\n"));
52454
+ };
52455
+ const emptyWorkSyncDrift = () => ({
52456
+ githubMissingLocal: [],
52457
+ localMissingGithub: [],
52458
+ statusMismatch: [],
52459
+ titleMismatch: []
52460
+ });
52461
+ const workSyncDriftIsClean = (drift) => {
52462
+ return drift.githubMissingLocal.length === 0 && drift.localMissingGithub.length === 0 && drift.statusMismatch.length === 0 && drift.titleMismatch.length === 0;
52463
+ };
52464
+ const recordLocalMissingGithub = (localItems, drift) => {
52465
+ for (const item of localItems) {
52466
+ if (isTerminalWorkStatus(item.status)) continue;
52467
+ if (readGithubStoreNumber(item.stores) === void 0) drift.localMissingGithub.push(item.id);
52468
+ }
52469
+ };
52470
+ const recordLinkedPairDrift = (issue, linked, drift) => {
52471
+ if (linked.title !== issue.title) drift.titleMismatch.push(`${linked.id}/#${String(issue.number)}`);
52472
+ const issueOpen = githubIssueIsOpen(issue);
52473
+ const localTerminal = isTerminalWorkStatus(linked.status);
52474
+ if (localTerminal && issueOpen) {
52475
+ drift.statusMismatch.push(`${linked.id} done/wontfix but GitHub #${String(issue.number)} open`);
52476
+ return;
52477
+ }
52478
+ if (!localTerminal && !issueOpen) drift.statusMismatch.push(`${linked.id} open locally but GitHub #${String(issue.number)} closed`);
52479
+ };
52480
+ const recordUnlinkedXyWorkDrift = (issue, localById, drift) => {
52481
+ if (!isXyWorkGithubIssue(issue)) return;
52482
+ const preferredId = parseXyWorkIdFromGithubBody(issue.body);
52483
+ if (preferredId !== void 0 && localById.has(preferredId)) {
52484
+ drift.githubMissingLocal.push(`#${String(issue.number)}↔${preferredId} (unlinked)`);
52485
+ return;
52486
+ }
52487
+ drift.githubMissingLocal.push(preferredId === void 0 ? `#${String(issue.number)} (${issue.title})` : `#${String(issue.number)}→${preferredId}`);
52488
+ };
52489
+ /**
52490
+ * Compute local ↔ GitHub drift without mutating either side.
52491
+ * Returns empty drift when GitHub is unavailable or disabled.
52492
+ */
52493
+ const computeWorkSyncDrift = (cwd, options = {}) => {
52494
+ const config = options.config ?? readWorkConfig(cwd);
52495
+ const drift = emptyWorkSyncDrift();
52496
+ const github = resolveGithubBridge(config, cwd, options.github);
52497
+ if (github === void 0) return drift;
52498
+ const localItems = listWorkItems(cwd);
52499
+ const localById = new Map(localItems.map((item) => [item.id, item]));
52500
+ const linkedNumbers = linkedGithubNumbers(localItems);
52501
+ recordLocalMissingGithub(localItems, drift);
52502
+ let issues;
52503
+ try {
52504
+ issues = github.listIssues(cwd, "all");
52505
+ } catch {
52506
+ return drift;
52507
+ }
52508
+ for (const issue of issues) {
52509
+ if (linkedNumbers.has(issue.number)) {
52510
+ const linked = localItems.find((item) => readGithubStoreNumber(item.stores) === issue.number);
52511
+ if (linked !== void 0) recordLinkedPairDrift(issue, linked, drift);
52512
+ continue;
52513
+ }
52514
+ recordUnlinkedXyWorkDrift(issue, localById, drift);
52515
+ }
52516
+ return drift;
52517
+ };
52518
+ /**
52519
+ * Bidirectional sync between repo-local work items and GitHub Issues when available.
52520
+ *
52521
+ * - Local active items without a GitHub link → create a marked GitHub issue
52522
+ * - Open/closed GitHub issues not present locally → import as local items
52523
+ * - Linked pairs: reconcile title (newer wins) and status (done/wontfix ↔ closed)
52524
+ */
52525
+ const workSync = (options = {}) => {
52526
+ const cwd = options.cwd ?? process.cwd();
52527
+ const config = readWorkConfig(cwd);
52528
+ const summary = emptySyncSummary();
52529
+ const github = resolveGithubBridge(config, cwd, options.github);
52530
+ if (github === void 0) {
52531
+ xyLog("GitHub sync skipped: GitHub Issues unavailable or disabled");
52532
+ return cleanResult({ summary });
52533
+ }
52534
+ const issuesByNumber = /* @__PURE__ */ new Map();
52535
+ for (const issue of github.listIssues(cwd, "all")) issuesByNumber.set(issue.number, issue);
52536
+ createMissingGithubIssues(cwd, listWorkItems(cwd), github, issuesByNumber, summary, options.now);
52537
+ attachOrImportGithubIssues(cwd, issuesByNumber, summary, options.now);
52538
+ reconcileLinkedPairs(cwd, github, issuesByNumber, summary, options.now);
52539
+ logSyncSummary(summary);
52540
+ return cleanResult({ summary });
52541
+ };
52542
+ //#endregion
52543
+ //#region src/actions/work/priority.ts
52544
+ const FIELD_SET = new Set(WORK_PRIORITY_FIELDS);
52545
+ const TERM_PATTERN = /([+-]?)\s*(impact|urgency|effort|risk|confidence)/g;
52546
+ const calculatePriorityScore = (priority, formula = DEFAULT_PRIORITY_FORMULA) => {
52547
+ if (priority === void 0) return void 0;
52548
+ let score = 0;
52549
+ let cursor = 0;
52550
+ for (const match of formula.matchAll(TERM_PATTERN)) {
52551
+ const index = match.index ?? 0;
52552
+ const skipped = formula.slice(cursor, index);
52553
+ if (!/^[\s+]*$/.test(skipped)) throw new Error(`Unsupported priority formula: ${formula}`);
52554
+ const operator = match[1] === "-" ? -1 : 1;
52555
+ const field = match[2];
52556
+ if (!FIELD_SET.has(field)) throw new Error(`Unknown priority field in formula: ${field}`);
52557
+ score += operator * priority[field];
52558
+ cursor = index + match[0].length;
52559
+ }
52560
+ if (!/^[\s+]*$/.test(formula.slice(cursor))) throw new Error(`Unsupported priority formula: ${formula}`);
52561
+ return score;
52562
+ };
52563
+ const compareWorkItemsByPriority = (a, b, formula = DEFAULT_PRIORITY_FORMULA) => {
52564
+ const aScore = calculatePriorityScore(a.priority, formula);
52565
+ const bScore = calculatePriorityScore(b.priority, formula);
52566
+ if (aScore !== void 0 && bScore !== void 0 && aScore !== bScore) return bScore - aScore;
52567
+ if (aScore !== void 0 && bScore === void 0) return -1;
52568
+ if (aScore === void 0 && bScore !== void 0) return 1;
52569
+ return a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id);
52570
+ };
52571
+ const priorityFromPartial = (partial) => {
52572
+ if (Object.values(partial).every((value) => value === void 0)) return void 0;
52573
+ return {
52574
+ confidence: partial.confidence ?? 3,
52575
+ effort: partial.effort ?? 3,
52576
+ impact: partial.impact ?? 3,
52577
+ risk: partial.risk ?? 3,
52578
+ urgency: partial.urgency ?? 3
52579
+ };
52580
+ };
52581
+ //#endregion
52582
+ //#region src/actions/work/workspace.ts
52583
+ const isWorkspaceScope = (options) => {
52584
+ return options.workspace === true || options.workspaceFile !== void 0 && options.workspaceFile.length > 0;
52585
+ };
52586
+ const singleRepo = (cwd) => {
52587
+ return {
52588
+ cwd: PATH.resolve(cwd),
52589
+ hasStore: workStoreExists(cwd),
52590
+ name: PATH.basename(PATH.resolve(cwd))
52591
+ };
52592
+ };
52593
+ const preferredFolderName = (absolutePath, explicitName) => {
52594
+ if (explicitName !== void 0 && explicitName.length > 0) return explicitName;
52595
+ return PATH.basename(absolutePath);
52596
+ };
52597
+ const disambiguateRepoNames = (folders) => {
52598
+ const nameCounts = /* @__PURE__ */ new Map();
52599
+ for (const folder of folders) nameCounts.set(folder.preferredName, (nameCounts.get(folder.preferredName) ?? 0) + 1);
52600
+ return folders.map((folder) => {
52601
+ const base = folder.preferredName;
52602
+ const name = (nameCounts.get(base) ?? 0) > 1 ? `${base}@${PATH.basename(PATH.dirname(folder.absolutePath))}` : base;
52603
+ return {
52604
+ cwd: folder.absolutePath,
52605
+ hasStore: workStoreExists(folder.absolutePath),
52606
+ name
52607
+ };
52608
+ });
52609
+ };
52610
+ const resolveWorkRepos = (options = {}) => {
52611
+ const cwd = PATH.resolve(options.cwd ?? process.cwd());
52612
+ if (!isWorkspaceScope(options)) {
52613
+ const repo = singleRepo(cwd);
52614
+ if (options.repo !== void 0 && options.repo.length > 0 && options.repo !== repo.name) throw new Error(`Repo filter "${options.repo}" does not match current directory repo "${repo.name}"`);
52615
+ return [repo];
52616
+ }
52617
+ const lookup = resolveCodeWorkspaceFile(options.workspaceFile, cwd);
52618
+ if (lookup === void 0) throw new Error("Could not resolve a *.code-workspace file. Pass --workspace-file <path> or open a multi-root workspace.");
52619
+ const folders = parseCodeWorkspace(lookup.path).map((folder) => ({
52620
+ absolutePath: PATH.resolve(folder.absolutePath),
52621
+ preferredName: preferredFolderName(folder.absolutePath, folder.name)
52622
+ })).filter((folder) => existsSync(folder.absolutePath));
52623
+ const seen = /* @__PURE__ */ new Set();
52624
+ const unique = folders.filter((folder) => {
52625
+ if (seen.has(folder.absolutePath)) return false;
52626
+ seen.add(folder.absolutePath);
52627
+ return true;
52628
+ });
52629
+ let repos = disambiguateRepoNames(unique);
52630
+ if (options.repo !== void 0 && options.repo.length > 0) {
52631
+ repos = repos.filter((repo) => repo.name === options.repo);
52632
+ if (repos.length === 0) {
52633
+ const available = disambiguateRepoNames(unique).map((repo) => repo.name).toSorted();
52634
+ throw new Error(`Workspace folder not found: ${options.repo}. Available: ${available.join(", ") || "(none)"}`);
52635
+ }
52636
+ }
52637
+ return repos;
52638
+ };
52639
+ const resolveWorkReposWithStore = (options = {}) => {
52640
+ return resolveWorkRepos(options).filter((repo) => repo.hasStore);
52641
+ };
52642
+ const toScopedWorkItem = (item, repo, formula = DEFAULT_PRIORITY_FORMULA) => {
52643
+ return {
52644
+ ...item,
52645
+ formula,
52646
+ repo: repo.name,
52647
+ repoCwd: repo.cwd
52648
+ };
52649
+ };
52650
+ /** Load work items for the current scope (auto-inits only in single-repo mode). */
52651
+ const listScopedWorkItems = (options = {}) => {
52652
+ if (!isWorkspaceScope(options)) {
52653
+ const cwd = PATH.resolve(options.cwd ?? process.cwd());
52654
+ const config = readWorkConfig(cwd);
52655
+ const repo = singleRepo(cwd);
52656
+ return listWorkItems(cwd).map((item) => toScopedWorkItem(item, repo, config.priority.formula));
52657
+ }
52658
+ const repos = resolveWorkReposWithStore(options);
52659
+ const items = [];
52660
+ for (const repo of repos) {
52661
+ const config = readWorkConfig(repo.cwd);
52662
+ for (const item of listWorkItems(repo.cwd)) items.push(toScopedWorkItem(item, repo, config.priority.formula));
52663
+ }
52664
+ return items;
52665
+ };
52666
+ const compareScopedWorkItemsByPriority = (a, b) => {
52667
+ const aScore = calculatePriorityScore(a.priority, a.formula);
52668
+ const bScore = calculatePriorityScore(b.priority, b.formula);
52669
+ if (aScore !== void 0 && bScore !== void 0 && aScore !== bScore) return bScore - aScore;
52670
+ if (aScore !== void 0 && bScore === void 0) return -1;
52671
+ if (aScore === void 0 && bScore !== void 0) return 1;
52672
+ return a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id) || a.repo.localeCompare(b.repo);
52673
+ };
52674
+ const selectScopedWorkItems = (items, options) => {
52675
+ const filtered = items.filter((item) => (options.status === void 0 || item.status === options.status) && (options.type === void 0 || item.type === options.type));
52676
+ if (options.sort === "priority") return filtered.toSorted(compareScopedWorkItemsByPriority);
52677
+ return filtered.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id) || a.repo.localeCompare(b.repo));
52678
+ };
52679
+ /**
52680
+ * Resolve a work item by id within the current scope.
52681
+ * In single-repo mode, uses cwd directly (same error as readWorkItem).
52682
+ */
52683
+ const resolveScopedWorkItem = (id, options = {}) => {
52684
+ if (!isWorkspaceScope(options)) {
52685
+ const cwd = PATH.resolve(options.cwd ?? process.cwd());
52686
+ const config = readWorkConfig(cwd);
52687
+ const item = readWorkItem(cwd, id);
52688
+ return toScopedWorkItem(item, singleRepo(cwd), config.priority.formula);
52689
+ }
52690
+ const repos = resolveWorkReposWithStore(options);
52691
+ const matches = [];
52692
+ for (const repo of repos) try {
52693
+ const item = readWorkItem(repo.cwd, id);
52694
+ const config = readWorkConfig(repo.cwd);
52695
+ matches.push(toScopedWorkItem(item, repo, config.priority.formula));
52696
+ } catch {}
52697
+ if (matches.length === 0) throw new Error(`Work item not found: ${id}`);
52698
+ if (matches.length > 1) {
52699
+ const reposList = matches.map((item) => item.repo).toSorted().join(", ");
52700
+ throw new Error(`Work item id ${id} is ambiguous across repos: ${reposList}. Pass --repo <name>.`);
52701
+ }
52702
+ const [match] = matches;
52703
+ if (match === void 0) throw new Error(`Work item not found: ${id}`);
52704
+ return match;
52705
+ };
52706
+ /**
52707
+ * Target repo for create operations (`add`).
52708
+ * Workspace mode: --repo, else deepest workspace folder containing cwd, else error.
52709
+ */
52710
+ const resolveAddTargetRepo = (options = {}) => {
52711
+ if (!isWorkspaceScope(options)) return singleRepo(PATH.resolve(options.cwd ?? process.cwd()));
52712
+ const repos = resolveWorkRepos({ ...options });
52713
+ if (options.repo !== void 0 && options.repo.length > 0) {
52714
+ const [target] = repos;
52715
+ if (target === void 0) throw new Error(`Workspace folder not found: ${options.repo}`);
52716
+ return target;
52717
+ }
52718
+ const cwd = PATH.resolve(options.cwd ?? process.cwd());
52719
+ const target = repos.filter((repo) => cwd === repo.cwd || cwd.startsWith(`${repo.cwd}${PATH.sep}`)).toSorted((a, b) => b.cwd.length - a.cwd.length)[0];
52720
+ if (target === void 0) {
52721
+ const available = resolveWorkRepos({
52722
+ cwd: options.cwd,
52723
+ workspace: options.workspace,
52724
+ workspaceFile: options.workspaceFile
52725
+ }).map((repo) => repo.name).toSorted();
52726
+ throw new Error(`xy work add --workspace requires --repo <name> when cwd is not inside a workspace folder. Available: ${available.join(", ") || "(none)"}`);
52727
+ }
52728
+ return target;
52729
+ };
52730
+ const findWorkRepoByName = (name, options = {}) => {
52731
+ const repos = resolveWorkRepos({
52732
+ ...options,
52733
+ repo: void 0,
52734
+ workspace: options.workspace ?? true,
52735
+ workspaceFile: options.workspaceFile
52736
+ });
52737
+ const match = repos.find((repo) => repo.name === name);
52738
+ if (match === void 0) throw new Error(`Workspace folder not found: ${name}. Available: ${repos.map((repo) => repo.name).toSorted().join(", ") || "(none)"}`);
52739
+ return match;
52740
+ };
52741
+ //#endregion
52742
+ //#region src/actions/work/lint.ts
52743
+ const pathLabel = (repo, absolutePath) => {
52744
+ const rel = PATH.relative(repo.cwd, absolutePath).split(PATH.sep).join("/");
52745
+ return rel.length === 0 ? "." : rel;
52746
+ };
52747
+ const collectGitignoredWorkPaths = (repo) => {
52748
+ if (!gitCleanGitignoreBackend.isGitRepo(repo.cwd)) return {
52749
+ gitignoredPaths: [],
52750
+ notGitRepo: true
52751
+ };
52752
+ const config = tryReadWorkConfig(repo.cwd);
52753
+ if (config === void 0) return {
52754
+ gitignoredPaths: [],
52755
+ notGitRepo: false
52756
+ };
52757
+ const paths = workStorePaths(repo.cwd, config);
52758
+ const candidates = [
52759
+ paths.rootDir,
52760
+ paths.configPath,
52761
+ paths.itemsDir
52762
+ ];
52763
+ const gitignoredPaths = [];
52764
+ for (const candidate of candidates) if (gitCleanGitignoreBackend.isIgnored(repo.cwd, candidate)) gitignoredPaths.push(pathLabel(repo, candidate));
52765
+ return {
52766
+ gitignoredPaths: [...new Set(gitignoredPaths)].toSorted(),
52767
+ notGitRepo: false
52768
+ };
52769
+ };
52770
+ const buildRepoContext = (repo, github) => {
52771
+ const config = tryReadWorkConfig(repo.cwd);
52772
+ const { gitignoredPaths, notGitRepo } = collectGitignoredWorkPaths(repo);
52773
+ if (config === void 0) return {
52774
+ driftMessages: [],
52775
+ githubEnabled: false,
52776
+ githubUnavailable: false,
52777
+ gitignoredPaths,
52778
+ notGitRepo,
52779
+ repo
52780
+ };
52781
+ const githubEnabled = config.stores.github.enabled;
52782
+ let githubUnavailable = false;
52783
+ const driftMessages = [];
52784
+ if (githubEnabled) {
52785
+ const bridge = resolveGithubBridge(config, repo.cwd, github);
52786
+ if (bridge === void 0) githubUnavailable = true;
52787
+ else try {
52788
+ const drift = computeWorkSyncDrift(repo.cwd, {
52789
+ config,
52790
+ github: bridge
52791
+ });
52792
+ if (!workSyncDriftIsClean(drift)) {
52793
+ for (const id of drift.localMissingGithub) driftMessages.push(`${id} — active local item missing GitHub link`);
52794
+ for (const entry of drift.githubMissingLocal) driftMessages.push(`${entry} — GitHub issue missing local item`);
52795
+ for (const entry of drift.titleMismatch) driftMessages.push(`${entry} — title mismatch`);
52796
+ for (const entry of drift.statusMismatch) driftMessages.push(entry);
52797
+ }
52798
+ } catch (error) {
52799
+ const message = error instanceof Error ? error.message : String(error);
52800
+ driftMessages.push(`failed to compute sync drift: ${message}`);
52801
+ }
52802
+ }
52803
+ return {
52804
+ driftMessages,
52805
+ githubEnabled,
52806
+ githubUnavailable,
52807
+ gitignoredPaths,
52808
+ notGitRepo,
52809
+ repo
52810
+ };
52811
+ };
52812
+ const withRepoPrefix = (repo, multi, message) => {
52813
+ return multi ? `${repo.name}: ${message}` : message;
52814
+ };
52815
+ const diagnosticsForMessages = (rule, messages) => {
52816
+ return messages.map((message) => ({
52817
+ message,
52818
+ rule
52819
+ }));
52820
+ };
52821
+ const WORK_LINT_RULES = [
52822
+ {
52823
+ check: ({ repos }) => {
52824
+ const multi = repos.length > 1;
52825
+ const messages = [];
52826
+ for (const ctx of repos) {
52827
+ if (ctx.notGitRepo) continue;
52828
+ for (const ignored of ctx.gitignoredPaths) messages.push(withRepoPrefix(ctx.repo, multi, `${ignored} is gitignored — work items must be committed; remove .xy/work from .gitignore`));
52829
+ }
52830
+ return { diagnostics: diagnosticsForMessages("work.store-not-gitignored", messages) };
52831
+ },
52832
+ defaultLevel: "error",
52833
+ description: "The .xy/work store is not gitignored",
52834
+ id: "work.store-not-gitignored"
52835
+ },
52836
+ {
52837
+ check: ({ repos }) => {
52838
+ const multi = repos.length > 1;
52839
+ const messages = [];
52840
+ for (const ctx of repos) {
52841
+ if (!ctx.githubEnabled) continue;
52842
+ if (ctx.githubUnavailable) messages.push(withRepoPrefix(ctx.repo, multi, "stores.github.enabled but gh is unavailable/unauthenticated for this repo"));
52843
+ }
52844
+ return { diagnostics: diagnosticsForMessages("work.github-available", messages) };
52845
+ },
52846
+ defaultLevel: "warn",
52847
+ description: "GitHub Issues are available when dual-write is enabled",
52848
+ id: "work.github-available"
52849
+ },
52850
+ {
52851
+ check: ({ repos }) => {
52852
+ const multi = repos.length > 1;
52853
+ const messages = [];
52854
+ for (const ctx of repos) {
52855
+ if (!ctx.githubEnabled || ctx.githubUnavailable) continue;
52856
+ for (const message of ctx.driftMessages) messages.push(withRepoPrefix(ctx.repo, multi, message));
52857
+ }
52858
+ return { diagnostics: diagnosticsForMessages("work.github-synced", messages) };
52859
+ },
52860
+ defaultLevel: "warn",
52861
+ description: "Local work items and GitHub Issues are in sync",
52862
+ id: "work.github-synced"
52863
+ }
52864
+ ];
52865
+ function logWorkDiagnostic(diagnostic) {
52866
+ if (diagnostic.level === "error") console.log(chalk.red(` ✗ ${diagnostic.message}`));
52867
+ else console.log(chalk.yellow(` ⚠ ${diagnostic.message}`));
52868
+ }
52869
+ const resolveLintRepos = (options) => {
52870
+ if (isWorkspaceScope(options)) return resolveWorkRepos(options).filter((repo) => repo.hasStore);
52871
+ return resolveWorkRepos({ cwd: PATH.resolve(options.cwd ?? process.cwd()) }).filter((repo) => repo.hasStore);
52872
+ };
52873
+ const workLint = async (options = {}) => {
52874
+ const repos = resolveLintRepos(options);
52875
+ if (repos.length === 0) {
52876
+ console.log(chalk.gray("No work stores found to lint"));
52877
+ return {
52878
+ envelope: {
52879
+ data: {
52880
+ diagnostics: [],
52881
+ errorCount: 0,
52882
+ fixedCount: 0,
52883
+ warningCount: 0
52884
+ },
52885
+ errorCount: 0,
52886
+ warningCount: 0
52887
+ },
52888
+ exitCode: 0
52889
+ };
52890
+ }
52891
+ const cwd = options.cwd ?? process.cwd();
52892
+ const context = { repos: repos.map((repo) => buildRepoContext(repo, options.github)) };
52893
+ return runRuleChecks({
52894
+ commandName: "work lint",
52895
+ config: await loadWorkspaceCommandConfig(cwd, "workLint"),
52896
+ configKey: "workLint",
52897
+ context,
52898
+ reporter: {
52899
+ diagnostic: logWorkDiagnostic,
52900
+ passed: (rule) => {
52901
+ console.log(chalk.green(` ✓ ${rule.id}`));
52902
+ }
52903
+ },
52904
+ rules: WORK_LINT_RULES,
52905
+ strict: options.strict === true
52906
+ });
52907
+ };
52908
+ //#endregion
52909
+ //#region src/actions/ruleCatalog.ts
52910
+ const REPO_LINT_RULES = [
52911
+ [
52912
+ "repo.root-private",
52913
+ "Root package is private",
52914
+ "error",
52915
+ true
52916
+ ],
52917
+ [
52918
+ "repo.no-private-publish-config",
52919
+ "Private root has no publishConfig",
52920
+ "error",
52921
+ true
52922
+ ],
52923
+ [
52924
+ "repo.packages-folder",
52925
+ "Workspace packages live under packages/",
52926
+ "error",
52927
+ false
52928
+ ],
52929
+ [
52930
+ "repo.spec-layout",
52931
+ "Spec files live in spec/ folders",
52932
+ "error",
52933
+ false
52934
+ ],
52935
+ [
52936
+ "repo.workspaces-field-placement",
52937
+ "Workspace fields are declared in the package-manager-specific location",
52938
+ "error",
52939
+ true
52940
+ ],
52941
+ [
52942
+ "repo.workspace-glob-coverage",
52943
+ "Workspace globs cover every package",
52944
+ "error",
52945
+ false
52946
+ ],
52947
+ [
52948
+ "repo.no-package-manager-in-workspaces",
52949
+ "Only the root package declares packageManager",
52950
+ "error",
52951
+ true
52952
+ ],
52953
+ [
52954
+ "repo.volta-only-root",
52955
+ "Only the root package declares volta",
52956
+ "error",
52957
+ true
52958
+ ],
52959
+ [
52960
+ "repo.engines-non-terminal",
52961
+ "Only non-terminal packages declare engines",
52962
+ "error",
52963
+ true
52964
+ ],
52965
+ [
52966
+ "repo.engines-lts",
52967
+ "Engine and volta versions include latest LTS",
52968
+ "error",
52969
+ false
52970
+ ],
52971
+ [
52972
+ "repo.version-consistency",
52973
+ "Workspace versions are consistent",
52974
+ "error",
52975
+ true
52976
+ ],
52977
+ [
52978
+ "repo.internal-dependency-ranges",
52979
+ "Internal dependencies use the expected workspace/version protocol",
52980
+ "error",
52981
+ true
52982
+ ],
52983
+ [
52984
+ "repo.internal-peer-ranges",
52985
+ "Internal peerDependencies use publishable ranges",
52986
+ "error",
52987
+ true
52988
+ ],
52989
+ [
52990
+ "repo.pnpm-release-age-excludes",
52991
+ "pnpm minimumReleaseAgeExclude matches imported scopes",
52992
+ "error",
52993
+ true
52994
+ ],
52995
+ [
52996
+ "repo.pnpm-minimum-release-age",
52997
+ "pnpm minimumReleaseAge is configured",
52998
+ "error",
52999
+ true
53000
+ ],
53001
+ [
53002
+ "repo.pnpm-no-overrides",
53003
+ "pnpm dependency overrides are not configured",
53004
+ "warn",
53005
+ false
53006
+ ]
53007
+ ].map(([id, description, defaultLevel, fixable]) => ({
53008
+ defaultLevel,
53009
+ description,
53010
+ fixable,
53011
+ id
53012
+ }));
53013
+ const NON_FIXABLE_DEAD_RULES = /* @__PURE__ */ new Set([
53014
+ "dead.repo.deprecated-export",
53015
+ "dead.workspace.deprecated-export",
53016
+ "dead.workspace.deprecated-unused-export"
53017
+ ]);
53018
+ function isDeadRuleFixable(ruleId) {
53019
+ return !NON_FIXABLE_DEAD_RULES.has(ruleId);
53020
+ }
53021
+ function severityToLevel(severity, enabled = true) {
53022
+ if (!enabled) return "off";
53023
+ return severity === "error" ? "error" : "warn";
53024
+ }
53025
+ async function loadCommandConfig(commandName, pkg) {
53026
+ if (pkg !== void 0 && pkg.length > 0) {
53027
+ const workspace = getPackageManager().findWorkspace(pkg);
53028
+ if (workspace === void 0) throw new Error(`Workspace not found: ${pkg}`);
53029
+ return loadWorkspaceCommandConfig(workspace.location, commandName);
53030
+ }
53031
+ return loadWorkspaceCommandConfig(process.cwd(), commandName);
53032
+ }
53033
+ function staticCatalog(command, configKey, definitions, config) {
53034
+ const ruleSettings = config?.rules ?? {};
53035
+ const known = new Set(definitions.flatMap((rule) => [rule.id, ...rule.aliases ?? []]));
53036
+ const unknown = Object.keys(ruleSettings).filter((id) => !known.has(id));
53037
+ if (unknown.length > 0) throw new TypeError(`Unknown ${command} rule ${unknown.map((id) => `"${id}"`).join(", ")} in commands.${configKey}.rules`);
53038
+ const resolveSetting = (rule) => {
53039
+ if (ruleSettings[rule.id] !== void 0) return ruleSettings[rule.id];
53040
+ const aliases = rule.aliases ?? [];
53041
+ for (const alias of aliases) if (ruleSettings[alias] !== void 0) return ruleSettings[alias];
53042
+ };
53043
+ return definitions.map((rule) => ({
53044
+ command,
53045
+ defaultLevel: rule.defaultLevel,
53046
+ description: rule.description,
53047
+ fixable: rule.fixable === true,
53048
+ id: rule.id,
53049
+ level: parseRuleLevelSetting(ruleConfigPath(configKey, rule.id), resolveSetting(rule), rule.defaultLevel)
53050
+ }));
53051
+ }
53052
+ function runtimeRuleCatalog(command, configKey, definitions, config) {
53053
+ return staticCatalog(command, configKey, definitions, config);
53054
+ }
53055
+ function commandPrefix(prefix, rules) {
53056
+ return rules.map((rule) => ({
53057
+ ...rule,
53058
+ command: `${prefix} ${rule.command}`
53059
+ }));
53060
+ }
53061
+ async function getDeplintRuleCatalog(pkg) {
53062
+ const config = await loadCommandConfig("deplint", pkg);
53063
+ const rules = await loadDeplintRules(config);
53064
+ const defaultRules = await loadDeplintRules(config === void 0 ? void 0 : {
53065
+ ...config,
53066
+ rules: void 0
53067
+ });
53068
+ const defaults = new Map(defaultRules.map((rule) => [rule.id, severityToLevel(rule.meta.severity, rule.enabled !== false)]));
53069
+ return sortRules(rules.map((rule) => ({
53070
+ command: RULE_COMMANDS.deplint.command,
53071
+ defaultLevel: defaults.get(rule.id) ?? "warn",
53072
+ description: rule.meta.description,
53073
+ fixable: isRuleFixable(rule),
53074
+ id: rule.id,
53075
+ level: severityToLevel(rule.meta.severity, rule.enabled !== false)
53076
+ })));
53077
+ }
53078
+ async function getDeadRuleCatalog(pkg, options) {
53079
+ const config = await loadCommandConfig("dead", pkg);
53080
+ const rules = loadDeadRules(config, { deprecated: options?.deprecated === true });
53081
+ const defaultConfig = config === void 0 ? void 0 : {
53082
+ ...config,
53083
+ rules: void 0
53084
+ };
53085
+ const defaults = new Map(loadDeadRules(defaultConfig, { deprecated: options?.deprecated === true }).map((rule) => [rule.id, severityToLevel(rule.meta.severity, rule.enabled)]));
53086
+ return sortRules(rules.map((rule) => ({
53087
+ command: RULE_COMMANDS.dead.command,
53088
+ defaultLevel: defaults.get(rule.id) ?? "warn",
53089
+ description: rule.meta.description,
53090
+ fixable: isDeadRuleFixable(rule.id),
53091
+ id: rule.id,
53092
+ level: severityToLevel(rule.meta.severity, rule.enabled)
53093
+ })));
53094
+ }
53095
+ async function getPublintRuleCatalog(command = RULE_COMMANDS.publint.command, pkg) {
53096
+ const levels = resolvePublintRuleLevels(await loadCommandConfig("publint", pkg));
53097
+ return ALL_PUBLINT_CHECKS.map((check) => ({
53098
+ command,
53099
+ defaultLevel: defaultPublintLevel(check),
53100
+ description: publintRuleDescription(check),
53101
+ fixable: publintRuleFixable(check),
53102
+ id: publintRuleId(check),
53103
+ level: levels.get(check) ?? "warn"
53104
+ }));
53105
+ }
53106
+ async function getApiExposureRuleCatalog(pkg) {
53107
+ const config = normalizeApiExposureConfig(await loadCommandConfig("apiExposure", pkg));
53108
+ const byId = new Map(config.rules.map((rule) => [rule.id, rule]));
53109
+ return AEI_RULES.map((rule) => {
53110
+ const resolved = byId.get(rule.id);
53111
+ return {
53112
+ command: RULE_COMMANDS.apiExposure.command,
53113
+ defaultLevel: rule.defaultEnabled === false ? "off" : "warn",
53114
+ description: rule.description,
53115
+ fixable: false,
53116
+ id: rule.id,
53117
+ level: resolved?.level ?? "warn",
53118
+ weight: resolved?.weight ?? rule.defaultWeight
53119
+ };
53120
+ });
53121
+ }
53122
+ async function getGitlintRuleCatalog() {
53123
+ return runtimeRuleCatalog(RULE_COMMANDS.gitLint.command, RULE_COMMANDS.gitLint.configKey, GITLINT_RULES, await loadCommandConfig("gitLint"));
53124
+ }
53125
+ async function getPackmanRuleCatalog() {
53126
+ return runtimeRuleCatalog(RULE_COMMANDS.packman.command, RULE_COMMANDS.packman.configKey, PACKMAN_RULES, await loadCommandConfig("packman"));
53127
+ }
53128
+ async function getRepoLintRuleCatalog() {
53129
+ return staticCatalog(RULE_COMMANDS.repoLint.command, RULE_COMMANDS.repoLint.configKey, REPO_LINT_RULES, await loadCommandConfig("repoLint"));
53130
+ }
53131
+ async function getNodeLintRuleCatalog() {
53132
+ return runtimeRuleCatalog(RULE_COMMANDS.nodeLint.command, RULE_COMMANDS.nodeLint.configKey, NODE_LINT_RULES, await loadCommandConfig("nodeLint"));
53133
+ }
53134
+ async function getLintlintRuleCatalog() {
53135
+ return runtimeRuleCatalog(RULE_COMMANDS.lintLint.command, RULE_COMMANDS.lintLint.configKey, LINTLINT_RULES, await loadCommandConfig("lintLint"));
53136
+ }
53137
+ async function getSkillsLintRuleCatalog() {
53138
+ return runtimeRuleCatalog(RULE_COMMANDS.skillsLint.command, RULE_COMMANDS.skillsLint.configKey, SKILLS_LINT_RULES, await loadCommandConfig("skillsLint"));
53139
+ }
53140
+ async function getWorkLintRuleCatalog() {
53141
+ return runtimeRuleCatalog(RULE_COMMANDS.workLint.command, RULE_COMMANDS.workLint.configKey, WORK_LINT_RULES, await loadCommandConfig("workLint"));
53142
+ }
53143
+ function parseEslintRuleLevel(setting) {
53144
+ let current = setting;
53145
+ while (Array.isArray(current) && current.length > 0) current = current[0];
53146
+ if (current === "error" || current === 2) return "error";
53147
+ if (current === "warn" || current === 1) return "warn";
53148
+ return "off";
53149
+ }
53150
+ function mergeEslintRules(configs) {
53151
+ const rules = /* @__PURE__ */ new Map();
53152
+ for (const config of configs) {
53153
+ if (config.rules === void 0) continue;
53154
+ for (const [id, setting] of Object.entries(config.rules)) rules.set(id, setting);
53155
+ }
53156
+ return rules;
53157
+ }
53158
+ function eslintRuleDescription(rule) {
53159
+ const description = rule?.meta?.docs?.description;
53160
+ return typeof description === "string" && description.length > 0 ? description : void 0;
53161
+ }
53162
+ function eslintRuleFixable(rule) {
53163
+ return rule?.meta?.fixable !== void 0;
53164
+ }
53165
+ function collectEslintRuleDescriptions(configs) {
53166
+ const descriptions = /* @__PURE__ */ new Map();
53167
+ for (const [id, rule] of builtinRules) {
53168
+ const description = eslintRuleDescription(rule);
53169
+ if (description !== void 0) descriptions.set(id, description);
53170
+ }
53171
+ for (const config of configs) {
53172
+ const plugins = Object.entries(config.plugins ?? {});
53173
+ for (const [pluginName, plugin] of plugins) {
53174
+ const rules = Object.entries(plugin?.rules ?? {});
53175
+ for (const [ruleName, rule] of rules) {
53176
+ const description = eslintRuleDescription(rule);
53177
+ if (description !== void 0) descriptions.set(`${pluginName}/${ruleName}`, description);
53178
+ }
53179
+ }
53180
+ }
53181
+ return descriptions;
53182
+ }
53183
+ function collectEslintRuleFixability(configs) {
53184
+ const fixability = /* @__PURE__ */ new Map();
53185
+ for (const [id, rule] of builtinRules) fixability.set(id, eslintRuleFixable(rule));
53186
+ for (const config of configs) {
53187
+ const plugins = Object.entries(config.plugins ?? {});
53188
+ for (const [pluginName, plugin] of plugins) {
53189
+ const rules = Object.entries(plugin?.rules ?? {});
53190
+ for (const [ruleName, rule] of rules) fixability.set(`${pluginName}/${ruleName}`, eslintRuleFixable(rule));
53191
+ }
53192
+ }
53193
+ return fixability;
53194
+ }
53195
+ async function getEslintRuleCatalog(command = RULE_COMMANDS.lint.command) {
53196
+ const configPath = await findUp(["eslint.config.ts", "eslint.config.mjs"]);
53197
+ if (configPath === void 0) return [];
53198
+ const module = await import(pathToFileURL(configPath).href);
53199
+ const configs = Array.isArray(module.default) ? module.default : [];
53200
+ const rules = mergeEslintRules(configs);
53201
+ const descriptions = collectEslintRuleDescriptions(configs);
53202
+ const fixability = collectEslintRuleFixability(configs);
53203
+ return rules.entries().map(([id, setting]) => ({
53204
+ command,
53205
+ defaultLevel: parseEslintRuleLevel(setting),
53206
+ description: descriptions.get(id),
53207
+ fixable: fixability.get(id) ?? false,
53208
+ id,
53209
+ level: parseEslintRuleLevel(setting),
53210
+ source: configPath
53211
+ })).toArray().toSorted((left, right) => left.id.localeCompare(right.id));
53212
+ }
53213
+ function getCycleRuleCatalog(depth = 25) {
53214
+ return [{
53215
+ command: RULE_COMMANDS.cycle.command,
53216
+ defaultLevel: "warn",
53217
+ description: `ESLint import cycle rule with maxDepth ${depth}`,
53218
+ fixable: false,
53219
+ id: "import-x/no-cycle",
53220
+ level: "warn"
53221
+ }];
53222
+ }
53223
+ async function loadDirectRuleCatalog() {
53224
+ return sortRules([...(await Promise.all([
53225
+ getApiExposureRuleCatalog(),
53226
+ getCleanRuleCatalog(),
53227
+ getDeadRuleCatalog(),
53228
+ getDeplintRuleCatalog(),
53229
+ getGitlintRuleCatalog(),
53230
+ getPackmanRuleCatalog(),
53231
+ getPublintRuleCatalog(),
53232
+ getRepoLintRuleCatalog(),
53233
+ getNodeLintRuleCatalog(),
53234
+ getLintlintRuleCatalog(),
53235
+ getSkillsLintRuleCatalog(),
53236
+ getWorkLintRuleCatalog()
53237
+ ])).flat(), ...getCycleRuleCatalog()]);
53238
+ }
53239
+ async function getCheckRuleCatalog() {
53240
+ return sortRules(commandPrefix("check", (await Promise.all([
53241
+ getGitlintRuleCatalog(),
53242
+ getPackmanRuleCatalog(),
53243
+ getPublintRuleCatalog(),
53244
+ getRepoLintRuleCatalog(),
53245
+ getLintlintRuleCatalog(),
53246
+ getSkillsLintRuleCatalog()
53247
+ ])).flat()));
53248
+ }
53249
+ async function getFixRuleCatalog() {
53250
+ return sortRules(commandPrefix("fix", (await Promise.all([
53251
+ getGitlintRuleCatalog(),
53252
+ getDeplintRuleCatalog(),
53253
+ getRepoLintRuleCatalog(),
53254
+ getPublintRuleCatalog(),
53255
+ getEslintRuleCatalog("lint"),
53256
+ getLintlintRuleCatalog()
53257
+ ])).flat()));
53258
+ }
53259
+ async function getMasterRuleCatalog() {
53260
+ return sortRules(await loadDirectRuleCatalog());
53261
+ }
53262
+ //#endregion
53263
+ //#region src/actions/secure.ts
53264
+ const secure = async ({ jobs = 16, pkg, verbose = false } = {}) => {
53265
+ return await runSecurityAudit(getPackageManager(), {
53266
+ concurrency: jobs,
53267
+ pkg,
53268
+ verbose
53269
+ });
53270
+ };
53271
+ //#endregion
53272
+ //#region src/actions/sitemap.ts
53273
+ const sitemap = () => {
53274
+ return runSteps("Sitemap", [["ts-node-script", "./scripts/sitemap.ts"]]);
53275
+ };
53276
+ //#endregion
53277
+ //#region src/actions/skills/updo.ts
53278
+ const SCOPE_FLAGS = /* @__PURE__ */ new Set([
53279
+ "-g",
53280
+ "--global",
53281
+ "-p",
53282
+ "--project"
53283
+ ]);
53284
+ const hasSkillsScopeFlag = (args) => args.some((a) => SCOPE_FLAGS.has(a));
53285
+ const skillsUpdoArgs = (args) => {
53286
+ return ["update", ...hasSkillsScopeFlag(args) ? args : ["-p", ...args]];
53287
+ };
53288
+ const skillsUpdo = (args) => {
53289
+ return runSkills(skillsUpdoArgs(args));
53290
+ };
53291
+ //#endregion
53292
+ //#region src/actions/sonar.ts
53293
+ const sonar = () => {
53294
+ return runSteps("Sonar", [["eslint", [
53295
+ "-c",
53296
+ "sonar.eslintrc",
53297
+ "."
53298
+ ]]]);
53299
+ };
53300
+ //#endregion
53301
+ //#region src/actions/start.ts
53302
+ const start = () => {
53303
+ return runSteps("Start", [[getPackageManager().command, "react-scripts start"]]);
53304
+ };
53305
+ //#endregion
53306
+ //#region src/actions/statics.ts
53307
+ const DefaultDependencies = [
53308
+ "axios",
53309
+ "@xylabs/pixel",
53310
+ "react",
53311
+ "graphql",
53312
+ "react-router",
53313
+ "@mui/material",
53314
+ "@mui/system"
53315
+ ];
53316
+ const statics = () => {
53317
+ console.log(chalk.green("Check Required Static Dependencies"));
53318
+ const staticsValue = ((parsedPackageJSON()?.xy)?.deps)?.statics;
53319
+ const result = detectDuplicateDependencies(staticsValue, DefaultDependencies, false);
53320
+ return isStrictMode() ? result : 0;
53321
+ };
53322
+ //#endregion
53323
+ //#region src/actions/test.ts
53324
+ const test = ({ target } = {}) => {
53325
+ const pm = getPackageManager();
53326
+ if (target != null && target.length > 0 && pm.findWorkspace(target)) return runSteps(`Test [${target}]`, [pm.runInWorkspace(target, "vitest", ["."])]);
53327
+ return runSteps("Test", [["vitest", [target ?? "."]]]);
53328
+ };
53329
+ //#endregion
53330
+ //#region src/actions/up.ts
53331
+ const up = () => {
53332
+ return runSteps("Up", [getPackageManager().outdated()]);
53333
+ };
53334
+ //#endregion
53335
+ //#region src/actions/updo.ts
53336
+ const updo = async ({ jobs, latest = false, next = false, risk = "green" } = {}) => {
53337
+ return await runUpdo(getPackageManager(), {
53338
+ jobs,
53339
+ latest,
53340
+ next,
53341
+ risk
53342
+ });
53343
+ };
53344
+ //#endregion
53345
+ //#region src/actions/work/helpers.ts
53346
+ const normalizeTags = (tags) => {
53347
+ return [...new Set((tags ?? []).map((tag) => tag.trim()).filter((tag) => tag.length > 0))].toSorted();
53348
+ };
53349
+ const normalizeTextList = (items) => {
53350
+ return (items ?? []).map((item) => item.trim()).filter((item) => item.length > 0);
53351
+ };
53352
+ const normalizeAnchor = (cwd, filePath, line) => {
53353
+ const { relativePath } = pathInsideRepo(cwd, filePath);
53354
+ return {
53355
+ kind: "file",
53356
+ line,
53357
+ path: relativePath
53358
+ };
53359
+ };
53360
+ const scopeFrom = (options) => ({
53361
+ cwd: options.cwd,
53362
+ repo: options.repo,
53363
+ workspace: options.workspace,
53364
+ workspaceFile: options.workspaceFile
53365
+ });
53366
+ const stripScope = (item) => {
53367
+ const { formula: _formula, repo: _repo, repoCwd: _repoCwd, ...rest } = item;
53368
+ return rest;
53369
+ };
53370
+ const toListedItem = (item, keepRepo) => {
53371
+ if (!keepRepo) return stripScope(item);
53372
+ return {
53373
+ ...stripScope(item),
53374
+ repo: item.repo
53375
+ };
53376
+ };
53377
+ const claimItem = (cwd, item, now) => {
53378
+ if (item.status === "done" || item.status === "wontfix") throw new Error(`Cannot claim ${item.status} item: ${item.id}`);
53379
+ const claimedAt = nowIso(now);
53380
+ const claimed = {
53381
+ ...item,
53382
+ claimedAt,
53383
+ status: "claimed",
53384
+ updatedAt: claimedAt
53385
+ };
53386
+ writeWorkItem(cwd, claimed);
53387
+ return claimed;
53388
+ };
53389
+ const repoBasename = (cwd) => PATH.basename(PATH.resolve(cwd));
53390
+ //#endregion
53391
+ //#region src/actions/work/inline.ts
53392
+ const markdownLikeExtensions = /* @__PURE__ */ new Set([
53393
+ ".htm",
53394
+ ".html",
53395
+ ".md",
53396
+ ".mdx"
53397
+ ]);
53398
+ const markerForFile = (filePath, marker, id) => {
53399
+ const ext = PATH.extname(filePath).toLowerCase();
53400
+ if (markdownLikeExtensions.has(ext)) return `<!-- ${marker}: ${id} -->`;
53401
+ return `// ${marker}: ${id}`;
53402
+ };
53403
+ const insertInlineWorkMarker = ({ cwd, filePath, id, line, marker }) => {
53404
+ const { absolutePath, relativePath } = pathInsideRepo(cwd, filePath);
53405
+ if (!existsSync(absolutePath)) throw new Error(`Inline anchor file not found: ${relativePath}`);
53406
+ const markerText = markerForFile(absolutePath, marker, id);
53407
+ const original = readFileSync(absolutePath, "utf8");
53408
+ if (original.includes(markerText)) return relativePath;
53409
+ if (line === void 0) {
53410
+ writeFileSync(absolutePath, `${original}${original.endsWith("\n") || original.length === 0 ? "" : "\n"}${markerText}\n`, "utf8");
53411
+ return relativePath;
53412
+ }
53413
+ const lines = original.split("\n");
53414
+ const index = Math.max(0, Math.min(line - 1, lines.length));
53415
+ lines.splice(index, 0, markerText);
53416
+ writeFileSync(absolutePath, lines.join("\n"), "utf8");
53417
+ return relativePath;
53418
+ };
53419
+ //#endregion
53420
+ //#region src/actions/work/lifecycle.ts
53421
+ const workClaim = (options) => {
53422
+ const scoped = resolveScopedWorkItem(options.id, scopeFrom(options));
53423
+ const item = claimItem(scoped.repoCwd, stripScope(scoped), options.now);
53424
+ const label = isWorkspaceScope(options) ? ` [${scoped.repo}]` : "";
53425
+ xyLog(`Claimed ${item.id}${label}`);
53426
+ return cleanResult({
53427
+ item,
53428
+ repo: scoped.repo
53429
+ });
53430
+ };
53431
+ const workDone = (options) => {
53432
+ if (options.evidence.trim().length === 0) throw new Error("done requires non-empty verification evidence");
53433
+ const scoped = resolveScopedWorkItem(options.id, scopeFrom(options));
53434
+ const item = stripScope(scoped);
53435
+ const completedAt = nowIso(options.now);
53436
+ const verification = [...item.verification, options.evidence.trim()];
53437
+ const done = {
53438
+ ...item,
53439
+ completedAt,
53440
+ status: "done",
53441
+ updatedAt: completedAt,
53442
+ verification: [...new Set(verification)]
53443
+ };
53444
+ writeWorkItem(scoped.repoCwd, done);
53445
+ const label = isWorkspaceScope(options) ? ` [${scoped.repo}]` : "";
53446
+ xyLog(`Done ${done.id}${label}`);
53447
+ return cleanResult({
53448
+ item: done,
53449
+ repo: scoped.repo
53450
+ });
53451
+ };
53452
+ const workUpdate = (options) => {
53453
+ const scoped = resolveScopedWorkItem(options.id, scopeFrom(options));
53454
+ const item = stripScope(scoped);
53455
+ const priority = priorityFromPartial({
53456
+ confidence: options.confidence,
53457
+ effort: options.effort,
53458
+ impact: options.impact,
53459
+ risk: options.risk,
53460
+ urgency: options.urgency
53461
+ });
53462
+ const updatedAt = nowIso(options.now);
53463
+ const updated = {
53464
+ ...item,
53465
+ acceptanceCriteria: options.acceptanceCriteria === void 0 ? item.acceptanceCriteria : normalizeTextList(options.acceptanceCriteria),
53466
+ area: options.area ?? item.area,
53467
+ blockedReason: options.blockedReason ?? item.blockedReason,
53468
+ description: options.description ?? item.description,
53469
+ priority: priority === void 0 ? item.priority : validateWorkPriority(priority),
53470
+ status: options.status ?? item.status,
53471
+ tags: options.tags === void 0 ? item.tags : normalizeTags(options.tags),
53472
+ title: options.title ?? item.title,
53473
+ updatedAt,
53474
+ verification: options.verification === void 0 ? item.verification : normalizeTextList(options.verification)
53475
+ };
53476
+ writeWorkItem(scoped.repoCwd, updated);
53477
+ const label = isWorkspaceScope(options) ? ` [${scoped.repo}]` : "";
53478
+ xyLog(`Updated ${updated.id}${label}`);
53479
+ return cleanResult({
53480
+ item: updated,
53481
+ repo: scoped.repo
53482
+ });
53483
+ };
53484
+ //#endregion
53485
+ //#region src/actions/work/render.ts
53486
+ const maxWidth = (headerLabel, values, max = Infinity) => {
53487
+ return Math.min(max, Math.max(headerLabel.length, ...values.map((value) => value.length)));
53488
+ };
53489
+ const resolveTableWidth = () => {
53490
+ const columns = process.stdout.isTTY ? process.stdout.columns : void 0;
53491
+ return Math.max(72, Math.min(columns ?? 120, 160) - 2);
53492
+ };
53493
+ const resolveWorkTableWidths = (rows, showRepo) => {
53494
+ const columnCount = showRepo ? 7 : 6;
53495
+ const tableChromeWidth = columnCount + 1 + columnCount * 2;
53496
+ const id = maxWidth("ID", rows.map((row) => row.id), 28);
53497
+ const status = maxWidth("Status", rows.map((row) => row.status), 12);
53498
+ const type = maxWidth("Type", rows.map((row) => row.type), 12);
53499
+ const score = maxWidth("Score", rows.map((row) => row.score), 8);
53500
+ const area = maxWidth("Area", rows.map((row) => row.area), 20);
53501
+ const repo = showRepo ? maxWidth("Repo", rows.map((row) => row.repo), 24) : 0;
53502
+ const fixedWidth = tableChromeWidth + id + status + type + score + area + repo;
53503
+ const availableTitle = Math.max(20, resolveTableWidth() - fixedWidth);
53504
+ const naturalTitle = maxWidth("Title", rows.map((row) => row.title), 72);
53505
+ return {
53506
+ area,
53507
+ id,
53508
+ repo,
53509
+ score,
53510
+ status,
53511
+ title: Math.min(naturalTitle, availableTitle),
53512
+ type
53513
+ };
53514
+ };
53515
+ const workTableConfig = (widths, showRepo) => {
53516
+ const columns = showRepo ? {
53517
+ 0: { width: widths.id },
53518
+ 1: { width: widths.repo },
53519
+ 2: { width: widths.status },
53520
+ 3: { width: widths.type },
53521
+ 4: {
53522
+ alignment: "right",
53523
+ width: widths.score
53524
+ },
53525
+ 5: { width: widths.area },
53526
+ 6: { width: widths.title }
53527
+ } : {
53528
+ 0: { width: widths.id },
53529
+ 1: { width: widths.status },
53530
+ 2: { width: widths.type },
53531
+ 3: {
53532
+ alignment: "right",
53533
+ width: widths.score
53534
+ },
53535
+ 4: { width: widths.area },
53536
+ 5: { width: widths.title }
53537
+ };
53538
+ return {
53539
+ border: (0, import_src.getBorderCharacters)("norc"),
53540
+ columnDefault: {
53541
+ paddingLeft: 1,
53542
+ paddingRight: 1,
53543
+ wrapWord: true
53544
+ },
53545
+ columns,
53546
+ drawHorizontalLine: (index, size) => [
53547
+ 0,
53548
+ 1,
53549
+ size
53550
+ ].includes(index)
53551
+ };
53552
+ };
53553
+ const toRow = (item, formula) => {
53554
+ const score = calculatePriorityScore(item.priority, item.formula ?? formula);
53555
+ return {
53556
+ area: item.area ?? "-",
53557
+ id: item.id,
53558
+ repo: item.repo ?? "-",
53559
+ score: score === void 0 ? "-" : String(score),
53560
+ status: item.status,
53561
+ title: item.title,
53562
+ type: item.type
53563
+ };
53564
+ };
53565
+ const formatWorkTable = (items, formula, options = {}) => {
53566
+ const showRepo = options.showRepo === true;
53567
+ const rows = items.map((item) => toRow(item, formula));
53568
+ const widths = resolveWorkTableWidths(rows, showRepo);
53569
+ return (0, import_src.table)([showRepo ? [
53570
+ chalk.gray.bold("ID"),
53571
+ chalk.gray.bold("Repo"),
53572
+ chalk.gray.bold("Status"),
53573
+ chalk.gray.bold("Type"),
53574
+ chalk.gray.bold("Score"),
53575
+ chalk.gray.bold("Area"),
53576
+ chalk.gray.bold("Title")
53577
+ ] : [
53578
+ chalk.gray.bold("ID"),
53579
+ chalk.gray.bold("Status"),
53580
+ chalk.gray.bold("Type"),
53581
+ chalk.gray.bold("Score"),
53582
+ chalk.gray.bold("Area"),
53583
+ chalk.gray.bold("Title")
53584
+ ], ...rows.map((row) => showRepo ? [
53585
+ chalk.cyan(row.id),
53586
+ chalk.magenta(row.repo),
53587
+ chalk.white(row.status),
53588
+ chalk.white(row.type),
53589
+ chalk.gray(row.score),
53590
+ chalk.gray(row.area),
53591
+ chalk.white(row.title)
53592
+ ] : [
53593
+ chalk.cyan(row.id),
53594
+ chalk.white(row.status),
53595
+ chalk.white(row.type),
53596
+ chalk.gray(row.score),
53597
+ chalk.gray(row.area),
53598
+ chalk.white(row.title)
53599
+ ])], workTableConfig(widths, showRepo)).trimEnd();
53600
+ };
53601
+ const printWorkItemsTable = (items, formula, options = {}) => {
53602
+ if (isJsonMode()) return;
53603
+ if (items.length === 0) {
53604
+ xyLog("No work items");
53605
+ return;
53606
+ }
53607
+ xyLog(formatWorkTable(items, formula, options));
53608
+ };
53609
+ const printWorkItemSummary = (item, score) => {
53610
+ const scoreText = score === void 0 ? "-" : String(score);
53611
+ xyLog(`${item.repo === void 0 ? "" : `${item.repo}\t`}${item.id}\t${item.status}\t${item.type}\t${scoreText}\t${item.title}`);
53612
+ };
53613
+ //#endregion
53614
+ //#region src/actions/work/list.ts
53615
+ const selectWorkItems = (items, options, formula) => {
53616
+ const filtered = items.filter((item) => (options.status === void 0 || item.status === options.status) && (options.type === void 0 || item.type === options.type));
53617
+ if (options.sort === "priority") return filtered.toSorted((a, b) => compareWorkItemsByPriority(a, b, formula));
53618
+ return filtered.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
53619
+ };
53620
+ const appendExternalGithubItems = (cwd, scoped, github, localItems, formula, repoName) => {
53621
+ const external = listExternalGithubWorkItems(cwd, localItems, github);
53622
+ return [...scoped, ...external.map((item) => ({
53623
+ ...item,
53624
+ formula,
53625
+ repo: repoName,
53626
+ repoCwd: PATH.resolve(cwd)
53627
+ }))];
53628
+ };
53629
+ const loadSingleRepoWithGithub = (options, scoped) => {
53630
+ const cwd = options.cwd ?? process.cwd();
53631
+ const config = readWorkConfig(cwd);
53632
+ const github = resolveGithubBridge(config, cwd, options.github);
53633
+ if (github === void 0) return scoped;
53634
+ try {
53635
+ return appendExternalGithubItems(cwd, scoped, github, listWorkItems(cwd), config.priority.formula, scoped[0]?.repo ?? PATH.basename(PATH.resolve(cwd)));
53636
+ } catch (error) {
53637
+ xyLog(`GitHub issues skipped: ${error instanceof Error ? error.message : String(error)}`);
53638
+ return scoped;
53639
+ }
53640
+ };
53641
+ const loadWorkspaceWithGithub = (options, scoped) => {
53642
+ const byRepo = /* @__PURE__ */ new Map();
53643
+ for (const item of scoped) {
53644
+ const list = byRepo.get(item.repoCwd) ?? [];
53645
+ list.push(item);
53646
+ byRepo.set(item.repoCwd, list);
53647
+ }
53648
+ const combined = [...scoped];
53649
+ for (const [repoCwd, localScoped] of byRepo) {
53650
+ const config = readWorkConfig(repoCwd);
53651
+ const github = resolveGithubBridge(config, repoCwd, options.github);
53652
+ if (github === void 0) continue;
53653
+ try {
53654
+ const external = listExternalGithubWorkItems(repoCwd, localScoped.map(stripScope), github);
53655
+ const repoName = localScoped[0]?.repo ?? PATH.basename(repoCwd);
53656
+ for (const item of external) combined.push({
53657
+ ...item,
53658
+ formula: config.priority.formula,
53659
+ repo: repoName,
53660
+ repoCwd
53661
+ });
53662
+ } catch (error) {
53663
+ const message = error instanceof Error ? error.message : String(error);
53664
+ xyLog(`GitHub issues skipped for ${PATH.basename(repoCwd)}: ${message}`);
53665
+ }
53666
+ }
53667
+ return combined;
53668
+ };
53669
+ const loadScopedItemsWithOptionalGithub = (options) => {
53670
+ const scoped = listScopedWorkItems(scopeFrom(options));
53671
+ if (options.all !== true) return scoped;
53672
+ if (!isWorkspaceScope(options)) return loadSingleRepoWithGithub(options, scoped);
53673
+ return loadWorkspaceWithGithub(options, scoped);
53674
+ };
53675
+ const workList = (options = {}) => {
53676
+ const items = selectScopedWorkItems(loadScopedItemsWithOptionalGithub(options), {
53677
+ sort: options.sort,
53678
+ status: options.status,
53679
+ type: options.type
53680
+ });
53681
+ const showRepo = isWorkspaceScope(options);
53682
+ printWorkItemsTable(items, items[0]?.formula ?? "impact + urgency + risk + confidence - effort", { showRepo });
53683
+ return cleanResult({ items: items.map((item) => toListedItem(item, showRepo)) });
53684
+ };
53685
+ const workShow = (options) => {
53686
+ const payload = toListedItem(resolveScopedWorkItem(options.id, scopeFrom(options)), isWorkspaceScope(options));
53687
+ xyLog(JSON.stringify(payload, null, 2));
53688
+ return cleanResult({ item: payload });
53689
+ };
53690
+ const needsTriage = (item) => {
53691
+ return item.status === "open" && (item.priority === void 0 || item.area === void 0 || item.acceptanceCriteria.length === 0 || item.verification.length === 0);
53692
+ };
53693
+ const workTriage = (options = {}) => {
53694
+ const items = listScopedWorkItems(scopeFrom(options)).filter(needsTriage);
53695
+ const showRepo = isWorkspaceScope(options);
53696
+ printWorkItemsTable(items, items[0]?.formula ?? "impact + urgency + risk + confidence - effort", { showRepo });
53697
+ return cleanResult({ items: items.map((item) => toListedItem(item, showRepo)) });
53698
+ };
53699
+ //#endregion
53700
+ //#region src/actions/work/move.ts
53701
+ const stripGithubStore = (item) => {
53702
+ const { github: _github, ...restStores } = item.stores;
53703
+ return {
53704
+ ...item,
53705
+ stores: restStores
53706
+ };
53707
+ };
53708
+ const withGithubLink = (item, number, url) => {
52758
53709
  return {
52759
53710
  ...item,
52760
53711
  stores: {
52761
53712
  ...item.stores,
52762
53713
  github: {
52763
- createdByXyWork,
53714
+ createdByXyWork: true,
52764
53715
  number,
52765
- ...!createdByXyWork && { source: "github" },
52766
53716
  url
52767
53717
  }
52768
53718
  }
52769
53719
  };
52770
53720
  };
52771
- const importGithubIssueLocally = (cwd, issue, now, preferredId) => {
52772
- const base = normalizeGithubIssueToWorkItem(issue);
52773
- const id = preferredId ?? base.id;
52774
- const createdByXyWork = isXyWorkGithubIssue(issue);
52775
- const open = githubIssueIsOpen(issue);
52776
- const item = {
52777
- ...base,
52778
- completedAt: open ? void 0 : base.updatedAt || nowIso(now),
52779
- id,
52780
- status: open ? "open" : "done",
52781
- stores: { github: {
52782
- createdByXyWork,
52783
- number: issue.number,
52784
- ...!createdByXyWork && { source: "github" },
52785
- url: issue.url
52786
- } },
52787
- updatedAt: nowIso(now)
52788
- };
52789
- writeWorkItem(cwd, item);
52790
- return item;
52791
- };
52792
- const createMissingGithubIssues = (cwd, localItems, github, issuesByNumber, summary, now) => {
52793
- for (const item of localItems) {
52794
- if (readGithubStoreNumber(item.stores) !== void 0) continue;
52795
- if (isTerminalWorkStatus(item.status)) continue;
52796
- try {
52797
- const ref = github.createIssue(cwd, item);
52798
- const linked = {
52799
- ...withGithubLink(item, ref.number, ref.url, true),
52800
- updatedAt: nowIso(now)
52801
- };
52802
- writeWorkItem(cwd, linked);
52803
- summary.createdGithub.push(`${item.id}→#${String(ref.number)}`);
52804
- issuesByNumber.set(ref.number, {
52805
- body: formatGithubWorkIssueBody(linked),
52806
- createdAt: linked.createdAt,
52807
- labels: ["xy-work"],
52808
- number: ref.number,
52809
- state: "OPEN",
52810
- title: linked.title,
52811
- updatedAt: linked.updatedAt,
52812
- url: ref.url
52813
- });
52814
- } catch (error) {
52815
- const message = error instanceof Error ? error.message : String(error);
52816
- xyLog(`Sync create failed for ${item.id}: ${message}`);
52817
- }
53721
+ const warnMissingAnchors = (item, destCwd) => {
53722
+ for (const anchor of item.anchors) {
53723
+ if (anchor.kind !== "file") continue;
53724
+ if (!existsSync(PATH.resolve(destCwd, anchor.path))) xyLog(`Warning: anchor path missing in destination: ${anchor.path}`);
53725
+ }
53726
+ };
53727
+ const cloneItemForMove = (source, updatedAt) => ({
53728
+ acceptanceCriteria: source.acceptanceCriteria,
53729
+ anchors: source.anchors,
53730
+ area: source.area,
53731
+ blockedReason: source.blockedReason,
53732
+ claimedAt: source.claimedAt,
53733
+ completedAt: source.completedAt,
53734
+ createdAt: source.createdAt,
53735
+ description: source.description,
53736
+ id: source.id,
53737
+ priority: source.priority,
53738
+ status: source.status,
53739
+ stores: { ...source.stores },
53740
+ tags: source.tags,
53741
+ title: source.title,
53742
+ type: source.type,
53743
+ updatedAt,
53744
+ verification: source.verification
53745
+ });
53746
+ const closeSourceGithubIssue = (source, sourceGithub, sourceNumber, sourceUrl, dest, moved, newIssueUrl) => {
53747
+ try {
53748
+ const note = [
53749
+ `Moved to workspace repo \`${dest.name}\` as \`${moved.id}\`.`,
53750
+ sourceUrl === void 0 ? void 0 : `Previous issue: ${sourceUrl}`,
53751
+ `New issue: ${newIssueUrl}`
53752
+ ].filter((line) => line !== void 0).join("\n");
53753
+ sourceGithub.updateIssue(source.repoCwd, sourceNumber, {
53754
+ body: note,
53755
+ state: "closed"
53756
+ });
53757
+ } catch (error) {
53758
+ const message = error instanceof Error ? error.message : String(error);
53759
+ xyLog(`Warning: could not close source GitHub issue #${String(sourceNumber)}: ${message}`);
52818
53760
  }
52819
53761
  };
52820
- const attachOrImportGithubIssues = (cwd, issuesByNumber, summary, now) => {
52821
- const localItems = listWorkItems(cwd);
52822
- const localById = new Map(localItems.map((item) => [item.id, item]));
52823
- const linkedNumbers = linkedGithubNumbers(localItems);
52824
- for (const issue of issuesByNumber.values()) {
52825
- if (linkedNumbers.has(issue.number)) continue;
52826
- const xyWorkId = isXyWorkGithubIssue(issue) ? parseXyWorkIdFromGithubBody(issue.body) : void 0;
52827
- if (xyWorkId !== void 0 && localById.has(xyWorkId)) {
52828
- const existing = localById.get(xyWorkId);
52829
- if (existing === void 0) continue;
52830
- if (readGithubStoreNumber(existing.stores) === void 0) {
52831
- const linked = {
52832
- ...withGithubLink(existing, issue.number, issue.url, true),
52833
- updatedAt: nowIso(now)
52834
- };
52835
- writeWorkItem(cwd, linked);
52836
- localById.set(xyWorkId, linked);
52837
- linkedNumbers.add(issue.number);
52838
- summary.updatedLocal.push(`${xyWorkId}↔#${String(issue.number)}`);
52839
- }
52840
- continue;
52841
- }
52842
- if (!githubIssueIsOpen(issue) && !isXyWorkGithubIssue(issue)) continue;
52843
- const preferredId = xyWorkId;
52844
- if (preferredId !== void 0 && localById.has(preferredId)) continue;
52845
- try {
52846
- const imported = importGithubIssueLocally(cwd, issue, now ?? /* @__PURE__ */ new Date(), preferredId);
52847
- localById.set(imported.id, imported);
52848
- linkedNumbers.add(issue.number);
52849
- summary.importedLocal.push(`${imported.id}←#${String(issue.number)}`);
52850
- } catch (error) {
52851
- const message = error instanceof Error ? error.message : String(error);
52852
- xyLog(`Sync import failed for GitHub #${String(issue.number)}: ${message}`);
52853
- }
53762
+ const recreateGithubOnMove = (source, dest, moved, options, sourceNumber) => {
53763
+ const destGithub = resolveGithubBridge(readWorkConfig(dest.cwd), dest.cwd, options.github);
53764
+ if (destGithub === void 0) {
53765
+ xyLog("Warning: destination GitHub unavailable; stripped GitHub link (run xy work sync later)");
53766
+ return stripGithubStore(moved);
52854
53767
  }
52855
- };
52856
- const reconcileTitleDrift = (cwd, github, item, issue, number, summary, now) => {
52857
- if (item.title === issue.title) return {
52858
- localChanged: false,
52859
- next: item
52860
- };
52861
- if (item.updatedAt.localeCompare(issue.updatedAt) >= 0) {
52862
- github.updateIssue(cwd, number, {
52863
- body: formatGithubWorkIssueBody(item),
52864
- title: item.title
52865
- });
52866
- summary.updatedGithub.push(`${item.id}→#${String(number)}`);
52867
- issue.title = item.title;
52868
- issue.updatedAt = nowIso(now);
52869
- return {
52870
- localChanged: false,
52871
- next: item
52872
- };
53768
+ const sourceGithub = resolveGithubBridge(readWorkConfig(source.repoCwd), source.repoCwd, options.github);
53769
+ const sourceUrl = readGithubStoreUrl(source.stores);
53770
+ try {
53771
+ const ref = destGithub.createIssue(dest.cwd, stripGithubStore(moved));
53772
+ const linked = withGithubLink(moved, ref.number, ref.url);
53773
+ if (sourceGithub !== void 0) closeSourceGithubIssue(source, sourceGithub, sourceNumber, sourceUrl, dest, linked, ref.url);
53774
+ xyLog(`GitHub: created #${String(ref.number)} in ${dest.name}; closed #${String(sourceNumber)} in ${source.repo}`);
53775
+ return linked;
53776
+ } catch (error) {
53777
+ xyLog(`Warning: GitHub recreate failed (${error instanceof Error ? error.message : String(error)}); moved local item without GitHub link`);
53778
+ return stripGithubStore(moved);
52873
53779
  }
52874
- return {
52875
- localChanged: true,
52876
- next: {
52877
- ...item,
52878
- title: issue.title,
52879
- updatedAt: nowIso(now)
52880
- }
52881
- };
52882
53780
  };
52883
- const ensureGithubStoreUrl = (item, issue, number) => {
52884
- const url = readGithubStoreUrl(item.stores) ?? issue.url;
52885
- if (readGithubStoreUrl(item.stores) === url) return {
52886
- localChanged: false,
52887
- next: item
53781
+ const resolveMoveEndpoints = (options) => {
53782
+ if (!isWorkspaceScope(options)) throw new Error("xy work move requires --workspace (or --workspace-file)");
53783
+ if (options.to.trim().length === 0) throw new Error("--to <repo> is required");
53784
+ const scope = {
53785
+ cwd: options.cwd,
53786
+ repo: options.from,
53787
+ workspace: options.workspace ?? true,
53788
+ workspaceFile: options.workspaceFile
52888
53789
  };
52889
- const store = item.stores.github;
52890
- const createdByXyWork = isXyWorkGithubIssue(issue) || typeof store === "object" && store !== null && store.createdByXyWork === true;
53790
+ const source = resolveScopedWorkItem(options.id, scope);
53791
+ if (options.from !== void 0 && options.from.length > 0 && source.repo !== options.from) throw new Error(`Work item ${options.id} is in repo "${source.repo}", not "${options.from}"`);
53792
+ const dest = findWorkRepoByName(options.to, {
53793
+ cwd: options.cwd,
53794
+ workspace: options.workspace ?? true,
53795
+ workspaceFile: options.workspaceFile
53796
+ });
53797
+ if (!dest.hasStore) throw new Error(`Destination repo "${dest.name}" has no work store. Run: xy work init --workspace --repo ${dest.name}`);
53798
+ if (PATH.resolve(dest.cwd) === PATH.resolve(source.repoCwd)) throw new Error(`Source and destination repo are the same: ${dest.name}`);
53799
+ if (workItemExists(dest.cwd, source.id)) throw new Error(`Destination already has work item ${source.id}`);
52891
53800
  return {
52892
- localChanged: true,
52893
- next: withGithubLink(item, number, url, createdByXyWork)
53801
+ dest,
53802
+ source
52894
53803
  };
52895
53804
  };
52896
- const reconcileLinkedItem = (cwd, github, item, issue, number, summary, now) => {
52897
- let next = item;
52898
- let localChanged = false;
52899
- const issueOpen = githubIssueIsOpen(issue);
52900
- const localTerminal = isTerminalWorkStatus(item.status);
52901
- if (localTerminal && issueOpen) {
52902
- github.updateIssue(cwd, number, { state: "closed" });
52903
- summary.closedGithub.push(`${item.id}→#${String(number)}`);
52904
- issue.state = "CLOSED";
52905
- } else if (!localTerminal && !issueOpen) {
52906
- next = {
52907
- ...next,
52908
- completedAt: next.completedAt ?? issue.updatedAt,
52909
- status: "done",
52910
- updatedAt: nowIso(now),
52911
- verification: [.../* @__PURE__ */ new Set([...next.verification, `synced closed from GitHub #${String(number)}`])]
52912
- };
52913
- localChanged = true;
52914
- } else if (!localTerminal && issueOpen) {
52915
- const titleResult = reconcileTitleDrift(cwd, github, next, issue, number, summary, now);
52916
- next = titleResult.next;
52917
- localChanged ||= titleResult.localChanged;
52918
- }
52919
- const urlResult = ensureGithubStoreUrl(next, issue, number);
52920
- next = urlResult.next;
52921
- localChanged ||= urlResult.localChanged;
52922
- if (localChanged) {
52923
- writeWorkItem(cwd, next);
52924
- summary.updatedLocal.push(`${next.id}←#${String(number)}`);
53805
+ /**
53806
+ * Move a work item from one workspace folder repo to another.
53807
+ * Requires workspace scope (or an explicit workspace file).
53808
+ */
53809
+ const workMove = (options) => {
53810
+ const { dest, source } = resolveMoveEndpoints(options);
53811
+ let moved = cloneItemForMove(source, nowIso(options.now));
53812
+ const sourceNumber = readGithubStoreNumber(source.stores);
53813
+ if (sourceNumber !== void 0) moved = recreateGithubOnMove(source, dest, moved, options, sourceNumber);
53814
+ warnMissingAnchors(moved, dest.cwd);
53815
+ writeWorkItem(dest.cwd, moved);
53816
+ deleteWorkItem(source.repoCwd, source.id);
53817
+ xyLog(`Moved ${moved.id}: ${source.repo} → ${dest.name}`);
53818
+ return cleanResult({
53819
+ from: source.repo,
53820
+ item: moved,
53821
+ to: dest.name
53822
+ });
53823
+ };
53824
+ //#endregion
53825
+ //#region src/actions/work/queue.ts
53826
+ const ELIGIBLE_QUEUE_STATUSES = /* @__PURE__ */ new Set([
53827
+ "open",
53828
+ "triaged",
53829
+ "queued"
53830
+ ]);
53831
+ const INACTIVE_QUEUE_STATUSES = /* @__PURE__ */ new Set([
53832
+ "done",
53833
+ "wontfix",
53834
+ "claimed",
53835
+ "blocked"
53836
+ ]);
53837
+ const NEXT_FALLBACK_STATUSES = /* @__PURE__ */ new Set([
53838
+ "open",
53839
+ "triaged",
53840
+ "queued"
53841
+ ]);
53842
+ const eligibleStatuses = (status) => {
53843
+ return status === void 0 ? ELIGIBLE_QUEUE_STATUSES : /* @__PURE__ */ new Set([status]);
53844
+ };
53845
+ const markItemsQueued = (cwd, items, queuedAt) => {
53846
+ for (const item of items) if (item.status === "open" || item.status === "triaged") writeWorkItem(cwd, {
53847
+ ...item,
53848
+ status: "queued",
53849
+ updatedAt: queuedAt
53850
+ });
53851
+ };
53852
+ const buildQueue = (name, selected, formula, queuedAt) => ({
53853
+ generatedAt: queuedAt,
53854
+ items: selected.map((item) => ({
53855
+ id: item.id,
53856
+ score: calculatePriorityScore(item.priority, formula)
53857
+ })),
53858
+ name,
53859
+ version: 1
53860
+ });
53861
+ const queueSingleRepo = (options) => {
53862
+ const cwd = options.cwd ?? process.cwd();
53863
+ const config = readWorkConfig(cwd);
53864
+ const name = options.name ?? config.defaultQueue;
53865
+ const selected = selectWorkItems(listWorkItems(cwd), { sort: "priority" }, config.priority.formula).filter((item) => eligibleStatuses(options.status).has(item.status)).slice(0, options.limit);
53866
+ const queuedAt = nowIso(options.now);
53867
+ const queue = buildQueue(name, selected, config.priority.formula, queuedAt);
53868
+ markItemsQueued(cwd, selected, queuedAt);
53869
+ writeWorkQueue(cwd, queue);
53870
+ xyLog(`Queued ${queue.items.length} item(s) in ${name}`);
53871
+ return cleanResult({
53872
+ items: selected,
53873
+ queue,
53874
+ queues: [{
53875
+ name,
53876
+ queue,
53877
+ repo: repoBasename(cwd)
53878
+ }]
53879
+ });
53880
+ };
53881
+ const queueWorkspace = (options) => {
53882
+ const selected = selectScopedWorkItems(listScopedWorkItems(scopeFrom(options)), { sort: "priority" }).filter((item) => eligibleStatuses(options.status).has(item.status)).slice(0, options.limit);
53883
+ const queuedAt = nowIso(options.now);
53884
+ const byRepo = /* @__PURE__ */ new Map();
53885
+ for (const item of selected) {
53886
+ const list = byRepo.get(item.repoCwd) ?? [];
53887
+ list.push(item);
53888
+ byRepo.set(item.repoCwd, list);
53889
+ }
53890
+ const queues = [];
53891
+ for (const [repoCwd, items] of byRepo) {
53892
+ const config = readWorkConfig(repoCwd);
53893
+ const name = options.name ?? config.defaultQueue;
53894
+ const queue = buildQueue(name, items.map(stripScope), items[0]?.formula ?? config.priority.formula, queuedAt);
53895
+ markItemsQueued(repoCwd, items.map(stripScope), queuedAt);
53896
+ writeWorkQueue(repoCwd, queue);
53897
+ queues.push({
53898
+ name,
53899
+ queue,
53900
+ repo: items[0]?.repo ?? PATH.basename(repoCwd)
53901
+ });
52925
53902
  }
53903
+ xyLog(`Queued ${selected.length} item(s) across ${queues.length} repo(s)`);
53904
+ return cleanResult({
53905
+ items: selected,
53906
+ queue: queues[0]?.queue ?? {
53907
+ generatedAt: queuedAt,
53908
+ items: [],
53909
+ name: options.name ?? "default",
53910
+ version: 1
53911
+ },
53912
+ queues
53913
+ });
52926
53914
  };
52927
- const reconcileLinkedPairs = (cwd, github, issuesByNumber, summary, now) => {
52928
- for (const item of listWorkItems(cwd)) {
52929
- const number = readGithubStoreNumber(item.stores);
52930
- if (number === void 0) continue;
52931
- const issue = issuesByNumber.get(number);
52932
- if (issue === void 0) continue;
52933
- try {
52934
- reconcileLinkedItem(cwd, github, item, issue, number, summary, now);
52935
- } catch (error) {
52936
- const message = error instanceof Error ? error.message : String(error);
52937
- xyLog(`Sync reconcile failed for ${item.id}/#${String(number)}: ${message}`);
52938
- }
53915
+ const workQueue = (options = {}) => {
53916
+ if (!isWorkspaceScope(options)) return queueSingleRepo(options);
53917
+ return queueWorkspace(options);
53918
+ };
53919
+ const activeQueueItem = (cwd, queue) => {
53920
+ for (const entry of queue.items) {
53921
+ const item = readWorkItem(cwd, entry.id);
53922
+ if (!INACTIVE_QUEUE_STATUSES.has(item.status)) return item;
52939
53923
  }
52940
53924
  };
52941
- const logSyncSummary = (summary) => {
52942
- if (summary.createdGithub.length + summary.importedLocal.length + summary.updatedLocal.length + summary.updatedGithub.length + summary.closedGithub.length + summary.reopenedGithub.length === 0) {
52943
- xyLog("GitHub sync: already in sync");
53925
+ const tryReadQueue = (cwd, name) => {
53926
+ try {
53927
+ return readWorkQueue(cwd, name);
53928
+ } catch {
52944
53929
  return;
52945
53930
  }
52946
- xyLog([
52947
- "GitHub sync complete:",
52948
- ` created GitHub: ${String(summary.createdGithub.length)}`,
52949
- ` imported local: ${String(summary.importedLocal.length)}`,
52950
- ` updated local: ${String(summary.updatedLocal.length)}`,
52951
- ` updated GitHub: ${String(summary.updatedGithub.length)}`,
52952
- ` closed GitHub: ${String(summary.closedGithub.length)}`
52953
- ].join("\n"));
52954
53931
  };
52955
- /**
52956
- * Bidirectional sync between repo-local work items and GitHub Issues when available.
52957
- *
52958
- * - Local active items without a GitHub link → create a marked GitHub issue
52959
- * - Open/closed GitHub issues not present locally → import as local items
52960
- * - Linked pairs: reconcile title (newer wins) and status (done/wontfix ↔ closed)
52961
- */
52962
- const workSync = (options = {}) => {
53932
+ const nextSingleRepo = (options) => {
52963
53933
  const cwd = options.cwd ?? process.cwd();
52964
53934
  const config = readWorkConfig(cwd);
52965
- const summary = emptySyncSummary();
52966
- const github = resolveGithubBridge(config, cwd, options.github);
52967
- if (github === void 0) {
52968
- xyLog("GitHub sync skipped: GitHub Issues unavailable or disabled");
52969
- return cleanResult({ summary });
53935
+ const queue = readWorkQueue(cwd, options.name ?? config.defaultQueue);
53936
+ const item = activeQueueItem(cwd, queue);
53937
+ if (item === void 0) {
53938
+ xyLog("No available queued work item");
53939
+ return cleanResult({ item: void 0 });
52970
53940
  }
52971
- const issuesByNumber = /* @__PURE__ */ new Map();
52972
- for (const issue of github.listIssues(cwd, "all")) issuesByNumber.set(issue.number, issue);
52973
- createMissingGithubIssues(cwd, listWorkItems(cwd), github, issuesByNumber, summary, options.now);
52974
- attachOrImportGithubIssues(cwd, issuesByNumber, summary, options.now);
52975
- reconcileLinkedPairs(cwd, github, issuesByNumber, summary, options.now);
52976
- logSyncSummary(summary);
52977
- return cleanResult({ summary });
53941
+ const next = options.claim === true ? claimItem(cwd, item, options.now) : item;
53942
+ printWorkItemSummary(next, calculatePriorityScore(next.priority, config.priority.formula));
53943
+ return cleanResult({ item: next });
52978
53944
  };
52979
- //#endregion
52980
- //#region src/actions/work/index.ts
52981
- const normalizeTags = (tags) => {
52982
- return [...new Set((tags ?? []).map((tag) => tag.trim()).filter((tag) => tag.length > 0))].toSorted();
53945
+ const collectQueuedCandidates = (options) => {
53946
+ const repos = resolveWorkReposWithStore(scopeFrom(options));
53947
+ const candidates = [];
53948
+ for (const repo of repos) {
53949
+ const config = readWorkConfig(repo.cwd);
53950
+ const queueName = options.name ?? config.defaultQueue;
53951
+ const queue = tryReadQueue(repo.cwd, queueName);
53952
+ if (queue === void 0) continue;
53953
+ const item = activeQueueItem(repo.cwd, queue);
53954
+ if (item === void 0) continue;
53955
+ candidates.push({
53956
+ ...item,
53957
+ formula: config.priority.formula,
53958
+ repo: repo.name,
53959
+ repoCwd: repo.cwd
53960
+ });
53961
+ }
53962
+ return candidates;
52983
53963
  };
52984
- const normalizeTextList = (items) => {
52985
- return (items ?? []).map((item) => item.trim()).filter((item) => item.length > 0);
53964
+ const pickNextScoped = (options) => {
53965
+ const fromQueues = selectScopedWorkItems(collectQueuedCandidates(options), { sort: "priority" })[0];
53966
+ if (fromQueues !== void 0) return fromQueues;
53967
+ return selectScopedWorkItems(listScopedWorkItems(scopeFrom(options)).filter((item) => NEXT_FALLBACK_STATUSES.has(item.status)), { sort: "priority" })[0];
52986
53968
  };
52987
- const normalizeAnchor = (cwd, filePath, line) => {
52988
- const { relativePath } = pathInsideRepo(cwd, filePath);
53969
+ const nextWorkspace = (options) => {
53970
+ const nextScoped = pickNextScoped(options);
53971
+ if (nextScoped === void 0) {
53972
+ xyLog("No available queued work item");
53973
+ return cleanResult({ item: void 0 });
53974
+ }
53975
+ const next = options.claim === true ? {
53976
+ ...claimItem(nextScoped.repoCwd, stripScope(nextScoped), options.now),
53977
+ formula: nextScoped.formula,
53978
+ repo: nextScoped.repo,
53979
+ repoCwd: nextScoped.repoCwd
53980
+ } : nextScoped;
53981
+ printWorkItemSummary(next, calculatePriorityScore(next.priority, next.formula));
53982
+ return cleanResult({ item: next });
53983
+ };
53984
+ const workNext = (options = {}) => {
53985
+ if (!isWorkspaceScope(options)) return nextSingleRepo(options);
53986
+ return nextWorkspace(options);
53987
+ };
53988
+ //#endregion
53989
+ //#region src/actions/work/index.ts
53990
+ const initRepoResult = (cwd, name) => {
53991
+ const paths = ensureWorkStore(cwd);
52989
53992
  return {
52990
- kind: "file",
52991
- line,
52992
- path: relativePath
53993
+ config: readWorkConfig(cwd),
53994
+ paths: {
53995
+ config: paths.configPath,
53996
+ items: paths.itemsDir,
53997
+ queues: paths.queuesDir
53998
+ },
53999
+ repo: name
52993
54000
  };
52994
54001
  };
52995
54002
  const workInit = (options = {}) => {
54003
+ if (isWorkspaceScope(options)) {
54004
+ const results = resolveWorkRepos(options).map((repo) => {
54005
+ const result = initRepoResult(repo.cwd, repo.name);
54006
+ xyLog(`Initialized work store for ${repo.name} at ${workStorePaths(repo.cwd).rootDir}`);
54007
+ return result;
54008
+ });
54009
+ return cleanResult({
54010
+ config: results[0]?.config,
54011
+ paths: results[0]?.paths,
54012
+ repos: results
54013
+ });
54014
+ }
52996
54015
  const cwd = options.cwd ?? process.cwd();
52997
- const paths = ensureWorkStore(cwd);
52998
- const config = readWorkConfig(cwd);
52999
- const queuePath = workStorePaths(cwd).queuesDir;
53000
- xyLog(`Initialized work store at ${paths.rootDir}`);
54016
+ const result = initRepoResult(cwd, repoBasename(cwd));
54017
+ xyLog(`Initialized work store at ${workStorePaths(cwd).rootDir}`);
53001
54018
  return cleanResult({
53002
- config,
53003
- paths: {
53004
- config: paths.configPath,
53005
- items: paths.itemsDir,
53006
- queues: queuePath
53007
- }
54019
+ config: result.config,
54020
+ paths: result.paths,
54021
+ repos: [result]
54022
+ });
54023
+ };
54024
+ const maybeInsertInline = (options, cwd, id, config) => {
54025
+ if (options.inline !== true) return;
54026
+ if (options.file === void 0) throw new Error("--inline requires --file");
54027
+ if (!config.stores.inline.enabled) throw new Error("Inline work store is disabled");
54028
+ insertInlineWorkMarker({
54029
+ cwd,
54030
+ filePath: options.file,
54031
+ id,
54032
+ line: options.line,
54033
+ marker: config.stores.inline.marker
53008
54034
  });
53009
54035
  };
54036
+ const linkGithubOnAdd = (cwd, item, github, now) => {
54037
+ const ref = github.createIssue(cwd, item);
54038
+ const linked = {
54039
+ ...item,
54040
+ stores: {
54041
+ ...item.stores,
54042
+ github: {
54043
+ createdByXyWork: true,
54044
+ number: ref.number,
54045
+ url: ref.url
54046
+ }
54047
+ },
54048
+ updatedAt: nowIso(now)
54049
+ };
54050
+ writeWorkItem(cwd, linked);
54051
+ return {
54052
+ item: linked,
54053
+ number: ref.number
54054
+ };
54055
+ };
53010
54056
  const workAdd = (options) => {
53011
- const cwd = options.cwd ?? process.cwd();
54057
+ const target = resolveAddTargetRepo(scopeFrom(options));
54058
+ const cwd = target.cwd;
53012
54059
  const config = readWorkConfig(cwd);
53013
54060
  const createdAt = nowIso(options.now);
53014
54061
  const priority = priorityFromPartial({
@@ -53040,196 +54087,74 @@ const workAdd = (options) => {
53040
54087
  verification: normalizeTextList(options.verification)
53041
54088
  };
53042
54089
  writeWorkItem(cwd, item);
53043
- if (options.inline === true) {
53044
- if (options.file === void 0) throw new Error("--inline requires --file");
53045
- if (!config.stores.inline.enabled) throw new Error("Inline work store is disabled");
53046
- insertInlineWorkMarker({
53047
- cwd,
53048
- filePath: options.file,
53049
- id,
53050
- line: options.line,
53051
- marker: config.stores.inline.marker
53052
- });
53053
- }
54090
+ maybeInsertInline(options, cwd, id, config);
53054
54091
  const github = resolveGithubBridge(config, cwd, options.github);
54092
+ const repoLabel = isWorkspaceScope(options) ? ` [${target.name}]` : "";
53055
54093
  if (github !== void 0) try {
53056
- const ref = github.createIssue(cwd, item);
53057
- item = {
53058
- ...item,
53059
- stores: {
53060
- ...item.stores,
53061
- github: {
53062
- createdByXyWork: true,
53063
- number: ref.number,
53064
- url: ref.url
53065
- }
53066
- },
53067
- updatedAt: nowIso(options.now)
53068
- };
53069
- writeWorkItem(cwd, item);
53070
- xyLog(`Added ${item.id}: ${item.title} (GitHub #${String(ref.number)})`);
53071
- return cleanResult({ item });
54094
+ const linked = linkGithubOnAdd(cwd, item, github, options.now);
54095
+ item = linked.item;
54096
+ xyLog(`Added ${item.id}: ${item.title}${repoLabel} (GitHub #${String(linked.number)})`);
54097
+ return cleanResult({
54098
+ item,
54099
+ repo: target.name
54100
+ });
53072
54101
  } catch (error) {
53073
54102
  const message = error instanceof Error ? error.message : String(error);
53074
- xyLog(`Added ${item.id}: ${item.title} (GitHub issue skipped: ${message})`);
53075
- return cleanResult({ item });
54103
+ xyLog(`Added ${item.id}: ${item.title}${repoLabel} (GitHub issue skipped: ${message})`);
54104
+ return cleanResult({
54105
+ item,
54106
+ repo: target.name
54107
+ });
53076
54108
  }
53077
- xyLog(`Added ${item.id}: ${item.title}`);
53078
- return cleanResult({ item });
53079
- };
53080
- const selectWorkItems = (items, options, formula) => {
53081
- const filtered = items.filter((item) => (options.status === void 0 || item.status === options.status) && (options.type === void 0 || item.type === options.type));
53082
- if (options.sort === "priority") return filtered.toSorted((a, b) => compareWorkItemsByPriority(a, b, formula));
53083
- return filtered.toSorted((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
53084
- };
53085
- const workList = (options = {}) => {
53086
- const cwd = options.cwd ?? process.cwd();
53087
- const config = readWorkConfig(cwd);
53088
- const localItems = listWorkItems(cwd);
53089
- let combined = localItems;
53090
- if (options.all === true) {
53091
- const github = resolveGithubBridge(config, cwd, options.github);
53092
- if (github !== void 0) try {
53093
- const external = listExternalGithubWorkItems(cwd, localItems, github);
53094
- combined = [...localItems, ...external];
54109
+ xyLog(`Added ${item.id}: ${item.title}${repoLabel}`);
54110
+ return cleanResult({
54111
+ item,
54112
+ repo: target.name
54113
+ });
54114
+ };
54115
+ /** Sync one repo, or each store in a code-workspace when --workspace is set. */
54116
+ const workSyncScoped = (options = {}) => {
54117
+ if (!isWorkspaceScope(options)) {
54118
+ const result = workSync({
54119
+ cwd: options.cwd,
54120
+ github: options.github,
54121
+ now: options.now
54122
+ });
54123
+ return cleanResult({
54124
+ results: [{
54125
+ repo: PATH.basename(PATH.resolve(options.cwd ?? process.cwd())),
54126
+ summary: result.data.summary
54127
+ }],
54128
+ summary: result.data.summary
54129
+ });
54130
+ }
54131
+ const repos = resolveWorkReposWithStore(scopeFrom(options));
54132
+ const results = [];
54133
+ for (const repo of repos) {
54134
+ xyLog(`Syncing ${repo.name}...`);
54135
+ try {
54136
+ const result = workSync({
54137
+ cwd: repo.cwd,
54138
+ github: options.github,
54139
+ now: options.now
54140
+ });
54141
+ results.push({
54142
+ repo: repo.name,
54143
+ summary: result.data.summary
54144
+ });
53095
54145
  } catch (error) {
53096
- xyLog(`GitHub issues skipped: ${error instanceof Error ? error.message : String(error)}`);
54146
+ const message = error instanceof Error ? error.message : String(error);
54147
+ xyLog(`Sync failed for ${repo.name}: ${message}`);
54148
+ results.push({
54149
+ repo: repo.name,
54150
+ summary: { error: message }
54151
+ });
53097
54152
  }
53098
54153
  }
53099
- const items = selectWorkItems(combined, options, config.priority.formula);
53100
- printWorkItemsTable(items, config.priority.formula);
53101
- return cleanResult({ items });
53102
- };
53103
- const workShow = (options) => {
53104
- const item = readWorkItem(options.cwd ?? process.cwd(), options.id);
53105
- xyLog(JSON.stringify(item, null, 2));
53106
- return cleanResult({ item });
53107
- };
53108
- const needsTriage = (item) => {
53109
- return item.status === "open" && (item.priority === void 0 || item.area === void 0 || item.acceptanceCriteria.length === 0 || item.verification.length === 0);
53110
- };
53111
- const workTriage = (options = {}) => {
53112
- const cwd = options.cwd ?? process.cwd();
53113
- const config = readWorkConfig(cwd);
53114
- const items = listWorkItems(cwd).filter(needsTriage);
53115
- printWorkItemsTable(items, config.priority.formula);
53116
- return cleanResult({ items });
53117
- };
53118
- const workQueue = (options = {}) => {
53119
- const cwd = options.cwd ?? process.cwd();
53120
- const config = readWorkConfig(cwd);
53121
- const name = options.name ?? config.defaultQueue;
53122
- const eligibleStatuses = options.status === void 0 ? /* @__PURE__ */ new Set([
53123
- "open",
53124
- "triaged",
53125
- "queued"
53126
- ]) : /* @__PURE__ */ new Set([options.status]);
53127
- const selected = selectWorkItems(listWorkItems(cwd), { sort: "priority" }, config.priority.formula).filter((item) => eligibleStatuses.has(item.status)).slice(0, options.limit);
53128
- const queuedAt = nowIso(options.now);
53129
- const queue = {
53130
- generatedAt: queuedAt,
53131
- items: selected.map((item) => ({
53132
- id: item.id,
53133
- score: calculatePriorityScore(item.priority, config.priority.formula)
53134
- })),
53135
- name,
53136
- version: 1
53137
- };
53138
- for (const item of selected) if (item.status === "open" || item.status === "triaged") writeWorkItem(cwd, {
53139
- ...item,
53140
- status: "queued",
53141
- updatedAt: queuedAt
53142
- });
53143
- writeWorkQueue(cwd, queue);
53144
- xyLog(`Queued ${queue.items.length} item(s) in ${name}`);
53145
- return cleanResult({ queue });
53146
- };
53147
- const activeQueueItem = (cwd, queue) => {
53148
- for (const entry of queue.items) {
53149
- const item = readWorkItem(cwd, entry.id);
53150
- if (![
53151
- "done",
53152
- "wontfix",
53153
- "claimed",
53154
- "blocked"
53155
- ].includes(item.status)) return item;
53156
- }
53157
- };
53158
- const workNext = (options = {}) => {
53159
- const cwd = options.cwd ?? process.cwd();
53160
- const config = readWorkConfig(cwd);
53161
- const queue = readWorkQueue(cwd, options.name ?? config.defaultQueue);
53162
- const item = activeQueueItem(cwd, queue);
53163
- if (item === void 0) {
53164
- xyLog("No available queued work item");
53165
- return cleanResult({ item: void 0 });
53166
- }
53167
- const next = options.claim === true ? claimItem(cwd, item, options.now) : item;
53168
- printWorkItemSummary(next, calculatePriorityScore(next.priority, config.priority.formula));
53169
- return cleanResult({ item: next });
53170
- };
53171
- const claimItem = (cwd, item, now) => {
53172
- if (item.status === "done" || item.status === "wontfix") throw new Error(`Cannot claim ${item.status} item: ${item.id}`);
53173
- const claimedAt = nowIso(now);
53174
- const claimed = {
53175
- ...item,
53176
- claimedAt,
53177
- status: "claimed",
53178
- updatedAt: claimedAt
53179
- };
53180
- writeWorkItem(cwd, claimed);
53181
- return claimed;
53182
- };
53183
- const workClaim = (options) => {
53184
- const cwd = options.cwd ?? process.cwd();
53185
- const item = claimItem(cwd, readWorkItem(cwd, options.id), options.now);
53186
- xyLog(`Claimed ${item.id}`);
53187
- return cleanResult({ item });
53188
- };
53189
- const workDone = (options) => {
53190
- if (options.evidence.trim().length === 0) throw new Error("done requires non-empty verification evidence");
53191
- const cwd = options.cwd ?? process.cwd();
53192
- const item = readWorkItem(cwd, options.id);
53193
- const completedAt = nowIso(options.now);
53194
- const verification = [...item.verification, options.evidence.trim()];
53195
- const done = {
53196
- ...item,
53197
- completedAt,
53198
- status: "done",
53199
- updatedAt: completedAt,
53200
- verification: [...new Set(verification)]
53201
- };
53202
- writeWorkItem(cwd, done);
53203
- xyLog(`Done ${done.id}`);
53204
- return cleanResult({ item: done });
53205
- };
53206
- const workUpdate = (options) => {
53207
- const cwd = options.cwd ?? process.cwd();
53208
- const item = readWorkItem(cwd, options.id);
53209
- const priority = priorityFromPartial({
53210
- confidence: options.confidence,
53211
- effort: options.effort,
53212
- impact: options.impact,
53213
- risk: options.risk,
53214
- urgency: options.urgency
54154
+ return cleanResult({
54155
+ results,
54156
+ summary: results[0]?.summary
53215
54157
  });
53216
- const updatedAt = nowIso(options.now);
53217
- const updated = {
53218
- ...item,
53219
- acceptanceCriteria: options.acceptanceCriteria === void 0 ? item.acceptanceCriteria : normalizeTextList(options.acceptanceCriteria),
53220
- area: options.area ?? item.area,
53221
- blockedReason: options.blockedReason ?? item.blockedReason,
53222
- description: options.description ?? item.description,
53223
- priority: priority === void 0 ? item.priority : validateWorkPriority(priority),
53224
- status: options.status ?? item.status,
53225
- tags: options.tags === void 0 ? item.tags : normalizeTags(options.tags),
53226
- title: options.title ?? item.title,
53227
- updatedAt,
53228
- verification: options.verification === void 0 ? item.verification : normalizeTextList(options.verification)
53229
- };
53230
- writeWorkItem(cwd, updated);
53231
- xyLog(`Updated ${updated.id}`);
53232
- return cleanResult({ item: updated });
53233
54158
  };
53234
54159
  //#endregion
53235
54160
  //#region src/xy/build/buildCommand.ts
@@ -53625,7 +54550,7 @@ const cleanCommand$1 = {
53625
54550
  await withEnvelope("packman clean", () => packmanClean({ isVerbose: !!Boolean(argv.verbose) }));
53626
54551
  }
53627
54552
  };
53628
- const lintCommand$2 = {
54553
+ const lintCommand$3 = {
53629
54554
  command: "lint",
53630
54555
  describe: "Check package manager configuration settings",
53631
54556
  builder: (yargs) => {
@@ -53653,7 +54578,7 @@ const lintCommand$2 = {
53653
54578
  };
53654
54579
  const packmanCommand = {
53655
54580
  builder: (yargs) => {
53656
- return yargs.command(cleanCommand$1).command(convertCommand).command(lintCommand$2).demandCommand(1, "Please specify a packman subcommand").strictCommands();
54581
+ return yargs.command(cleanCommand$1).command(convertCommand).command(lintCommand$3).demandCommand(1, "Please specify a packman subcommand").strictCommands();
53657
54582
  },
53658
54583
  command: "packman",
53659
54584
  describe: "Package Manager - Configuration and conversion utilities",
@@ -53724,7 +54649,7 @@ const initCommand$2 = {
53724
54649
  };
53725
54650
  //#endregion
53726
54651
  //#region src/xy/common/repo/lintCommand.ts
53727
- const lintCommand$1 = {
54652
+ const lintCommand$2 = {
53728
54653
  command: "lint",
53729
54654
  describe: "Check monorepo package structure",
53730
54655
  builder: (yargs) => {
@@ -53751,7 +54676,7 @@ const lintCommand$1 = {
53751
54676
  //#region src/xy/common/repo/index.ts
53752
54677
  const repoCommand = {
53753
54678
  builder: (yargs) => {
53754
- return yargs.command(initCommand$2).command(lintCommand$1).demandCommand(1, "Please specify a repo subcommand").strictCommands();
54679
+ return yargs.command(initCommand$2).command(lintCommand$2).demandCommand(1, "Please specify a repo subcommand").strictCommands();
53755
54680
  },
53756
54681
  command: "repo",
53757
54682
  describe: "Repo - Repository structure utilities",
@@ -53934,11 +54859,37 @@ const optionalNumber = (value) => {
53934
54859
  const optionalString = (value) => {
53935
54860
  return typeof value === "string" && value.length > 0 ? value : void 0;
53936
54861
  };
54862
+ /** Shared --workspace / --workspace-file / --repo flags for work subcommands. */
54863
+ const withWorkScopeOptions = (yargs) => {
54864
+ const y = yargs;
54865
+ y.option("workspace", {
54866
+ default: false,
54867
+ describe: "Operate across folders in the active/local *.code-workspace",
54868
+ type: "boolean"
54869
+ });
54870
+ y.option("workspace-file", {
54871
+ describe: "Explicit *.code-workspace path (implies --workspace)",
54872
+ type: "string"
54873
+ });
54874
+ y.option("repo", {
54875
+ describe: "Limit or target a single workspace folder by name",
54876
+ type: "string"
54877
+ });
54878
+ return yargs;
54879
+ };
54880
+ const scopeFromArgv = (argv) => {
54881
+ const workspaceFile = optionalString(argv["workspace-file"]);
54882
+ return {
54883
+ repo: optionalString(argv.repo),
54884
+ workspace: Boolean(argv.workspace) || workspaceFile !== void 0,
54885
+ workspaceFile
54886
+ };
54887
+ };
53937
54888
  //#endregion
53938
54889
  //#region src/xy/common/work/addCommand.ts
53939
54890
  const addCommand = {
53940
54891
  builder: (yargs) => {
53941
- return yargs.positional("type", {
54892
+ return withWorkScopeOptions(yargs.positional("type", {
53942
54893
  choices: WORK_TYPES,
53943
54894
  describe: "Work item type",
53944
54895
  type: "string"
@@ -53988,12 +54939,14 @@ const addCommand = {
53988
54939
  }).option("confidence", {
53989
54940
  describe: "Priority confidence from 1 to 5",
53990
54941
  type: "number"
53991
- });
54942
+ }));
53992
54943
  },
53993
54944
  command: "add <type> <title>",
53994
54945
  describe: "Create a work item (also creates a GitHub issue when available)",
53995
54946
  handler: async (argv) => {
54947
+ const scope = scopeFromArgv(argv);
53996
54948
  await withEnvelope("work add", () => workAdd({
54949
+ ...scope,
53997
54950
  acceptanceCriteria: stringArray(argv.acceptance),
53998
54951
  area: optionalString(argv.area),
53999
54952
  confidence: optionalNumber(argv.confidence),
@@ -54016,34 +54969,40 @@ const addCommand = {
54016
54969
  //#region src/xy/common/work/claimCommand.ts
54017
54970
  const claimCommand = {
54018
54971
  builder: (yargs) => {
54019
- return yargs.positional("id", {
54972
+ return withWorkScopeOptions(yargs.positional("id", {
54020
54973
  describe: "Work item id",
54021
54974
  type: "string"
54022
- });
54975
+ }));
54023
54976
  },
54024
54977
  command: "claim <id>",
54025
54978
  describe: "Claim a work item",
54026
54979
  handler: async (argv) => {
54027
- await withEnvelope("work claim", () => workClaim({ id: String(argv.id) }));
54980
+ const scope = scopeFromArgv(argv);
54981
+ await withEnvelope("work claim", () => workClaim({
54982
+ ...scope,
54983
+ id: String(argv.id)
54984
+ }));
54028
54985
  }
54029
54986
  };
54030
54987
  //#endregion
54031
54988
  //#region src/xy/common/work/doneCommand.ts
54032
54989
  const doneCommand = {
54033
54990
  builder: (yargs) => {
54034
- return yargs.positional("id", {
54991
+ return withWorkScopeOptions(yargs.positional("id", {
54035
54992
  describe: "Work item id",
54036
54993
  type: "string"
54037
54994
  }).option("evidence", {
54038
54995
  demandOption: true,
54039
54996
  describe: "Verification evidence proving the work is complete",
54040
54997
  type: "string"
54041
- });
54998
+ }));
54042
54999
  },
54043
55000
  command: "done <id>",
54044
55001
  describe: "Mark a work item done with verification evidence",
54045
55002
  handler: async (argv) => {
55003
+ const scope = scopeFromArgv(argv);
54046
55004
  await withEnvelope("work done", () => workDone({
55005
+ ...scope,
54047
55006
  evidence: String(argv.evidence),
54048
55007
  id: String(argv.id)
54049
55008
  }));
@@ -54052,17 +55011,47 @@ const doneCommand = {
54052
55011
  //#endregion
54053
55012
  //#region src/xy/common/work/initCommand.ts
54054
55013
  const initCommand$1 = {
55014
+ builder: (yargs) => withWorkScopeOptions(yargs),
54055
55015
  command: "init",
54056
55016
  describe: "Initialize the repo-local work item store",
54057
- handler: async () => {
54058
- await withEnvelope("work init", () => workInit());
55017
+ handler: async (argv) => {
55018
+ const scope = scopeFromArgv(argv);
55019
+ await withEnvelope("work init", () => workInit(scope));
55020
+ }
55021
+ };
55022
+ //#endregion
55023
+ //#region src/xy/common/work/lintCommand.ts
55024
+ const lintCommand$1 = {
55025
+ builder: (yargs) => {
55026
+ return withWorkScopeOptions(yargs.option("strict", {
55027
+ default: false,
55028
+ describe: "Fail on warnings",
55029
+ type: "boolean"
55030
+ }).option("rules", {
55031
+ default: false,
55032
+ describe: "List supported work lint rules and their effective levels",
55033
+ type: "boolean"
55034
+ }));
55035
+ },
55036
+ command: "lint",
55037
+ describe: "Lint work store health (gitignore, GitHub availability, sync drift)",
55038
+ handler: async (argv) => {
55039
+ if (argv.rules === true) {
55040
+ await withEnvelope("work lint rules", async () => ruleCatalogResult(await getWorkLintRuleCatalog(), RULE_COMMANDS.workLint.title));
55041
+ return;
55042
+ }
55043
+ const scope = scopeFromArgv(argv);
55044
+ await withEnvelope("work lint", () => workLint({
55045
+ ...scope,
55046
+ strict: Boolean(argv.strict)
55047
+ }));
54059
55048
  }
54060
55049
  };
54061
55050
  //#endregion
54062
55051
  //#region src/xy/common/work/listCommand.ts
54063
55052
  const listCommand = {
54064
55053
  builder: (yargs) => {
54065
- return yargs.option("all", {
55054
+ return withWorkScopeOptions(yargs.option("all", {
54066
55055
  default: false,
54067
55056
  describe: "Also list/normalize open GitHub issues not created by xy work",
54068
55057
  type: "boolean"
@@ -54079,12 +55068,14 @@ const listCommand = {
54079
55068
  default: "created",
54080
55069
  describe: "Sort order",
54081
55070
  type: "string"
54082
- });
55071
+ }));
54083
55072
  },
54084
55073
  command: "list",
54085
55074
  describe: "List work items",
54086
55075
  handler: async (argv) => {
55076
+ const scope = scopeFromArgv(argv);
54087
55077
  await withEnvelope("work list", () => workList({
55078
+ ...scope,
54088
55079
  all: Boolean(argv.all),
54089
55080
  sort: argv.sort,
54090
55081
  status: argv.status,
@@ -54093,22 +55084,53 @@ const listCommand = {
54093
55084
  }
54094
55085
  };
54095
55086
  //#endregion
55087
+ //#region src/xy/common/work/moveCommand.ts
55088
+ const moveCommand = {
55089
+ builder: (yargs) => {
55090
+ return withWorkScopeOptions(yargs.positional("id", {
55091
+ describe: "Work item id",
55092
+ type: "string"
55093
+ }).option("to", {
55094
+ demandOption: true,
55095
+ describe: "Destination workspace folder name",
55096
+ type: "string"
55097
+ }).option("from", {
55098
+ describe: "Source workspace folder name (disambiguates id)",
55099
+ type: "string"
55100
+ }));
55101
+ },
55102
+ command: "move <id>",
55103
+ describe: "Move a work item between workspace folder repos",
55104
+ handler: async (argv) => {
55105
+ const scope = scopeFromArgv(argv);
55106
+ await withEnvelope("work move", () => workMove({
55107
+ ...scope,
55108
+ from: optionalString(argv.from),
55109
+ id: String(argv.id),
55110
+ to: String(argv.to),
55111
+ workspace: true
55112
+ }));
55113
+ }
55114
+ };
55115
+ //#endregion
54096
55116
  //#region src/xy/common/work/nextCommand.ts
54097
55117
  const nextCommand = {
54098
55118
  builder: (yargs) => {
54099
- return yargs.option("name", {
55119
+ return withWorkScopeOptions(yargs.option("name", {
54100
55120
  describe: "Queue name",
54101
55121
  type: "string"
54102
55122
  }).option("claim", {
54103
55123
  default: false,
54104
55124
  describe: "Claim the returned item",
54105
55125
  type: "boolean"
54106
- });
55126
+ }));
54107
55127
  },
54108
55128
  command: "next",
54109
55129
  describe: "Show the next available queued work item",
54110
55130
  handler: async (argv) => {
55131
+ const scope = scopeFromArgv(argv);
54111
55132
  await withEnvelope("work next", () => workNext({
55133
+ ...scope,
54112
55134
  claim: Boolean(argv.claim),
54113
55135
  name: optionalString(argv.name)
54114
55136
  }));
@@ -54118,7 +55140,7 @@ const nextCommand = {
54118
55140
  //#region src/xy/common/work/queueCommand.ts
54119
55141
  const queueCommand = {
54120
55142
  builder: (yargs) => {
54121
- return yargs.option("name", {
55143
+ return withWorkScopeOptions(yargs.option("name", {
54122
55144
  describe: "Queue name",
54123
55145
  type: "string"
54124
55146
  }).option("limit", {
@@ -54128,12 +55150,14 @@ const queueCommand = {
54128
55150
  choices: WORK_STATUSES,
54129
55151
  describe: "Only queue items with this status",
54130
55152
  type: "string"
54131
- });
55153
+ }));
54132
55154
  },
54133
55155
  command: "queue",
54134
55156
  describe: "Materialize a priority-sorted work queue",
54135
55157
  handler: async (argv) => {
55158
+ const scope = scopeFromArgv(argv);
54136
55159
  await withEnvelope("work queue", () => workQueue({
55160
+ ...scope,
54137
55161
  limit: optionalNumber(argv.limit),
54138
55162
  name: optionalString(argv.name),
54139
55163
  status: argv.status
@@ -54143,41 +55167,49 @@ const queueCommand = {
54143
55167
  //#endregion
54144
55168
  //#region src/xy/common/work/showCommand.ts
54145
55169
  const showCommand = {
54146
- command: "show <id>",
54147
- describe: "Show a work item as JSON",
54148
55170
  builder: (yargs) => {
54149
- return yargs.positional("id", {
55171
+ return withWorkScopeOptions(yargs.positional("id", {
54150
55172
  describe: "Work item id",
54151
55173
  type: "string"
54152
- });
55174
+ }));
54153
55175
  },
55176
+ command: "show <id>",
55177
+ describe: "Show a work item as JSON",
54154
55178
  handler: async (argv) => {
54155
- await withEnvelope("work show", () => workShow({ id: String(argv.id) }));
55179
+ const scope = scopeFromArgv(argv);
55180
+ await withEnvelope("work show", () => workShow({
55181
+ ...scope,
55182
+ id: String(argv.id)
55183
+ }));
54156
55184
  }
54157
55185
  };
54158
55186
  //#endregion
54159
55187
  //#region src/xy/common/work/syncCommand.ts
54160
55188
  const syncCommand = {
55189
+ builder: (yargs) => withWorkScopeOptions(yargs),
54161
55190
  command: "sync",
54162
55191
  describe: "Sync repo-local work items with GitHub Issues when available",
54163
- handler: async () => {
54164
- await withEnvelope("work sync", () => workSync());
55192
+ handler: async (argv) => {
55193
+ const scope = scopeFromArgv(argv);
55194
+ await withEnvelope("work sync", () => workSyncScoped(scope));
54165
55195
  }
54166
55196
  };
54167
55197
  //#endregion
54168
55198
  //#region src/xy/common/work/triageCommand.ts
54169
55199
  const triageCommand = {
55200
+ builder: (yargs) => withWorkScopeOptions(yargs),
54170
55201
  command: "triage",
54171
55202
  describe: "List open work items missing triage fields",
54172
- handler: async () => {
54173
- await withEnvelope("work triage", () => workTriage());
55203
+ handler: async (argv) => {
55204
+ const scope = scopeFromArgv(argv);
55205
+ await withEnvelope("work triage", () => workTriage(scope));
54174
55206
  }
54175
55207
  };
54176
55208
  //#endregion
54177
55209
  //#region src/xy/common/work/updateCommand.ts
54178
55210
  const updateCommand = {
54179
55211
  builder: (yargs) => {
54180
- return yargs.positional("id", {
55212
+ return withWorkScopeOptions(yargs.positional("id", {
54181
55213
  describe: "Work item id",
54182
55214
  type: "string"
54183
55215
  }).option("title", {
@@ -54208,12 +55240,14 @@ const updateCommand = {
54208
55240
  array: true,
54209
55241
  describe: "Replace verification entries; repeatable",
54210
55242
  type: "string"
54211
- }).option("impact", { type: "number" }).option("urgency", { type: "number" }).option("effort", { type: "number" }).option("risk", { type: "number" }).option("confidence", { type: "number" });
55243
+ }).option("impact", { type: "number" }).option("urgency", { type: "number" }).option("effort", { type: "number" }).option("risk", { type: "number" }).option("confidence", { type: "number" }));
54212
55244
  },
54213
55245
  command: "update <id>",
54214
55246
  describe: "Update triage fields on a work item",
54215
55247
  handler: async (argv) => {
55248
+ const scope = scopeFromArgv(argv);
54216
55249
  await withEnvelope("work update", () => workUpdate({
55250
+ ...scope,
54217
55251
  acceptanceCriteria: optionalStringArray(argv.acceptance),
54218
55252
  area: optionalString(argv.area),
54219
55253
  blockedReason: optionalString(argv["blocked-reason"]),
@@ -54235,7 +55269,7 @@ const updateCommand = {
54235
55269
  //#region src/xy/common/work/index.ts
54236
55270
  const workCommand = {
54237
55271
  builder: (yargs) => {
54238
- return yargs.command(initCommand$1).command(addCommand).command(listCommand).command(showCommand).command(syncCommand).command(triageCommand).command(queueCommand).command(nextCommand).command(claimCommand).command(doneCommand).command(updateCommand).demandCommand(1, "Please specify a work subcommand").strictCommands();
55272
+ return yargs.command(initCommand$1).command(addCommand).command(listCommand).command(showCommand).command(syncCommand).command(triageCommand).command(queueCommand).command(nextCommand).command(claimCommand).command(doneCommand).command(updateCommand).command(moveCommand).command(lintCommand$1).demandCommand(1, "Please specify a work subcommand").strictCommands();
54239
55273
  },
54240
55274
  command: "work",
54241
55275
  describe: "Work - AI-friendly work tracking (repo-local, with optional GitHub Issues)",