@theholocron/cli 5.0.0-alpha.593 → 5.0.0-alpha.595

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/cli.mjs CHANGED
@@ -9,19 +9,19 @@ import { addGlobalOptions, groupMenu as groupMenu$1, tokenContext as tokenContex
9
9
  import { DRY_RUN_NOOP_EXIT_CODE, createCommandRegistry, createMenu, dryRunPreviewEnvVar, numeric, spawnChild } from "@theholocron/kyber/menu";
10
10
  import { checkForUpdates } from "@theholocron/kyber/notifier";
11
11
  import { NonInteractiveError, commandFailureMessage, createProgress, createRetryNotice, declaredVsActual, describeError, logReason, openPath, pad as pad$1, printCheckRows, printCheckSummary, sanitizeDetail, setProgressListener, startCommandProgress, statusRow as statusRow$1, stopCommandSpinner, stripControl, style, summariseChecks, viewJson, withProgress, withSpinner } from "@theholocron/kyber/ui";
12
- import { LOG_LEVELS } from "@theholocron/observability/core";
12
+ import { LOG_LEVELS, redact } from "@theholocron/observability/core";
13
13
  import yargs from "yargs";
14
14
  import { hideBin } from "yargs/helpers";
15
15
  import { appendFileSync, closeSync, copyFileSync, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync, writeSync } from "node:fs";
16
16
  import { Entry, findCredentials } from "@napi-rs/keyring";
17
- import { AuthError, DOTENV_FILE, copyToClipboard, createFeatureResolver as createFeatureResolver$1, createKeyring, createPrivateFile, dotenvLine, findCredential, finishCredentialsFile, hasCredentials, isGitIgnored, readDotenvFile, resolveValue as resolveValue$1, resolveValue as resolveValue$2, setCredentials, writeCredentialsFile } from "@theholocron/kyber/secrets";
17
+ import { AuthError, DOTENV_FILE, copyToClipboard, createFeatureResolver as createFeatureResolver$1, createKeyring, createPrivateFile, deferCredentials, dotenvLine, findCredential, finishCredentialsFile, hasCredentials, isGitIgnored, readDotenvFile, resolveValue as resolveValue$1, resolveValue as resolveValue$2, setCredentials, writeCredentialsFile } from "@theholocron/kyber/secrets";
18
18
  import { AGGREGATE_CHECK, AGGREGATE_CHECK_NAME, AGGREGATE_SHADOW_CHECK_NAME, DEFAULT_ORG, DOCUMENTATION_FLAG, DOT_GITHUB_REPO, HOLOCRON_REPO, KNOWN_TASKS, KNOWN_WORKFLOWS, LEGACY_NAMES, PNPM_BUILTIN_COMMANDS, PRERELEASE_CHANNEL, RELEASE_BRANCHES, RESERVED_SCRIPT_NAMES, SUITES, TASKS, aggregateChecks, aggregatePoster, checkPackageScripts, checkReleaseLines, codecovFlagNames, createAstromech, createCommitMsg, createDependabot, createDevmoji, createEditorconfig, createEditorconfigChecker, createHeader, createLabeler, createPreCommit, createPrePush, createPrepareCommitMsg, createYamlignore, createYamllint, defaultListDirs, defaultPaths, defaultReadJson, deployOnRelease, describeTasks, extractPreviewConfig, formatJson, frozenReusablePaths, generateThinCallerContent, hostedReusableWorkflows, isDeprecated, isTask, legacyCaller, legacyCallerFile, legacyGate, legacyWorkflowKey, localize, localizeActions, mergeScripts, packageLocation, postAggregate, readWorkspacePackages, recordDeploys, requiredChecks, resolveTaskName, reusableTemplates, scriptName, stampDeprecated, wedgeFix, workflowFile, workflowKey, workflowKeys, workspacePackages as workspacePackages$1 } from "@theholocron/astromech";
19
19
  import { loadTasksConfig, releaseGroups } from "@theholocron/astromech/config";
20
20
  import { createCliLogger, createCliTelemetry } from "@theholocron/kyber/observability";
21
21
  import { resolveAxiomFromEnv } from "@theholocron/observability/logger";
22
+ import { readGitRemote, updateGitignore, upsertManagedBlock } from "@theholocron/git-utils";
22
23
  import { ConfigError, ConfigError as ConfigError$1, createConfigSystem, lastWins, mergeByKey, shallowMerge, union } from "@theholocron/kyber/config";
23
24
  import { LoaderError, assertPluginsResolvable as assertPluginsResolvable$1, createPluginSystem, defaultImporter as defaultImporter$1, isModuleNotFound, isModuleNotFound as isModuleNotFound$1, resolvePluginPackage as resolvePluginPackage$1 } from "@theholocron/kyber/plugins";
24
- import { readGitRemote, updateGitignore, upsertManagedBlock } from "@theholocron/git-utils";
25
25
  import { bumpCatalogPins, discoverWorkspacePackages, parseCatalogs, readPackageJson, readPackageJsonSync, resolveWorkspaceGlobs } from "@theholocron/pkg-utils";
26
26
  import { runCheckAgainstUrl } from "@theholocron/kyber/checks";
27
27
  import { access, copyFile, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
@@ -30,7 +30,7 @@ import { promptForPositionals } from "@theholocron/kyber/prompts";
30
30
  import { fileURLToPath, pathToFileURL } from "node:url";
31
31
  import { errorMessage } from "@theholocron/misc-utils";
32
32
  import { execFile, execFileSync, spawn, spawnSync } from "node:child_process";
33
- import { moveMajorTag, runGit } from "@theholocron/kyber/git";
33
+ import { moveMajorTag, runGit as runGit$1 } from "@theholocron/kyber/git";
34
34
  import { ADR_DIR, ADR_STATUSES, CLOSED_STATUSES, SPEC_DIRS, SPEC_STATUSES, WITHDRAWN_STATE, assignSpecIds, checkSpecs, classifySpecPath, discussionBody, discussionIdLine, discussionPrLine, discussionTitle, evaluateDocsPresence, isAddedDocComment, isFeat, packageOf, parseFrontmatter, parseSkipDocs, reconcileSpecStatus, specSummary, specTitle, updateFrontmatter } from "@theholocron/astromech/repo-validation";
35
35
  import { stringifyJson } from "@theholocron/json-utils";
36
36
  import { findRootSync, isWorkspaceRoot, walkFilesSync } from "@theholocron/fs-utils";
@@ -146,6 +146,7 @@ const COMMAND_CONTEXTS = {
146
146
  "sync github": "workspace",
147
147
  "sync issues": "workspace",
148
148
  "sync incidents": "workspace",
149
+ "sync prs": "workspace",
149
150
  "sync releases": "workspace",
150
151
  "sync ideas": "workspace",
151
152
  "sync tooling": "workspace",
@@ -2230,6 +2231,15 @@ const syncIssuesEntry = {
2230
2231
  skipOptions: ["yes"],
2231
2232
  supportsDryRun: true
2232
2233
  };
2234
+ // src/commands/sync-prs/sync-prs.entry.ts
2235
+ const syncPrsEntry = {
2236
+ name: "sync prs",
2237
+ description: "Keep the pull request forum's posts in step with GitHub",
2238
+ positionals: [],
2239
+ options: [],
2240
+ skipOptions: ["provider", "yes"],
2241
+ supportsDryRun: true
2242
+ };
2233
2243
  // src/commands/sync-readme/sync-readme.entry.ts
2234
2244
  const syncReadmeEntry = {
2235
2245
  name: "sync readme",
@@ -2495,6 +2505,7 @@ const registry = createCommandRegistry([
2495
2505
  syncGithubEntry,
2496
2506
  syncIssuesEntry,
2497
2507
  syncIncidentsEntry,
2508
+ syncPrsEntry,
2498
2509
  syncReleasesEntry,
2499
2510
  ideasSyncEntry,
2500
2511
  syncToolingEntry,
@@ -2786,7 +2797,7 @@ function withoutDryRun(args) {
2786
2797
  return [...own.filter((arg) => arg !== "--dry-run" && !arg.startsWith("--dry-run=")), ...rest];
2787
2798
  }
2788
2799
  // src/commands/offer-real-run/offer-real-run.ts
2789
- const INFO_FLAGS = /* @__PURE__ */ new Set([
2800
+ const INFO_FLAGS$1 = /* @__PURE__ */ new Set([
2790
2801
  "--help",
2791
2802
  "-h",
2792
2803
  "--version",
@@ -2804,11 +2815,90 @@ const INFO_FLAGS = /* @__PURE__ */ new Set([
2804
2815
  async function offerRealRun(input) {
2805
2816
  if (!input.dryRun || input.exitCode !== 0) return void 0;
2806
2817
  if (!input.interactive || input.ci || input.preview) return void 0;
2807
- if (input.args.some((arg) => INFO_FLAGS.has(arg))) return void 0;
2818
+ if (input.args.some((arg) => INFO_FLAGS$1.has(arg))) return void 0;
2808
2819
  if (!input.supportsDryRun(input.words)) return void 0;
2809
2820
  if (!await input.confirm("Dry run complete — run it for real?")) return void 0;
2810
2821
  return input.spawn(withoutDryRun(input.args));
2811
2822
  }
2823
+ // src/observability/format-log-line/format-log-line.ts
2824
+ /** The longest message a thread line keeps, in characters. */
2825
+ const MAX_MESSAGE_CHARS = 300;
2826
+ /** The most numeric fields a thread line names. */
2827
+ const MAX_FIELDS = 6;
2828
+ /**
2829
+ * One log call as a single line for a Discord thread: `[warn] message (count=3, status=200)`. Only what is safe to show
2830
+ * by name: the level, the message (scrubbed with the logger's own token-shape `redact()`, collapsed to one line and cut
2831
+ * to 300 characters) and the names and values of the numeric fields; a string, an object or a flag value in the context
2832
+ * is never read. A call with no message, and the step 6 `command_run` event (the thread ends with its own status line),
2833
+ * give no line.
2834
+ *
2835
+ * @param level - `info`, `warn` or `error`.
2836
+ * @param objOrMsg - The call's context object, or its bare message.
2837
+ * @param msg - The message that goes with a context object.
2838
+ */
2839
+ function formatLogLine(level, objOrMsg, msg) {
2840
+ const context = typeof objOrMsg === "string" ? {} : objOrMsg;
2841
+ const message = typeof objOrMsg === "string" ? objOrMsg : msg;
2842
+ if (!message || context.event === "command_run") return void 0;
2843
+ const text = redact(message).replace(/\s+/g, " ").trim().slice(0, MAX_MESSAGE_CHARS);
2844
+ if (!text) return void 0;
2845
+ const fields = Object.entries(context).filter(([, value]) => typeof value === "number" && Number.isFinite(value)).slice(0, MAX_FIELDS).map(([name, value]) => `${name.replace(/[^\w.-]/g, "_")}=${String(value)}`);
2846
+ return `[${level}] ${text}${fields.length > 0 ? ` (${fields.join(", ")})` : ""}`;
2847
+ }
2848
+ // src/observability/log-tap/log-tap.ts
2849
+ /** Where the CLI's own log lines are copied to while a command thread is open; `undefined` when none is. */
2850
+ let sink;
2851
+ /**
2852
+ * Start (or, with `undefined`, stop) copying the CLI logger's formatted lines to `next` (spec
2853
+ * `tech-discord-notifications-v2`, step 7). There is one at a time: a process runs one command.
2854
+ *
2855
+ * @param next - Receives each line the logger writes at `info` or above; `undefined` stops the copy.
2856
+ */
2857
+ function setLogTap(next) {
2858
+ sink = next;
2859
+ }
2860
+ /**
2861
+ * Hand one formatted line to the tap, if one is set. A tap that throws is ignored: the logger must not be affected.
2862
+ *
2863
+ * @param line - The line, from `formatLogLine()`.
2864
+ */
2865
+ function pushToLogTap(line) {
2866
+ try {
2867
+ sink?.(line);
2868
+ } catch {}
2869
+ }
2870
+ // src/observability/tap-logger/tap-logger.ts
2871
+ /**
2872
+ * Wrap a logger so that each `info`, `warn` and `error` call is also copied, as one formatted line, to the log tap
2873
+ * (`setLogTap()`), which a command thread streams to Discord (spec `tech-discord-notifications-v2`, step 7). The
2874
+ * wrapped logger writes exactly what the original writes; a child is wrapped too, so a line from any module is seen.
2875
+ * `debug` is never copied.
2876
+ *
2877
+ * @param inner - The logger to wrap.
2878
+ */
2879
+ function tapLogger(inner) {
2880
+ const copy = (level, objOrMsg, msg) => {
2881
+ const line = formatLogLine(level, objOrMsg, msg);
2882
+ if (line) pushToLogTap(line);
2883
+ };
2884
+ return {
2885
+ debug: (objOrMsg, msg) => inner.debug(objOrMsg, msg),
2886
+ info: (objOrMsg, msg) => {
2887
+ inner.info(objOrMsg, msg);
2888
+ copy("info", objOrMsg, msg);
2889
+ },
2890
+ warn: (objOrMsg, msg) => {
2891
+ inner.warn(objOrMsg, msg);
2892
+ copy("warn", objOrMsg, msg);
2893
+ },
2894
+ error: (objOrMsg, msg) => {
2895
+ inner.error(objOrMsg, msg);
2896
+ copy("error", objOrMsg, msg);
2897
+ },
2898
+ child: (bindings) => tapLogger(inner.child(bindings)),
2899
+ flush: () => inner.flush()
2900
+ };
2901
+ }
2812
2902
  // src/observability/logger/logger.ts
2813
2903
  /**
2814
2904
  * CLI-side wiring for `@theholocron/observability/logger`.
@@ -2861,89 +2951,222 @@ const logger = createCliLogger({
2861
2951
  * rebuilt at most once more when a handler supplies `holocron.config` context.
2862
2952
  * See `createCliLogger` in `@theholocron/kyber/observability`.
2863
2953
  */
2864
- const buildCliLogger = logger.buildCliLogger;
2954
+ const buildCliLogger = (argv, opts) => {
2955
+ const built = logger.buildCliLogger(argv, opts);
2956
+ return {
2957
+ ...built,
2958
+ logger: tapLogger(built.logger)
2959
+ };
2960
+ };
2865
2961
  /** Lazily-memoized `Logger` for call sites with no `argv` in scope (yargs' `.fail()`). */
2866
- const getLogger = logger.getLogger;
2962
+ const getLogger = () => tapLogger(logger.getLogger());
2867
2963
  /** Report a fatal, command-ending CLI error: printed with `style.fail` and logged. */
2868
- const reportError = logger.reportError;
2964
+ const reportError = (message, log = getLogger()) => logger.reportError(message, log);
2869
2965
  /** The current root logger's correlation id, if a root has been built. */
2870
2966
  const getRunId = logger.getRunId;
2871
2967
  logger.resetCliLogger;
2872
2968
  logger.resolveLogLevel;
2873
- // src/observability/resolve-telemetry/resolve-telemetry.ts
2874
- const env$10 = holocronEnv();
2969
+ // src/credentials-environments/derives-environment/derives-environment.ts
2970
+ /** The providers whose `credentials` entry may leave `environment` out and have it derived (#2063). */
2971
+ const DERIVING = /* @__PURE__ */ new Set(["1password"]);
2972
+ /** Whether a `credentials` provider with no `environment` option derives its Environment names. */
2973
+ function derivesEnvironment(provider) {
2974
+ return DERIVING.has(provider);
2975
+ }
2976
+ // src/credentials-environments/layer-environment/layer-environment.ts
2977
+ /** The layer words, in the order the docs list them. */
2978
+ const ENVIRONMENT_LAYERS = [
2979
+ "local",
2980
+ "dev",
2981
+ "ci",
2982
+ "prod",
2983
+ "preview",
2984
+ "agent"
2985
+ ];
2986
+ /** Whether `value` is exactly one of the layer words (case-sensitive: `Prod` is a literal Environment name). */
2987
+ function isEnvironmentLayer(value) {
2988
+ return typeof value === "string" && ENVIRONMENT_LAYERS.includes(value);
2989
+ }
2875
2990
  /**
2876
- * Holocron-specific credential resolution for the telemetry sinks — the env
2877
- * chain plus Holocron's own shipped fallbacks. This is **CLI policy**, not part
2878
- * of the portable adapter set: `sentry-sink.ts` / `posthog-sink.ts` take a
2879
- * resolved DSN / key and never read the environment. When the adapters move to
2880
- * `@theholocron/observability` (#635) this module stays here.
2881
- *
2882
- * errors: HOLOCRON_SENTRY_DSN → SENTRY_DSN → FALLBACK_DSN
2883
- * analytics: HOLOCRON_POSTHOG_PROJECT_TOKEN → POSTHOG_PROJECT_TOKEN → FALLBACK_POSTHOG_PROJECT_TOKEN
2884
- * host: HOLOCRON_POSTHOG_HOST → POSTHOG_HOST → DEFAULT_POSTHOG_HOST
2885
- *
2886
- * The `SENTRY_DSN` / `POSTHOG_PROJECT_TOKEN` fallbacks are the vendor-native
2887
- * names a consumer repo sets to route CLI telemetry to its own project. The
2888
- * built-in fallbacks are ingest-only keys — publishable by design, same risk
2889
- * model as ADR-0007 / ADR-0008.
2991
+ * The Environment a layer of a repository is kept in: `<org/repo> - <layer>`. The one place the name is built, for the
2992
+ * `credentials` providers (`environmentLayers()`) and for the config entries that name a `layer`.
2890
2993
  */
2891
- /** Holocron's own Sentry project — the fallback when no env var points elsewhere. */
2892
- const FALLBACK_DSN = "https://95cbb72ad5636c94e119a5405ee8f55f@o4508238154104832.ingest.us.sentry.io/4511810950791168";
2893
- /** Holocron's own PostHog project write key — ingest-only. */
2894
- const FALLBACK_POSTHOG_PROJECT_TOKEN = "phc_AC4vFCvYzwnzmG7Vg5nEc3PZKZztoPyfKp4Lb9BbXcLK";
2895
- const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
2896
- /** Resolve the Sentry DSN. `""` → error telemetry disabled. */
2897
- function resolveDsn() {
2898
- return env$10.get("SENTRY_DSN") ?? FALLBACK_DSN;
2994
+ function layerEnvironment(slug, layer) {
2995
+ return `${slug} - ${layer}`;
2899
2996
  }
2900
- /** Resolve the PostHog project key. `""` → usage analytics disabled. */
2901
- function resolvePostHogKey() {
2902
- return env$10.get("POSTHOG_PROJECT_TOKEN") ?? FALLBACK_POSTHOG_PROJECT_TOKEN;
2997
+ // src/credentials-environments/environment-layers/environment-layers.ts
2998
+ /** The suffix each layer's Environment carries: `<org/repo> - <suffix>`. `test` and `preview` have none. */
2999
+ const SUFFIX = {
3000
+ local: "local",
3001
+ development: "dev",
3002
+ ci: "ci",
3003
+ production: "prod",
3004
+ agent: "agent"
3005
+ };
3006
+ /**
3007
+ * The Environments a layer reads, in the order they are tried (#2063, #2058). A machine (`local`) reads
3008
+ * `<slug> - local` and then `<slug> - dev`: that is the only fallback there is. `development` reads `- dev`, `ci`
3009
+ * reads `- ci` and `production` reads `- prod`; a missing name is a missing name. `agent` (an agent's process, spec
3010
+ * `tech-agent-secrets`) reads `- agent` and nothing else, not `- local` or `- dev`, so an agent never sees a value that
3011
+ * belongs to a person's layer. `test` and `preview` read none (a preview deployment gets its values from the
3012
+ * deployment, not from a vault). Only `- local` is optional.
3013
+ */
3014
+ function environmentLayers(slug, layer) {
3015
+ if (layer === "test" || layer === "preview") return [];
3016
+ const candidate = (suffix, optional) => ({
3017
+ name: layerEnvironment(slug, suffix),
3018
+ optional
3019
+ });
3020
+ return layer === "local" ? [candidate(SUFFIX.local, true), candidate(SUFFIX.development, false)] : [candidate(SUFFIX[layer], false)];
2903
3021
  }
2904
- /** Resolve the PostHog ingest host. */
2905
- function resolvePostHogHost() {
2906
- return env$10.get("POSTHOG_HOST") ?? DEFAULT_POSTHOG_HOST;
3022
+ // src/credentials-environments/repo-slug/repo-slug.ts
3023
+ /**
3024
+ * The `<org>/<repo>` of the repository at `cwd`, from its `origin` remote. A remote that is missing or cannot be
3025
+ * parsed is a `ConfigError` that names the `environment` option as the fix.
3026
+ */
3027
+ async function repoSlug(cwd, exec) {
3028
+ const remote = await readGitRemote(cwd, exec ? { exec } : {});
3029
+ if (!remote) throw new ConfigError$1(`cannot derive the 1Password Environment name: the \`origin\` remote of ${cwd} is missing or not an owner/repo URL. Give the \`credentials\` provider an \`environment\` option to name it.`);
3030
+ return remote.slug;
2907
3031
  }
2908
- // src/observability/telemetry/telemetry.ts
3032
+ // src/credentials-environments/resolve-environments/resolve-environments.ts
2909
3033
  /**
2910
- * CLI self-telemetry — errors (Sentry), usage analytics (PostHog).
3034
+ * The Environments one `credentials` entry reads. An explicit name (the entry's `environment` option, else the shared
3035
+ * `credentials.environment`) is the only candidate and wins. Otherwise a deriving provider gets the names of its layer
3036
+ * (`environmentLayers()`) from the repo's `origin` and `detectEnvironment()`. Nothing is read from a provider here. An empty list means there is nothing to read (the `test` layer).
3037
+ */
3038
+ async function resolveEnvironments(provider, explicit, input) {
3039
+ if (explicit !== void 0) return [{
3040
+ name: explicit,
3041
+ optional: false
3042
+ }];
3043
+ if (!derivesEnvironment(provider)) return [];
3044
+ const layer = detectEnvironment(input.env);
3045
+ if (layer === "test") return [];
3046
+ return environmentLayers(await repoSlug(input.repoRoot, input.gitExec), layer);
3047
+ }
3048
+ // src/credentials-environments/try-environments/try-environments.ts
3049
+ /** A provider's "no such Environment": its API error with status 404 (`ProviderApiError`, matched by shape). */
3050
+ function isNotFound(err) {
3051
+ return typeof err === "object" && err !== null && err.status === 404;
3052
+ }
3053
+ /**
3054
+ * Calls `attempt` for each candidate and sorts the answers into found and missing. A 404 is a miss; any other error
3055
+ * is thrown. A missing optional Environment is silent; a missing required one is reported by name.
3056
+ */
3057
+ async function tryEnvironments(candidates, attempt) {
3058
+ const found = [];
3059
+ const missing = [];
3060
+ for (const candidate of candidates) try {
3061
+ found.push({
3062
+ name: candidate.name,
3063
+ result: await attempt(candidate.name)
3064
+ });
3065
+ } catch (err) {
3066
+ if (!isNotFound(err)) throw err;
3067
+ if (!candidate.optional) missing.push(candidate.name);
3068
+ }
3069
+ return {
3070
+ found,
3071
+ missing
3072
+ };
3073
+ }
3074
+ // src/credentials-environments/try-environments-sync/try-environments-sync.ts
3075
+ /**
3076
+ * `tryEnvironments()` for an `attempt` that is synchronous, which a deferred credentials read must be (the token
3077
+ * resolvers that trigger it cannot wait). A 404 is a miss; any other error is thrown. A missing optional Environment
3078
+ * is silent; a missing required one is reported by name.
3079
+ */
3080
+ function tryEnvironmentsSync(candidates, attempt) {
3081
+ const found = [];
3082
+ const missing = [];
3083
+ for (const candidate of candidates) try {
3084
+ found.push({
3085
+ name: candidate.name,
3086
+ result: attempt(candidate.name)
3087
+ });
3088
+ } catch (err) {
3089
+ if (err?.status !== 404) throw err;
3090
+ if (!candidate.optional) missing.push(candidate.name);
3091
+ }
3092
+ return {
3093
+ found,
3094
+ missing
3095
+ };
3096
+ }
3097
+ // src/credentials-environments/unsynced-layer/unsynced-layer.ts
3098
+ /**
3099
+ * The layers this machine reads for itself (`agent` is the one an agent's process reads, spec `tech-agent-secrets`). They
3100
+ * are never synced to GitHub, a deployment or a Worker (#2104).
3101
+ */
3102
+ const UNSYNCED_LAYERS = [
3103
+ "local",
3104
+ "dev",
3105
+ "agent"
3106
+ ];
3107
+ /** Whether `layer` is one of {@link UNSYNCED_LAYERS}. */
3108
+ function isUnsyncedLayer(layer) {
3109
+ return isEnvironmentLayer(layer) && UNSYNCED_LAYERS.includes(layer);
3110
+ }
3111
+ /**
3112
+ * The text of the error for an Environment of an unsynced layer, shared by the command and the config checks.
2911
3113
  *
2912
- * The orchestration is `createCliTelemetry` in `@theholocron/kyber/observability`
2913
- * (no vendor SDK import here either: the sinks live in `@theholocron/observability`).
2914
- * This module binds it to Holocron's values: the `HOLOCRON` env prefix, the
2915
- * credentials resolved by `resolve-telemetry.ts`, and the logger's run id.
2916
- * The single kill switch is `HOLOCRON_TELEMETRY=false` (legacy alias
2917
- * `NO_HOLOCRON_TELEMETRY`); see ADR-0007 / ADR-0008.
3114
+ * @param what - What names the layer, e.g. "`sync secrets --env dev`" or "a `repo.secrets.sync` entry".
3115
+ * @param layer - The unsynced layer.
2918
3116
  */
2919
- const telemetry = createCliTelemetry({
2920
- envPrefix: PREFIX$1,
2921
- dsn: resolveDsn,
2922
- posthogKey: resolvePostHogKey,
2923
- posthogHost: resolvePostHogHost,
2924
- getRunId: () => getRunId()
2925
- });
2926
- /** Install the live sinks unless telemetry is opted out or a credential is empty. */
2927
- const init = telemetry.init;
2928
- /** Apply the `telemetry` config block; it only ever narrows what `init` turned on. */
2929
- const applyConfig = telemetry.applyConfig;
2930
- /** Capture a PostHog event, scrubbed of secrets. */
2931
- const event = telemetry.event;
2932
- /** Start a command span; call the returned function with the outcome. */
2933
- const startCommand$1 = telemetry.startCommand;
2934
- /** Report an error to Sentry. */
2935
- const captureException = telemetry.captureException;
2936
- /** End the Sentry session. */
2937
- const endSession = telemetry.endSession;
2938
- /** Drain both sinks and return to the no-ops. */
2939
- const flush = telemetry.flush;
2940
- telemetry.resetTelemetry;
2941
- // src/credentials-environments/derives-environment/derives-environment.ts
2942
- /** The providers whose `credentials` entry may leave `environment` out and have it derived (#2063). */
2943
- const DERIVING = /* @__PURE__ */ new Set(["1password"]);
2944
- /** Whether a `credentials` provider with no `environment` option derives its Environment names. */
2945
- function derivesEnvironment(provider) {
2946
- return DERIVING.has(provider);
3117
+ function unsyncedLayerMessage(what, layer) {
3118
+ return `${what} names the \`${layer}\` layer: \`local\`, \`dev\` and \`agent\` are read by this machine and are never synced. Only ${ENVIRONMENT_LAYERS.filter((l) => !isUnsyncedLayer(l)).map((l) => `\`${String(l)}\``).join(" and ")} can be synced`;
3119
+ }
3120
+ /**
3121
+ * Refuse a sync of an unsynced layer, before anything is read. The argument is a layer word, or the literal name of a
3122
+ * layer's Environment (`<org/repo> - dev`, built by `layerEnvironment()` from the `origin` remote). A remote that
3123
+ * cannot be read means no literal name can be matched, so only a layer word is checked then.
3124
+ *
3125
+ * @param id - The environment as given on the command line.
3126
+ * @param input - Where the repository is, and optionally how to read its remote.
3127
+ * @throws {ConfigError} For an unsynced layer, whatever other flags are given.
3128
+ */
3129
+ async function assertSyncableLayer(id, input) {
3130
+ if (isEnvironmentLayer(id)) {
3131
+ if (isUnsyncedLayer(id)) throw new ConfigError$1(unsyncedLayerMessage(`\`sync secrets --env ${id}\``, id));
3132
+ return;
3133
+ }
3134
+ const slug = await repoSlug(input.repoRoot, input.gitExec).catch(() => void 0);
3135
+ if (slug === void 0) return;
3136
+ for (const layer of UNSYNCED_LAYERS) if (id === layerEnvironment(slug, layer)) throw new ConfigError$1(unsyncedLayerMessage(`\`sync secrets --env\` for ${JSON.stringify(id)}`, layer));
3137
+ }
3138
+ // src/observability/command-path/command-path.ts
3139
+ /** The first word of every command Holocron has. */
3140
+ const VERBS = new Set(Object.keys(COMMAND_CONTEXTS).map((name) => name.split(" ")[0]));
3141
+ /** A command word as the commands spell it: lower-case letters, digits and dashes. A number, a path or a value is not one. */
3142
+ const COMMAND_WORD = /^[a-z][a-z0-9-]*$/;
3143
+ /** The most words a command path has (`probe docs coverage`). */
3144
+ const MAX_WORDS = 3;
3145
+ /**
3146
+ * The command path to record (`sync specs`, `start work`) from yargs' `argv._`. Only the words that are spelled like a
3147
+ * command's own are kept, up to three, and the first must be a command Holocron knows, so a positional or a value that
3148
+ * ends up in `argv._` is never recorded. Anything else is `unknown`.
3149
+ *
3150
+ * @param words - `argv._`.
3151
+ */
3152
+ function commandPath(words) {
3153
+ const path = [];
3154
+ for (const word of words.slice(0, MAX_WORDS)) {
3155
+ if (typeof word !== "string" || !COMMAND_WORD.test(word)) break;
3156
+ path.push(word);
3157
+ }
3158
+ return path.length > 0 && VERBS.has(path[0]) ? path.join(" ") : "unknown";
3159
+ }
3160
+ // src/commands/resolve-org/resolve-org.ts
3161
+ const env$10 = createEnvLookup();
3162
+ /**
3163
+ * Resolves the active org in priority order:
3164
+ * 1. `--org` CLI flag
3165
+ * 2. `HOLOCRON_ORG` env var
3166
+ * 3. `org` from `holocron.config.ts`
3167
+ */
3168
+ function resolveOrg(argv, config) {
3169
+ return argv.org ?? env$10.get("HOLOCRON_ORG") ?? config.org;
2947
3170
  }
2948
3171
  // src/plugin/capabilities/capabilities.ts
2949
3172
  /** How many providers each capability resolves to: one (`"single"`) or several active at once (`"many"`). */
@@ -3054,26 +3277,44 @@ function splitAgent(raw) {
3054
3277
  agentOptions: options
3055
3278
  };
3056
3279
  }
3057
- // src/credentials-environments/layer-environment/layer-environment.ts
3058
- /** The layer words, in the order the docs list them. */
3059
- const ENVIRONMENT_LAYERS = [
3060
- "local",
3061
- "dev",
3062
- "ci",
3063
- "prod",
3064
- "preview",
3065
- "agent"
3280
+ // src/config/validate-command-log/validate-command-log.ts
3281
+ /** The values `notifications.commandLog` accepts. */
3282
+ const COMMAND_LOG_MODES = [
3283
+ "agents",
3284
+ "all",
3285
+ "off"
3066
3286
  ];
3067
- /** Whether `value` is exactly one of the layer words (case-sensitive: `Prod` is a literal Environment name). */
3068
- function isEnvironmentLayer(value) {
3069
- return typeof value === "string" && ENVIRONMENT_LAYERS.includes(value);
3287
+ /**
3288
+ * Check `notifications.commandLog` (spec `tech-discord-notifications-v2`, step 6): `agents`, `all` or `off`.
3289
+ *
3290
+ * @param notifications - The config's top-level `notifications` block, if it has one.
3291
+ * @throws {ConfigError} Naming the path and the allowed values.
3292
+ */
3293
+ function validateCommandLog(notifications) {
3294
+ if (notifications === void 0) return;
3295
+ if (typeof notifications !== "object" || notifications === null || Array.isArray(notifications)) throw new ConfigError$1("`notifications` must be an object (for example `{ commandLog: \"agents\" }`)");
3296
+ const mode = notifications.commandLog;
3297
+ if (mode === void 0) return;
3298
+ if (typeof mode !== "string" || !COMMAND_LOG_MODES.includes(mode)) throw new ConfigError$1(`\`notifications.commandLog\` must be one of ${COMMAND_LOG_MODES.map((m) => `"${m}"`).join(", ")}, got ${JSON.stringify(mode)}`);
3070
3299
  }
3300
+ // src/config/validate-command-threads/validate-command-threads.ts
3301
+ /** The values `notifications.commandThreads` accepts. */
3302
+ const COMMAND_THREADS_MODES = [
3303
+ "agents",
3304
+ "all",
3305
+ "off"
3306
+ ];
3071
3307
  /**
3072
- * The Environment a layer of a repository is kept in: `<org/repo> - <layer>`. The one place the name is built, for the
3073
- * `credentials` providers (`environmentLayers()`) and for the config entries that name a `layer`.
3308
+ * Check `notifications.commandThreads` (spec `tech-discord-notifications-v2`, step 7): `agents`, `all` or `off`. The
3309
+ * block itself is checked by `validateCommandLog()`, which runs first.
3310
+ *
3311
+ * @param notifications - The config's top-level `notifications` block, if it has one.
3312
+ * @throws {ConfigError} Naming the path and the allowed values.
3074
3313
  */
3075
- function layerEnvironment(slug, layer) {
3076
- return `${slug} - ${layer}`;
3314
+ function validateCommandThreads(notifications) {
3315
+ const mode = notifications?.commandThreads;
3316
+ if (mode === void 0) return;
3317
+ if (typeof mode !== "string" || !COMMAND_THREADS_MODES.includes(mode)) throw new ConfigError$1(`\`notifications.commandThreads\` must be one of ${COMMAND_THREADS_MODES.map((m) => `"${m}"`).join(", ")}, got ${JSON.stringify(mode)}`);
3077
3318
  }
3078
3319
  // src/config/validate-environment-choice/validate-environment-choice.ts
3079
3320
  /**
@@ -3341,57 +3582,6 @@ function validateRequiredChecks(checks) {
3341
3582
  seen.add(context);
3342
3583
  });
3343
3584
  }
3344
- // src/credentials-environments/repo-slug/repo-slug.ts
3345
- /**
3346
- * The `<org>/<repo>` of the repository at `cwd`, from its `origin` remote. A remote that is missing or cannot be
3347
- * parsed is a `ConfigError` that names the `environment` option as the fix.
3348
- */
3349
- async function repoSlug(cwd, exec) {
3350
- const remote = await readGitRemote(cwd, exec ? { exec } : {});
3351
- if (!remote) throw new ConfigError$1(`cannot derive the 1Password Environment name: the \`origin\` remote of ${cwd} is missing or not an owner/repo URL. Give the \`credentials\` provider an \`environment\` option to name it.`);
3352
- return remote.slug;
3353
- }
3354
- // src/credentials-environments/unsynced-layer/unsynced-layer.ts
3355
- /**
3356
- * The layers this machine reads for itself (`agent` is the one an agent's process reads, spec `tech-agent-secrets`). They
3357
- * are never synced to GitHub, a deployment or a Worker (#2104).
3358
- */
3359
- const UNSYNCED_LAYERS = [
3360
- "local",
3361
- "dev",
3362
- "agent"
3363
- ];
3364
- /** Whether `layer` is one of {@link UNSYNCED_LAYERS}. */
3365
- function isUnsyncedLayer(layer) {
3366
- return isEnvironmentLayer(layer) && UNSYNCED_LAYERS.includes(layer);
3367
- }
3368
- /**
3369
- * The text of the error for an Environment of an unsynced layer, shared by the command and the config checks.
3370
- *
3371
- * @param what - What names the layer, e.g. "`sync secrets --env dev`" or "a `repo.secrets.sync` entry".
3372
- * @param layer - The unsynced layer.
3373
- */
3374
- function unsyncedLayerMessage(what, layer) {
3375
- return `${what} names the \`${layer}\` layer: \`local\`, \`dev\` and \`agent\` are read by this machine and are never synced. Only ${ENVIRONMENT_LAYERS.filter((l) => !isUnsyncedLayer(l)).map((l) => `\`${String(l)}\``).join(" and ")} can be synced`;
3376
- }
3377
- /**
3378
- * Refuse a sync of an unsynced layer, before anything is read. The argument is a layer word, or the literal name of a
3379
- * layer's Environment (`<org/repo> - dev`, built by `layerEnvironment()` from the `origin` remote). A remote that
3380
- * cannot be read means no literal name can be matched, so only a layer word is checked then.
3381
- *
3382
- * @param id - The environment as given on the command line.
3383
- * @param input - Where the repository is, and optionally how to read its remote.
3384
- * @throws {ConfigError} For an unsynced layer, whatever other flags are given.
3385
- */
3386
- async function assertSyncableLayer(id, input) {
3387
- if (isEnvironmentLayer(id)) {
3388
- if (isUnsyncedLayer(id)) throw new ConfigError$1(unsyncedLayerMessage(`\`sync secrets --env ${id}\``, id));
3389
- return;
3390
- }
3391
- const slug = await repoSlug(input.repoRoot, input.gitExec).catch(() => void 0);
3392
- if (slug === void 0) return;
3393
- for (const layer of UNSYNCED_LAYERS) if (id === layerEnvironment(slug, layer)) throw new ConfigError$1(unsyncedLayerMessage(`\`sync secrets --env\` for ${JSON.stringify(id)}`, layer));
3394
- }
3395
3585
  // src/config/validate-secrets-deploy/validate-secrets-deploy.ts
3396
3586
  /**
3397
3587
  * Check `repo.secrets.deploy`: each entry names a vault environment (or a `layer`) and at least one of a non-empty `keys` list and a
@@ -3650,6 +3840,8 @@ function resolveConfig(raw) {
3650
3840
  if (raw.issueTypes !== void 0) validateIssueTypes(raw.issueTypes);
3651
3841
  validateRepoLabels(raw.repo?.labels);
3652
3842
  validateRepoViews(raw.repo?.views);
3843
+ validateCommandLog(raw.notifications);
3844
+ validateCommandThreads(raw.notifications);
3653
3845
  validateRepoEnvironments(raw.repo?.environments);
3654
3846
  validateRequiredChecks(raw.repo?.requiredChecks);
3655
3847
  validateVariablesSync(raw.repo?.variables);
@@ -3693,6 +3885,7 @@ function resolveConfig(raw) {
3693
3885
  ideas: raw.ideas,
3694
3886
  log: raw.log,
3695
3887
  telemetry: raw.telemetry,
3888
+ notifications: raw.notifications,
3696
3889
  eslint: raw.eslint
3697
3890
  };
3698
3891
  }
@@ -4027,73 +4220,6 @@ function placeAreas(areas, raw) {
4027
4220
  else if (area.area === "org") result = placeOrg(result, area);
4028
4221
  return result;
4029
4222
  }
4030
- // src/credentials-environments/environment-layers/environment-layers.ts
4031
- /** The suffix each layer's Environment carries: `<org/repo> - <suffix>`. `test` and `preview` have none. */
4032
- const SUFFIX = {
4033
- local: "local",
4034
- development: "dev",
4035
- ci: "ci",
4036
- production: "prod",
4037
- agent: "agent"
4038
- };
4039
- /**
4040
- * The Environments a layer reads, in the order they are tried (#2063, #2058). A machine (`local`) reads
4041
- * `<slug> - local` and then `<slug> - dev`: that is the only fallback there is. `development` reads `- dev`, `ci`
4042
- * reads `- ci` and `production` reads `- prod`; a missing name is a missing name. `agent` (an agent's process, spec
4043
- * `tech-agent-secrets`) reads `- agent` and nothing else, not `- local` or `- dev`, so an agent never sees a value that
4044
- * belongs to a person's layer. `test` and `preview` read none (a preview deployment gets its values from the
4045
- * deployment, not from a vault). Only `- local` is optional.
4046
- */
4047
- function environmentLayers(slug, layer) {
4048
- if (layer === "test" || layer === "preview") return [];
4049
- const candidate = (suffix, optional) => ({
4050
- name: layerEnvironment(slug, suffix),
4051
- optional
4052
- });
4053
- return layer === "local" ? [candidate(SUFFIX.local, true), candidate(SUFFIX.development, false)] : [candidate(SUFFIX[layer], false)];
4054
- }
4055
- // src/credentials-environments/resolve-environments/resolve-environments.ts
4056
- /**
4057
- * The Environments one `credentials` entry reads. An explicit name (the entry's `environment` option, else the shared
4058
- * `credentials.environment`) is the only candidate and wins. Otherwise a deriving provider gets the names of its layer
4059
- * (`environmentLayers()`) from the repo's `origin` and `detectEnvironment()`. Nothing is read from a provider here. An empty list means there is nothing to read (the `test` layer).
4060
- */
4061
- async function resolveEnvironments(provider, explicit, input) {
4062
- if (explicit !== void 0) return [{
4063
- name: explicit,
4064
- optional: false
4065
- }];
4066
- if (!derivesEnvironment(provider)) return [];
4067
- const layer = detectEnvironment(input.env);
4068
- if (layer === "test") return [];
4069
- return environmentLayers(await repoSlug(input.repoRoot, input.gitExec), layer);
4070
- }
4071
- // src/credentials-environments/try-environments/try-environments.ts
4072
- /** A provider's "no such Environment": its API error with status 404 (`ProviderApiError`, matched by shape). */
4073
- function isNotFound(err) {
4074
- return typeof err === "object" && err !== null && err.status === 404;
4075
- }
4076
- /**
4077
- * Calls `attempt` for each candidate and sorts the answers into found and missing. A 404 is a miss; any other error
4078
- * is thrown. A missing optional Environment is silent; a missing required one is reported by name.
4079
- */
4080
- async function tryEnvironments(candidates, attempt) {
4081
- const found = [];
4082
- const missing = [];
4083
- for (const candidate of candidates) try {
4084
- found.push({
4085
- name: candidate.name,
4086
- result: await attempt(candidate.name)
4087
- });
4088
- } catch (err) {
4089
- if (!isNotFound(err)) throw err;
4090
- if (!candidate.optional) missing.push(candidate.name);
4091
- }
4092
- return {
4093
- found,
4094
- missing
4095
- };
4096
- }
4097
4223
  // src/config/resolve-layers/resolve-layers.ts
4098
4224
  /**
4099
4225
  * Turns every `layer` in a loaded config into the `environment` it names (spec `tech-environment-layers`, #2069), so
@@ -4217,46 +4343,6 @@ function resolvedEnvironment(entry) {
4217
4343
  if (entry.environment === void 0) throw new ConfigError$1(`an entry names the layer ${JSON.stringify(entry.layer)} but its Environment was not derived: load the config with loadConfig()`);
4218
4344
  return entry.environment;
4219
4345
  }
4220
- // src/commands/resolve-org/resolve-org.ts
4221
- const env$9 = createEnvLookup();
4222
- /**
4223
- * Resolves the active org in priority order:
4224
- * 1. `--org` CLI flag
4225
- * 2. `HOLOCRON_ORG` env var
4226
- * 3. `org` from `holocron.config.ts`
4227
- */
4228
- function resolveOrg(argv, config) {
4229
- return argv.org ?? env$9.get("HOLOCRON_ORG") ?? config.org;
4230
- }
4231
- // src/commands/apply-resolved-config/apply-resolved-config.ts
4232
- /**
4233
- * `buildCliLogger` options derived from a loaded `holocron.config` — the
4234
- * level, the Axiom dataset, and the resolved org for a keyring-backed
4235
- * Axiom token. Used by every handler that has already called `loadConfig`.
4236
- */
4237
- function cliLoggerOpts(argv, resolved) {
4238
- return {
4239
- configLevel: resolved.log?.level,
4240
- configAxiomDataset: resolved.log?.axiom?.dataset,
4241
- org: resolveOrg(argv, resolved)
4242
- };
4243
- }
4244
- /**
4245
- * Fold a loaded `holocron.config` into the running process: reconfigure the
4246
- * logger from `log:`, then apply the `telemetry:` override layer. Every handler
4247
- * that has called `loadConfig` runs this, so a repo's `telemetry.enabled: false`
4248
- * (or `analytics: "none"`) is honoured for that command. Env still wins —
4249
- * `applyConfig` only narrows what `init` already turned on.
4250
- */
4251
- function applyResolvedConfig(argv, resolved) {
4252
- buildCliLogger(argv, cliLoggerOpts(argv, resolved));
4253
- applyConfig(resolved.telemetry);
4254
- }
4255
- // src/commands/token-context/token-context.ts
4256
- /** Parses --token values and returns the context spread, or null on parse error (exits with code 1). */
4257
- function tokenContext(rawTokens) {
4258
- return tokenContext$1(rawTokens, reportError);
4259
- }
4260
4346
  // src/plugin/missing-plugin-hint/missing-plugin-hint.ts
4261
4347
  /**
4262
4348
  * The line that says how to get a plugin package that does not resolve: add it to the `holocron` catalog of
@@ -4350,6 +4436,8 @@ function assertPluginsResolvable(loader, command) {
4350
4436
  * `importer` is injectable so tests don't need real network or
4351
4437
  * sibling packages installed.
4352
4438
  */
4439
+ /** The prefix of the key a deferred read of a `credentials` provider is kept under. */
4440
+ const LAZY = "lazy:";
4353
4441
  const system = createPluginSystem({
4354
4442
  packagePrefix: "@theholocron/holocron-plugin-",
4355
4443
  communityPrefix: "holocron-plugin-",
@@ -4385,15 +4473,31 @@ const system = createPluginSystem({
4385
4473
  const impl = await api.loadOne("credentials", tuple);
4386
4474
  impls.push(impl);
4387
4475
  if (options?.readCredentials === false) continue;
4388
- const { missing } = await tryEnvironments(await resolveEnvironments(tuple.provider, explicit, {
4476
+ const candidates = await resolveEnvironments(tuple.provider, explicit, {
4389
4477
  repoRoot: context.repoRoot,
4390
4478
  ...options?.env ? { env: options.env } : {},
4391
4479
  ...options?.gitExec ? { gitExec: options.gitExec } : {}
4392
- }), async (name) => {
4480
+ });
4481
+ const missingError = (missing) => new LoaderError(`${tuple.provider} has no Environment named ${missing.map((n) => `"${n}"`).join(", ")}`);
4482
+ if (impl.readSync) {
4483
+ const read = impl.readSync.bind(impl);
4484
+ deferCredentials(`${LAZY}${tuple.provider}:${candidates.map((c) => c.name).join("|")}`, () => {
4485
+ try {
4486
+ const { missing } = tryEnvironmentsSync(candidates, (name) => {
4487
+ setCredentials(`${tuple.provider}:${name}`, read(name));
4488
+ });
4489
+ if (missing.length > 0) throw missingError(missing);
4490
+ } catch (err) {
4491
+ api.fail("credentials", tuple, err);
4492
+ }
4493
+ });
4494
+ continue;
4495
+ }
4496
+ const { missing } = await tryEnvironments(candidates, async (name) => {
4393
4497
  const sourceName = `${tuple.provider}:${name}`;
4394
4498
  if (!hasCredentials(sourceName)) setCredentials(sourceName, await impl.read(name));
4395
4499
  });
4396
- if (missing.length > 0) throw new LoaderError(`${tuple.provider} has no Environment named ${missing.map((n) => `"${n}"`).join(", ")}`);
4500
+ if (missing.length > 0) throw missingError(missing);
4397
4501
  } catch (err) {
4398
4502
  api.fail("credentials", tuple, err);
4399
4503
  }
@@ -4537,6 +4641,476 @@ function actionsOf(plugin) {
4537
4641
  ...plugin.whoami ? { whoami: plugin.whoami } : {}
4538
4642
  };
4539
4643
  }
4644
+ // src/observability/command-log-disabled/command-log-disabled.ts
4645
+ /**
4646
+ * Whether the command log is off for this process: in CI (a run nobody watches posts through its own workflow) and
4647
+ * under test (`NODE_ENV=test`, which vitest sets), so neither writes an event or posts a line.
4648
+ *
4649
+ * @param source - The environment to read; the process environment when left out.
4650
+ */
4651
+ function commandLogDisabled(source) {
4652
+ const env = createEnvLookup(source);
4653
+ return isCI(source) || env.get("NODE_ENV") === "test";
4654
+ }
4655
+ // src/observability/command-log-skipped/command-log-skipped.ts
4656
+ /**
4657
+ * Commands that are not recorded: the ones that stay up for a whole session or run another command (a record would be
4658
+ * noise, or would say nothing about what was done). The menu starts the commands it runs as runs of their own, and those
4659
+ * are recorded.
4660
+ */
4661
+ const COMMAND_LOG_SKIPPED = [
4662
+ "dev",
4663
+ "menu",
4664
+ "open requests",
4665
+ "start agent",
4666
+ "unknown"
4667
+ ];
4668
+ /**
4669
+ * Whether a command is left out of the command log: it is, or starts with, an entry of {@link COMMAND_LOG_SKIPPED}.
4670
+ *
4671
+ * @param command - The command path, `sync specs`.
4672
+ */
4673
+ function isCommandLogSkipped(command) {
4674
+ return COMMAND_LOG_SKIPPED.some((skipped) => command === skipped || command.startsWith(`${skipped} `));
4675
+ }
4676
+ /**
4677
+ * The thread name for a command: `holocron sync specs — 2026-12-02 14:05 UTC`.
4678
+ *
4679
+ * @param command - The command path.
4680
+ * @param at - When it started, `Date.now()`.
4681
+ */
4682
+ function commandThreadName(command, at) {
4683
+ return `holocron ${command} — ${new Date(at).toISOString().slice(0, 16).replace("T", " ")} UTC`;
4684
+ }
4685
+ /**
4686
+ * Start a command's Discord thread (spec `tech-discord-notifications-v2`, step 7). Nothing waits for it: the setting is
4687
+ * read and the thread opened in the background while the command runs, lines that arrive earlier are kept, and they are
4688
+ * posted in batches of one per {@link COMMAND_THREAD_BATCH_MS}. A run the setting does not cover (`off`, or `agents` for
4689
+ * a person) opens nothing and its `finish()` is `false`. Every failure is swallowed; the caller bounds `finish()` with
4690
+ * its own deadline.
4691
+ *
4692
+ * @param command - The command path, `sync specs`.
4693
+ * @param deps - Who is running, the setting, how a thread is opened and the clock.
4694
+ */
4695
+ function startCommandThread(command, deps) {
4696
+ const batchMs = deps.batchMs ?? 3e3;
4697
+ const buffer = [];
4698
+ let taken = 0;
4699
+ let dropped = 0;
4700
+ let timer;
4701
+ let sending = Promise.resolve();
4702
+ const ready = (async () => {
4703
+ const mode = await deps.mode();
4704
+ if (mode === "off" || mode === "agents" && deps.actor.actor !== "agent") return void 0;
4705
+ return deps.open(commandThreadName(command, deps.now()));
4706
+ })().catch(() => void 0);
4707
+ const send = () => {
4708
+ sending = sending.then(async () => {
4709
+ const session = await ready;
4710
+ const lines = buffer.splice(0);
4711
+ if (session && lines.length > 0) await session.post(lines).catch(() => void 0);
4712
+ });
4713
+ };
4714
+ return {
4715
+ push(line) {
4716
+ if (taken >= 150) {
4717
+ dropped += 1;
4718
+ return;
4719
+ }
4720
+ taken += 1;
4721
+ buffer.push(line);
4722
+ if (timer === void 0) {
4723
+ timer = setTimeout(() => {
4724
+ timer = void 0;
4725
+ send();
4726
+ }, batchMs);
4727
+ timer.unref();
4728
+ }
4729
+ },
4730
+ async finish(finalLine) {
4731
+ clearTimeout(timer);
4732
+ timer = void 0;
4733
+ const session = await ready;
4734
+ if (!session) return false;
4735
+ await sending;
4736
+ if (dropped > 0) buffer.push(`… ${dropped} more lines not shown`);
4737
+ buffer.push(finalLine);
4738
+ try {
4739
+ await session.post(buffer.splice(0));
4740
+ return true;
4741
+ } catch {
4742
+ return false;
4743
+ }
4744
+ }
4745
+ };
4746
+ }
4747
+ // src/observability/command-run-deps/command-run-deps.ts
4748
+ /** The channel a command run is posted to; the layout declares it (`.holocron/notifications.ts`). */
4749
+ const AGENT_LOG_CHANNEL = "agent-log";
4750
+ /** Whether a provider has the three methods a command thread needs. */
4751
+ function canThread$1(provider) {
4752
+ return typeof provider.sendWithId === "function" && typeof provider.startThread === "function" && typeof provider.postToThread === "function";
4753
+ }
4754
+ /**
4755
+ * The real dependencies of `recordCommandRun()`, and (step 7) the run's command thread, started here so that it opens
4756
+ * while the command runs. The config is read at most once, and only when the recorder or the thread asks for a setting
4757
+ * (a run that is left out for CI, test or the skip list never does); the plugin loader is built only when a post or a
4758
+ * thread is due, so a human run in the default modes never builds one. The post goes to every configured
4759
+ * `notifications` provider through its `send`, which reads its own webhook (`HOLOCRON_NOTIFY_WEBHOOK_AGENT_LOG`) and
4760
+ * throws when there is none: the recorder swallows that. A thread is opened on the first provider that has `sendWithId`,
4761
+ * `startThread` and `postToThread`, and the CLI logger's lines are copied into it through the log tap. Provider tokens
4762
+ * given with `--token` are not passed on.
4763
+ */
4764
+ function createCommandRunDeps(input) {
4765
+ const disabled = input.disabled ?? commandLogDisabled();
4766
+ let loaded;
4767
+ let providers;
4768
+ const load = () => loaded ??= loadConfig(input.cwd);
4769
+ const notifications = () => providers ??= (async () => {
4770
+ const { resolved } = await load();
4771
+ const loader = new PluginLoader(resolved, {
4772
+ repoRoot: input.cwd,
4773
+ org: resolveOrg({ org: input.org }, resolved)
4774
+ });
4775
+ await loader.load();
4776
+ return loader.has("notifications") ? loader.get("notifications") : [];
4777
+ })();
4778
+ let thread;
4779
+ if (!disabled && !isCommandLogSkipped(input.command)) {
4780
+ thread = startCommandThread(input.command, {
4781
+ actor: input.actor,
4782
+ now: Date.now,
4783
+ mode: async () => (await load()).resolved.notifications?.commandThreads ?? "off",
4784
+ open: async (name) => {
4785
+ const provider = (await notifications()).find(canThread$1);
4786
+ if (!provider) return void 0;
4787
+ const anchor = await provider.sendWithId(AGENT_LOG_CHANNEL, `🧵 ${name}`);
4788
+ const opened = await provider.startThread(anchor, name);
4789
+ return { post: (lines) => provider.postToThread(opened.id, lines) };
4790
+ }
4791
+ });
4792
+ const started = thread;
4793
+ setLogTap((line) => started.push(line));
4794
+ }
4795
+ return {
4796
+ logger: input.logger,
4797
+ disabled,
4798
+ thread,
4799
+ mode: async () => (await load()).resolved.notifications?.commandLog ?? "agents",
4800
+ post: async (line) => {
4801
+ await Promise.all((await notifications()).map((provider) => provider.send(AGENT_LOG_CHANNEL, line)));
4802
+ }
4803
+ };
4804
+ }
4805
+ // src/observability/detect-actor/detect-actor.ts
4806
+ /** The variable each known agent sets in the processes it starts, with the name the record gives that agent. */
4807
+ const AGENT_VARIABLES = [
4808
+ ["CLAUDECODE", "claude"],
4809
+ ["CODEX_SANDBOX", "codex"],
4810
+ ["GEMINI_CLI", "gemini"]
4811
+ ];
4812
+ /**
4813
+ * Who is running this command (spec `tech-discord-notifications-v2`, step 6). An agent when a known agent's variable is
4814
+ * set (`CLAUDECODE`, `CODEX_SANDBOX`, `GEMINI_CLI`, which names it) or when `HOLOCRON_ENVIRONMENT=agent`, which the
4815
+ * `start agent` launcher sets (named `unknown` when no variable says which agent it is); otherwise a human. Only the
4816
+ * presence of a variable is read, never its value.
4817
+ *
4818
+ * @param source - The environment to read; the process environment when left out.
4819
+ */
4820
+ function detectActor(source) {
4821
+ const env = createEnvLookup(source);
4822
+ const named = AGENT_VARIABLES.find(([variable]) => env.get(variable) !== void 0);
4823
+ if (named) return {
4824
+ actor: "agent",
4825
+ agent: named[1]
4826
+ };
4827
+ if (holocronEnv(source).get("ENVIRONMENT") === "agent") return {
4828
+ actor: "agent",
4829
+ agent: "unknown"
4830
+ };
4831
+ return { actor: "human" };
4832
+ }
4833
+ // src/observability/is-info-run/is-info-run.ts
4834
+ /** Arguments that print help or the version instead of running a command. */
4835
+ const INFO_FLAGS = /* @__PURE__ */ new Set([
4836
+ "--help",
4837
+ "-h",
4838
+ "--version",
4839
+ "-v"
4840
+ ]);
4841
+ /**
4842
+ * Whether the command line asks for help or the version: such a run is not a command that ran, so it is neither recorded
4843
+ * nor given a thread.
4844
+ *
4845
+ * @param args - The command line as typed, without the program and script.
4846
+ */
4847
+ function isInfoRun(args) {
4848
+ return args.some((arg) => INFO_FLAGS.has(arg));
4849
+ }
4850
+ // src/observability/command-flag-names/command-flag-names.ts
4851
+ /** Flags that are on every command and say nothing about what it did. */
4852
+ const IGNORED = /* @__PURE__ */ new Set([
4853
+ "help",
4854
+ "version",
4855
+ "h",
4856
+ "v"
4857
+ ]);
4858
+ /** A long flag's name as typed: letters, digits and dashes, starting with a letter. Anything else is not recorded. */
4859
+ const LONG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;
4860
+ /**
4861
+ * The **names** of the flags given on a command line (spec `tech-discord-notifications-v2`, step 6): `--dry-run`,
4862
+ * `--env=prod` and `-y` give `dry-run`, `env` and `y`. Never a value, never a positional.
4863
+ *
4864
+ * It reads the arguments as typed, not yargs' `argv`, because `argv` also holds every default and the camelCase twin of
4865
+ * each kebab-case flag. Reading stops at a bare `--` (what follows is for another program). A value that only looks like
4866
+ * a flag is still only a name, and a short cluster (`-abc`) or a name with other characters is left out, so a value
4867
+ * that starts with a dash cannot leak through.
4868
+ *
4869
+ * @param args - The command line without the program and script (`process.argv.slice(2)`).
4870
+ * @returns The names in the order first given, once each.
4871
+ */
4872
+ function commandFlagNames(args) {
4873
+ const names = [];
4874
+ for (const arg of args) {
4875
+ if (arg === "--") break;
4876
+ let name;
4877
+ if (arg.startsWith("--")) name = arg.slice(2).split("=")[0];
4878
+ else if (/^-[A-Za-z](=|$)/.test(arg)) name = arg.slice(1, 2);
4879
+ if (name === void 0 || !LONG_NAME.test(name) || IGNORED.has(name) || names.includes(name)) continue;
4880
+ names.push(name);
4881
+ }
4882
+ return names;
4883
+ }
4884
+ // src/observability/command-run-line/command-run-line.ts
4885
+ /**
4886
+ * The one line posted for a command run: `🤖 claude ran sync specs --dry-run (exit 0, 1.2s) in theholocron/holocron`.
4887
+ * Text only, from names the CLI itself checked: the actor's name, the command words, flag names, the exit code, the
4888
+ * duration and the repository.
4889
+ */
4890
+ function commandRunLine(input) {
4891
+ const who = input.actor.actor === "agent" ? `🤖 ${input.actor.agent ?? "unknown"}` : "🧑 human";
4892
+ const flags = input.flags.map((name) => name.length === 1 ? `-${name}` : `--${name}`);
4893
+ const ran = [input.command, ...flags].join(" ");
4894
+ const where = input.repo ? ` in ${input.repo}` : "";
4895
+ return `${who} ran ${ran} (exit ${input.exitCode}, ${(input.durationMs / 1e3).toFixed(1)}s)${where}`;
4896
+ }
4897
+ // src/observability/record-command-run/record-command-run.ts
4898
+ /** How long recording may take before the CLI stops waiting for it (spec `tech-discord-notifications-v2`, step 6). */
4899
+ const COMMAND_LOG_POST_TIMEOUT_MS = 2e3;
4900
+ /** True while a record is being made, so a post that somehow runs a command cannot record itself again. */
4901
+ let recording = false;
4902
+ /**
4903
+ * Record one command run (spec `tech-discord-notifications-v2`, step 6). Every run is one `command_run` event through
4904
+ * the CLI's logger, which ships to Axiom when a dataset and token are set. An agent's run (or any run, with
4905
+ * `notifications.commandLog: "all"`) is also posted as one line to the `agent-log` channel, or, when the run has a command thread open (step 7), as that
4906
+ * thread's last post. The whole path (the
4907
+ * logger's flush, the config read, the plugin load and the post) waits at most {@link COMMAND_LOG_POST_TIMEOUT_MS}.
4908
+ *
4909
+ * It never throws and never touches the exit code or the command's output: a missing provider or webhook, a refusal, a
4910
+ * timeout and a thrown error all end quietly. Nothing is recorded in CI or under test, for the commands in
4911
+ * `COMMAND_LOG_SKIPPED`, or while another record is being made.
4912
+ *
4913
+ * @param input - The run: names and numbers, never a value.
4914
+ * @param deps - The logger, the setting and the post.
4915
+ */
4916
+ async function recordCommandRun(input, deps) {
4917
+ if (recording || deps.disabled || isCommandLogSkipped(input.command)) return;
4918
+ recording = true;
4919
+ try {
4920
+ await within$1(record(input, deps), COMMAND_LOG_POST_TIMEOUT_MS);
4921
+ } catch {} finally {
4922
+ recording = false;
4923
+ }
4924
+ }
4925
+ /** The work of one record: log the event, start flushing the logger, read the setting and post when it says to. */
4926
+ async function record(input, deps) {
4927
+ deps.logger.info({
4928
+ event: "command_run",
4929
+ command: input.command,
4930
+ flags: [...input.flags],
4931
+ repo: input.repo,
4932
+ exit_code: input.exitCode,
4933
+ duration_ms: input.durationMs,
4934
+ actor: input.actor.actor,
4935
+ agent: input.actor.agent
4936
+ }, "command run");
4937
+ const flushed = deps.logger.flush().catch(() => void 0);
4938
+ const line = commandRunLine(input);
4939
+ if (!(deps.thread ? await deps.thread.finish(line) : false)) {
4940
+ const mode = await deps.mode();
4941
+ if (mode !== "off" && (mode === "all" || input.actor.actor === "agent")) await deps.post(line);
4942
+ }
4943
+ await flushed;
4944
+ }
4945
+ /** Wait for `work` for at most `ms`; a rejection is thrown to the caller, a late finish is ignored. */
4946
+ async function within$1(work, ms) {
4947
+ let timer;
4948
+ const timeout = new Promise((resolve) => {
4949
+ timer = setTimeout(resolve, ms);
4950
+ });
4951
+ work.catch(() => void 0);
4952
+ try {
4953
+ await Promise.race([work, timeout]);
4954
+ } finally {
4955
+ clearTimeout(timer);
4956
+ }
4957
+ }
4958
+ // src/observability/record-cli-run/record-cli-run.ts
4959
+ /**
4960
+ * Record the command that just ended (spec `tech-discord-notifications-v2`, step 6): the one call `cli.ts` makes after
4961
+ * the command's result is known. It turns what `cli.ts` has (yargs' words, the typed arguments, the start time and the
4962
+ * exit code) into the names and numbers `recordCommandRun()` takes, and never throws. `--help` and `--version` are not
4963
+ * commands that ran and are not recorded.
4964
+ *
4965
+ * @param input - The finished command.
4966
+ * @param deps - Who is running, the clock, the repository lookup and the recorder's dependencies.
4967
+ */
4968
+ async function recordCliRun(input, deps) {
4969
+ try {
4970
+ const command = commandPath(input.words);
4971
+ if (isInfoRun(input.args) || deps.record.disabled || isCommandLogSkipped(command)) return;
4972
+ await recordCommandRun({
4973
+ command,
4974
+ flags: commandFlagNames(input.args),
4975
+ exitCode: input.exitCode,
4976
+ durationMs: deps.now() - input.startedAt,
4977
+ repo: await deps.repo(input.cwd),
4978
+ actor: deps.actor
4979
+ }, deps.record);
4980
+ } catch {}
4981
+ }
4982
+ // src/observability/record-this-run/record-this-run.ts
4983
+ /** The CLI's logger as it is when a line is written: a handler may rebuild the root logger after the command starts. */
4984
+ const currentLogger = {
4985
+ info: (objOrMsg, msg) => getLogger().info(objOrMsg, msg),
4986
+ flush: () => getLogger().flush()
4987
+ };
4988
+ /**
4989
+ * Start recording the command that is about to run, with the real logger, environment, clock, git remote and plugin
4990
+ * loader. Besides keeping what `recordThisRun()` needs, this is where the run's Discord thread opens (step 7, spec
4991
+ * `tech-discord-notifications-v2`), in the background, so the command's own log lines can stream into it. A `--help` or
4992
+ * `--version` run starts nothing.
4993
+ *
4994
+ * @param start - The command as it starts.
4995
+ * @returns What `cli.ts` calls once the command has ended.
4996
+ */
4997
+ function startThisRun(start) {
4998
+ const actor = detectActor();
4999
+ const record = isInfoRun(start.args) ? void 0 : createCommandRunDeps({
5000
+ cwd: start.cwd,
5001
+ org: start.org,
5002
+ command: commandPath(start.words),
5003
+ actor,
5004
+ logger: currentLogger
5005
+ });
5006
+ return { async record(input) {
5007
+ if (!record) return;
5008
+ await recordCliRun(input, {
5009
+ record,
5010
+ actor,
5011
+ now: Date.now,
5012
+ repo: (cwd) => repoSlug(cwd).catch(() => void 0)
5013
+ });
5014
+ setLogTap(void 0);
5015
+ } };
5016
+ }
5017
+ // src/observability/resolve-telemetry/resolve-telemetry.ts
5018
+ const env$9 = holocronEnv();
5019
+ /**
5020
+ * Holocron-specific credential resolution for the telemetry sinks — the env
5021
+ * chain plus Holocron's own shipped fallbacks. This is **CLI policy**, not part
5022
+ * of the portable adapter set: `sentry-sink.ts` / `posthog-sink.ts` take a
5023
+ * resolved DSN / key and never read the environment. When the adapters move to
5024
+ * `@theholocron/observability` (#635) this module stays here.
5025
+ *
5026
+ * errors: HOLOCRON_SENTRY_DSN → SENTRY_DSN → FALLBACK_DSN
5027
+ * analytics: HOLOCRON_POSTHOG_PROJECT_TOKEN → POSTHOG_PROJECT_TOKEN → FALLBACK_POSTHOG_PROJECT_TOKEN
5028
+ * host: HOLOCRON_POSTHOG_HOST → POSTHOG_HOST → DEFAULT_POSTHOG_HOST
5029
+ *
5030
+ * The `SENTRY_DSN` / `POSTHOG_PROJECT_TOKEN` fallbacks are the vendor-native
5031
+ * names a consumer repo sets to route CLI telemetry to its own project. The
5032
+ * built-in fallbacks are ingest-only keys — publishable by design, same risk
5033
+ * model as ADR-0007 / ADR-0008.
5034
+ */
5035
+ /** Holocron's own Sentry project — the fallback when no env var points elsewhere. */
5036
+ const FALLBACK_DSN = "https://95cbb72ad5636c94e119a5405ee8f55f@o4508238154104832.ingest.us.sentry.io/4511810950791168";
5037
+ /** Holocron's own PostHog project write key — ingest-only. */
5038
+ const FALLBACK_POSTHOG_PROJECT_TOKEN = "phc_AC4vFCvYzwnzmG7Vg5nEc3PZKZztoPyfKp4Lb9BbXcLK";
5039
+ const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
5040
+ /** Resolve the Sentry DSN. `""` → error telemetry disabled. */
5041
+ function resolveDsn() {
5042
+ return env$9.get("SENTRY_DSN") ?? FALLBACK_DSN;
5043
+ }
5044
+ /** Resolve the PostHog project key. `""` → usage analytics disabled. */
5045
+ function resolvePostHogKey() {
5046
+ return env$9.get("POSTHOG_PROJECT_TOKEN") ?? FALLBACK_POSTHOG_PROJECT_TOKEN;
5047
+ }
5048
+ /** Resolve the PostHog ingest host. */
5049
+ function resolvePostHogHost() {
5050
+ return env$9.get("POSTHOG_HOST") ?? DEFAULT_POSTHOG_HOST;
5051
+ }
5052
+ // src/observability/telemetry/telemetry.ts
5053
+ /**
5054
+ * CLI self-telemetry — errors (Sentry), usage analytics (PostHog).
5055
+ *
5056
+ * The orchestration is `createCliTelemetry` in `@theholocron/kyber/observability`
5057
+ * (no vendor SDK import here either: the sinks live in `@theholocron/observability`).
5058
+ * This module binds it to Holocron's values: the `HOLOCRON` env prefix, the
5059
+ * credentials resolved by `resolve-telemetry.ts`, and the logger's run id.
5060
+ * The single kill switch is `HOLOCRON_TELEMETRY=false` (legacy alias
5061
+ * `NO_HOLOCRON_TELEMETRY`); see ADR-0007 / ADR-0008.
5062
+ */
5063
+ const telemetry = createCliTelemetry({
5064
+ envPrefix: PREFIX$1,
5065
+ dsn: resolveDsn,
5066
+ posthogKey: resolvePostHogKey,
5067
+ posthogHost: resolvePostHogHost,
5068
+ getRunId: () => getRunId()
5069
+ });
5070
+ /** Install the live sinks unless telemetry is opted out or a credential is empty. */
5071
+ const init = telemetry.init;
5072
+ /** Apply the `telemetry` config block; it only ever narrows what `init` turned on. */
5073
+ const applyConfig = telemetry.applyConfig;
5074
+ /** Capture a PostHog event, scrubbed of secrets. */
5075
+ const event = telemetry.event;
5076
+ /** Start a command span; call the returned function with the outcome. */
5077
+ const startCommand$1 = telemetry.startCommand;
5078
+ /** Report an error to Sentry. */
5079
+ const captureException = telemetry.captureException;
5080
+ /** End the Sentry session. */
5081
+ const endSession = telemetry.endSession;
5082
+ /** Drain both sinks and return to the no-ops. */
5083
+ const flush = telemetry.flush;
5084
+ telemetry.resetTelemetry;
5085
+ // src/commands/apply-resolved-config/apply-resolved-config.ts
5086
+ /**
5087
+ * `buildCliLogger` options derived from a loaded `holocron.config` — the
5088
+ * level, the Axiom dataset, and the resolved org for a keyring-backed
5089
+ * Axiom token. Used by every handler that has already called `loadConfig`.
5090
+ */
5091
+ function cliLoggerOpts(argv, resolved) {
5092
+ return {
5093
+ configLevel: resolved.log?.level,
5094
+ configAxiomDataset: resolved.log?.axiom?.dataset,
5095
+ org: resolveOrg(argv, resolved)
5096
+ };
5097
+ }
5098
+ /**
5099
+ * Fold a loaded `holocron.config` into the running process: reconfigure the
5100
+ * logger from `log:`, then apply the `telemetry:` override layer. Every handler
5101
+ * that has called `loadConfig` runs this, so a repo's `telemetry.enabled: false`
5102
+ * (or `analytics: "none"`) is honoured for that command. Env still wins —
5103
+ * `applyConfig` only narrows what `init` already turned on.
5104
+ */
5105
+ function applyResolvedConfig(argv, resolved) {
5106
+ buildCliLogger(argv, cliLoggerOpts(argv, resolved));
5107
+ applyConfig(resolved.telemetry);
5108
+ }
5109
+ // src/commands/token-context/token-context.ts
5110
+ /** Parses --token values and returns the context spread, or null on parse error (exits with code 1). */
5111
+ function tokenContext(rawTokens) {
5112
+ return tokenContext$1(rawTokens, reportError);
5113
+ }
4540
5114
  // src/commands/issue-types/classify-type-error/classify-type-error.ts
4541
5115
  /** Reads a thrown error as one of the four things `ensureIssueTypes()` acts on differently. */
4542
5116
  function classifyTypeError(err) {
@@ -5080,7 +5654,8 @@ async function provisionChannel(deps, spec) {
5080
5654
  ...spec.access ? { access: spec.access } : {},
5081
5655
  ...spec.kind ? { kind: spec.kind } : {},
5082
5656
  ...spec.tags ? { tags: spec.tags } : {},
5083
- ...spec.defaultReaction ? { defaultReaction: spec.defaultReaction } : {}
5657
+ ...spec.defaultReaction ? { defaultReaction: spec.defaultReaction } : {},
5658
+ ...spec.autoArchiveMinutes ? { autoArchiveMinutes: spec.autoArchiveMinutes } : {}
5084
5659
  });
5085
5660
  const changed = channel.created || (channel.updated?.length ?? 0) > 0;
5086
5661
  const verb = channel.created ? "created" : changed ? "updated" : "exists ";
@@ -8290,7 +8865,7 @@ const row$37 = (id, status, detail) => ({
8290
8865
  */
8291
8866
  async function abandonWork(a) {
8292
8867
  const { input, key, source, pullRequest: pr } = a;
8293
- const git = input.git ?? runGit;
8868
+ const git = input.git ?? runGit$1;
8294
8869
  const repoRoot = input.context.repoRoot;
8295
8870
  const dryRun = Boolean(input.context.dryRun);
8296
8871
  const rows = [];
@@ -8902,7 +9477,7 @@ async function readIssueBoards(input) {
8902
9477
  /** The real git and file system {@link runStartWork} runs against; tests pass a fake. */
8903
9478
  function createRealStartWorkIo() {
8904
9479
  return {
8905
- git: runGit,
9480
+ git: runGit$1,
8906
9481
  exists: (path) => existsSync(path),
8907
9482
  read: (path) => readFileSync(path, "utf8"),
8908
9483
  write: (path, text) => {
@@ -10385,7 +10960,7 @@ async function runCloseWork(input) {
10385
10960
  return finish();
10386
10961
  }
10387
10962
  if (!pr) return fail("pull request", `no pull request for ${key} (its branch is <type>/<issue>-<slug>; --pr names one)`);
10388
- const git = input.git ?? runGit;
10963
+ const git = input.git ?? runGit$1;
10389
10964
  const repoRoot = input.context.repoRoot;
10390
10965
  if (pr.state === "closed") {
10391
10966
  if (!pr.merged) {
@@ -15660,6 +16235,7 @@ function forumFeedChecks(input, spec) {
15660
16235
  const forumProblems = [];
15661
16236
  const tagProblems = [];
15662
16237
  const botProblems = [];
16238
+ const leftOver = [];
15663
16239
  for (const { cat, channel } of fed) {
15664
16240
  const name = shown$6(channel.name);
15665
16241
  const have = found.channels.find((c) => same$6(c.name, channel.name) && c.category !== void 0 && same$6(c.category, cat));
@@ -15672,6 +16248,8 @@ function forumFeedChecks(input, spec) {
15672
16248
  continue;
15673
16249
  }
15674
16250
  for (const tag of spec.tags) if (!have.tags?.some((t) => same$6(t.name, tag))) tagProblems.push(`#${name}: tag "${tag}" is missing`);
16251
+ const old = spec.retired?.tag;
16252
+ if (old && have.tags?.some((t) => same$6(t.name, old))) leftOver.push(`#${name}`);
15675
16253
  if (have.botThreadsError) botProblems.push(`#${name}: could not read the bot's permissions (${shown$6(have.botThreadsError)})`);
15676
16254
  else if (have.botThreads) {
15677
16255
  if (!have.botThreads.post) botProblems.push(`#${name}: the bot cannot start posts or reply in it`);
@@ -15679,11 +16257,13 @@ function forumFeedChecks(input, spec) {
15679
16257
  } else botProblems.push(`#${name}: the provider did not report the bot's permissions`);
15680
16258
  }
15681
16259
  const ok = `${fed.length} of ${fed.length} as declared`;
15682
- return [
16260
+ const rows = [
15683
16261
  resultRow(spec.ids.forum, forumTitle, forumProblems, ok),
15684
16262
  resultRow(spec.ids.tags, tagsTitle, tagProblems, ok),
15685
16263
  resultRow(spec.ids.bot, botTitle, botProblems, ok)
15686
16264
  ];
16265
+ if (spec.retired && leftOver.length > 0) rows.push(skipRow$1(spec.retired.id, `${spec.label} forum has no retired tag`, `${leftOver.join(", ")} still has the tag "${spec.retired.tag}", which no post uses now; \`setup\` never deletes a tag, so delete it in Discord`));
16266
+ return rows;
15687
16267
  }
15688
16268
  // src/commands/notifications-setup/layout-picture-problem/layout-picture-problem.ts
15689
16269
  /** The first reason a picture in the layout (`webhookAvatar`, a channel's `webhook.avatar`) cannot work, or undefined. */
@@ -16194,10 +16774,17 @@ const PR_FEED_TAGS = [
16194
16774
  "failing",
16195
16775
  "changes requested",
16196
16776
  "ready",
16197
- "waiting",
16777
+ "in review",
16198
16778
  "merged",
16199
16779
  "closed"
16200
16780
  ];
16781
+ /** The idle times, in minutes, Discord allows a forum's posts before they are archived. */
16782
+ const AUTO_ARCHIVE_MINUTES = [
16783
+ 60,
16784
+ 1440,
16785
+ 4320,
16786
+ 10080
16787
+ ];
16201
16788
  /** The states an incident's post can be tagged with, so a forum with `feeds.incidents` must have all of them (lower case). */
16202
16789
  const INCIDENT_FEED_TAGS = [
16203
16790
  "investigating",
@@ -16221,6 +16808,7 @@ function forumLayoutProblem(layout) {
16221
16808
  const where = `channel \`${channel.name}\``;
16222
16809
  if (channel.kind !== "forum") {
16223
16810
  if (channel.tags) return `${where}: \`tags\` belong to a forum -- set \`kind: "forum"\` or remove them`;
16811
+ if (channel.autoArchiveMinutes !== void 0) return `${where}: \`autoArchiveMinutes\` belongs to a forum -- set \`kind: "forum"\` or remove it`;
16224
16812
  if (channel.defaultReaction || channel.starterReactions) return `${where}: reactions belong to a forum -- set \`kind: "forum"\` or remove them`;
16225
16813
  if (channel.feeds?.prs) return `${where}: \`feeds.prs\` belongs to a forum, where each pull request is a post -- set \`kind: "forum"\` or remove it`;
16226
16814
  if (channel.feeds?.incidents) return `${where}: \`feeds.incidents\` belongs to a forum, where each incident is a post -- set \`kind: "forum"\` or remove it`;
@@ -16235,6 +16823,9 @@ function forumLayoutProblem(layout) {
16235
16823
  const problem = reactionProblem("a starter reaction", reaction);
16236
16824
  if (problem) return `${where}: ${problem}`;
16237
16825
  }
16826
+ if (channel.autoArchiveMinutes !== void 0 && !AUTO_ARCHIVE_MINUTES.includes(channel.autoArchiveMinutes)) return `${where}: \`autoArchiveMinutes\` must be one of ${AUTO_ARCHIVE_MINUTES.join(", ")} (Discord's values), not ${String(channel.autoArchiveMinutes)}`;
16827
+ const retain = typeof channel.feeds?.prs === "object" ? channel.feeds.prs.retainDays : void 0;
16828
+ if (retain !== void 0 && (!Number.isInteger(retain) || retain < 1)) return `${where}: \`feeds.prs.retainDays\` must be a positive whole number of days, not ${String(retain)}`;
16238
16829
  const seen = /* @__PURE__ */ new Set();
16239
16830
  for (const tag of channel.tags ?? []) {
16240
16831
  const name = tag.name.trim().toLowerCase();
@@ -16686,6 +17277,7 @@ async function runNotificationsSetup(input$1) {
16686
17277
  ...channel.kind ? { kind: channel.kind } : {},
16687
17278
  ...channel.tags ? { tags: channel.tags } : {},
16688
17279
  ...channel.defaultReaction ? { defaultReaction: channel.defaultReaction } : {},
17280
+ ...channel.autoArchiveMinutes ? { autoArchiveMinutes: channel.autoArchiveMinutes } : {},
16689
17281
  ...webhook ? { webhook } : {},
16690
17282
  ...channel.feeds?.monitoring || channel.feeds?.errors || relayFeedsOf(channel).length > 0 ? { feeds: {
16691
17283
  ...channel.feeds?.monitoring ? { monitoring: {
@@ -17652,7 +18244,11 @@ function prFeedChecks(input) {
17652
18244
  bot: "pr-feed-bot"
17653
18245
  },
17654
18246
  label: "pull request feed",
17655
- tags: PR_FEED_TAGS
18247
+ tags: PR_FEED_TAGS,
18248
+ retired: {
18249
+ id: "pr-feed-retired-tag",
18250
+ tag: "waiting"
18251
+ }
17656
18252
  });
17657
18253
  }
17658
18254
  // src/commands/relay-checks/relay-checks.ts
@@ -18022,6 +18618,7 @@ async function runDoctorNotifications(input) {
18022
18618
  else if (isForum) {
18023
18619
  const wantReaction = channel.defaultReaction ? reactionSpelling(channel.defaultReaction) : void 0;
18024
18620
  if (wantReaction && (match.defaultReaction ?? "") !== wantReaction) channelProblems.push(`#${shown(channel.name)}: default reaction is ${match.defaultReaction ? `"${shown(match.defaultReaction)}"` : "not set"} but the layout says "${shown(wantReaction)}"`);
18621
+ if (channel.autoArchiveMinutes && match.autoArchiveMinutes !== channel.autoArchiveMinutes) channelProblems.push(`#${shown(channel.name)}: posts are archived after ${match.autoArchiveMinutes === void 0 ? "an unknown time" : `${match.autoArchiveMinutes} minutes`} idle but the layout says ${channel.autoArchiveMinutes}`);
18025
18622
  for (const tag of channel.tags ?? []) {
18026
18623
  const have = match.tags?.find((t) => same$2(t.name, tag.name));
18027
18624
  if (!have) channelProblems.push(`#${shown(channel.name)}: tag "${shown(tag.name)}" is missing`);
@@ -30852,7 +31449,7 @@ async function promptEffort() {
30852
31449
  }
30853
31450
  // src/commands/new-work/read-git-config/read-git-config.ts
30854
31451
  /** One `git config --get` value in a directory, or `undefined` when the key is unset or git fails. */
30855
- function readGitConfig(cwd, key, run = runGit) {
31452
+ function readGitConfig(cwd, key, run = runGit$1) {
30856
31453
  try {
30857
31454
  return run([
30858
31455
  "config",
@@ -41104,7 +41701,7 @@ function planIncidentFeed(input) {
41104
41701
  // src/commands/render-incident/render-incident.ts
41105
41702
  /** Discord's message limit is 2000; an update's text is cut well short of it, leaving room for its heading and marker. */
41106
41703
  const UPDATE_TEXT_LIMIT = 1500;
41107
- const TITLE_LIMIT = 100;
41704
+ const TITLE_LIMIT$1 = 100;
41108
41705
  const IMPACT_WORDS = {
41109
41706
  maintenance: "under maintenance",
41110
41707
  degraded: "degraded",
@@ -41152,7 +41749,7 @@ function renderIncident(incident, statusPage) {
41152
41749
  lines.push(statusPage.url ? `Status page: [${statusPage.name}](<${statusPage.url}>)` : `Status page: ${statusPage.name}`);
41153
41750
  lines.push(incidentMarker(incident.id));
41154
41751
  return {
41155
- title: clip(incident.title, TITLE_LIMIT),
41752
+ title: clip(incident.title, TITLE_LIMIT$1),
41156
41753
  body: lines.join("\n"),
41157
41754
  tag
41158
41755
  };
@@ -41171,9 +41768,9 @@ function renderIncident(incident, statusPage) {
41171
41768
  */
41172
41769
  const DEFAULT_SINCE = "2d";
41173
41770
  /** How many of a post's messages are read to find the markers of its updates (Discord's limit per read). */
41174
- const MESSAGES = 100;
41771
+ const MESSAGES$1 = 100;
41175
41772
  /** The channel carrying the feed, and the name of the status page it follows. */
41176
- function feedOf(notifications, pages) {
41773
+ function feedOf$1(notifications, pages) {
41177
41774
  const fed = (notifications.layout?.categories ?? []).flatMap((c) => c.channels ?? []).filter((c) => c.feeds?.incidents);
41178
41775
  if (fed.length === 0) return { problem: "no forum in the layout has `feeds.incidents`" };
41179
41776
  if (fed.length > 1) return { problem: `several forums have \`feeds.incidents\` (${fed.map((c) => `\`${c.name}\``).join(", ")})` };
@@ -41215,7 +41812,7 @@ async function runSyncIncidents(input) {
41215
41812
  }
41216
41813
  const monitoring = loader.has("monitoring") ? loader.get("monitoring") : void 0;
41217
41814
  if (!monitoring?.listIncidents) return stop("skip", "no `monitoring` provider that lists status page incidents");
41218
- const feed = feedOf(notifications, monitoring.statusPages ?? []);
41815
+ const feed = feedOf$1(notifications, monitoring.statusPages ?? []);
41219
41816
  if ("problem" in feed) return stop(feed.problem.startsWith("no forum") ? "skip" : "fail", feed.problem);
41220
41817
  const { channel, page } = feed;
41221
41818
  const statusPage = {
@@ -41258,7 +41855,7 @@ async function runSyncIncidents(input) {
41258
41855
  incident,
41259
41856
  rendered,
41260
41857
  post,
41261
- messages: post ? await notifications.readDiscussionMessages(channel, key, MESSAGES) : []
41858
+ messages: post ? await notifications.readDiscussionMessages(channel, key, MESSAGES$1) : []
41262
41859
  });
41263
41860
  plans.push(plan);
41264
41861
  if (plan.steps.length === 0) {
@@ -41331,11 +41928,11 @@ async function apply(notifications, channel, key, rendered, plan) {
41331
41928
  quiet: true
41332
41929
  })).created) {
41333
41930
  if (await notifications.dedupeDiscussion(channel, key, { refresh: true }) > 0) {
41334
- const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES));
41931
+ const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES$1));
41335
41932
  append = append.filter((u) => !posted.has(u.id));
41336
41933
  }
41337
41934
  } else {
41338
- const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES));
41935
+ const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES$1));
41339
41936
  append = append.filter((u) => !posted.has(u.id));
41340
41937
  }
41341
41938
  } else if (plan.rewrite || plan.retag || plan.close === false) await notifications.updateDiscussion(channel, key, {
@@ -41643,6 +42240,443 @@ const syncIssuesCommand = {
41643
42240
  })).status === "fail") process.exitCode = 1;
41644
42241
  }
41645
42242
  };
42243
+ // src/pull-request-post/pr-key/pr-key.ts
42244
+ /** The key a pull request's post is found by: `owner/repo#123`. */
42245
+ function prKey(repo, number) {
42246
+ return `${repo}#${number}`;
42247
+ }
42248
+ // src/pull-request-post/pull-request-tag/pull-request-tag.ts
42249
+ /** The tag of a pull request: the first that applies of merged, closed, draft, conflicts, failing, changes requested, ready, in review. */
42250
+ function pullRequestTag(state) {
42251
+ if (state.merged) return "merged";
42252
+ if (state.closed) return "closed";
42253
+ if (state.draft) return "draft";
42254
+ if (state.mergeable === "conflicting") return "conflicts";
42255
+ if (state.ci === "failing") return "failing";
42256
+ if (state.review === "changes_requested") return "changes requested";
42257
+ if (state.review === "approved" && state.ci === "passing") return "ready";
42258
+ return "in review";
42259
+ }
42260
+ // src/pull-request-post/age-text/age-text.ts
42261
+ const MINUTE = 6e4;
42262
+ const HOUR = 60 * MINUTE;
42263
+ const DAY$1 = 24 * HOUR;
42264
+ /** How long ago something happened, in the largest whole unit: `just now`, `5 minutes ago`, `1 hour ago`, `3 days ago`. */
42265
+ function ageText(createdAt, now) {
42266
+ const elapsed = Math.max(0, now.getTime() - new Date(createdAt).getTime());
42267
+ if (elapsed < MINUTE) return "just now";
42268
+ const [value, unit] = elapsed >= DAY$1 ? [Math.floor(elapsed / DAY$1), "day"] : elapsed >= HOUR ? [Math.floor(elapsed / HOUR), "hour"] : [Math.floor(elapsed / MINUTE), "minute"];
42269
+ return `${value} ${unit}${value === 1 ? "" : "s"} ago`;
42270
+ }
42271
+ /** What Sourcery writes between its start and end markers, e.g. the reviewer's guide. */
42272
+ const SOURCERY_BLOCK = /<!--\s*Generated by sourcery-ai[^>]*?start\s+(\w+)\s*-->[\s\S]*?<!--\s*Generated by sourcery-ai[^>]*?end\s+\1\s*-->/gi;
42273
+ /** Sourcery's auto-generated summary starts at this marker and runs to the end of the description. */
42274
+ const SOURCERY_SUMMARY = /<!--\s*This is an auto-generated description by sourcery-ai\.?\s*-->[\s\S]*$/i;
42275
+ /** A command someone typed to Sourcery (`@sourcery-ai summary`). */
42276
+ const SOURCERY_COMMAND = /^.*@sourcery-ai\b.*$/gim;
42277
+ /** Drops each heading that names Sourcery with its section, up to the next heading of the same or a higher level. */
42278
+ function withoutSourcerySections(text) {
42279
+ const kept = [];
42280
+ let skipping = 0;
42281
+ for (const line of text.split("\n")) {
42282
+ const heading = /^(#{1,6})\s/.exec(line);
42283
+ if (heading) {
42284
+ const level = heading[1].length;
42285
+ if (/sourcery/i.test(line)) {
42286
+ skipping = level;
42287
+ continue;
42288
+ }
42289
+ if (skipping > 0 && level <= skipping) skipping = 0;
42290
+ }
42291
+ if (skipping === 0) kept.push(line);
42292
+ }
42293
+ return kept.join("\n");
42294
+ }
42295
+ /**
42296
+ * `text` without its HTML comments, repeated until none is left: taking one out can join the pieces around it into a new
42297
+ * one (`<!<!-- x -->-- y -->`), which a single pass would leave in the post.
42298
+ */
42299
+ function withoutHtmlComments(text) {
42300
+ let current = text;
42301
+ for (;;) {
42302
+ const next = current.replace(/<!--[\s\S]*?-->/g, "");
42303
+ if (next === current) return next;
42304
+ current = next;
42305
+ }
42306
+ }
42307
+ /**
42308
+ * The part of a pull request's description worth showing in its post: the text the author wrote. Sourcery's summary,
42309
+ * reviewer's guide and commands are removed, and so is every HTML comment (a template's hints), the blank runs they
42310
+ * leave are closed up, and what is left is cut to {@link DESCRIPTION_LIMIT} characters with an ellipsis. A description
42311
+ * with nothing left, or none, is an empty string.
42312
+ */
42313
+ function prDescription(body) {
42314
+ if (!body) return "";
42315
+ const text = withoutHtmlComments(withoutSourcerySections(body.replace(/\r\n?/g, "\n").replace(SOURCERY_BLOCK, "").replace(SOURCERY_SUMMARY, "")).replace(SOURCERY_COMMAND, "")).replace(/\n{3,}/g, "\n\n").trim();
42316
+ return text.length <= 1500 ? text : `${text.slice(0, 1499).trimEnd()}…`;
42317
+ }
42318
+ // src/pull-request-post/render-pull-request/render-pull-request.ts
42319
+ /** Discord's limit on a post's title. */
42320
+ const TITLE_LIMIT = 100;
42321
+ const CI_TEXT = {
42322
+ passing: "passing",
42323
+ failing: "failing",
42324
+ pending: "running",
42325
+ none: "no result yet"
42326
+ };
42327
+ function cut(text) {
42328
+ return text.length <= TITLE_LIMIT ? text : `${text.slice(0, 99)}…`;
42329
+ }
42330
+ function reviewText(state) {
42331
+ if (state.review === "approved") return "approved";
42332
+ if (state.review === "changes_requested") return "changes requested";
42333
+ if (state.requestedReviewers.length > 0) return `waiting on review from ${state.requestedReviewers.join(", ")}`;
42334
+ return "waiting on review";
42335
+ }
42336
+ /**
42337
+ * The post for a pull request: its title (`repo#123: title`, plain text, because a forum post's title is not
42338
+ * markdown), the summary that is the first message (edited in place, no footer: a link to the pull request without
42339
+ * repeating the title, the status lines and the author's description with Sourcery's parts removed) and its tag. A pure function of the current state; the caller fetches it, and the provider adds the sync footer.
42340
+ */
42341
+ function renderPullRequest(state, now) {
42342
+ const tag = pullRequestTag(state);
42343
+ const name = state.repo.slice(state.repo.indexOf("/") + 1);
42344
+ const author = state.authorIsBot ? `${state.author} (bot)` : state.author;
42345
+ const status = state.merged ? "merged" : state.closed ? "closed" : state.draft ? "draft" : reviewText(state);
42346
+ const lines = [
42347
+ `**[${state.repo}#${state.number}](${state.url})**`,
42348
+ `by ${author} into \`${state.base}\`, opened ${ageText(state.createdAt, now)}`,
42349
+ `Status: ${status}`,
42350
+ `CI: ${CI_TEXT[state.ci]}`
42351
+ ];
42352
+ if (state.mergeable === "conflicting") lines.push(`Conflicts with \`${state.base}\``);
42353
+ const description = prDescription(state.body);
42354
+ const body = description ? `${lines.join("\n")}\n\n${description}` : lines.join("\n");
42355
+ return {
42356
+ title: cut(`${name}#${state.number}: ${state.title}`),
42357
+ body,
42358
+ tag
42359
+ };
42360
+ }
42361
+ // src/commands/first-message-body/first-message-body.ts
42362
+ /**
42363
+ * The text of a post's first message without the footer the provider ends it with (`-# sync: <key> | <state>`), found
42364
+ * among its recent messages (newest first) by that footer; `undefined` when the message is not among them, as when the
42365
+ * thread is longer than one read.
42366
+ */
42367
+ function firstMessageBody(messages, key) {
42368
+ const footer = `-# sync: ${key} |`;
42369
+ for (const message of messages) {
42370
+ const at = message.lastIndexOf(`\n\n${footer}`);
42371
+ if (at >= 0) return message.slice(0, at);
42372
+ }
42373
+ }
42374
+ // src/commands/plan-pull-request-post/plan-pull-request-post.ts
42375
+ /** The age in the summary's second line (`opened 5 minutes ago`), which changes by the minute and so is not a difference. */
42376
+ const AGE = /, opened (?:just now|\d+ (?:minute|hour|day)s? ago)/;
42377
+ /** Whether the first message's text must be written again: it differs, apart from the age and a cut made to fit Discord's limit. */
42378
+ function bodyDiffers(existing, wanted) {
42379
+ if (existing === void 0) return false;
42380
+ const had = existing.replace(AGE, ", opened");
42381
+ const want = wanted.replace(AGE, ", opened");
42382
+ if (had === want) return false;
42383
+ return !(had.endsWith("…") && want.startsWith(had.slice(0, -1)));
42384
+ }
42385
+ /**
42386
+ * What a pull request's post needs: its tag (set back when a person changed it: Discord never sets a pull request's
42387
+ * state), its title, the text of its first message and whether it is archived. Pure, and the one comparison
42388
+ * `holocron sync prs` uses. Messages the feed appends (the CI and lifecycle lines) are never part of it.
42389
+ */
42390
+ function planPullRequestPost(input) {
42391
+ const { rendered, post } = input;
42392
+ const steps = [];
42393
+ const patch = {};
42394
+ if (post.state !== rendered.tag) {
42395
+ steps.push(post.state === void 0 ? `tag set to \`${rendered.tag}\`` : `tag set back to \`${rendered.tag}\` (was \`${post.state}\`)`);
42396
+ patch.state = rendered.tag;
42397
+ }
42398
+ if (post.title !== void 0 && post.title !== rendered.title) {
42399
+ steps.push("title updated");
42400
+ patch.title = rendered.title;
42401
+ }
42402
+ if (bodyDiffers(input.firstBody, rendered.body)) {
42403
+ steps.push("first message updated");
42404
+ patch.body = rendered.body;
42405
+ }
42406
+ if ((post.closed ?? false) !== input.closed) {
42407
+ steps.push(input.closed ? "archived and locked" : "opened again");
42408
+ patch.closed = input.closed;
42409
+ }
42410
+ return {
42411
+ steps,
42412
+ patch
42413
+ };
42414
+ }
42415
+ // src/commands/pull-request-post-expired/pull-request-post-expired.ts
42416
+ const DAY = 864e5;
42417
+ /**
42418
+ * Whether a closed pull request's post is past `feeds.prs.retainDays`: closed more than that many days before `now`. A
42419
+ * pull request with no known close time, or a feed with no `retainDays`, never is.
42420
+ */
42421
+ function pullRequestPostExpired(closedAt, retainDays, now) {
42422
+ if (retainDays === void 0 || closedAt === void 0) return false;
42423
+ return now.getTime() - new Date(closedAt).getTime() > retainDays * DAY;
42424
+ }
42425
+ // src/commands/sync-prs/map-in-batches/map-in-batches.ts
42426
+ /** Runs `fn` over `items`, `size` at a time, and returns the results in the order of the items. */
42427
+ async function mapInBatches(items, size, fn) {
42428
+ const results = [];
42429
+ for (let i = 0; i < items.length; i += size) results.push(...await Promise.all(items.slice(i, i + size).map(fn)));
42430
+ return results;
42431
+ }
42432
+ // src/commands/sync-prs/run-sync-prs/run-sync-prs.ts
42433
+ /**
42434
+ * `holocron sync prs` -- keep the pull request forum's posts in step with GitHub (spec `tech-discord-notifications-v2`,
42435
+ * step 3, #2853).
42436
+ *
42437
+ * Sentinel's feed writes a post on each webhook delivery; a missed delivery, an outage or a hand-changed tag leaves a
42438
+ * post wrong until the next event. This reads the repository's open pull requests, each as `Source.readPullRequestState`
42439
+ * gives it, and the forum's posts, and puts each post's tag, title and first message right through the same
42440
+ * `renderPullRequest()` the feed uses, and archives the post of a pull request that is closed or merged. Discord does
42441
+ * not set a pull request's state: a tag a person changed is set back, and the row says so. A post whose pull request is
42442
+ * gone and a key with several posts are reported and left alone; a missing post is left to the feed. When
42443
+ * `feeds.prs.retainDays` is set, the post of a pull request closed longer ago than that is deleted, unless a person
42444
+ * wrote in it. The messages the feed appends (CI and lifecycle lines) are never touched. It reads state, so a second run
42445
+ * changes nothing. A rate limit (429) stops the run and the next one continues. It writes, so it asks first; `--yes`
42446
+ * skips the question and, without a terminal, a run with neither `--yes` nor `--dry-run` refuses.
42447
+ */
42448
+ /** How many of a post's messages are read to find its first one (Discord's limit per read). */
42449
+ const MESSAGES = 100;
42450
+ /** How many pull requests are read from GitHub and Discord at once. */
42451
+ const BATCH = 4;
42452
+ /** The forum that carries the pull request feed, or why there is none. */
42453
+ function feedOf(notifications) {
42454
+ const fed = (notifications.layout?.categories ?? []).flatMap((c) => c.channels ?? []).filter((c) => c.feeds?.prs);
42455
+ if (fed.length === 0) return { problem: "no forum in the layout has `feeds.prs`" };
42456
+ if (fed.length > 1) return { problem: `several forums have \`feeds.prs\` (${fed.map((c) => `\`${c.name}\``).join(", ")})` };
42457
+ return { channel: fed[0] };
42458
+ }
42459
+ async function runSyncPrs(input) {
42460
+ const print = input.print ?? ((line) => console.log(line));
42461
+ const row = (status, ...parts) => print(statusRow$1(status, ["sync prs", ...parts]));
42462
+ const stop = (status, reason) => {
42463
+ row(status, reason);
42464
+ return {
42465
+ status,
42466
+ reason
42467
+ };
42468
+ };
42469
+ const now = input.now ?? /* @__PURE__ */ new Date();
42470
+ const dryRun = Boolean(input.context.dryRun);
42471
+ /* v8 ignore next -- the real loader is only built outside tests, which always inject one */
42472
+ const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
42473
+ await loader.load();
42474
+ assertPluginsResolvable(loader, "sync prs");
42475
+ let notifications;
42476
+ try {
42477
+ notifications = pickDiscussionProvider(notificationProviders(loader), input.provider);
42478
+ } catch (err) {
42479
+ return stop("skip", errorMessage(err));
42480
+ }
42481
+ if (!notifications.listDiscussions || !notifications.readDiscussionMessages) return stop("fail", `the \`${notifications.providerName}\` provider cannot list or read discussion posts`);
42482
+ const feed = feedOf(notifications);
42483
+ if ("problem" in feed) return stop(feed.problem.startsWith("no forum") ? "skip" : "fail", feed.problem);
42484
+ const channel = feed.channel.name;
42485
+ const prsFeed = feed.channel.feeds.prs;
42486
+ const retainDays = typeof prsFeed === "object" ? prsFeed.retainDays : void 0;
42487
+ const exclude = typeof prsFeed === "object" ? prsFeed.exclude : void 0;
42488
+ if (retainDays !== void 0 && !notifications.deleteDiscussion) return stop("fail", `\`feeds.prs.retainDays\` is set but the \`${notifications.providerName}\` provider cannot delete a post`);
42489
+ const source = loader.has("source") ? loader.get("source") : void 0;
42490
+ if (!source) return stop("skip", "no `source` provider to read pull requests from");
42491
+ if (!source.listPullRequests || !source.readPullRequestState) return stop("fail", `the \`${source.providerName}\` provider cannot read a pull request's state`);
42492
+ const repo = input.context.repo ?? (input.context.org && input.loaded.resolved.name ? `${input.context.org}/${input.loaded.resolved.name}` : void 0);
42493
+ if (!repo) return stop("fail", "cannot tell which repository this is; run it from a checkout with a name and an org");
42494
+ if (exclude?.repos?.includes(repo)) return stop("skip", `\`feeds.prs.exclude\` leaves ${repo} out`);
42495
+ const excludedAuthors = new Set((exclude?.authors ?? []).map((a) => a.toLowerCase()));
42496
+ const counts = {
42497
+ updated: 0,
42498
+ deleted: 0,
42499
+ unchanged: 0,
42500
+ reported: 0,
42501
+ failed: 0,
42502
+ left: 0
42503
+ };
42504
+ let posts;
42505
+ let open;
42506
+ let required;
42507
+ try {
42508
+ if (aggregatePoster({ ci: input.loaded.resolved.ci }) === "none") required = (await resolveRequiredChecks({
42509
+ source,
42510
+ config: input.loaded.resolved
42511
+ })).required;
42512
+ [posts, open] = await Promise.all([notifications.listDiscussions(channel), source.listPullRequests("open", repo)]);
42513
+ } catch (err) {
42514
+ return stop("fail", `reading the pull requests and #${channel}: ${describeError(err)}`);
42515
+ }
42516
+ const prefix = prKey(repo, 0).slice(0, -1);
42517
+ const mine = /* @__PURE__ */ new Map();
42518
+ for (const post of posts) {
42519
+ const rest = post.key?.startsWith(prefix) ? post.key.slice(prefix.length) : "";
42520
+ if (/^\d+$/.test(rest)) mine.set(Number(rest), post);
42521
+ }
42522
+ for (const post of mine.values()) if (post.duplicates) {
42523
+ counts.reported++;
42524
+ row("skip", post.key, `${post.duplicates} more post(s) carry this key; \`holocron cleanup posts\` removes them`);
42525
+ }
42526
+ const finished = (post) => post.closed && (post.state === "merged" || post.state === "closed");
42527
+ const numbers = [.../* @__PURE__ */ new Set([...open.map((p) => p.number), ...mine.keys()])].filter((n) => {
42528
+ if (open.some((p) => p.number === n) || retainDays !== void 0) return true;
42529
+ if (finished(mine.get(n))) {
42530
+ counts.unchanged++;
42531
+ return false;
42532
+ }
42533
+ return true;
42534
+ });
42535
+ let limited = false;
42536
+ const looked = await mapInBatches(numbers, BATCH, async (number) => {
42537
+ const key = prKey(repo, number);
42538
+ if (limited) return { kind: "left" };
42539
+ try {
42540
+ const state = await source.readPullRequestState(number, repo, required);
42541
+ if (!state) return {
42542
+ kind: "gone",
42543
+ key
42544
+ };
42545
+ if (excludedAuthors.has(state.author.toLowerCase())) return { kind: "excluded" };
42546
+ const post = mine.get(number);
42547
+ if (!post) return {
42548
+ kind: "no-post",
42549
+ key
42550
+ };
42551
+ if (state.closed && pullRequestPostExpired(state.closedAt, retainDays, now)) return {
42552
+ kind: "work",
42553
+ work: {
42554
+ key,
42555
+ steps: [`deleted (closed more than ${retainDays} day(s) ago)`],
42556
+ patch: {},
42557
+ remove: true
42558
+ }
42559
+ };
42560
+ const messages = await notifications.readDiscussionMessages(channel, key, MESSAGES);
42561
+ const plan = planPullRequestPost({
42562
+ rendered: renderPullRequest(state, now),
42563
+ closed: state.closed,
42564
+ post,
42565
+ firstBody: firstMessageBody(messages, key)
42566
+ });
42567
+ return plan.steps.length === 0 ? { kind: "same" } : {
42568
+ kind: "work",
42569
+ work: {
42570
+ key,
42571
+ steps: plan.steps,
42572
+ patch: plan.patch
42573
+ }
42574
+ };
42575
+ } catch (err) {
42576
+ if (rateLimitedFor(err) !== void 0) {
42577
+ limited = true;
42578
+ return { kind: "left" };
42579
+ }
42580
+ return {
42581
+ kind: "fail",
42582
+ key,
42583
+ reason: describeError(err)
42584
+ };
42585
+ }
42586
+ });
42587
+ const work = [];
42588
+ for (const item of looked) if (item.kind === "work") work.push(item.work);
42589
+ else if (item.kind === "same") counts.unchanged++;
42590
+ else if (item.kind === "left") counts.left++;
42591
+ else if (item.kind === "gone") {
42592
+ counts.reported++;
42593
+ row("skip", item.key, "its pull request was not found; the post is left alone");
42594
+ } else if (item.kind === "no-post") {
42595
+ counts.reported++;
42596
+ row("skip", item.key, "has no post yet; the feed makes it on the pull request's next event");
42597
+ } else if (item.kind === "fail") {
42598
+ counts.failed++;
42599
+ row("fail", item.key, `reading it: ${item.reason}`);
42600
+ }
42601
+ if (dryRun) {
42602
+ for (const w of work) row("skip", w.key, `would be: ${w.steps.join("; ")}`);
42603
+ row("skip", `dry run, nothing written; ${work.length} post(s) would change, ${counts.unchanged} in step`);
42604
+ return {
42605
+ status: counts.failed > 0 ? "fail" : "ok",
42606
+ counts
42607
+ };
42608
+ }
42609
+ if (work.length > 0 && !input.yes) {
42610
+ if (!(input.interactive ?? Boolean(process.stdin.isTTY))) throw new NonInteractiveError(`\`sync prs\` changes posts in #${channel}; pass --yes to run it without asking, or --dry-run to look`);
42611
+ if (!await (input.confirm ?? ((message) => confirm({
42612
+ message,
42613
+ default: false
42614
+ })))(`Change ${work.length} pull request post(s) in #${channel}?`)) {
42615
+ row("skip", "cancelled; nothing was changed");
42616
+ return {
42617
+ status: "cancelled",
42618
+ counts
42619
+ };
42620
+ }
42621
+ }
42622
+ for (const [index, w] of work.entries()) try {
42623
+ if (w.remove) {
42624
+ if (await notifications.deleteDiscussion(channel, w.key)) {
42625
+ counts.deleted++;
42626
+ row("ok", w.key, w.steps.join("; "));
42627
+ } else {
42628
+ counts.reported++;
42629
+ row("skip", w.key, "kept past `retainDays`: a person has written in it");
42630
+ }
42631
+ } else {
42632
+ await notifications.updateDiscussion(channel, w.key, w.patch);
42633
+ counts.updated++;
42634
+ row("ok", w.key, w.steps.join("; "));
42635
+ }
42636
+ } catch (err) {
42637
+ if (rateLimitedFor(err) !== void 0) {
42638
+ counts.left += work.length - index;
42639
+ break;
42640
+ }
42641
+ counts.failed++;
42642
+ row("fail", w.key, describeError(err));
42643
+ }
42644
+ if (counts.left > 0) row("skip", `stopped: a service is rate limiting; ${counts.left} post(s) are left for the next run`);
42645
+ row(counts.failed > 0 ? "fail" : "ok", `#${channel}: updated ${counts.updated}, deleted ${counts.deleted}, unchanged ${counts.unchanged}, reported ${counts.reported}, failed ${counts.failed}, left ${counts.left}`);
42646
+ return {
42647
+ status: counts.failed > 0 ? "fail" : "ok",
42648
+ counts
42649
+ };
42650
+ }
42651
+ // src/commands/sync-prs/sync-prs.command.ts
42652
+ const syncPrsCommand = {
42653
+ command: "prs",
42654
+ describe: "Keep the pull request forum's posts in step with GitHub: tag, title and first message, and archive finished ones",
42655
+ builder: (y) => y.option("provider", {
42656
+ type: "string",
42657
+ describe: "The `notifications` provider to write through, when several are configured"
42658
+ }).option("yes", {
42659
+ type: "boolean",
42660
+ describe: "Change the posts without asking (a scheduled run needs it)"
42661
+ }),
42662
+ handler: async (argv) => {
42663
+ const tokens = tokenContext(argv.token);
42664
+ if (!tokens) return;
42665
+ const loaded = await loadConfig(argv.cwd);
42666
+ applyResolvedConfig(argv, loaded.resolved);
42667
+ if ((await runSyncPrs({
42668
+ loaded,
42669
+ context: {
42670
+ repoRoot: argv.cwd,
42671
+ dryRun: argv.dryRun,
42672
+ ...tokens,
42673
+ org: resolveOrg(argv, loaded.resolved)
42674
+ },
42675
+ ...argv.provider ? { provider: argv.provider } : {},
42676
+ ...argv.yes ? { yes: true } : {}
42677
+ })).status === "fail") process.exitCode = 1;
42678
+ }
42679
+ };
41646
42680
  // src/commands/sync-readme/generate-readme.ts
41647
42681
  /** Scripts that are neither a task nor a check: what a contributor runs while working (spec: "the dev scripts"). */
41648
42682
  const DEV_SCRIPTS = [
@@ -41926,6 +42960,77 @@ const syncReadmeCommand = {
41926
42960
  }
41927
42961
  }
41928
42962
  };
42963
+ // src/commands/sync-releases/run-git/run-git.ts
42964
+ /** The most output of one git call, so a long range is read whole and not cut by Node's 1 MiB default. */
42965
+ const MAX_BUFFER = 67108864;
42966
+ /** The real `git`: runs it in `cwd` and returns its output; throws when git fails. */
42967
+ const runGit = (cwd, args) => execFileSync("git", args, {
42968
+ cwd,
42969
+ encoding: "utf8",
42970
+ stdio: [
42971
+ "ignore",
42972
+ "pipe",
42973
+ "ignore"
42974
+ ],
42975
+ maxBuffer: MAX_BUFFER
42976
+ });
42977
+ // src/commands/sync-releases/release-changes/release-changes.ts
42978
+ /** A subject that is not a change worth announcing: the release bot's own commit. */
42979
+ const RELEASE_COMMIT = /^chore\(release\)!?:/i;
42980
+ /** A ticket reference line of a commit body: `Closes #1`, `Refs #2, #3`. Only these lines are read from a body. */
42981
+ const REFERENCE_LINE = /^(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?|refs?)\b[:\s]+(.*)$/i;
42982
+ const TRAILING_PR = /\s*\(#(\d+)\)\s*$/;
42983
+ /**
42984
+ * The changes of a release, newest first: each non-merge commit of `from..to` as its subject and the ticket numbers
42985
+ * it names (a trailing `(#123)` in the subject, and `Closes`/`Fixes`/`Resolves`/`Refs #N` lines of the body; nothing
42986
+ * else of the body is read). The release commits (`chore(release)`) are left out. Local git only, so it needs no
42987
+ * network call. With no `from` (a first release), or when git cannot read the range, there are no changes.
42988
+ *
42989
+ * @param cwd - The repository root.
42990
+ * @param from - The commit the release started from.
42991
+ * @param to - The release commit.
42992
+ * @param git - Runs git; tests pass a fake.
42993
+ */
42994
+ function releaseChanges(cwd, from, to, git = runGit) {
42995
+ if (!from) return [];
42996
+ let out;
42997
+ try {
42998
+ out = git(cwd, [
42999
+ "log",
43000
+ "--no-merges",
43001
+ "-z",
43002
+ "--format=%s%x00%b",
43003
+ `${from}..${to}`
43004
+ ]);
43005
+ } catch {
43006
+ return [];
43007
+ }
43008
+ const changes = [];
43009
+ const fields = out.split("\0");
43010
+ if (fields.length % 2 === 1) fields.push("");
43011
+ for (let at = 0; at < fields.length; at += 2) {
43012
+ const rawSubject = fields[at];
43013
+ const body = fields[at + 1];
43014
+ let subject = rawSubject.trim();
43015
+ if (!subject || RELEASE_COMMIT.test(subject)) continue;
43016
+ const issues = [];
43017
+ const pr = TRAILING_PR.exec(subject);
43018
+ if (pr) {
43019
+ subject = subject.slice(0, pr.index);
43020
+ issues.push(Number(pr[1]));
43021
+ }
43022
+ for (const line of body.split("\n")) {
43023
+ const refs = REFERENCE_LINE.exec(line.trim());
43024
+ if (!refs) continue;
43025
+ for (const m of refs[1].matchAll(/#(\d+)/g)) issues.push(Number(m[1]));
43026
+ }
43027
+ changes.push({
43028
+ subject,
43029
+ issues: [...new Set(issues)]
43030
+ });
43031
+ }
43032
+ return changes;
43033
+ }
41929
43034
  // src/commands/sync-releases/release-marker/release-marker.ts
41930
43035
  /**
41931
43036
  * The marker that ends a release's message: Discord's small-text line, so it is quiet to read, carrying the release id
@@ -42018,6 +43123,20 @@ function releasedPackages(cwd, from, to) {
42018
43123
  }
42019
43124
  return released.sort((a, b) => a.name.localeCompare(b.name));
42020
43125
  }
43126
+ // src/commands/sync-releases/change-line/change-line.ts
43127
+ /**
43128
+ * One change as a list item: its subject (type, scope and emoji kept) and a link per ticket,
43129
+ * `- feat(cli): add x [#1](https://github.com/o/r/issues/1)`. Without a repository the numbers are plain text. An `@`
43130
+ * in the subject is broken so a commit message cannot mention anyone, Markdown characters are escaped so it cannot
43131
+ * make a link or format the line, and `://` is broken so a bare address is not made a link.
43132
+ */
43133
+ function changeLine(change, repo) {
43134
+ return [
43135
+ "-",
43136
+ change.subject.replaceAll("@", "@​").replaceAll("://", ":​//").replace(/[\\[\]*_~`|<>]/g, "\\$&"),
43137
+ ...change.issues.map((n) => repo ? `[#${n}](https://github.com/${repo}/issues/${n})` : `#${n}`)
43138
+ ].join(" ");
43139
+ }
42021
43140
  // src/commands/sync-releases/package-line/package-line.ts
42022
43141
  /** The page of one version of a package on npm. */
42023
43142
  function npmVersionUrl(pkg) {
@@ -42035,21 +43154,40 @@ function packageLine(pkg) {
42035
43154
  // src/commands/sync-releases/render-release/render-release.ts
42036
43155
  /** Discord's limit on a thread's name. */
42037
43156
  const THREAD_NAME_LIMIT = 100;
43157
+ /** Discord's limit on a message, and the most changes the blurb lists. */
43158
+ const MESSAGE_LIMIT = 2e3;
43159
+ const MAX_CHANGES = 8;
42038
43160
  /**
42039
43161
  * The text of a release's announcement: a message with the headline, the link to the GitHub release (when a tag and
42040
43162
  * the repository are known) and the marker last, a thread name, and one list item per package that links to the
42041
- * version's page on npm. Chunking the lines to the provider's limit is the provider's job.
43163
+ * version's page on npm. With `changes`, up to eight of them follow the link (an `and N more` line when some are left
43164
+ * out or do not fit), and the whole message stays under Discord's 2,000 characters, cut on a line, never inside a link. Chunking the lines to the provider's limit is the provider's job.
42042
43165
  */
42043
43166
  function renderRelease(input) {
42044
- const { id, tag, repo, packages } = input;
43167
+ const { id, tag, repo, packages, changes = [] } = input;
42045
43168
  const count = packages.length;
42046
43169
  const tags = [...new Set(packages.map((p) => p.distTag))].join(", ");
43170
+ const head = [`**${tag ?? id}** released: ${count} package${count === 1 ? "" : "s"} on ${tags}`, ...tag && repo ? [`https://github.com/${repo}/releases/tag/${tag}`] : []];
43171
+ const marker = releaseMarker(id);
43172
+ const candidates = changes.slice(0, MAX_CHANGES).map((c) => changeLine(c, repo));
43173
+ const build = (kept) => {
43174
+ const left = changes.length - kept;
43175
+ return [
43176
+ ...head,
43177
+ ...candidates.slice(0, kept),
43178
+ ...left > 0 ? [`- and ${left} more`] : [],
43179
+ marker
43180
+ ].join("\n");
43181
+ };
43182
+ let kept = 0;
43183
+ while (kept < candidates.length && build(kept + 1).length < MESSAGE_LIMIT) kept++;
43184
+ let message = build(kept);
43185
+ if (message.length >= MESSAGE_LIMIT) {
43186
+ const room = MESSAGE_LIMIT - marker.length - 2;
43187
+ message = [head[0].slice(0, room), marker].join("\n");
43188
+ }
42047
43189
  return {
42048
- message: [
42049
- `**${tag ?? id}** released: ${count} package${count === 1 ? "" : "s"} on ${tags}`,
42050
- ...tag && repo ? [`https://github.com/${repo}/releases/tag/${tag}`] : [],
42051
- releaseMarker(id)
42052
- ].join("\n"),
43190
+ message,
42053
43191
  threadName: (tag ?? id).slice(0, THREAD_NAME_LIMIT),
42054
43192
  lines: packages.map(packageLine)
42055
43193
  };
@@ -42097,7 +43235,8 @@ async function runSyncReleases(input) {
42097
43235
  id,
42098
43236
  ...input.tag ? { tag: input.tag } : {},
42099
43237
  ...repo ? { repo } : {},
42100
- packages
43238
+ packages,
43239
+ changes: releaseChanges(input.context.repoRoot, input.from || void 0, input.to)
42101
43240
  });
42102
43241
  const marker = releaseMarker(id);
42103
43242
  if (dryRun) {
@@ -43502,7 +44641,7 @@ async function syncApp(argv) {
43502
44641
  const syncCommand = {
43503
44642
  command: "sync [steps..]",
43504
44643
  describe: "Sync state from config to the provider and local files (labels, properties, teams, topics, keywords, description, homepage, readme, workflows, scripts, wiki)",
43505
- builder: (y) => syncArgs(y).command(syncGithubCommand).command(syncIssuesCommand).command(syncIncidentsCommand).command(syncReleasesCommand).command(syncReadmeCommand).command(ideasSyncCommand).command(syncToolingCommand).command(syncRequestsCommand).command(specsSyncCommand).command(secretsSyncCommand).command(notificationsSyncRolesCommand),
44644
+ builder: (y) => syncArgs(y).command(syncGithubCommand).command(syncIssuesCommand).command(syncIncidentsCommand).command(syncPrsCommand).command(syncReleasesCommand).command(syncReadmeCommand).command(ideasSyncCommand).command(syncToolingCommand).command(syncRequestsCommand).command(specsSyncCommand).command(secretsSyncCommand).command(notificationsSyncRolesCommand),
43506
44645
  handler: async (argv) => {
43507
44646
  if (argv.env !== void 0 || argv.steps?.[0] !== void 0) {
43508
44647
  if (await syncApp(argv)) return;
@@ -44371,6 +45510,8 @@ let finishCommand = () => {};
44371
45510
  /** What ran, for the offer to run it for real after a `--dry-run` of it. */
44372
45511
  let ranWords = [];
44373
45512
  let ranDryRun = false;
45513
+ /** When the command started and what it was run with, for the command log; unset when no command ran (`--help`). */
45514
+ let runLog;
44374
45515
  /** Set by `.fail()` once it has printed an error, so the outer catch doesn't repeat it. */
44375
45516
  let errorReported = false;
44376
45517
  try {
@@ -44410,6 +45551,17 @@ try {
44410
45551
  command: name,
44411
45552
  org: argv.org
44412
45553
  });
45554
+ const cwd = String(argv.cwd);
45555
+ runLog = {
45556
+ startedAt: Date.now(),
45557
+ cwd,
45558
+ run: startThisRun({
45559
+ words: ranWords,
45560
+ args: process.argv.slice(2),
45561
+ cwd,
45562
+ org: argv.org
45563
+ })
45564
+ };
44413
45565
  finishCommand = startCommand$1(name);
44414
45566
  const label = commandProgressLabel(argv._);
44415
45567
  if (label) startCommandProgress(label);
@@ -44436,6 +45588,13 @@ try {
44436
45588
  }
44437
45589
  finishCommand(!process.exitCode);
44438
45590
  endSession();
45591
+ if (runLog) await runLog.run.record({
45592
+ startedAt: runLog.startedAt,
45593
+ cwd: runLog.cwd,
45594
+ words: ranWords,
45595
+ args: process.argv.slice(2),
45596
+ exitCode: Number(process.exitCode ?? 0)
45597
+ });
44439
45598
  const offered = await offerRealRun({
44440
45599
  words: ranWords,
44441
45600
  args: process.argv.slice(2),