@staff0rd/assist 0.1075.2 → 0.1076.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ import { Command } from "commander";
6
6
  // package.json
7
7
  var package_default = {
8
8
  name: "@staff0rd/assist",
9
- version: "0.1075.2",
9
+ version: "0.1076.1",
10
10
  type: "module",
11
11
  main: "dist/index.js",
12
12
  bin: {
@@ -280,13 +280,13 @@ function runHandler(handler, req, res, port) {
280
280
  logRequest(method, url, res.statusCode, Date.now() - startedAt);
281
281
  });
282
282
  Promise.resolve(handler(req, res, port)).catch((error) => {
283
+ const message3 = error instanceof Error ? error.message : String(error);
283
284
  console.error(
284
- `${(/* @__PURE__ */ new Date()).toISOString()} ${method} ${url} failed: ${error instanceof Error ? error.message : String(error)}`
285
+ `${(/* @__PURE__ */ new Date()).toISOString()} ${method} ${url} failed: ${message3}`
285
286
  );
286
287
  if (!res.headersSent)
287
288
  res.writeHead(500, { "Content-Type": "application/json" });
288
- if (!res.writableEnded)
289
- res.end(JSON.stringify({ error: "internal error" }));
289
+ if (!res.writableEnded) res.end(JSON.stringify({ error: message3 }));
290
290
  });
291
291
  }
292
292
 
@@ -468,452 +468,6 @@ import { existsSync as existsSync6 } from "fs";
468
468
  import { homedir as homedir4 } from "os";
469
469
  import { dirname as dirname3, join as join7 } from "path";
470
470
 
471
- // src/shared/linkedWorktree.ts
472
- import { existsSync, readFileSync, statSync as statSync3 } from "fs";
473
- import { basename as basename2, dirname as dirname2, isAbsolute, join as join4, resolve as resolve2 } from "path";
474
- function linkedWorktree(dir) {
475
- const root2 = findGitLink(dir);
476
- if (!root2) return null;
477
- const gitDir = readGitDirPointer(root2);
478
- if (!gitDir) return null;
479
- const commonDir = resolveCommonDir(gitDir);
480
- if (!commonDir || basename2(commonDir) !== ".git") return null;
481
- const clone = dirname2(commonDir);
482
- return existsSync(clone) ? { root: root2, clone } : null;
483
- }
484
- function findGitLink(dir) {
485
- let current2 = resolve2(dir);
486
- while (current2 !== dirname2(current2)) {
487
- const entry = join4(current2, ".git");
488
- if (existsSync(entry)) return isFile(entry) ? current2 : null;
489
- current2 = dirname2(current2);
490
- }
491
- return null;
492
- }
493
- function isFile(path109) {
494
- try {
495
- return statSync3(path109).isFile();
496
- } catch {
497
- return false;
498
- }
499
- }
500
- function readGitDirPointer(root2) {
501
- const target = readTrimmed(join4(root2, ".git"));
502
- if (!target?.startsWith("gitdir:")) return null;
503
- return absolute(target.slice("gitdir:".length).trim(), root2);
504
- }
505
- function resolveCommonDir(gitDir) {
506
- const recorded = readTrimmed(join4(gitDir, "commondir"));
507
- if (recorded) return absolute(recorded, gitDir);
508
- return linkedGitDirParent(gitDir);
509
- }
510
- function linkedGitDirParent(gitDir) {
511
- const match = /^(.*)[/\\]worktrees[/\\][^/\\]+[/\\]?$/.exec(gitDir);
512
- return match ? match[1] : null;
513
- }
514
- function readTrimmed(path109) {
515
- try {
516
- const content = readFileSync(path109, "utf8").trim();
517
- return content === "" ? null : content;
518
- } catch {
519
- return null;
520
- }
521
- }
522
- function absolute(target, from) {
523
- return isAbsolute(target) ? target : resolve2(from, target);
524
- }
525
-
526
- // src/shared/loadRawYaml.ts
527
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
528
- import { parse as parseYaml } from "yaml";
529
- function loadRawYaml(path109) {
530
- if (!existsSync2(path109)) return {};
531
- try {
532
- const content = readFileSync2(path109, "utf8");
533
- return parseYaml(content) || {};
534
- } catch {
535
- return {};
536
- }
537
- }
538
-
539
- // src/shared/deepMergeRawConfig.ts
540
- function isPlainObject(value) {
541
- return typeof value === "object" && value !== null && !Array.isArray(value);
542
- }
543
- function deepMergeRawConfig(base, override) {
544
- const merged = { ...base };
545
- for (const [key, value] of Object.entries(override)) {
546
- const existing = merged[key];
547
- merged[key] = isPlainObject(existing) && isPlainObject(value) ? deepMergeRawConfig(existing, value) : value;
548
- }
549
- return merged;
550
- }
551
-
552
- // src/shared/mergeAdviceRules.ts
553
- function adviceRules(raw) {
554
- const advice = raw.advice;
555
- return Array.isArray(advice?.rules) ? advice.rules : void 0;
556
- }
557
- function mergeAdviceRules(globalRaw, projectRaw) {
558
- const globalRules = adviceRules(globalRaw);
559
- const projectRules = adviceRules(projectRaw);
560
- if (!globalRules || !projectRules) return void 0;
561
- return [...globalRules, ...projectRules];
562
- }
563
-
564
- // src/shared/mergeDenyRules.ts
565
- function mergeDenyRules(globalDeny, projectDeny) {
566
- if (!globalDeny && !projectDeny) return void 0;
567
- if (!globalDeny) return projectDeny;
568
- if (!projectDeny) return globalDeny;
569
- const projectPatterns = new Set(projectDeny.map((r) => r.pattern));
570
- const globalOnly = globalDeny.filter((r) => !projectPatterns.has(r.pattern));
571
- return [...globalOnly, ...projectDeny];
572
- }
573
- function runKey(r) {
574
- return typeof r.name === "string" ? r.name : void 0;
575
- }
576
- function mergeRunConfigs(globalRun, projectRun) {
577
- if (!globalRun && !projectRun) return void 0;
578
- if (!globalRun) return projectRun;
579
- if (!projectRun) return globalRun;
580
- const projectNames = new Set(
581
- projectRun.map(runKey).filter((n) => n !== void 0)
582
- );
583
- const globalOnly = globalRun.filter((r) => {
584
- const key = runKey(r);
585
- return key === void 0 || !projectNames.has(key);
586
- });
587
- return [...globalOnly, ...projectRun];
588
- }
589
- function mergeRawConfigs(globalRaw, projectRaw) {
590
- const deny = mergeDenyRules(
591
- globalRaw.deny,
592
- projectRaw.deny
593
- );
594
- const run4 = mergeRunConfigs(
595
- globalRaw.run,
596
- projectRaw.run
597
- );
598
- const adviceRules3 = mergeAdviceRules(globalRaw, projectRaw);
599
- const merged = deepMergeRawConfig(globalRaw, projectRaw);
600
- if (adviceRules3 !== void 0) {
601
- merged.advice = { ...merged.advice, rules: adviceRules3 };
602
- }
603
- if (deny !== void 0) {
604
- merged.deny = deny;
605
- }
606
- if (run4 !== void 0) {
607
- merged.run = run4;
608
- }
609
- return merged;
610
- }
611
-
612
- // src/shared/readRepoConfigCache.ts
613
- import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
614
- import { join as join6 } from "path";
615
-
616
- // src/shared/loadJson.ts
617
- import {
618
- existsSync as existsSync3,
619
- mkdirSync as mkdirSync2,
620
- readFileSync as readFileSync3,
621
- renameSync,
622
- rmSync as rmSync2,
623
- writeFileSync
624
- } from "fs";
625
- import { homedir as homedir3 } from "os";
626
- import { join as join5 } from "path";
627
- function getStoreDir() {
628
- return process.env.ASSIST_STORE_DIR || join5(homedir3(), ".assist");
629
- }
630
- function getStorePath(filename) {
631
- return join5(getStoreDir(), filename);
632
- }
633
- function loadJson(filename) {
634
- const path109 = getStorePath(filename);
635
- if (existsSync3(path109)) {
636
- try {
637
- return JSON.parse(readFileSync3(path109, "utf8"));
638
- } catch {
639
- return {};
640
- }
641
- }
642
- return {};
643
- }
644
- function saveJson(filename, data) {
645
- const dir = getStoreDir();
646
- if (!existsSync3(dir)) {
647
- mkdirSync2(dir, { recursive: true });
648
- }
649
- const path109 = getStorePath(filename);
650
- const tmp = `${path109}.${process.pid}.tmp`;
651
- try {
652
- writeFileSync(tmp, JSON.stringify(data, null, 2));
653
- renameSync(tmp, path109);
654
- } catch (error) {
655
- rmSync2(tmp, { force: true });
656
- throw error;
657
- }
658
- }
659
-
660
- // src/shared/readRepoConfigCache.ts
661
- function repoConfigCachePath() {
662
- return join6(getStoreDir(), "repo-config-cache.json");
663
- }
664
- function readConfigCacheFile() {
665
- const path109 = repoConfigCachePath();
666
- if (!existsSync4(path109)) return {};
667
- try {
668
- const parsed = JSON.parse(readFileSync4(path109, "utf8"));
669
- return parsed ?? {};
670
- } catch {
671
- return {};
672
- }
673
- }
674
- function readRepoConfigCache() {
675
- return readConfigCacheFile().repos ?? {};
676
- }
677
-
678
- // src/shared/resolveRepoLayer.ts
679
- import chalk2 from "chalk";
680
-
681
- // src/shared/findRepoRoot.ts
682
- import { existsSync as existsSync5 } from "fs";
683
- import path from "path";
684
- function findRepoRoot(dir) {
685
- let current2 = dir;
686
- while (current2 !== path.dirname(current2)) {
687
- if (existsSync5(path.join(current2, ".git"))) {
688
- return current2;
689
- }
690
- current2 = path.dirname(current2);
691
- }
692
- return null;
693
- }
694
-
695
- // src/commands/backlog/remoteUrl.ts
696
- import { execFileSync } from "child_process";
697
- function runGit(cwd, args) {
698
- const windows = /^[A-Za-z]:[\\/]/.test(cwd);
699
- const file = windows ? "git.exe" : "git";
700
- const argv = windows ? ["-C", cwd, ...args] : args;
701
- try {
702
- const out = execFileSync(file, argv, {
703
- encoding: "utf8",
704
- windowsHide: true,
705
- stdio: ["ignore", "pipe", "pipe"],
706
- ...windows ? {} : { cwd }
707
- }).trim();
708
- return { ok: true, out };
709
- } catch {
710
- return { ok: false, out: "" };
711
- }
712
- }
713
- function tryGit(cwd, args) {
714
- return runGit(cwd, args).out || null;
715
- }
716
- function remoteUrl(cwd) {
717
- const origin = runGit(cwd, ["remote", "get-url", "origin"]);
718
- if (origin.out) return { url: origin.out, ok: true };
719
- const remotes = runGit(cwd, ["remote"]);
720
- if (!remotes.ok) return { url: null, ok: false };
721
- let failed3 = false;
722
- for (const remote of remotes.out.split("\n").map((r) => r.trim()).filter(Boolean)) {
723
- const url = runGit(cwd, ["remote", "get-url", remote]);
724
- if (url.out) return { url: url.out, ok: true };
725
- if (!url.ok) failed3 = true;
726
- }
727
- return { url: null, ok: !failed3 };
728
- }
729
- function getRemoteOriginUrl(cwd) {
730
- return remoteUrl(cwd).url;
731
- }
732
-
733
- // src/commands/backlog/getCurrentOrigin.ts
734
- var WINDOWS_PATH = /^[A-Za-z]:[\\/]/;
735
- function stripLeadingSlashes(path109) {
736
- return path109.replace(/^\/+/, "");
737
- }
738
- function normalizeOrigin(raw) {
739
- const trimmed = raw.trim().replace(/\.git$/i, "").replace(/\/+$/, "");
740
- const url = trimmed.match(
741
- /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/
742
- );
743
- if (url) {
744
- return `${url[1].toLowerCase()}/${stripLeadingSlashes(url[2])}`;
745
- }
746
- if (!trimmed.includes("://")) {
747
- const scp = trimmed.match(/^(?:[^@/]+@)?([^/:]+):(.+)$/);
748
- if (scp) {
749
- return `${scp[1].toLowerCase()}/${stripLeadingSlashes(scp[2])}`;
750
- }
751
- }
752
- return trimmed.toLowerCase();
753
- }
754
- function resolveCurrentOrigin(cwd) {
755
- if (!WINDOWS_PATH.test(cwd) && findRepoRoot(cwd) === null)
756
- return { origin: `local:${cwd}`, stable: false };
757
- const remote = remoteUrl(cwd);
758
- if (remote.url) return { origin: normalizeOrigin(remote.url), stable: true };
759
- const root2 = tryGit(cwd, ["rev-parse", "--show-toplevel"]);
760
- return { origin: `local:${root2 ?? cwd}`, stable: remote.ok };
761
- }
762
- function getCurrentOrigin(cwd) {
763
- return resolveCurrentOrigin(cwd).origin;
764
- }
765
-
766
- // src/commands/backlog/getCachedOrigin.ts
767
- var stableOrigins = /* @__PURE__ */ new Map();
768
- function getCachedOrigin(cwd) {
769
- const cached2 = stableOrigins.get(cwd);
770
- if (cached2 !== void 0) return cached2;
771
- const { origin, stable } = resolveCurrentOrigin(cwd);
772
- if (stable) stableOrigins.set(cwd, origin);
773
- return origin;
774
- }
775
-
776
- // src/commands/backlog/originDisplayName.ts
777
- function originDisplayName(origin) {
778
- if (origin.startsWith("local:")) {
779
- const path109 = origin.slice("local:".length).replace(/\/+$/, "");
780
- const segments = path109.split("/").filter(Boolean);
781
- return segments[segments.length - 1] ?? origin;
782
- }
783
- const firstSlash = origin.indexOf("/");
784
- if (firstSlash === -1) return origin;
785
- return origin.slice(firstSlash + 1);
786
- }
787
-
788
- // src/shared/resolveRepoOverride.ts
789
- var AmbiguousRepoConfigError = class extends Error {
790
- name = "AmbiguousRepoConfigError";
791
- };
792
- function originKeyCandidates(origin) {
793
- const displayName = originDisplayName(origin);
794
- const segments = displayName.split("/");
795
- const bare = segments[segments.length - 1] ?? displayName;
796
- return /* @__PURE__ */ new Set([origin, displayName, bare]);
797
- }
798
- function matchRepoConfigKey(globalRaw, origin, source = "~/.assist.yml") {
799
- const repos2 = globalRaw.repos;
800
- if (!repos2 || typeof repos2 !== "object" || Array.isArray(repos2))
801
- return void 0;
802
- const entries = repos2;
803
- const candidates = originKeyCandidates(origin);
804
- const matches = Object.keys(entries).filter((key) => candidates.has(key));
805
- if (matches.length === 0) return void 0;
806
- if (matches.length > 1) {
807
- throw new AmbiguousRepoConfigError(
808
- `Ambiguous repos config in ${source}: keys ${matches.map((m) => `"${m}"`).join(", ")} all match the current repository (${origin}). Keep a single key per repository.`
809
- );
810
- }
811
- return matches[0];
812
- }
813
- function resolveRepoOverride(globalRaw, origin, source) {
814
- const matched = matchRepoConfigKey(globalRaw, origin, source);
815
- if (matched === void 0) return {};
816
- const override = globalRaw.repos[matched];
817
- if (!override || typeof override !== "object" || Array.isArray(override))
818
- return {};
819
- return override;
820
- }
821
-
822
- // src/shared/resolveRepoLayer.ts
823
- var SHARED_REPO_CONFIG_SOURCE = "the shared db";
824
- var warnedYmlKeys = /* @__PURE__ */ new Set();
825
- function resolveRepoLayer(globalRaw, cwd) {
826
- const cached2 = { repos: readRepoConfigCache() };
827
- if (Object.keys(cached2.repos).length === 0 && !globalRaw.repos)
828
- return { override: {} };
829
- const origin = getCachedOrigin(cwd);
830
- const dbKey = matchRepoConfigKey(cached2, origin, SHARED_REPO_CONFIG_SOURCE);
831
- if (dbKey !== void 0)
832
- return {
833
- override: resolveRepoOverride(cached2, origin, SHARED_REPO_CONFIG_SOURCE),
834
- key: dbKey,
835
- source: "db"
836
- };
837
- const ymlKey = matchRepoConfigKey(globalRaw, origin);
838
- if (ymlKey === void 0) return { override: {} };
839
- warnYmlRepoOverride(ymlKey);
840
- return {
841
- override: resolveRepoOverride(globalRaw, origin),
842
- key: ymlKey,
843
- source: "yml"
844
- };
845
- }
846
- function warnYmlRepoOverride(key) {
847
- if (warnedYmlKeys.has(key)) return;
848
- warnedYmlKeys.add(key);
849
- console.error(
850
- chalk2.yellow(
851
- `repos.${key} in ~/.assist.yml is not in the shared db, so other nodes don't see it. Run 'assist config import-repos' to share it.`
852
- )
853
- );
854
- }
855
-
856
- // src/shared/stripLegacyReviewKeys.ts
857
- var LEGACY_REVIEW_HIGH_LEVEL_KEYS = ["slices"];
858
- function stripLegacyReviewKeys(review2) {
859
- if (!review2 || typeof review2 !== "object") return review2;
860
- const { highLevel, ...rest } = review2;
861
- if (!highLevel || typeof highLevel !== "object") return review2;
862
- const kept = { ...highLevel };
863
- for (const key of LEGACY_REVIEW_HIGH_LEVEL_KEYS) delete kept[key];
864
- return { ...rest, highLevel: kept };
865
- }
866
-
867
- // src/shared/stripLegacyConfigKeys.ts
868
- var LEGACY_SESSIONS_KEYS = [
869
- "windowsProjectsRoot",
870
- "windowsDaemonHost",
871
- "windowsDaemonPort",
872
- "windowsVersionCheck",
873
- "topBar",
874
- "floatWaiting",
875
- "floatWaitingAfterMs",
876
- "parkWaitingAfterMs",
877
- "askQuestionAutoApprove"
878
- ];
879
- var LEGACY_WORKTREE_KEYS = ["watcher", "includeDrafts"];
880
- var LEGACY_DEVLOG_KEYS = ["skip"];
881
- function withoutKeys(value, keys) {
882
- if (!value || typeof value !== "object") return value;
883
- const rest = { ...value };
884
- for (const key of keys) delete rest[key];
885
- return rest;
886
- }
887
- function stripRepos(repos2) {
888
- if (!repos2 || typeof repos2 !== "object") return repos2;
889
- return Object.fromEntries(
890
- Object.entries(repos2).map(([name, entry]) => [
891
- name,
892
- entry && typeof entry === "object" ? stripLegacyConfigKeys(entry) : entry
893
- ])
894
- );
895
- }
896
- function stripLegacyConfigKeys(config) {
897
- const stripped = { ...config };
898
- if (stripped.repos) stripped.repos = stripRepos(stripped.repos);
899
- delete stripped.backlog;
900
- delete stripped.cliReadVerbs;
901
- delete stripped.roam;
902
- const news = stripped.news;
903
- if (news && typeof news === "object" && "feeds" in news) {
904
- const { feeds: _feeds, ...rest } = news;
905
- stripped.news = rest;
906
- }
907
- if (stripped.sessions)
908
- stripped.sessions = withoutKeys(stripped.sessions, LEGACY_SESSIONS_KEYS);
909
- if (stripped.worktree)
910
- stripped.worktree = withoutKeys(stripped.worktree, LEGACY_WORKTREE_KEYS);
911
- if (stripped.devlog)
912
- stripped.devlog = withoutKeys(stripped.devlog, LEGACY_DEVLOG_KEYS);
913
- if (stripped.review) stripped.review = stripLegacyReviewKeys(stripped.review);
914
- return stripped;
915
- }
916
-
917
471
  // src/shared/types.ts
918
472
  import { z as z6 } from "zod";
919
473
 
@@ -1462,6 +1016,485 @@ var assistConfigSchema = z6.strictObject({
1462
1016
  repos: z6.record(z6.string(), repoConfigSchema).optional()
1463
1017
  });
1464
1018
 
1019
+ // src/shared/dropUnknownConfigKeys.ts
1020
+ function objectAt(root2, path109) {
1021
+ let node = root2;
1022
+ for (const segment of path109) {
1023
+ if (!node || typeof node !== "object") return void 0;
1024
+ node = node[segment];
1025
+ }
1026
+ if (!node || typeof node !== "object" || Array.isArray(node))
1027
+ return void 0;
1028
+ return node;
1029
+ }
1030
+ function removeUnrecognizedKeys(config) {
1031
+ const parsed = assistConfigSchema.safeParse(config);
1032
+ if (parsed.success) return false;
1033
+ let removed = false;
1034
+ for (const issue of parsed.error.issues) {
1035
+ if (issue.code !== "unrecognized_keys") continue;
1036
+ const target = objectAt(config, issue.path);
1037
+ for (const key of issue.keys) {
1038
+ if (target && key in target) {
1039
+ delete target[key];
1040
+ removed = true;
1041
+ }
1042
+ }
1043
+ }
1044
+ return removed;
1045
+ }
1046
+ function dropUnknownConfigKeys(raw) {
1047
+ const config = structuredClone(raw);
1048
+ while (removeUnrecognizedKeys(config)) ;
1049
+ return config;
1050
+ }
1051
+
1052
+ // src/shared/linkedWorktree.ts
1053
+ import { existsSync, readFileSync, statSync as statSync3 } from "fs";
1054
+ import { basename as basename2, dirname as dirname2, isAbsolute, join as join4, resolve as resolve2 } from "path";
1055
+ function linkedWorktree(dir) {
1056
+ const root2 = findGitLink(dir);
1057
+ if (!root2) return null;
1058
+ const gitDir = readGitDirPointer(root2);
1059
+ if (!gitDir) return null;
1060
+ const commonDir = resolveCommonDir(gitDir);
1061
+ if (!commonDir || basename2(commonDir) !== ".git") return null;
1062
+ const clone = dirname2(commonDir);
1063
+ return existsSync(clone) ? { root: root2, clone } : null;
1064
+ }
1065
+ function findGitLink(dir) {
1066
+ let current2 = resolve2(dir);
1067
+ while (current2 !== dirname2(current2)) {
1068
+ const entry = join4(current2, ".git");
1069
+ if (existsSync(entry)) return isFile(entry) ? current2 : null;
1070
+ current2 = dirname2(current2);
1071
+ }
1072
+ return null;
1073
+ }
1074
+ function isFile(path109) {
1075
+ try {
1076
+ return statSync3(path109).isFile();
1077
+ } catch {
1078
+ return false;
1079
+ }
1080
+ }
1081
+ function readGitDirPointer(root2) {
1082
+ const target = readTrimmed(join4(root2, ".git"));
1083
+ if (!target?.startsWith("gitdir:")) return null;
1084
+ return absolute(target.slice("gitdir:".length).trim(), root2);
1085
+ }
1086
+ function resolveCommonDir(gitDir) {
1087
+ const recorded = readTrimmed(join4(gitDir, "commondir"));
1088
+ if (recorded) return absolute(recorded, gitDir);
1089
+ return linkedGitDirParent(gitDir);
1090
+ }
1091
+ function linkedGitDirParent(gitDir) {
1092
+ const match = /^(.*)[/\\]worktrees[/\\][^/\\]+[/\\]?$/.exec(gitDir);
1093
+ return match ? match[1] : null;
1094
+ }
1095
+ function readTrimmed(path109) {
1096
+ try {
1097
+ const content = readFileSync(path109, "utf8").trim();
1098
+ return content === "" ? null : content;
1099
+ } catch {
1100
+ return null;
1101
+ }
1102
+ }
1103
+ function absolute(target, from) {
1104
+ return isAbsolute(target) ? target : resolve2(from, target);
1105
+ }
1106
+
1107
+ // src/shared/loadRawYaml.ts
1108
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
1109
+ import { parse as parseYaml } from "yaml";
1110
+ function loadRawYaml(path109) {
1111
+ if (!existsSync2(path109)) return {};
1112
+ try {
1113
+ const content = readFileSync2(path109, "utf8");
1114
+ return parseYaml(content) || {};
1115
+ } catch {
1116
+ return {};
1117
+ }
1118
+ }
1119
+
1120
+ // src/shared/deepMergeRawConfig.ts
1121
+ function isPlainObject(value) {
1122
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1123
+ }
1124
+ function deepMergeRawConfig(base, override) {
1125
+ const merged = { ...base };
1126
+ for (const [key, value] of Object.entries(override)) {
1127
+ const existing = merged[key];
1128
+ merged[key] = isPlainObject(existing) && isPlainObject(value) ? deepMergeRawConfig(existing, value) : value;
1129
+ }
1130
+ return merged;
1131
+ }
1132
+
1133
+ // src/shared/mergeAdviceRules.ts
1134
+ function adviceRules(raw) {
1135
+ const advice = raw.advice;
1136
+ return Array.isArray(advice?.rules) ? advice.rules : void 0;
1137
+ }
1138
+ function mergeAdviceRules(globalRaw, projectRaw) {
1139
+ const globalRules = adviceRules(globalRaw);
1140
+ const projectRules = adviceRules(projectRaw);
1141
+ if (!globalRules || !projectRules) return void 0;
1142
+ return [...globalRules, ...projectRules];
1143
+ }
1144
+
1145
+ // src/shared/mergeDenyRules.ts
1146
+ function mergeDenyRules(globalDeny, projectDeny) {
1147
+ if (!globalDeny && !projectDeny) return void 0;
1148
+ if (!globalDeny) return projectDeny;
1149
+ if (!projectDeny) return globalDeny;
1150
+ const projectPatterns = new Set(projectDeny.map((r) => r.pattern));
1151
+ const globalOnly = globalDeny.filter((r) => !projectPatterns.has(r.pattern));
1152
+ return [...globalOnly, ...projectDeny];
1153
+ }
1154
+ function runKey(r) {
1155
+ return typeof r.name === "string" ? r.name : void 0;
1156
+ }
1157
+ function mergeRunConfigs(globalRun, projectRun) {
1158
+ if (!globalRun && !projectRun) return void 0;
1159
+ if (!globalRun) return projectRun;
1160
+ if (!projectRun) return globalRun;
1161
+ const projectNames = new Set(
1162
+ projectRun.map(runKey).filter((n) => n !== void 0)
1163
+ );
1164
+ const globalOnly = globalRun.filter((r) => {
1165
+ const key = runKey(r);
1166
+ return key === void 0 || !projectNames.has(key);
1167
+ });
1168
+ return [...globalOnly, ...projectRun];
1169
+ }
1170
+ function mergeRawConfigs(globalRaw, projectRaw) {
1171
+ const deny = mergeDenyRules(
1172
+ globalRaw.deny,
1173
+ projectRaw.deny
1174
+ );
1175
+ const run4 = mergeRunConfigs(
1176
+ globalRaw.run,
1177
+ projectRaw.run
1178
+ );
1179
+ const adviceRules3 = mergeAdviceRules(globalRaw, projectRaw);
1180
+ const merged = deepMergeRawConfig(globalRaw, projectRaw);
1181
+ if (adviceRules3 !== void 0) {
1182
+ merged.advice = { ...merged.advice, rules: adviceRules3 };
1183
+ }
1184
+ if (deny !== void 0) {
1185
+ merged.deny = deny;
1186
+ }
1187
+ if (run4 !== void 0) {
1188
+ merged.run = run4;
1189
+ }
1190
+ return merged;
1191
+ }
1192
+
1193
+ // src/shared/readRepoConfigCache.ts
1194
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "fs";
1195
+ import { join as join6 } from "path";
1196
+
1197
+ // src/shared/loadJson.ts
1198
+ import {
1199
+ existsSync as existsSync3,
1200
+ mkdirSync as mkdirSync2,
1201
+ readFileSync as readFileSync3,
1202
+ renameSync,
1203
+ rmSync as rmSync2,
1204
+ writeFileSync
1205
+ } from "fs";
1206
+ import { homedir as homedir3 } from "os";
1207
+ import { join as join5 } from "path";
1208
+ function getStoreDir() {
1209
+ return process.env.ASSIST_STORE_DIR || join5(homedir3(), ".assist");
1210
+ }
1211
+ function getStorePath(filename) {
1212
+ return join5(getStoreDir(), filename);
1213
+ }
1214
+ function loadJson(filename) {
1215
+ const path109 = getStorePath(filename);
1216
+ if (existsSync3(path109)) {
1217
+ try {
1218
+ return JSON.parse(readFileSync3(path109, "utf8"));
1219
+ } catch {
1220
+ return {};
1221
+ }
1222
+ }
1223
+ return {};
1224
+ }
1225
+ function saveJson(filename, data) {
1226
+ const dir = getStoreDir();
1227
+ if (!existsSync3(dir)) {
1228
+ mkdirSync2(dir, { recursive: true });
1229
+ }
1230
+ const path109 = getStorePath(filename);
1231
+ const tmp = `${path109}.${process.pid}.tmp`;
1232
+ try {
1233
+ writeFileSync(tmp, JSON.stringify(data, null, 2));
1234
+ renameSync(tmp, path109);
1235
+ } catch (error) {
1236
+ rmSync2(tmp, { force: true });
1237
+ throw error;
1238
+ }
1239
+ }
1240
+
1241
+ // src/shared/readRepoConfigCache.ts
1242
+ function repoConfigCachePath() {
1243
+ return join6(getStoreDir(), "repo-config-cache.json");
1244
+ }
1245
+ function readConfigCacheFile() {
1246
+ const path109 = repoConfigCachePath();
1247
+ if (!existsSync4(path109)) return {};
1248
+ try {
1249
+ const parsed = JSON.parse(readFileSync4(path109, "utf8"));
1250
+ return parsed ?? {};
1251
+ } catch {
1252
+ return {};
1253
+ }
1254
+ }
1255
+ function readRepoConfigCache() {
1256
+ return readConfigCacheFile().repos ?? {};
1257
+ }
1258
+
1259
+ // src/shared/resolveRepoLayer.ts
1260
+ import chalk2 from "chalk";
1261
+
1262
+ // src/shared/findRepoRoot.ts
1263
+ import { existsSync as existsSync5 } from "fs";
1264
+ import path from "path";
1265
+ function findRepoRoot(dir) {
1266
+ let current2 = dir;
1267
+ while (current2 !== path.dirname(current2)) {
1268
+ if (existsSync5(path.join(current2, ".git"))) {
1269
+ return current2;
1270
+ }
1271
+ current2 = path.dirname(current2);
1272
+ }
1273
+ return null;
1274
+ }
1275
+
1276
+ // src/commands/backlog/remoteUrl.ts
1277
+ import { execFileSync } from "child_process";
1278
+ function runGit(cwd, args) {
1279
+ const windows = /^[A-Za-z]:[\\/]/.test(cwd);
1280
+ const file = windows ? "git.exe" : "git";
1281
+ const argv = windows ? ["-C", cwd, ...args] : args;
1282
+ try {
1283
+ const out = execFileSync(file, argv, {
1284
+ encoding: "utf8",
1285
+ windowsHide: true,
1286
+ stdio: ["ignore", "pipe", "pipe"],
1287
+ ...windows ? {} : { cwd }
1288
+ }).trim();
1289
+ return { ok: true, out };
1290
+ } catch {
1291
+ return { ok: false, out: "" };
1292
+ }
1293
+ }
1294
+ function tryGit(cwd, args) {
1295
+ return runGit(cwd, args).out || null;
1296
+ }
1297
+ function remoteUrl(cwd) {
1298
+ const origin = runGit(cwd, ["remote", "get-url", "origin"]);
1299
+ if (origin.out) return { url: origin.out, ok: true };
1300
+ const remotes = runGit(cwd, ["remote"]);
1301
+ if (!remotes.ok) return { url: null, ok: false };
1302
+ let failed3 = false;
1303
+ for (const remote of remotes.out.split("\n").map((r) => r.trim()).filter(Boolean)) {
1304
+ const url = runGit(cwd, ["remote", "get-url", remote]);
1305
+ if (url.out) return { url: url.out, ok: true };
1306
+ if (!url.ok) failed3 = true;
1307
+ }
1308
+ return { url: null, ok: !failed3 };
1309
+ }
1310
+ function getRemoteOriginUrl(cwd) {
1311
+ return remoteUrl(cwd).url;
1312
+ }
1313
+
1314
+ // src/commands/backlog/getCurrentOrigin.ts
1315
+ var WINDOWS_PATH = /^[A-Za-z]:[\\/]/;
1316
+ function stripLeadingSlashes(path109) {
1317
+ return path109.replace(/^\/+/, "");
1318
+ }
1319
+ function normalizeOrigin(raw) {
1320
+ const trimmed = raw.trim().replace(/\.git$/i, "").replace(/\/+$/, "");
1321
+ const url = trimmed.match(
1322
+ /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/(?:[^@/]+@)?([^/:]+)(?::\d+)?\/(.+)$/
1323
+ );
1324
+ if (url) {
1325
+ return `${url[1].toLowerCase()}/${stripLeadingSlashes(url[2])}`;
1326
+ }
1327
+ if (!trimmed.includes("://")) {
1328
+ const scp = trimmed.match(/^(?:[^@/]+@)?([^/:]+):(.+)$/);
1329
+ if (scp) {
1330
+ return `${scp[1].toLowerCase()}/${stripLeadingSlashes(scp[2])}`;
1331
+ }
1332
+ }
1333
+ return trimmed.toLowerCase();
1334
+ }
1335
+ function resolveCurrentOrigin(cwd) {
1336
+ if (!WINDOWS_PATH.test(cwd) && findRepoRoot(cwd) === null)
1337
+ return { origin: `local:${cwd}`, stable: false };
1338
+ const remote = remoteUrl(cwd);
1339
+ if (remote.url) return { origin: normalizeOrigin(remote.url), stable: true };
1340
+ const root2 = tryGit(cwd, ["rev-parse", "--show-toplevel"]);
1341
+ return { origin: `local:${root2 ?? cwd}`, stable: remote.ok };
1342
+ }
1343
+ function getCurrentOrigin(cwd) {
1344
+ return resolveCurrentOrigin(cwd).origin;
1345
+ }
1346
+
1347
+ // src/commands/backlog/getCachedOrigin.ts
1348
+ var stableOrigins = /* @__PURE__ */ new Map();
1349
+ function getCachedOrigin(cwd) {
1350
+ const cached2 = stableOrigins.get(cwd);
1351
+ if (cached2 !== void 0) return cached2;
1352
+ const { origin, stable } = resolveCurrentOrigin(cwd);
1353
+ if (stable) stableOrigins.set(cwd, origin);
1354
+ return origin;
1355
+ }
1356
+
1357
+ // src/commands/backlog/originDisplayName.ts
1358
+ function originDisplayName(origin) {
1359
+ if (origin.startsWith("local:")) {
1360
+ const path109 = origin.slice("local:".length).replace(/\/+$/, "");
1361
+ const segments = path109.split("/").filter(Boolean);
1362
+ return segments[segments.length - 1] ?? origin;
1363
+ }
1364
+ const firstSlash = origin.indexOf("/");
1365
+ if (firstSlash === -1) return origin;
1366
+ return origin.slice(firstSlash + 1);
1367
+ }
1368
+
1369
+ // src/shared/resolveRepoOverride.ts
1370
+ var AmbiguousRepoConfigError = class extends Error {
1371
+ name = "AmbiguousRepoConfigError";
1372
+ };
1373
+ function originKeyCandidates(origin) {
1374
+ const displayName = originDisplayName(origin);
1375
+ const segments = displayName.split("/");
1376
+ const bare = segments[segments.length - 1] ?? displayName;
1377
+ return /* @__PURE__ */ new Set([origin, displayName, bare]);
1378
+ }
1379
+ function matchRepoConfigKey(globalRaw, origin, source = "~/.assist.yml") {
1380
+ const repos2 = globalRaw.repos;
1381
+ if (!repos2 || typeof repos2 !== "object" || Array.isArray(repos2))
1382
+ return void 0;
1383
+ const entries = repos2;
1384
+ const candidates = originKeyCandidates(origin);
1385
+ const matches = Object.keys(entries).filter((key) => candidates.has(key));
1386
+ if (matches.length === 0) return void 0;
1387
+ if (matches.length > 1) {
1388
+ throw new AmbiguousRepoConfigError(
1389
+ `Ambiguous repos config in ${source}: keys ${matches.map((m) => `"${m}"`).join(", ")} all match the current repository (${origin}). Keep a single key per repository.`
1390
+ );
1391
+ }
1392
+ return matches[0];
1393
+ }
1394
+ function resolveRepoOverride(globalRaw, origin, source) {
1395
+ const matched = matchRepoConfigKey(globalRaw, origin, source);
1396
+ if (matched === void 0) return {};
1397
+ const override = globalRaw.repos[matched];
1398
+ if (!override || typeof override !== "object" || Array.isArray(override))
1399
+ return {};
1400
+ return override;
1401
+ }
1402
+
1403
+ // src/shared/resolveRepoLayer.ts
1404
+ var SHARED_REPO_CONFIG_SOURCE = "the shared db";
1405
+ var warnedYmlKeys = /* @__PURE__ */ new Set();
1406
+ function resolveRepoLayer(globalRaw, cwd) {
1407
+ const cached2 = { repos: readRepoConfigCache() };
1408
+ if (Object.keys(cached2.repos).length === 0 && !globalRaw.repos)
1409
+ return { override: {} };
1410
+ const origin = getCachedOrigin(cwd);
1411
+ const dbKey = matchRepoConfigKey(cached2, origin, SHARED_REPO_CONFIG_SOURCE);
1412
+ if (dbKey !== void 0)
1413
+ return {
1414
+ override: resolveRepoOverride(cached2, origin, SHARED_REPO_CONFIG_SOURCE),
1415
+ key: dbKey,
1416
+ source: "db"
1417
+ };
1418
+ const ymlKey = matchRepoConfigKey(globalRaw, origin);
1419
+ if (ymlKey === void 0) return { override: {} };
1420
+ warnYmlRepoOverride(ymlKey);
1421
+ return {
1422
+ override: resolveRepoOverride(globalRaw, origin),
1423
+ key: ymlKey,
1424
+ source: "yml"
1425
+ };
1426
+ }
1427
+ function warnYmlRepoOverride(key) {
1428
+ if (warnedYmlKeys.has(key)) return;
1429
+ warnedYmlKeys.add(key);
1430
+ console.error(
1431
+ chalk2.yellow(
1432
+ `repos.${key} in ~/.assist.yml is not in the shared db, so other nodes don't see it. Run 'assist config import-repos' to share it.`
1433
+ )
1434
+ );
1435
+ }
1436
+
1437
+ // src/shared/stripLegacyReviewKeys.ts
1438
+ var LEGACY_REVIEW_HIGH_LEVEL_KEYS = ["slices"];
1439
+ function stripLegacyReviewKeys(review2) {
1440
+ if (!review2 || typeof review2 !== "object") return review2;
1441
+ const { highLevel, ...rest } = review2;
1442
+ if (!highLevel || typeof highLevel !== "object") return review2;
1443
+ const kept = { ...highLevel };
1444
+ for (const key of LEGACY_REVIEW_HIGH_LEVEL_KEYS) delete kept[key];
1445
+ return { ...rest, highLevel: kept };
1446
+ }
1447
+
1448
+ // src/shared/stripLegacyConfigKeys.ts
1449
+ var LEGACY_SESSIONS_KEYS = [
1450
+ "windowsProjectsRoot",
1451
+ "windowsDaemonHost",
1452
+ "windowsDaemonPort",
1453
+ "windowsVersionCheck",
1454
+ "topBar",
1455
+ "floatWaiting",
1456
+ "floatWaitingAfterMs",
1457
+ "parkWaitingAfterMs",
1458
+ "askQuestionAutoApprove"
1459
+ ];
1460
+ var LEGACY_WORKTREE_KEYS = ["watcher", "includeDrafts"];
1461
+ var LEGACY_DEVLOG_KEYS = ["skip"];
1462
+ function withoutKeys(value, keys) {
1463
+ if (!value || typeof value !== "object") return value;
1464
+ const rest = { ...value };
1465
+ for (const key of keys) delete rest[key];
1466
+ return rest;
1467
+ }
1468
+ function stripRepos(repos2) {
1469
+ if (!repos2 || typeof repos2 !== "object") return repos2;
1470
+ return Object.fromEntries(
1471
+ Object.entries(repos2).map(([name, entry]) => [
1472
+ name,
1473
+ entry && typeof entry === "object" ? stripLegacyConfigKeys(entry) : entry
1474
+ ])
1475
+ );
1476
+ }
1477
+ function stripLegacyConfigKeys(config) {
1478
+ const stripped = { ...config };
1479
+ if (stripped.repos) stripped.repos = stripRepos(stripped.repos);
1480
+ delete stripped.backlog;
1481
+ delete stripped.cliReadVerbs;
1482
+ delete stripped.roam;
1483
+ const news = stripped.news;
1484
+ if (news && typeof news === "object" && "feeds" in news) {
1485
+ const { feeds: _feeds, ...rest } = news;
1486
+ stripped.news = rest;
1487
+ }
1488
+ if (stripped.sessions)
1489
+ stripped.sessions = withoutKeys(stripped.sessions, LEGACY_SESSIONS_KEYS);
1490
+ if (stripped.worktree)
1491
+ stripped.worktree = withoutKeys(stripped.worktree, LEGACY_WORKTREE_KEYS);
1492
+ if (stripped.devlog)
1493
+ stripped.devlog = withoutKeys(stripped.devlog, LEGACY_DEVLOG_KEYS);
1494
+ if (stripped.review) stripped.review = stripLegacyReviewKeys(stripped.review);
1495
+ return stripped;
1496
+ }
1497
+
1465
1498
  // src/shared/warnUnsharedAdviceRules.ts
1466
1499
  import { isDeepStrictEqual } from "util";
1467
1500
  import chalk3 from "chalk";
@@ -1515,13 +1548,16 @@ function projectConfigPathFrom(cwd) {
1515
1548
  function loadConfigFrom(cwd, globalConfigPath = getGlobalConfigPath()) {
1516
1549
  return assistConfigSchema.parse(loadMergedRawConfig(cwd, globalConfigPath));
1517
1550
  }
1551
+ function sharedUserLayer(userDb) {
1552
+ return userDb ? dropUnknownConfigKeys(userDb) : {};
1553
+ }
1518
1554
  function loadMergedRawConfig(cwd, globalConfigPath = getGlobalConfigPath()) {
1519
1555
  const globalRaw = loadRawYaml(globalConfigPath);
1520
1556
  const projectRaw = loadRawYaml(projectConfigPathFrom(cwd));
1521
1557
  const userDb = readConfigCacheFile().user;
1522
1558
  warnUnsharedAdviceRules(globalRaw, userDb);
1523
1559
  const globalWithRepo = mergeRawConfigs(
1524
- mergeRawConfigs(userDb ?? {}, globalRaw),
1560
+ mergeRawConfigs(sharedUserLayer(userDb), globalRaw),
1525
1561
  resolveRepoLayer(globalRaw, cwd).override
1526
1562
  );
1527
1563
  const merged = stripLegacyConfigKeys(
@@ -1766,11 +1802,11 @@ function createLinkState({
1766
1802
  // src/commands/sessions/web/browser/createPendingReplies.ts
1767
1803
  import { randomUUID } from "crypto";
1768
1804
  function createPendingReplies() {
1769
- const pending = /* @__PURE__ */ new Map();
1805
+ const pending2 = /* @__PURE__ */ new Map();
1770
1806
  function take(id) {
1771
- const entry = pending.get(id);
1807
+ const entry = pending2.get(id);
1772
1808
  if (!entry) return void 0;
1773
- pending.delete(id);
1809
+ pending2.delete(id);
1774
1810
  clearTimeout(entry.timer);
1775
1811
  return entry;
1776
1812
  }
@@ -1779,7 +1815,7 @@ function createPendingReplies() {
1779
1815
  const id = randomUUID();
1780
1816
  return new Promise((resolve34, reject) => {
1781
1817
  const timer = setTimeout(() => {
1782
- pending.delete(id);
1818
+ pending2.delete(id);
1783
1819
  reject(
1784
1820
  relayError(
1785
1821
  `the assist extension did not reply within ${timeoutMs / 1e3}s`,
@@ -1787,7 +1823,7 @@ function createPendingReplies() {
1787
1823
  )
1788
1824
  );
1789
1825
  }, timeoutMs);
1790
- pending.set(id, { ws, timer, resolve: resolve34, reject });
1826
+ pending2.set(id, { ws, timer, resolve: resolve34, reject });
1791
1827
  write2(id);
1792
1828
  });
1793
1829
  },
@@ -1795,7 +1831,7 @@ function createPendingReplies() {
1795
1831
  take(id)?.resolve(reply2);
1796
1832
  },
1797
1833
  dropSocket(ws) {
1798
- for (const [id, entry] of pending) {
1834
+ for (const [id, entry] of pending2) {
1799
1835
  if (entry.ws !== ws) continue;
1800
1836
  take(id)?.reject(
1801
1837
  relayError("the assist extension disconnected before replying", 502)
@@ -3604,9 +3640,9 @@ function compareMigrations(appliedIds) {
3604
3640
  const expected = maxId(bundledIds);
3605
3641
  const ahead = appliedIds.filter((id) => !bundledSet.has(id));
3606
3642
  if (ahead.length > 0) return { state: "ahead", applied, expected };
3607
- const pending = bundledIds.filter((id) => !appliedSet.has(id));
3608
- if (pending.length > 0)
3609
- return { state: "behind", applied, expected, pending };
3643
+ const pending2 = bundledIds.filter((id) => !appliedSet.has(id));
3644
+ if (pending2.length > 0)
3645
+ return { state: "behind", applied, expected, pending: pending2 };
3610
3646
  return { state: "in-sync", version: expected };
3611
3647
  }
3612
3648
  async function readAppliedIds2(exec3) {
@@ -5066,8 +5102,8 @@ async function committedPaths(cwd, sessionId2) {
5066
5102
  const key = `${cwd} ${sessionId2}`;
5067
5103
  const cached2 = cache.get(key);
5068
5104
  if (cached2 && cached2.expiresAt > Date.now()) return cached2.value;
5069
- const pending = inFlight.get(key);
5070
- if (pending) return pending;
5105
+ const pending2 = inFlight.get(key);
5106
+ if (pending2) return pending2;
5071
5107
  const lookup = loadCommittedPaths(cwd, sessionId2).then((value) => {
5072
5108
  cache.set(key, { value, expiresAt: Date.now() + CACHE_TTL_MS });
5073
5109
  return value;
@@ -20251,6 +20287,12 @@ function buildHarnessCodexArgs() {
20251
20287
  // src/shared/codexIsolatedHookArgs.ts
20252
20288
  var codexIsolatedHookArgs = ["--no-daemon"];
20253
20289
 
20290
+ // src/shared/codexSandboxNetworkArgs.ts
20291
+ var codexSandboxNetworkArgs = [
20292
+ "-c",
20293
+ "sandbox_workspace_write.network_access=true"
20294
+ ];
20295
+
20254
20296
  // src/shared/codexSessionEnvArgs.ts
20255
20297
  var SESSION_ENV_KEYS = [
20256
20298
  "ASSIST_SESSION",
@@ -20280,6 +20322,7 @@ function spawnCodex(prompt, options2 = {}) {
20280
20322
  ...codexIsolatedHookArgs,
20281
20323
  ...override.args,
20282
20324
  ...codexSessionEnvArgs(process.env),
20325
+ ...codexSandboxNetworkArgs,
20283
20326
  "-C",
20284
20327
  cwd,
20285
20328
  "--sandbox",
@@ -21305,14 +21348,14 @@ async function done(id, summary) {
21305
21348
  const { orm, item } = found;
21306
21349
  if (item.plan && item.plan.length > 0) {
21307
21350
  const completedCount = (item.currentPhase ?? 1) - 1;
21308
- const pending = authoredPhases(item.plan).slice(completedCount);
21309
- if (pending.length > 0) {
21351
+ const pending2 = authoredPhases(item.plan).slice(completedCount);
21352
+ if (pending2.length > 0) {
21310
21353
  console.log(
21311
21354
  chalk92.red(
21312
- `Cannot complete item ${formatItemId(item.id)}: ${pending.length} pending phase(s):`
21355
+ `Cannot complete item ${formatItemId(item.id)}: ${pending2.length} pending phase(s):`
21313
21356
  )
21314
21357
  );
21315
- for (const phase of pending) {
21358
+ for (const phase of pending2) {
21316
21359
  console.log(chalk92.yellow(` - ${phase.name}`));
21317
21360
  }
21318
21361
  process.exitCode = 1;
@@ -22746,7 +22789,7 @@ function skipBody(command, start2, delimiter) {
22746
22789
  function stripHeredocBodies(command) {
22747
22790
  if (!command.includes("<<")) return command;
22748
22791
  let out = "";
22749
- let pending = [];
22792
+ let pending2 = [];
22750
22793
  let quote;
22751
22794
  let i = 0;
22752
22795
  while (i < command.length) {
@@ -22768,15 +22811,15 @@ function stripHeredocBodies(command) {
22768
22811
  i++;
22769
22812
  continue;
22770
22813
  }
22771
- if (char === "\n" && pending.length > 0) {
22814
+ if (char === "\n" && pending2.length > 0) {
22772
22815
  out += char;
22773
- i = skipHeredocBodies(command, i + 1, pending);
22774
- pending = [];
22816
+ i = skipHeredocBodies(command, i + 1, pending2);
22817
+ pending2 = [];
22775
22818
  continue;
22776
22819
  }
22777
22820
  if (char === "<") {
22778
22821
  const header = matchHeredocHeader(command, i);
22779
- if (header.delimiter !== void 0) pending.push(header.delimiter);
22822
+ if (header.delimiter !== void 0) pending2.push(header.delimiter);
22780
22823
  out += header.text;
22781
22824
  i += header.text.length;
22782
22825
  continue;
@@ -31658,10 +31701,10 @@ function errorEvent(detail) {
31658
31701
  async function scanUnopenedThreads(threadIds, scanThreads, onEvent = () => {
31659
31702
  }) {
31660
31703
  const messages2 = [];
31661
- let pending = threadIds;
31662
- for (let attempt2 = 0; attempt2 < MAX_ATTEMPTS && pending.length; attempt2++) {
31704
+ let pending2 = threadIds;
31705
+ for (let attempt2 = 0; attempt2 < MAX_ATTEMPTS && pending2.length; attempt2++) {
31663
31706
  const results = await mapAsync(
31664
- chunk(pending, BATCH_SIZE),
31707
+ chunk(pending2, BATCH_SIZE),
31665
31708
  CONCURRENCY2,
31666
31709
  (batch) => scanThreads(batch).catch((error) => {
31667
31710
  onEvent(
@@ -31672,12 +31715,12 @@ async function scanUnopenedThreads(threadIds, scanThreads, onEvent = () => {
31672
31715
  );
31673
31716
  const opened = new Set(results.flatMap((r) => r?.threads.opened ?? []));
31674
31717
  messages2.push(...results.flatMap((r) => r?.messages ?? []));
31675
- pending = pending.filter((id) => !opened.has(id));
31718
+ pending2 = pending2.filter((id) => !opened.has(id));
31676
31719
  }
31677
- if (pending.length)
31720
+ if (pending2.length)
31678
31721
  onEvent(
31679
31722
  errorEvent(
31680
- `${pending.length} unread thread(s) never opened: ${pending.join(" ")}`
31723
+ `${pending2.length} unread thread(s) never opened: ${pending2.join(" ")}`
31681
31724
  )
31682
31725
  );
31683
31726
  return messages2;
@@ -46581,8 +46624,8 @@ function registerSync(program) {
46581
46624
  // src/commands/testflight/testflightAdd.ts
46582
46625
  import chalk281 from "chalk";
46583
46626
 
46584
- // src/commands/testflight/addExternalTester.ts
46585
- async function addExternalTester(client, groupId, email) {
46627
+ // src/commands/testflight/addToBetaGroup.ts
46628
+ async function addToBetaGroup(client, groupId, email) {
46586
46629
  const inGroup = await client.get("/v1/betaTesters", {
46587
46630
  "filter[email]": email,
46588
46631
  "filter[betaGroups]": groupId,
@@ -46612,6 +46655,64 @@ async function addExternalTester(client, groupId, email) {
46612
46655
  return "created";
46613
46656
  }
46614
46657
 
46658
+ // src/commands/testflight/nameFromEmail.ts
46659
+ function capitalise(word) {
46660
+ return word.charAt(0).toUpperCase() + word.slice(1);
46661
+ }
46662
+ function nameFromEmail(email) {
46663
+ const [first = email, ...rest] = email.split("@")[0].split(/[._+-]+/).filter(Boolean).map(capitalise);
46664
+ return { firstName: first, lastName: rest.join(" ") || "Tester" };
46665
+ }
46666
+
46667
+ // src/commands/testflight/inviteTeamMember.ts
46668
+ async function inviteTeamMember(client, appId, email) {
46669
+ const { firstName, lastName } = nameFromEmail(email);
46670
+ await client.post("/v1/userInvitations", {
46671
+ data: {
46672
+ type: "userInvitations",
46673
+ attributes: {
46674
+ email,
46675
+ firstName,
46676
+ lastName,
46677
+ roles: ["DEVELOPER"],
46678
+ allAppsVisible: false,
46679
+ provisioningAllowed: false
46680
+ },
46681
+ relationships: {
46682
+ visibleApps: { data: [{ type: "apps", id: appId }] }
46683
+ }
46684
+ }
46685
+ });
46686
+ }
46687
+
46688
+ // src/commands/testflight/addInternalTester.ts
46689
+ async function hasMatch(client, path109, params, attribute, email) {
46690
+ const { data } = await client.get(path109, params);
46691
+ return data.some(
46692
+ (item) => String(item.attributes?.[attribute]).toLowerCase() === email.toLowerCase()
46693
+ );
46694
+ }
46695
+ async function addInternalTester(client, target, email) {
46696
+ const isMember = await hasMatch(
46697
+ client,
46698
+ "/v1/users",
46699
+ { "filter[username]": email, "fields[users]": "username" },
46700
+ "username",
46701
+ email
46702
+ );
46703
+ if (isMember) return addToBetaGroup(client, target.groupId, email);
46704
+ const isInvited = await hasMatch(
46705
+ client,
46706
+ "/v1/userInvitations",
46707
+ { "filter[email]": email, "fields[userInvitations]": "email" },
46708
+ "email",
46709
+ email
46710
+ );
46711
+ if (isInvited) return "invite-pending";
46712
+ await inviteTeamMember(client, target.appId, email);
46713
+ return "invited";
46714
+ }
46715
+
46615
46716
  // src/commands/testflight/formatAscError.ts
46616
46717
  var statusHints = {
46617
46718
  401: "Check testflight.keyId, testflight.issuerId and that testflight.keyRef points at the matching .p8.",
@@ -46742,22 +46843,34 @@ async function findBetaGroupId(client, appId, lookup) {
46742
46843
  return group.id;
46743
46844
  }
46744
46845
 
46846
+ // src/commands/testflight/requireInternalGroup.ts
46847
+ function requireInternalGroup(config) {
46848
+ if (config.internalGroup) return config.internalGroup;
46849
+ const entry = testflightConfigHelp.find(
46850
+ (help) => help.key === "testflight.internalGroup"
46851
+ );
46852
+ throw new TestflightError(
46853
+ `testflight.internalGroup is not set. Set it with: ${entry?.setter}`
46854
+ );
46855
+ }
46856
+
46745
46857
  // src/commands/testflight/addTester.ts
46746
- async function addTester(config, email, deps2 = {}) {
46747
- const privateKey = (deps2.readKey ?? resolveOpSecret)(config.keyRef);
46858
+ async function addTester(config, email, options2 = {}) {
46859
+ const internalGroup = options2.internal ? requireInternalGroup(config) : void 0;
46860
+ const privateKey = (options2.readKey ?? resolveOpSecret)(config.keyRef);
46748
46861
  const token = createAscToken({
46749
46862
  keyId: config.keyId,
46750
46863
  issuerId: config.issuerId,
46751
46864
  privateKey
46752
46865
  });
46753
- const client = createAscClient(token, deps2.fetchFn);
46866
+ const client = createAscClient(token, options2.fetchFn);
46754
46867
  const appId = await findAppId(client, config.bundleId);
46755
46868
  const groupId = await findBetaGroupId(client, appId, {
46756
- name: config.externalGroup,
46757
- configKey: "testflight.externalGroup",
46758
- internal: false
46869
+ name: internalGroup ?? config.externalGroup,
46870
+ configKey: internalGroup ? "testflight.internalGroup" : "testflight.externalGroup",
46871
+ internal: Boolean(internalGroup)
46759
46872
  });
46760
- return addExternalTester(client, groupId, email);
46873
+ return internalGroup ? addInternalTester(client, { appId, groupId }, email) : addToBetaGroup(client, groupId, email);
46761
46874
  }
46762
46875
 
46763
46876
  // src/commands/testflight/readTestflightConfig.ts
@@ -46789,15 +46902,24 @@ function readTestflightConfig(config) {
46789
46902
  var messages = {
46790
46903
  created: (email, group) => `Invited ${email} to TestFlight group "${group}"`,
46791
46904
  added: (email, group) => `Added existing tester ${email} to TestFlight group "${group}"`,
46792
- "already-in-group": (email, group) => `${email} is already in TestFlight group "${group}"`
46905
+ "already-in-group": (email, group) => `${email} is already in TestFlight group "${group}"`,
46906
+ invited: (email) => `Sent ${email} an App Store Connect team invite. Once they accept, re-run this command to add them to TestFlight.`,
46907
+ "invite-pending": (email) => `${email} has not yet accepted their App Store Connect team invite. Re-run this command once they do.`
46793
46908
  };
46794
- async function testflightAdd(email) {
46909
+ var pending = /* @__PURE__ */ new Set([
46910
+ "already-in-group",
46911
+ "invite-pending"
46912
+ ]);
46913
+ async function testflightAdd(email, options2) {
46795
46914
  try {
46796
46915
  const config = readTestflightConfig(loadConfig());
46797
- const result = await addTester(config, email);
46798
- const message3 = messages[result](email, config.externalGroup);
46916
+ const result = await addTester(config, email, {
46917
+ internal: options2.internal
46918
+ });
46919
+ const group = options2.internal ? config.internalGroup ?? "" : config.externalGroup;
46920
+ const message3 = messages[result](email, group);
46799
46921
  console.log(
46800
- result === "already-in-group" ? chalk281.yellow(message3) : chalk281.green(message3)
46922
+ pending.has(result) ? chalk281.yellow(message3) : chalk281.green(message3)
46801
46923
  );
46802
46924
  } catch (error) {
46803
46925
  if (!(error instanceof TestflightError)) throw error;
@@ -46809,7 +46931,14 @@ async function testflightAdd(email) {
46809
46931
  // src/commands/registerTestflight.ts
46810
46932
  function registerTestflight(program) {
46811
46933
  const cmd = program.command("testflight").description("Manage TestFlight testers via the App Store Connect API");
46812
- const addCommand = cmd.command("add <email>").description("Add an external tester to the configured beta group").action((email) => testflightAdd(email));
46934
+ const addCommand = cmd.command("add <email>").description(
46935
+ "Add a tester to the external beta group, or with --internal invite them to the team and add them to the internal group"
46936
+ ).option(
46937
+ "--internal",
46938
+ "Invite to the App Store Connect team; re-run after they accept to add them to the internal group"
46939
+ ).action(
46940
+ (email, options2) => testflightAdd(email, options2)
46941
+ );
46813
46942
  configHelp(addCommand, testflightConfigHelp);
46814
46943
  }
46815
46944
 
@@ -47810,14 +47939,14 @@ var pendingConfigDocumentation = /* @__PURE__ */ new Set([
47810
47939
  function configKeys2() {
47811
47940
  const schemaKeys = new Set(enumerateConfigLeafKeys(assistConfigSchema));
47812
47941
  const documented = getDocumentedConfigKeys();
47813
- const pending = pendingConfigDocumentation;
47942
+ const pending2 = pendingConfigDocumentation;
47814
47943
  const aggregated = new Set(configHelpEntries.map((entry) => entry.key));
47815
47944
  reportVerifyProblems(
47816
47945
  [
47817
47946
  verifySection(
47818
47947
  "Config keys documented by no command (surface them with configHelp)",
47819
47948
  [...schemaKeys].filter(
47820
- (key) => !documented.has(key) && !pending.has(key)
47949
+ (key) => !documented.has(key) && !pending2.has(key)
47821
47950
  )
47822
47951
  ),
47823
47952
  verifySection(
@@ -47826,11 +47955,11 @@ function configKeys2() {
47826
47955
  ),
47827
47956
  verifySection(
47828
47957
  "Keys now documented but still in pendingConfigDocumentation (remove them)",
47829
- [...pending].filter((key) => documented.has(key))
47958
+ [...pending2].filter((key) => documented.has(key))
47830
47959
  ),
47831
47960
  verifySection(
47832
47961
  "pendingConfigDocumentation lists keys not in assistConfigSchema (remove them)",
47833
- [...pending].filter((key) => !schemaKeys.has(key))
47962
+ [...pending2].filter((key) => !schemaKeys.has(key))
47834
47963
  ),
47835
47964
  verifySection(
47836
47965
  "Keys documented by a command but missing from configHelpEntries (add their module to src/commands/configHelpEntries.ts)",
@@ -49727,29 +49856,29 @@ function queryDaemon(socket) {
49727
49856
  `);
49728
49857
  return new Promise((resolve34) => {
49729
49858
  const result = { sessions: [] };
49730
- const pending = /* @__PURE__ */ new Set(["sessions", "pong"]);
49859
+ const pending2 = /* @__PURE__ */ new Set(["sessions", "pong"]);
49731
49860
  const timer = setTimeout(() => resolve34(result), STATUS_TIMEOUT_MS2);
49732
49861
  const lines2 = createInterface8({ input: socket });
49733
49862
  lines2.on("error", () => {
49734
49863
  });
49735
49864
  lines2.on("line", (line) => {
49736
- applyLine(result, pending, line);
49737
- if (pending.size === 0) {
49865
+ applyLine(result, pending2, line);
49866
+ if (pending2.size === 0) {
49738
49867
  clearTimeout(timer);
49739
49868
  resolve34(result);
49740
49869
  }
49741
49870
  });
49742
49871
  });
49743
49872
  }
49744
- function applyLine(result, pending, line) {
49873
+ function applyLine(result, pending2, line) {
49745
49874
  try {
49746
49875
  const data = JSON.parse(line);
49747
49876
  if (data.type === "sessions") {
49748
49877
  result.sessions = data.sessions ?? [];
49749
- pending.delete("sessions");
49878
+ pending2.delete("sessions");
49750
49879
  } else if (data.type === "pong") {
49751
49880
  result.pid = data.pid;
49752
- pending.delete("pong");
49881
+ pending2.delete("pong");
49753
49882
  }
49754
49883
  } catch {
49755
49884
  }
@@ -49960,17 +50089,17 @@ async function failInterruptedJobRuns(startedBefore = /* @__PURE__ */ new Date()
49960
50089
  // src/commands/sessions/daemon/inbox/createActivityThrottle.ts
49961
50090
  var ACTIVITY_THROTTLE_MS = 1e3;
49962
50091
  function createActivityThrottle(onActivity) {
49963
- let pending;
50092
+ let pending2;
49964
50093
  return {
49965
50094
  schedule() {
49966
- pending ??= setTimeout(() => {
49967
- pending = void 0;
50095
+ pending2 ??= setTimeout(() => {
50096
+ pending2 = void 0;
49968
50097
  onActivity();
49969
50098
  }, ACTIVITY_THROTTLE_MS);
49970
50099
  },
49971
50100
  cancel() {
49972
- clearTimeout(pending);
49973
- pending = void 0;
50101
+ clearTimeout(pending2);
50102
+ pending2 = void 0;
49974
50103
  }
49975
50104
  };
49976
50105
  }
@@ -50858,10 +50987,10 @@ function clearPendingSubmit(session) {
50858
50987
  function watchSubmitOutcome(session, onStatusChange) {
50859
50988
  clearPendingSubmit(session);
50860
50989
  const fingerprint = session.transcriptFingerprint;
50861
- const pending = { fingerprint, cancel: () => {
50990
+ const pending2 = { fingerprint, cancel: () => {
50862
50991
  } };
50863
50992
  const check2 = async () => {
50864
- if (session.pendingSubmit !== pending) return;
50993
+ if (session.pendingSubmit !== pending2) return;
50865
50994
  session.pendingSubmit = void 0;
50866
50995
  if (session.status !== "running") return;
50867
50996
  if (await turnStarted(session, fingerprint)) return;
@@ -50873,8 +51002,8 @@ function watchSubmitOutcome(session, onStatusChange) {
50873
51002
  };
50874
51003
  const timer = setTimeout(() => void check2(), SUBMIT_GRACE_MS);
50875
51004
  timer.unref?.();
50876
- pending.cancel = () => clearTimeout(timer);
50877
- session.pendingSubmit = pending;
51005
+ pending2.cancel = () => clearTimeout(timer);
51006
+ session.pendingSubmit = pending2;
50878
51007
  }
50879
51008
 
50880
51009
  // src/commands/sessions/daemon/watchPromptSubmit.ts
@@ -51231,6 +51360,7 @@ function spawnCodex2(opts = {}) {
51231
51360
  ...codexIsolatedHookArgs,
51232
51361
  ...override.args,
51233
51362
  ...sessionEnv,
51363
+ ...codexSandboxNetworkArgs,
51234
51364
  ...codexArgs2(opts)
51235
51365
  ],
51236
51366
  opts.cwd,
@@ -51806,10 +51936,10 @@ function escalateDivergence(ctx, cwd, output) {
51806
51936
 
51807
51937
  // src/commands/sessions/daemon/autoUpdate/lineRecorder.ts
51808
51938
  function lineRecorder(onLine) {
51809
- let pending = "";
51939
+ let pending2 = "";
51810
51940
  return (text20) => {
51811
- const lines2 = (pending + text20).split(/\r?\n|\r/);
51812
- pending = lines2.pop() ?? "";
51941
+ const lines2 = (pending2 + text20).split(/\r?\n|\r/);
51942
+ pending2 = lines2.pop() ?? "";
51813
51943
  for (const line of lines2) {
51814
51944
  const clean2 = stripAnsi(line).trimEnd();
51815
51945
  if (clean2.trim()) onLine(clean2);
@@ -52213,10 +52343,10 @@ function killPtyTree(pty2) {
52213
52343
 
52214
52344
  // src/commands/sessions/daemon/reportUndeliveredPrompts.ts
52215
52345
  function reportUndeliveredPrompts(session, why) {
52216
- const pending = session.pendingPrompts;
52217
- if (!pending?.length) return;
52346
+ const pending2 = session.pendingPrompts;
52347
+ if (!pending2?.length) return;
52218
52348
  session.pendingPrompts = void 0;
52219
- for (const text20 of pending) {
52349
+ for (const text20 of pending2) {
52220
52350
  daemonLog(
52221
52351
  `session ${session.id} ${why}; queued prompt undelivered: ${JSON.stringify(text20)}`
52222
52352
  );
@@ -52840,18 +52970,18 @@ function previewTargetLabel(kind, itemType, prNumber, draft) {
52840
52970
 
52841
52971
  // src/commands/sessions/daemon/placeShowPreview.ts
52842
52972
  function placeShowPreview(session, show4) {
52843
- const pending = session.pendingPrPreview;
52844
- if (!pending || pending.kind === "show") {
52973
+ const pending2 = session.pendingPrPreview;
52974
+ if (!pending2 || pending2.kind === "show") {
52845
52975
  session.pendingPrPreview = show4;
52846
52976
  session.pendingShow = void 0;
52847
52977
  return false;
52848
52978
  }
52849
52979
  session.pendingShow = show4;
52850
52980
  const target = previewTargetLabel(
52851
- pending.kind ?? "pr",
52852
- pending.itemType ?? "story",
52853
- pending.prNumber,
52854
- pending.draft === true
52981
+ pending2.kind ?? "pr",
52982
+ pending2.itemType ?? "story",
52983
+ pending2.prNumber,
52984
+ pending2.draft === true
52855
52985
  );
52856
52986
  daemonLog(
52857
52987
  `pr-preview show stacked: id=${session.id} requestId=${show4.requestId} over=${target}`
@@ -52861,18 +52991,18 @@ function placeShowPreview(session, show4) {
52861
52991
 
52862
52992
  // src/commands/sessions/daemon/supersedePendingPreview.ts
52863
52993
  function supersedePendingPreview(session, waiters, newRequestId) {
52864
- const pending = session.pendingPrPreview;
52994
+ const pending2 = session.pendingPrPreview;
52865
52995
  const waiter = waiters.get(session.id);
52866
- if (!pending || pending.kind === "show" || !waiter) return void 0;
52996
+ if (!pending2 || pending2.kind === "show" || !waiter) return void 0;
52867
52997
  sendTo(waiter, {
52868
52998
  type: "pr-superseded",
52869
- requestId: pending.requestId,
52999
+ requestId: pending2.requestId,
52870
53000
  supersededBy: newRequestId
52871
53001
  });
52872
53002
  daemonLog(
52873
- `pr-preview superseded: id=${session.id} old=${pending.requestId} new=${newRequestId}`
53003
+ `pr-preview superseded: id=${session.id} old=${pending2.requestId} new=${newRequestId}`
52874
53004
  );
52875
- return pending.requestId;
53005
+ return pending2.requestId;
52876
53006
  }
52877
53007
 
52878
53008
  // src/commands/sessions/daemon/holdBlockingPreview.ts
@@ -56330,10 +56460,10 @@ function armCreateTimeout(ctx, client, data, traceId) {
56330
56460
  const node = ctx.spec.name;
56331
56461
  const timer = setTimeout(
56332
56462
  () => {
56333
- const pending = ctx.relay.pendingCreators;
56334
- const index3 = pending.findIndex((p) => p.timer === timer);
56463
+ const pending2 = ctx.relay.pendingCreators;
56464
+ const index3 = pending2.findIndex((p) => p.timer === timer);
56335
56465
  if (index3 === -1) return;
56336
- pending.splice(index3, 1);
56466
+ pending2.splice(index3, 1);
56337
56467
  daemonLog(`link ${node} ws: ${data.type} timed out (cwd=${data.cwd})`);
56338
56468
  sendTo(client, {
56339
56469
  type: "error",
@@ -56448,10 +56578,10 @@ function relayLinkSessions(state, msg) {
56448
56578
  function takePendingCreator(state, traceId) {
56449
56579
  const index3 = pendingIndex(state, traceId);
56450
56580
  if (index3 === -1) return void 0;
56451
- const [pending] = state.pendingCreators.splice(index3, 1);
56452
- if (!pending) return void 0;
56453
- clearTimeout(pending.timer);
56454
- return pending.client;
56581
+ const [pending2] = state.pendingCreators.splice(index3, 1);
56582
+ if (!pending2) return void 0;
56583
+ clearTimeout(pending2.timer);
56584
+ return pending2.client;
56455
56585
  }
56456
56586
  function pendingIndex(state, traceId) {
56457
56587
  if (typeof traceId !== "string") return 0;