@theholocron/cli 5.0.0-alpha.592 → 5.0.0-alpha.594

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,7 +9,7 @@ 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";
@@ -19,9 +19,9 @@ import { AGGREGATE_CHECK, AGGREGATE_CHECK_NAME, AGGREGATE_SHADOW_CHECK_NAME, DEF
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",
@@ -293,6 +294,11 @@ const cleanupEmbedsEntry = {
293
294
  description: "Hide the link-preview cards under the messages already in a text channel, keeping the links",
294
295
  positionals: [],
295
296
  options: [{
297
+ key: "channel",
298
+ flag: "--channel",
299
+ type: "input",
300
+ message: "Which text channel (a name, with or without #; leave empty for alerts releases deploys sync):"
301
+ }, {
296
302
  key: "limit",
297
303
  flag: "--limit",
298
304
  type: "input",
@@ -2225,6 +2231,15 @@ const syncIssuesEntry = {
2225
2231
  skipOptions: ["yes"],
2226
2232
  supportsDryRun: true
2227
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
+ };
2228
2243
  // src/commands/sync-readme/sync-readme.entry.ts
2229
2244
  const syncReadmeEntry = {
2230
2245
  name: "sync readme",
@@ -2490,6 +2505,7 @@ const registry = createCommandRegistry([
2490
2505
  syncGithubEntry,
2491
2506
  syncIssuesEntry,
2492
2507
  syncIncidentsEntry,
2508
+ syncPrsEntry,
2493
2509
  syncReleasesEntry,
2494
2510
  ideasSyncEntry,
2495
2511
  syncToolingEntry,
@@ -2781,7 +2797,7 @@ function withoutDryRun(args) {
2781
2797
  return [...own.filter((arg) => arg !== "--dry-run" && !arg.startsWith("--dry-run=")), ...rest];
2782
2798
  }
2783
2799
  // src/commands/offer-real-run/offer-real-run.ts
2784
- const INFO_FLAGS = /* @__PURE__ */ new Set([
2800
+ const INFO_FLAGS$1 = /* @__PURE__ */ new Set([
2785
2801
  "--help",
2786
2802
  "-h",
2787
2803
  "--version",
@@ -2799,11 +2815,90 @@ const INFO_FLAGS = /* @__PURE__ */ new Set([
2799
2815
  async function offerRealRun(input) {
2800
2816
  if (!input.dryRun || input.exitCode !== 0) return void 0;
2801
2817
  if (!input.interactive || input.ci || input.preview) return void 0;
2802
- 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;
2803
2819
  if (!input.supportsDryRun(input.words)) return void 0;
2804
2820
  if (!await input.confirm("Dry run complete — run it for real?")) return void 0;
2805
2821
  return input.spawn(withoutDryRun(input.args));
2806
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
+ }
2807
2902
  // src/observability/logger/logger.ts
2808
2903
  /**
2809
2904
  * CLI-side wiring for `@theholocron/observability/logger`.
@@ -2856,89 +2951,199 @@ const logger = createCliLogger({
2856
2951
  * rebuilt at most once more when a handler supplies `holocron.config` context.
2857
2952
  * See `createCliLogger` in `@theholocron/kyber/observability`.
2858
2953
  */
2859
- 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
+ };
2860
2961
  /** Lazily-memoized `Logger` for call sites with no `argv` in scope (yargs' `.fail()`). */
2861
- const getLogger = logger.getLogger;
2962
+ const getLogger = () => tapLogger(logger.getLogger());
2862
2963
  /** Report a fatal, command-ending CLI error: printed with `style.fail` and logged. */
2863
- const reportError = logger.reportError;
2964
+ const reportError = (message, log = getLogger()) => logger.reportError(message, log);
2864
2965
  /** The current root logger's correlation id, if a root has been built. */
2865
2966
  const getRunId = logger.getRunId;
2866
2967
  logger.resetCliLogger;
2867
2968
  logger.resolveLogLevel;
2868
- // src/observability/resolve-telemetry/resolve-telemetry.ts
2869
- 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
+ }
2870
2990
  /**
2871
- * Holocron-specific credential resolution for the telemetry sinks — the env
2872
- * chain plus Holocron's own shipped fallbacks. This is **CLI policy**, not part
2873
- * of the portable adapter set: `sentry-sink.ts` / `posthog-sink.ts` take a
2874
- * resolved DSN / key and never read the environment. When the adapters move to
2875
- * `@theholocron/observability` (#635) this module stays here.
2876
- *
2877
- * errors: HOLOCRON_SENTRY_DSN → SENTRY_DSN → FALLBACK_DSN
2878
- * analytics: HOLOCRON_POSTHOG_PROJECT_TOKEN → POSTHOG_PROJECT_TOKEN → FALLBACK_POSTHOG_PROJECT_TOKEN
2879
- * host: HOLOCRON_POSTHOG_HOST → POSTHOG_HOST → DEFAULT_POSTHOG_HOST
2880
- *
2881
- * The `SENTRY_DSN` / `POSTHOG_PROJECT_TOKEN` fallbacks are the vendor-native
2882
- * names a consumer repo sets to route CLI telemetry to its own project. The
2883
- * built-in fallbacks are ingest-only keys — publishable by design, same risk
2884
- * 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`.
2885
2993
  */
2886
- /** Holocron's own Sentry project — the fallback when no env var points elsewhere. */
2887
- const FALLBACK_DSN = "https://95cbb72ad5636c94e119a5405ee8f55f@o4508238154104832.ingest.us.sentry.io/4511810950791168";
2888
- /** Holocron's own PostHog project write key — ingest-only. */
2889
- const FALLBACK_POSTHOG_PROJECT_TOKEN = "phc_AC4vFCvYzwnzmG7Vg5nEc3PZKZztoPyfKp4Lb9BbXcLK";
2890
- const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
2891
- /** Resolve the Sentry DSN. `""` → error telemetry disabled. */
2892
- function resolveDsn() {
2893
- return env$10.get("SENTRY_DSN") ?? FALLBACK_DSN;
2994
+ function layerEnvironment(slug, layer) {
2995
+ return `${slug} - ${layer}`;
2894
2996
  }
2895
- /** Resolve the PostHog project key. `""` → usage analytics disabled. */
2896
- function resolvePostHogKey() {
2897
- 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)];
2898
3021
  }
2899
- /** Resolve the PostHog ingest host. */
2900
- function resolvePostHogHost() {
2901
- 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;
2902
3031
  }
2903
- // src/observability/telemetry/telemetry.ts
3032
+ // src/credentials-environments/resolve-environments/resolve-environments.ts
2904
3033
  /**
2905
- * 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/unsynced-layer/unsynced-layer.ts
3075
+ /**
3076
+ * The layers this machine reads for itself (`agent` is the one an agent's process reads, spec `tech-agent-secrets`). They
3077
+ * are never synced to GitHub, a deployment or a Worker (#2104).
3078
+ */
3079
+ const UNSYNCED_LAYERS = [
3080
+ "local",
3081
+ "dev",
3082
+ "agent"
3083
+ ];
3084
+ /** Whether `layer` is one of {@link UNSYNCED_LAYERS}. */
3085
+ function isUnsyncedLayer(layer) {
3086
+ return isEnvironmentLayer(layer) && UNSYNCED_LAYERS.includes(layer);
3087
+ }
3088
+ /**
3089
+ * The text of the error for an Environment of an unsynced layer, shared by the command and the config checks.
2906
3090
  *
2907
- * The orchestration is `createCliTelemetry` in `@theholocron/kyber/observability`
2908
- * (no vendor SDK import here either: the sinks live in `@theholocron/observability`).
2909
- * This module binds it to Holocron's values: the `HOLOCRON` env prefix, the
2910
- * credentials resolved by `resolve-telemetry.ts`, and the logger's run id.
2911
- * The single kill switch is `HOLOCRON_TELEMETRY=false` (legacy alias
2912
- * `NO_HOLOCRON_TELEMETRY`); see ADR-0007 / ADR-0008.
3091
+ * @param what - What names the layer, e.g. "`sync secrets --env dev`" or "a `repo.secrets.sync` entry".
3092
+ * @param layer - The unsynced layer.
2913
3093
  */
2914
- const telemetry = createCliTelemetry({
2915
- envPrefix: PREFIX$1,
2916
- dsn: resolveDsn,
2917
- posthogKey: resolvePostHogKey,
2918
- posthogHost: resolvePostHogHost,
2919
- getRunId: () => getRunId()
2920
- });
2921
- /** Install the live sinks unless telemetry is opted out or a credential is empty. */
2922
- const init = telemetry.init;
2923
- /** Apply the `telemetry` config block; it only ever narrows what `init` turned on. */
2924
- const applyConfig = telemetry.applyConfig;
2925
- /** Capture a PostHog event, scrubbed of secrets. */
2926
- const event = telemetry.event;
2927
- /** Start a command span; call the returned function with the outcome. */
2928
- const startCommand$1 = telemetry.startCommand;
2929
- /** Report an error to Sentry. */
2930
- const captureException = telemetry.captureException;
2931
- /** End the Sentry session. */
2932
- const endSession = telemetry.endSession;
2933
- /** Drain both sinks and return to the no-ops. */
2934
- const flush = telemetry.flush;
2935
- telemetry.resetTelemetry;
2936
- // src/credentials-environments/derives-environment/derives-environment.ts
2937
- /** The providers whose `credentials` entry may leave `environment` out and have it derived (#2063). */
2938
- const DERIVING = /* @__PURE__ */ new Set(["1password"]);
2939
- /** Whether a `credentials` provider with no `environment` option derives its Environment names. */
2940
- function derivesEnvironment(provider) {
2941
- return DERIVING.has(provider);
3094
+ function unsyncedLayerMessage(what, layer) {
3095
+ 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`;
3096
+ }
3097
+ /**
3098
+ * Refuse a sync of an unsynced layer, before anything is read. The argument is a layer word, or the literal name of a
3099
+ * layer's Environment (`<org/repo> - dev`, built by `layerEnvironment()` from the `origin` remote). A remote that
3100
+ * cannot be read means no literal name can be matched, so only a layer word is checked then.
3101
+ *
3102
+ * @param id - The environment as given on the command line.
3103
+ * @param input - Where the repository is, and optionally how to read its remote.
3104
+ * @throws {ConfigError} For an unsynced layer, whatever other flags are given.
3105
+ */
3106
+ async function assertSyncableLayer(id, input) {
3107
+ if (isEnvironmentLayer(id)) {
3108
+ if (isUnsyncedLayer(id)) throw new ConfigError$1(unsyncedLayerMessage(`\`sync secrets --env ${id}\``, id));
3109
+ return;
3110
+ }
3111
+ const slug = await repoSlug(input.repoRoot, input.gitExec).catch(() => void 0);
3112
+ if (slug === void 0) return;
3113
+ for (const layer of UNSYNCED_LAYERS) if (id === layerEnvironment(slug, layer)) throw new ConfigError$1(unsyncedLayerMessage(`\`sync secrets --env\` for ${JSON.stringify(id)}`, layer));
3114
+ }
3115
+ // src/observability/command-path/command-path.ts
3116
+ /** The first word of every command Holocron has. */
3117
+ const VERBS = new Set(Object.keys(COMMAND_CONTEXTS).map((name) => name.split(" ")[0]));
3118
+ /** A command word as the commands spell it: lower-case letters, digits and dashes. A number, a path or a value is not one. */
3119
+ const COMMAND_WORD = /^[a-z][a-z0-9-]*$/;
3120
+ /** The most words a command path has (`probe docs coverage`). */
3121
+ const MAX_WORDS = 3;
3122
+ /**
3123
+ * The command path to record (`sync specs`, `start work`) from yargs' `argv._`. Only the words that are spelled like a
3124
+ * command's own are kept, up to three, and the first must be a command Holocron knows, so a positional or a value that
3125
+ * ends up in `argv._` is never recorded. Anything else is `unknown`.
3126
+ *
3127
+ * @param words - `argv._`.
3128
+ */
3129
+ function commandPath(words) {
3130
+ const path = [];
3131
+ for (const word of words.slice(0, MAX_WORDS)) {
3132
+ if (typeof word !== "string" || !COMMAND_WORD.test(word)) break;
3133
+ path.push(word);
3134
+ }
3135
+ return path.length > 0 && VERBS.has(path[0]) ? path.join(" ") : "unknown";
3136
+ }
3137
+ // src/commands/resolve-org/resolve-org.ts
3138
+ const env$10 = createEnvLookup();
3139
+ /**
3140
+ * Resolves the active org in priority order:
3141
+ * 1. `--org` CLI flag
3142
+ * 2. `HOLOCRON_ORG` env var
3143
+ * 3. `org` from `holocron.config.ts`
3144
+ */
3145
+ function resolveOrg(argv, config) {
3146
+ return argv.org ?? env$10.get("HOLOCRON_ORG") ?? config.org;
2942
3147
  }
2943
3148
  // src/plugin/capabilities/capabilities.ts
2944
3149
  /** How many providers each capability resolves to: one (`"single"`) or several active at once (`"many"`). */
@@ -3049,26 +3254,44 @@ function splitAgent(raw) {
3049
3254
  agentOptions: options
3050
3255
  };
3051
3256
  }
3052
- // src/credentials-environments/layer-environment/layer-environment.ts
3053
- /** The layer words, in the order the docs list them. */
3054
- const ENVIRONMENT_LAYERS = [
3055
- "local",
3056
- "dev",
3057
- "ci",
3058
- "prod",
3059
- "preview",
3060
- "agent"
3257
+ // src/config/validate-command-log/validate-command-log.ts
3258
+ /** The values `notifications.commandLog` accepts. */
3259
+ const COMMAND_LOG_MODES = [
3260
+ "agents",
3261
+ "all",
3262
+ "off"
3061
3263
  ];
3062
- /** Whether `value` is exactly one of the layer words (case-sensitive: `Prod` is a literal Environment name). */
3063
- function isEnvironmentLayer(value) {
3064
- return typeof value === "string" && ENVIRONMENT_LAYERS.includes(value);
3264
+ /**
3265
+ * Check `notifications.commandLog` (spec `tech-discord-notifications-v2`, step 6): `agents`, `all` or `off`.
3266
+ *
3267
+ * @param notifications - The config's top-level `notifications` block, if it has one.
3268
+ * @throws {ConfigError} Naming the path and the allowed values.
3269
+ */
3270
+ function validateCommandLog(notifications) {
3271
+ if (notifications === void 0) return;
3272
+ if (typeof notifications !== "object" || notifications === null || Array.isArray(notifications)) throw new ConfigError$1("`notifications` must be an object (for example `{ commandLog: \"agents\" }`)");
3273
+ const mode = notifications.commandLog;
3274
+ if (mode === void 0) return;
3275
+ 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)}`);
3065
3276
  }
3277
+ // src/config/validate-command-threads/validate-command-threads.ts
3278
+ /** The values `notifications.commandThreads` accepts. */
3279
+ const COMMAND_THREADS_MODES = [
3280
+ "agents",
3281
+ "all",
3282
+ "off"
3283
+ ];
3066
3284
  /**
3067
- * The Environment a layer of a repository is kept in: `<org/repo> - <layer>`. The one place the name is built, for the
3068
- * `credentials` providers (`environmentLayers()`) and for the config entries that name a `layer`.
3285
+ * Check `notifications.commandThreads` (spec `tech-discord-notifications-v2`, step 7): `agents`, `all` or `off`. The
3286
+ * block itself is checked by `validateCommandLog()`, which runs first.
3287
+ *
3288
+ * @param notifications - The config's top-level `notifications` block, if it has one.
3289
+ * @throws {ConfigError} Naming the path and the allowed values.
3069
3290
  */
3070
- function layerEnvironment(slug, layer) {
3071
- return `${slug} - ${layer}`;
3291
+ function validateCommandThreads(notifications) {
3292
+ const mode = notifications?.commandThreads;
3293
+ if (mode === void 0) return;
3294
+ 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)}`);
3072
3295
  }
3073
3296
  // src/config/validate-environment-choice/validate-environment-choice.ts
3074
3297
  /**
@@ -3336,57 +3559,6 @@ function validateRequiredChecks(checks) {
3336
3559
  seen.add(context);
3337
3560
  });
3338
3561
  }
3339
- // src/credentials-environments/repo-slug/repo-slug.ts
3340
- /**
3341
- * The `<org>/<repo>` of the repository at `cwd`, from its `origin` remote. A remote that is missing or cannot be
3342
- * parsed is a `ConfigError` that names the `environment` option as the fix.
3343
- */
3344
- async function repoSlug(cwd, exec) {
3345
- const remote = await readGitRemote(cwd, exec ? { exec } : {});
3346
- 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.`);
3347
- return remote.slug;
3348
- }
3349
- // src/credentials-environments/unsynced-layer/unsynced-layer.ts
3350
- /**
3351
- * The layers this machine reads for itself (`agent` is the one an agent's process reads, spec `tech-agent-secrets`). They
3352
- * are never synced to GitHub, a deployment or a Worker (#2104).
3353
- */
3354
- const UNSYNCED_LAYERS = [
3355
- "local",
3356
- "dev",
3357
- "agent"
3358
- ];
3359
- /** Whether `layer` is one of {@link UNSYNCED_LAYERS}. */
3360
- function isUnsyncedLayer(layer) {
3361
- return isEnvironmentLayer(layer) && UNSYNCED_LAYERS.includes(layer);
3362
- }
3363
- /**
3364
- * The text of the error for an Environment of an unsynced layer, shared by the command and the config checks.
3365
- *
3366
- * @param what - What names the layer, e.g. "`sync secrets --env dev`" or "a `repo.secrets.sync` entry".
3367
- * @param layer - The unsynced layer.
3368
- */
3369
- function unsyncedLayerMessage(what, layer) {
3370
- 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`;
3371
- }
3372
- /**
3373
- * Refuse a sync of an unsynced layer, before anything is read. The argument is a layer word, or the literal name of a
3374
- * layer's Environment (`<org/repo> - dev`, built by `layerEnvironment()` from the `origin` remote). A remote that
3375
- * cannot be read means no literal name can be matched, so only a layer word is checked then.
3376
- *
3377
- * @param id - The environment as given on the command line.
3378
- * @param input - Where the repository is, and optionally how to read its remote.
3379
- * @throws {ConfigError} For an unsynced layer, whatever other flags are given.
3380
- */
3381
- async function assertSyncableLayer(id, input) {
3382
- if (isEnvironmentLayer(id)) {
3383
- if (isUnsyncedLayer(id)) throw new ConfigError$1(unsyncedLayerMessage(`\`sync secrets --env ${id}\``, id));
3384
- return;
3385
- }
3386
- const slug = await repoSlug(input.repoRoot, input.gitExec).catch(() => void 0);
3387
- if (slug === void 0) return;
3388
- for (const layer of UNSYNCED_LAYERS) if (id === layerEnvironment(slug, layer)) throw new ConfigError$1(unsyncedLayerMessage(`\`sync secrets --env\` for ${JSON.stringify(id)}`, layer));
3389
- }
3390
3562
  // src/config/validate-secrets-deploy/validate-secrets-deploy.ts
3391
3563
  /**
3392
3564
  * 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
@@ -3645,6 +3817,8 @@ function resolveConfig(raw) {
3645
3817
  if (raw.issueTypes !== void 0) validateIssueTypes(raw.issueTypes);
3646
3818
  validateRepoLabels(raw.repo?.labels);
3647
3819
  validateRepoViews(raw.repo?.views);
3820
+ validateCommandLog(raw.notifications);
3821
+ validateCommandThreads(raw.notifications);
3648
3822
  validateRepoEnvironments(raw.repo?.environments);
3649
3823
  validateRequiredChecks(raw.repo?.requiredChecks);
3650
3824
  validateVariablesSync(raw.repo?.variables);
@@ -3688,6 +3862,7 @@ function resolveConfig(raw) {
3688
3862
  ideas: raw.ideas,
3689
3863
  log: raw.log,
3690
3864
  telemetry: raw.telemetry,
3865
+ notifications: raw.notifications,
3691
3866
  eslint: raw.eslint
3692
3867
  };
3693
3868
  }
@@ -4022,73 +4197,6 @@ function placeAreas(areas, raw) {
4022
4197
  else if (area.area === "org") result = placeOrg(result, area);
4023
4198
  return result;
4024
4199
  }
4025
- // src/credentials-environments/environment-layers/environment-layers.ts
4026
- /** The suffix each layer's Environment carries: `<org/repo> - <suffix>`. `test` and `preview` have none. */
4027
- const SUFFIX = {
4028
- local: "local",
4029
- development: "dev",
4030
- ci: "ci",
4031
- production: "prod",
4032
- agent: "agent"
4033
- };
4034
- /**
4035
- * The Environments a layer reads, in the order they are tried (#2063, #2058). A machine (`local`) reads
4036
- * `<slug> - local` and then `<slug> - dev`: that is the only fallback there is. `development` reads `- dev`, `ci`
4037
- * reads `- ci` and `production` reads `- prod`; a missing name is a missing name. `agent` (an agent's process, spec
4038
- * `tech-agent-secrets`) reads `- agent` and nothing else, not `- local` or `- dev`, so an agent never sees a value that
4039
- * belongs to a person's layer. `test` and `preview` read none (a preview deployment gets its values from the
4040
- * deployment, not from a vault). Only `- local` is optional.
4041
- */
4042
- function environmentLayers(slug, layer) {
4043
- if (layer === "test" || layer === "preview") return [];
4044
- const candidate = (suffix, optional) => ({
4045
- name: layerEnvironment(slug, suffix),
4046
- optional
4047
- });
4048
- return layer === "local" ? [candidate(SUFFIX.local, true), candidate(SUFFIX.development, false)] : [candidate(SUFFIX[layer], false)];
4049
- }
4050
- // src/credentials-environments/resolve-environments/resolve-environments.ts
4051
- /**
4052
- * The Environments one `credentials` entry reads. An explicit name (the entry's `environment` option, else the shared
4053
- * `credentials.environment`) is the only candidate and wins. Otherwise a deriving provider gets the names of its layer
4054
- * (`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).
4055
- */
4056
- async function resolveEnvironments(provider, explicit, input) {
4057
- if (explicit !== void 0) return [{
4058
- name: explicit,
4059
- optional: false
4060
- }];
4061
- if (!derivesEnvironment(provider)) return [];
4062
- const layer = detectEnvironment(input.env);
4063
- if (layer === "test") return [];
4064
- return environmentLayers(await repoSlug(input.repoRoot, input.gitExec), layer);
4065
- }
4066
- // src/credentials-environments/try-environments/try-environments.ts
4067
- /** A provider's "no such Environment": its API error with status 404 (`ProviderApiError`, matched by shape). */
4068
- function isNotFound(err) {
4069
- return typeof err === "object" && err !== null && err.status === 404;
4070
- }
4071
- /**
4072
- * Calls `attempt` for each candidate and sorts the answers into found and missing. A 404 is a miss; any other error
4073
- * is thrown. A missing optional Environment is silent; a missing required one is reported by name.
4074
- */
4075
- async function tryEnvironments(candidates, attempt) {
4076
- const found = [];
4077
- const missing = [];
4078
- for (const candidate of candidates) try {
4079
- found.push({
4080
- name: candidate.name,
4081
- result: await attempt(candidate.name)
4082
- });
4083
- } catch (err) {
4084
- if (!isNotFound(err)) throw err;
4085
- if (!candidate.optional) missing.push(candidate.name);
4086
- }
4087
- return {
4088
- found,
4089
- missing
4090
- };
4091
- }
4092
4200
  // src/config/resolve-layers/resolve-layers.ts
4093
4201
  /**
4094
4202
  * Turns every `layer` in a loaded config into the `environment` it names (spec `tech-environment-layers`, #2069), so
@@ -4212,46 +4320,6 @@ function resolvedEnvironment(entry) {
4212
4320
  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()`);
4213
4321
  return entry.environment;
4214
4322
  }
4215
- // src/commands/resolve-org/resolve-org.ts
4216
- const env$9 = createEnvLookup();
4217
- /**
4218
- * Resolves the active org in priority order:
4219
- * 1. `--org` CLI flag
4220
- * 2. `HOLOCRON_ORG` env var
4221
- * 3. `org` from `holocron.config.ts`
4222
- */
4223
- function resolveOrg(argv, config) {
4224
- return argv.org ?? env$9.get("HOLOCRON_ORG") ?? config.org;
4225
- }
4226
- // src/commands/apply-resolved-config/apply-resolved-config.ts
4227
- /**
4228
- * `buildCliLogger` options derived from a loaded `holocron.config` — the
4229
- * level, the Axiom dataset, and the resolved org for a keyring-backed
4230
- * Axiom token. Used by every handler that has already called `loadConfig`.
4231
- */
4232
- function cliLoggerOpts(argv, resolved) {
4233
- return {
4234
- configLevel: resolved.log?.level,
4235
- configAxiomDataset: resolved.log?.axiom?.dataset,
4236
- org: resolveOrg(argv, resolved)
4237
- };
4238
- }
4239
- /**
4240
- * Fold a loaded `holocron.config` into the running process: reconfigure the
4241
- * logger from `log:`, then apply the `telemetry:` override layer. Every handler
4242
- * that has called `loadConfig` runs this, so a repo's `telemetry.enabled: false`
4243
- * (or `analytics: "none"`) is honoured for that command. Env still wins —
4244
- * `applyConfig` only narrows what `init` already turned on.
4245
- */
4246
- function applyResolvedConfig(argv, resolved) {
4247
- buildCliLogger(argv, cliLoggerOpts(argv, resolved));
4248
- applyConfig(resolved.telemetry);
4249
- }
4250
- // src/commands/token-context/token-context.ts
4251
- /** Parses --token values and returns the context spread, or null on parse error (exits with code 1). */
4252
- function tokenContext(rawTokens) {
4253
- return tokenContext$1(rawTokens, reportError);
4254
- }
4255
4323
  // src/plugin/missing-plugin-hint/missing-plugin-hint.ts
4256
4324
  /**
4257
4325
  * The line that says how to get a plugin package that does not resolve: add it to the `holocron` catalog of
@@ -4532,6 +4600,476 @@ function actionsOf(plugin) {
4532
4600
  ...plugin.whoami ? { whoami: plugin.whoami } : {}
4533
4601
  };
4534
4602
  }
4603
+ // src/observability/command-log-disabled/command-log-disabled.ts
4604
+ /**
4605
+ * Whether the command log is off for this process: in CI (a run nobody watches posts through its own workflow) and
4606
+ * under test (`NODE_ENV=test`, which vitest sets), so neither writes an event or posts a line.
4607
+ *
4608
+ * @param source - The environment to read; the process environment when left out.
4609
+ */
4610
+ function commandLogDisabled(source) {
4611
+ const env = createEnvLookup(source);
4612
+ return isCI(source) || env.get("NODE_ENV") === "test";
4613
+ }
4614
+ // src/observability/command-log-skipped/command-log-skipped.ts
4615
+ /**
4616
+ * Commands that are not recorded: the ones that stay up for a whole session or run another command (a record would be
4617
+ * noise, or would say nothing about what was done). The menu starts the commands it runs as runs of their own, and those
4618
+ * are recorded.
4619
+ */
4620
+ const COMMAND_LOG_SKIPPED = [
4621
+ "dev",
4622
+ "menu",
4623
+ "open requests",
4624
+ "start agent",
4625
+ "unknown"
4626
+ ];
4627
+ /**
4628
+ * Whether a command is left out of the command log: it is, or starts with, an entry of {@link COMMAND_LOG_SKIPPED}.
4629
+ *
4630
+ * @param command - The command path, `sync specs`.
4631
+ */
4632
+ function isCommandLogSkipped(command) {
4633
+ return COMMAND_LOG_SKIPPED.some((skipped) => command === skipped || command.startsWith(`${skipped} `));
4634
+ }
4635
+ /**
4636
+ * The thread name for a command: `holocron sync specs — 2026-12-02 14:05 UTC`.
4637
+ *
4638
+ * @param command - The command path.
4639
+ * @param at - When it started, `Date.now()`.
4640
+ */
4641
+ function commandThreadName(command, at) {
4642
+ return `holocron ${command} — ${new Date(at).toISOString().slice(0, 16).replace("T", " ")} UTC`;
4643
+ }
4644
+ /**
4645
+ * Start a command's Discord thread (spec `tech-discord-notifications-v2`, step 7). Nothing waits for it: the setting is
4646
+ * read and the thread opened in the background while the command runs, lines that arrive earlier are kept, and they are
4647
+ * posted in batches of one per {@link COMMAND_THREAD_BATCH_MS}. A run the setting does not cover (`off`, or `agents` for
4648
+ * a person) opens nothing and its `finish()` is `false`. Every failure is swallowed; the caller bounds `finish()` with
4649
+ * its own deadline.
4650
+ *
4651
+ * @param command - The command path, `sync specs`.
4652
+ * @param deps - Who is running, the setting, how a thread is opened and the clock.
4653
+ */
4654
+ function startCommandThread(command, deps) {
4655
+ const batchMs = deps.batchMs ?? 3e3;
4656
+ const buffer = [];
4657
+ let taken = 0;
4658
+ let dropped = 0;
4659
+ let timer;
4660
+ let sending = Promise.resolve();
4661
+ const ready = (async () => {
4662
+ const mode = await deps.mode();
4663
+ if (mode === "off" || mode === "agents" && deps.actor.actor !== "agent") return void 0;
4664
+ return deps.open(commandThreadName(command, deps.now()));
4665
+ })().catch(() => void 0);
4666
+ const send = () => {
4667
+ sending = sending.then(async () => {
4668
+ const session = await ready;
4669
+ const lines = buffer.splice(0);
4670
+ if (session && lines.length > 0) await session.post(lines).catch(() => void 0);
4671
+ });
4672
+ };
4673
+ return {
4674
+ push(line) {
4675
+ if (taken >= 150) {
4676
+ dropped += 1;
4677
+ return;
4678
+ }
4679
+ taken += 1;
4680
+ buffer.push(line);
4681
+ if (timer === void 0) {
4682
+ timer = setTimeout(() => {
4683
+ timer = void 0;
4684
+ send();
4685
+ }, batchMs);
4686
+ timer.unref();
4687
+ }
4688
+ },
4689
+ async finish(finalLine) {
4690
+ clearTimeout(timer);
4691
+ timer = void 0;
4692
+ const session = await ready;
4693
+ if (!session) return false;
4694
+ await sending;
4695
+ if (dropped > 0) buffer.push(`… ${dropped} more lines not shown`);
4696
+ buffer.push(finalLine);
4697
+ try {
4698
+ await session.post(buffer.splice(0));
4699
+ return true;
4700
+ } catch {
4701
+ return false;
4702
+ }
4703
+ }
4704
+ };
4705
+ }
4706
+ // src/observability/command-run-deps/command-run-deps.ts
4707
+ /** The channel a command run is posted to; the layout declares it (`.holocron/notifications.ts`). */
4708
+ const AGENT_LOG_CHANNEL = "agent-log";
4709
+ /** Whether a provider has the three methods a command thread needs. */
4710
+ function canThread$1(provider) {
4711
+ return typeof provider.sendWithId === "function" && typeof provider.startThread === "function" && typeof provider.postToThread === "function";
4712
+ }
4713
+ /**
4714
+ * The real dependencies of `recordCommandRun()`, and (step 7) the run's command thread, started here so that it opens
4715
+ * while the command runs. The config is read at most once, and only when the recorder or the thread asks for a setting
4716
+ * (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
4717
+ * thread is due, so a human run in the default modes never builds one. The post goes to every configured
4718
+ * `notifications` provider through its `send`, which reads its own webhook (`HOLOCRON_NOTIFY_WEBHOOK_AGENT_LOG`) and
4719
+ * throws when there is none: the recorder swallows that. A thread is opened on the first provider that has `sendWithId`,
4720
+ * `startThread` and `postToThread`, and the CLI logger's lines are copied into it through the log tap. Provider tokens
4721
+ * given with `--token` are not passed on.
4722
+ */
4723
+ function createCommandRunDeps(input) {
4724
+ const disabled = input.disabled ?? commandLogDisabled();
4725
+ let loaded;
4726
+ let providers;
4727
+ const load = () => loaded ??= loadConfig(input.cwd);
4728
+ const notifications = () => providers ??= (async () => {
4729
+ const { resolved } = await load();
4730
+ const loader = new PluginLoader(resolved, {
4731
+ repoRoot: input.cwd,
4732
+ org: resolveOrg({ org: input.org }, resolved)
4733
+ });
4734
+ await loader.load();
4735
+ return loader.has("notifications") ? loader.get("notifications") : [];
4736
+ })();
4737
+ let thread;
4738
+ if (!disabled && !isCommandLogSkipped(input.command)) {
4739
+ thread = startCommandThread(input.command, {
4740
+ actor: input.actor,
4741
+ now: Date.now,
4742
+ mode: async () => (await load()).resolved.notifications?.commandThreads ?? "off",
4743
+ open: async (name) => {
4744
+ const provider = (await notifications()).find(canThread$1);
4745
+ if (!provider) return void 0;
4746
+ const anchor = await provider.sendWithId(AGENT_LOG_CHANNEL, `🧵 ${name}`);
4747
+ const opened = await provider.startThread(anchor, name);
4748
+ return { post: (lines) => provider.postToThread(opened.id, lines) };
4749
+ }
4750
+ });
4751
+ const started = thread;
4752
+ setLogTap((line) => started.push(line));
4753
+ }
4754
+ return {
4755
+ logger: input.logger,
4756
+ disabled,
4757
+ thread,
4758
+ mode: async () => (await load()).resolved.notifications?.commandLog ?? "agents",
4759
+ post: async (line) => {
4760
+ await Promise.all((await notifications()).map((provider) => provider.send(AGENT_LOG_CHANNEL, line)));
4761
+ }
4762
+ };
4763
+ }
4764
+ // src/observability/detect-actor/detect-actor.ts
4765
+ /** The variable each known agent sets in the processes it starts, with the name the record gives that agent. */
4766
+ const AGENT_VARIABLES = [
4767
+ ["CLAUDECODE", "claude"],
4768
+ ["CODEX_SANDBOX", "codex"],
4769
+ ["GEMINI_CLI", "gemini"]
4770
+ ];
4771
+ /**
4772
+ * Who is running this command (spec `tech-discord-notifications-v2`, step 6). An agent when a known agent's variable is
4773
+ * set (`CLAUDECODE`, `CODEX_SANDBOX`, `GEMINI_CLI`, which names it) or when `HOLOCRON_ENVIRONMENT=agent`, which the
4774
+ * `start agent` launcher sets (named `unknown` when no variable says which agent it is); otherwise a human. Only the
4775
+ * presence of a variable is read, never its value.
4776
+ *
4777
+ * @param source - The environment to read; the process environment when left out.
4778
+ */
4779
+ function detectActor(source) {
4780
+ const env = createEnvLookup(source);
4781
+ const named = AGENT_VARIABLES.find(([variable]) => env.get(variable) !== void 0);
4782
+ if (named) return {
4783
+ actor: "agent",
4784
+ agent: named[1]
4785
+ };
4786
+ if (holocronEnv(source).get("ENVIRONMENT") === "agent") return {
4787
+ actor: "agent",
4788
+ agent: "unknown"
4789
+ };
4790
+ return { actor: "human" };
4791
+ }
4792
+ // src/observability/is-info-run/is-info-run.ts
4793
+ /** Arguments that print help or the version instead of running a command. */
4794
+ const INFO_FLAGS = /* @__PURE__ */ new Set([
4795
+ "--help",
4796
+ "-h",
4797
+ "--version",
4798
+ "-v"
4799
+ ]);
4800
+ /**
4801
+ * Whether the command line asks for help or the version: such a run is not a command that ran, so it is neither recorded
4802
+ * nor given a thread.
4803
+ *
4804
+ * @param args - The command line as typed, without the program and script.
4805
+ */
4806
+ function isInfoRun(args) {
4807
+ return args.some((arg) => INFO_FLAGS.has(arg));
4808
+ }
4809
+ // src/observability/command-flag-names/command-flag-names.ts
4810
+ /** Flags that are on every command and say nothing about what it did. */
4811
+ const IGNORED = /* @__PURE__ */ new Set([
4812
+ "help",
4813
+ "version",
4814
+ "h",
4815
+ "v"
4816
+ ]);
4817
+ /** A long flag's name as typed: letters, digits and dashes, starting with a letter. Anything else is not recorded. */
4818
+ const LONG_NAME = /^[A-Za-z][A-Za-z0-9-]*$/;
4819
+ /**
4820
+ * The **names** of the flags given on a command line (spec `tech-discord-notifications-v2`, step 6): `--dry-run`,
4821
+ * `--env=prod` and `-y` give `dry-run`, `env` and `y`. Never a value, never a positional.
4822
+ *
4823
+ * It reads the arguments as typed, not yargs' `argv`, because `argv` also holds every default and the camelCase twin of
4824
+ * each kebab-case flag. Reading stops at a bare `--` (what follows is for another program). A value that only looks like
4825
+ * a flag is still only a name, and a short cluster (`-abc`) or a name with other characters is left out, so a value
4826
+ * that starts with a dash cannot leak through.
4827
+ *
4828
+ * @param args - The command line without the program and script (`process.argv.slice(2)`).
4829
+ * @returns The names in the order first given, once each.
4830
+ */
4831
+ function commandFlagNames(args) {
4832
+ const names = [];
4833
+ for (const arg of args) {
4834
+ if (arg === "--") break;
4835
+ let name;
4836
+ if (arg.startsWith("--")) name = arg.slice(2).split("=")[0];
4837
+ else if (/^-[A-Za-z](=|$)/.test(arg)) name = arg.slice(1, 2);
4838
+ if (name === void 0 || !LONG_NAME.test(name) || IGNORED.has(name) || names.includes(name)) continue;
4839
+ names.push(name);
4840
+ }
4841
+ return names;
4842
+ }
4843
+ // src/observability/command-run-line/command-run-line.ts
4844
+ /**
4845
+ * The one line posted for a command run: `🤖 claude ran sync specs --dry-run (exit 0, 1.2s) in theholocron/holocron`.
4846
+ * Text only, from names the CLI itself checked: the actor's name, the command words, flag names, the exit code, the
4847
+ * duration and the repository.
4848
+ */
4849
+ function commandRunLine(input) {
4850
+ const who = input.actor.actor === "agent" ? `🤖 ${input.actor.agent ?? "unknown"}` : "🧑 human";
4851
+ const flags = input.flags.map((name) => name.length === 1 ? `-${name}` : `--${name}`);
4852
+ const ran = [input.command, ...flags].join(" ");
4853
+ const where = input.repo ? ` in ${input.repo}` : "";
4854
+ return `${who} ran ${ran} (exit ${input.exitCode}, ${(input.durationMs / 1e3).toFixed(1)}s)${where}`;
4855
+ }
4856
+ // src/observability/record-command-run/record-command-run.ts
4857
+ /** How long recording may take before the CLI stops waiting for it (spec `tech-discord-notifications-v2`, step 6). */
4858
+ const COMMAND_LOG_POST_TIMEOUT_MS = 2e3;
4859
+ /** True while a record is being made, so a post that somehow runs a command cannot record itself again. */
4860
+ let recording = false;
4861
+ /**
4862
+ * Record one command run (spec `tech-discord-notifications-v2`, step 6). Every run is one `command_run` event through
4863
+ * the CLI's logger, which ships to Axiom when a dataset and token are set. An agent's run (or any run, with
4864
+ * `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
4865
+ * thread's last post. The whole path (the
4866
+ * logger's flush, the config read, the plugin load and the post) waits at most {@link COMMAND_LOG_POST_TIMEOUT_MS}.
4867
+ *
4868
+ * It never throws and never touches the exit code or the command's output: a missing provider or webhook, a refusal, a
4869
+ * timeout and a thrown error all end quietly. Nothing is recorded in CI or under test, for the commands in
4870
+ * `COMMAND_LOG_SKIPPED`, or while another record is being made.
4871
+ *
4872
+ * @param input - The run: names and numbers, never a value.
4873
+ * @param deps - The logger, the setting and the post.
4874
+ */
4875
+ async function recordCommandRun(input, deps) {
4876
+ if (recording || deps.disabled || isCommandLogSkipped(input.command)) return;
4877
+ recording = true;
4878
+ try {
4879
+ await within$1(record(input, deps), COMMAND_LOG_POST_TIMEOUT_MS);
4880
+ } catch {} finally {
4881
+ recording = false;
4882
+ }
4883
+ }
4884
+ /** The work of one record: log the event, start flushing the logger, read the setting and post when it says to. */
4885
+ async function record(input, deps) {
4886
+ deps.logger.info({
4887
+ event: "command_run",
4888
+ command: input.command,
4889
+ flags: [...input.flags],
4890
+ repo: input.repo,
4891
+ exit_code: input.exitCode,
4892
+ duration_ms: input.durationMs,
4893
+ actor: input.actor.actor,
4894
+ agent: input.actor.agent
4895
+ }, "command run");
4896
+ const flushed = deps.logger.flush().catch(() => void 0);
4897
+ const line = commandRunLine(input);
4898
+ if (!(deps.thread ? await deps.thread.finish(line) : false)) {
4899
+ const mode = await deps.mode();
4900
+ if (mode !== "off" && (mode === "all" || input.actor.actor === "agent")) await deps.post(line);
4901
+ }
4902
+ await flushed;
4903
+ }
4904
+ /** Wait for `work` for at most `ms`; a rejection is thrown to the caller, a late finish is ignored. */
4905
+ async function within$1(work, ms) {
4906
+ let timer;
4907
+ const timeout = new Promise((resolve) => {
4908
+ timer = setTimeout(resolve, ms);
4909
+ });
4910
+ work.catch(() => void 0);
4911
+ try {
4912
+ await Promise.race([work, timeout]);
4913
+ } finally {
4914
+ clearTimeout(timer);
4915
+ }
4916
+ }
4917
+ // src/observability/record-cli-run/record-cli-run.ts
4918
+ /**
4919
+ * Record the command that just ended (spec `tech-discord-notifications-v2`, step 6): the one call `cli.ts` makes after
4920
+ * the command's result is known. It turns what `cli.ts` has (yargs' words, the typed arguments, the start time and the
4921
+ * exit code) into the names and numbers `recordCommandRun()` takes, and never throws. `--help` and `--version` are not
4922
+ * commands that ran and are not recorded.
4923
+ *
4924
+ * @param input - The finished command.
4925
+ * @param deps - Who is running, the clock, the repository lookup and the recorder's dependencies.
4926
+ */
4927
+ async function recordCliRun(input, deps) {
4928
+ try {
4929
+ const command = commandPath(input.words);
4930
+ if (isInfoRun(input.args) || deps.record.disabled || isCommandLogSkipped(command)) return;
4931
+ await recordCommandRun({
4932
+ command,
4933
+ flags: commandFlagNames(input.args),
4934
+ exitCode: input.exitCode,
4935
+ durationMs: deps.now() - input.startedAt,
4936
+ repo: await deps.repo(input.cwd),
4937
+ actor: deps.actor
4938
+ }, deps.record);
4939
+ } catch {}
4940
+ }
4941
+ // src/observability/record-this-run/record-this-run.ts
4942
+ /** The CLI's logger as it is when a line is written: a handler may rebuild the root logger after the command starts. */
4943
+ const currentLogger = {
4944
+ info: (objOrMsg, msg) => getLogger().info(objOrMsg, msg),
4945
+ flush: () => getLogger().flush()
4946
+ };
4947
+ /**
4948
+ * Start recording the command that is about to run, with the real logger, environment, clock, git remote and plugin
4949
+ * loader. Besides keeping what `recordThisRun()` needs, this is where the run's Discord thread opens (step 7, spec
4950
+ * `tech-discord-notifications-v2`), in the background, so the command's own log lines can stream into it. A `--help` or
4951
+ * `--version` run starts nothing.
4952
+ *
4953
+ * @param start - The command as it starts.
4954
+ * @returns What `cli.ts` calls once the command has ended.
4955
+ */
4956
+ function startThisRun(start) {
4957
+ const actor = detectActor();
4958
+ const record = isInfoRun(start.args) ? void 0 : createCommandRunDeps({
4959
+ cwd: start.cwd,
4960
+ org: start.org,
4961
+ command: commandPath(start.words),
4962
+ actor,
4963
+ logger: currentLogger
4964
+ });
4965
+ return { async record(input) {
4966
+ if (!record) return;
4967
+ await recordCliRun(input, {
4968
+ record,
4969
+ actor,
4970
+ now: Date.now,
4971
+ repo: (cwd) => repoSlug(cwd).catch(() => void 0)
4972
+ });
4973
+ setLogTap(void 0);
4974
+ } };
4975
+ }
4976
+ // src/observability/resolve-telemetry/resolve-telemetry.ts
4977
+ const env$9 = holocronEnv();
4978
+ /**
4979
+ * Holocron-specific credential resolution for the telemetry sinks — the env
4980
+ * chain plus Holocron's own shipped fallbacks. This is **CLI policy**, not part
4981
+ * of the portable adapter set: `sentry-sink.ts` / `posthog-sink.ts` take a
4982
+ * resolved DSN / key and never read the environment. When the adapters move to
4983
+ * `@theholocron/observability` (#635) this module stays here.
4984
+ *
4985
+ * errors: HOLOCRON_SENTRY_DSN → SENTRY_DSN → FALLBACK_DSN
4986
+ * analytics: HOLOCRON_POSTHOG_PROJECT_TOKEN → POSTHOG_PROJECT_TOKEN → FALLBACK_POSTHOG_PROJECT_TOKEN
4987
+ * host: HOLOCRON_POSTHOG_HOST → POSTHOG_HOST → DEFAULT_POSTHOG_HOST
4988
+ *
4989
+ * The `SENTRY_DSN` / `POSTHOG_PROJECT_TOKEN` fallbacks are the vendor-native
4990
+ * names a consumer repo sets to route CLI telemetry to its own project. The
4991
+ * built-in fallbacks are ingest-only keys — publishable by design, same risk
4992
+ * model as ADR-0007 / ADR-0008.
4993
+ */
4994
+ /** Holocron's own Sentry project — the fallback when no env var points elsewhere. */
4995
+ const FALLBACK_DSN = "https://95cbb72ad5636c94e119a5405ee8f55f@o4508238154104832.ingest.us.sentry.io/4511810950791168";
4996
+ /** Holocron's own PostHog project write key — ingest-only. */
4997
+ const FALLBACK_POSTHOG_PROJECT_TOKEN = "phc_AC4vFCvYzwnzmG7Vg5nEc3PZKZztoPyfKp4Lb9BbXcLK";
4998
+ const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
4999
+ /** Resolve the Sentry DSN. `""` → error telemetry disabled. */
5000
+ function resolveDsn() {
5001
+ return env$9.get("SENTRY_DSN") ?? FALLBACK_DSN;
5002
+ }
5003
+ /** Resolve the PostHog project key. `""` → usage analytics disabled. */
5004
+ function resolvePostHogKey() {
5005
+ return env$9.get("POSTHOG_PROJECT_TOKEN") ?? FALLBACK_POSTHOG_PROJECT_TOKEN;
5006
+ }
5007
+ /** Resolve the PostHog ingest host. */
5008
+ function resolvePostHogHost() {
5009
+ return env$9.get("POSTHOG_HOST") ?? DEFAULT_POSTHOG_HOST;
5010
+ }
5011
+ // src/observability/telemetry/telemetry.ts
5012
+ /**
5013
+ * CLI self-telemetry — errors (Sentry), usage analytics (PostHog).
5014
+ *
5015
+ * The orchestration is `createCliTelemetry` in `@theholocron/kyber/observability`
5016
+ * (no vendor SDK import here either: the sinks live in `@theholocron/observability`).
5017
+ * This module binds it to Holocron's values: the `HOLOCRON` env prefix, the
5018
+ * credentials resolved by `resolve-telemetry.ts`, and the logger's run id.
5019
+ * The single kill switch is `HOLOCRON_TELEMETRY=false` (legacy alias
5020
+ * `NO_HOLOCRON_TELEMETRY`); see ADR-0007 / ADR-0008.
5021
+ */
5022
+ const telemetry = createCliTelemetry({
5023
+ envPrefix: PREFIX$1,
5024
+ dsn: resolveDsn,
5025
+ posthogKey: resolvePostHogKey,
5026
+ posthogHost: resolvePostHogHost,
5027
+ getRunId: () => getRunId()
5028
+ });
5029
+ /** Install the live sinks unless telemetry is opted out or a credential is empty. */
5030
+ const init = telemetry.init;
5031
+ /** Apply the `telemetry` config block; it only ever narrows what `init` turned on. */
5032
+ const applyConfig = telemetry.applyConfig;
5033
+ /** Capture a PostHog event, scrubbed of secrets. */
5034
+ const event = telemetry.event;
5035
+ /** Start a command span; call the returned function with the outcome. */
5036
+ const startCommand$1 = telemetry.startCommand;
5037
+ /** Report an error to Sentry. */
5038
+ const captureException = telemetry.captureException;
5039
+ /** End the Sentry session. */
5040
+ const endSession = telemetry.endSession;
5041
+ /** Drain both sinks and return to the no-ops. */
5042
+ const flush = telemetry.flush;
5043
+ telemetry.resetTelemetry;
5044
+ // src/commands/apply-resolved-config/apply-resolved-config.ts
5045
+ /**
5046
+ * `buildCliLogger` options derived from a loaded `holocron.config` — the
5047
+ * level, the Axiom dataset, and the resolved org for a keyring-backed
5048
+ * Axiom token. Used by every handler that has already called `loadConfig`.
5049
+ */
5050
+ function cliLoggerOpts(argv, resolved) {
5051
+ return {
5052
+ configLevel: resolved.log?.level,
5053
+ configAxiomDataset: resolved.log?.axiom?.dataset,
5054
+ org: resolveOrg(argv, resolved)
5055
+ };
5056
+ }
5057
+ /**
5058
+ * Fold a loaded `holocron.config` into the running process: reconfigure the
5059
+ * logger from `log:`, then apply the `telemetry:` override layer. Every handler
5060
+ * that has called `loadConfig` runs this, so a repo's `telemetry.enabled: false`
5061
+ * (or `analytics: "none"`) is honoured for that command. Env still wins —
5062
+ * `applyConfig` only narrows what `init` already turned on.
5063
+ */
5064
+ function applyResolvedConfig(argv, resolved) {
5065
+ buildCliLogger(argv, cliLoggerOpts(argv, resolved));
5066
+ applyConfig(resolved.telemetry);
5067
+ }
5068
+ // src/commands/token-context/token-context.ts
5069
+ /** Parses --token values and returns the context spread, or null on parse error (exits with code 1). */
5070
+ function tokenContext(rawTokens) {
5071
+ return tokenContext$1(rawTokens, reportError);
5072
+ }
4535
5073
  // src/commands/issue-types/classify-type-error/classify-type-error.ts
4536
5074
  /** Reads a thrown error as one of the four things `ensureIssueTypes()` acts on differently. */
4537
5075
  function classifyTypeError(err) {
@@ -5075,7 +5613,8 @@ async function provisionChannel(deps, spec) {
5075
5613
  ...spec.access ? { access: spec.access } : {},
5076
5614
  ...spec.kind ? { kind: spec.kind } : {},
5077
5615
  ...spec.tags ? { tags: spec.tags } : {},
5078
- ...spec.defaultReaction ? { defaultReaction: spec.defaultReaction } : {}
5616
+ ...spec.defaultReaction ? { defaultReaction: spec.defaultReaction } : {},
5617
+ ...spec.autoArchiveMinutes ? { autoArchiveMinutes: spec.autoArchiveMinutes } : {}
5079
5618
  });
5080
5619
  const changed = channel.created || (channel.updated?.length ?? 0) > 0;
5081
5620
  const verb = channel.created ? "created" : changed ? "updated" : "exists ";
@@ -6118,10 +6657,20 @@ const checkCommand = {
6118
6657
  handler: () => {}
6119
6658
  };
6120
6659
  // src/commands/cleanup-embeds/cleanup-embeds.args.ts
6121
- const cleanupEmbedsArgs = (y) => y.positional("channel", {
6660
+ const cleanupEmbedsArgs = (y) => y.option("channel", {
6661
+ type: "string",
6662
+ array: true,
6663
+ nargs: 1,
6664
+ alias: "c",
6665
+ describe: "A text channel to clean, with or without a leading # (repeat for more; default: alerts releases deploys sync)"
6666
+ }).positional("words", {
6122
6667
  type: "string",
6123
6668
  array: true,
6124
- describe: "The text channels to clean (default: alerts releases deploys sync)"
6669
+ hidden: true
6670
+ }).check((argv) => {
6671
+ const words = argv.words;
6672
+ if (words.length > 0) throw new Error(`cleanup embeds takes its channels with --channel, not as words (got: ${words.join(" ")}). Try: --channel ${words[0].replace(/^#/, "")}`);
6673
+ return true;
6125
6674
  }).option("limit", {
6126
6675
  type: "number",
6127
6676
  default: 200,
@@ -6381,7 +6930,7 @@ async function runCleanupEmbeds(input) {
6381
6930
  }
6382
6931
  // src/commands/cleanup-embeds/cleanup-embeds.command.ts
6383
6932
  const cleanupEmbedsCommand = {
6384
- command: "embeds [channel..]",
6933
+ command: "embeds [words..]",
6385
6934
  describe: "Hide the link-preview cards under the messages already in a text channel, keeping the links",
6386
6935
  builder: cleanupEmbedsArgs,
6387
6936
  handler: async (argv) => {
@@ -8275,7 +8824,7 @@ const row$37 = (id, status, detail) => ({
8275
8824
  */
8276
8825
  async function abandonWork(a) {
8277
8826
  const { input, key, source, pullRequest: pr } = a;
8278
- const git = input.git ?? runGit;
8827
+ const git = input.git ?? runGit$1;
8279
8828
  const repoRoot = input.context.repoRoot;
8280
8829
  const dryRun = Boolean(input.context.dryRun);
8281
8830
  const rows = [];
@@ -8887,7 +9436,7 @@ async function readIssueBoards(input) {
8887
9436
  /** The real git and file system {@link runStartWork} runs against; tests pass a fake. */
8888
9437
  function createRealStartWorkIo() {
8889
9438
  return {
8890
- git: runGit,
9439
+ git: runGit$1,
8891
9440
  exists: (path) => existsSync(path),
8892
9441
  read: (path) => readFileSync(path, "utf8"),
8893
9442
  write: (path, text) => {
@@ -10370,7 +10919,7 @@ async function runCloseWork(input) {
10370
10919
  return finish();
10371
10920
  }
10372
10921
  if (!pr) return fail("pull request", `no pull request for ${key} (its branch is <type>/<issue>-<slug>; --pr names one)`);
10373
- const git = input.git ?? runGit;
10922
+ const git = input.git ?? runGit$1;
10374
10923
  const repoRoot = input.context.repoRoot;
10375
10924
  if (pr.state === "closed") {
10376
10925
  if (!pr.merged) {
@@ -15645,6 +16194,7 @@ function forumFeedChecks(input, spec) {
15645
16194
  const forumProblems = [];
15646
16195
  const tagProblems = [];
15647
16196
  const botProblems = [];
16197
+ const leftOver = [];
15648
16198
  for (const { cat, channel } of fed) {
15649
16199
  const name = shown$6(channel.name);
15650
16200
  const have = found.channels.find((c) => same$6(c.name, channel.name) && c.category !== void 0 && same$6(c.category, cat));
@@ -15657,6 +16207,8 @@ function forumFeedChecks(input, spec) {
15657
16207
  continue;
15658
16208
  }
15659
16209
  for (const tag of spec.tags) if (!have.tags?.some((t) => same$6(t.name, tag))) tagProblems.push(`#${name}: tag "${tag}" is missing`);
16210
+ const old = spec.retired?.tag;
16211
+ if (old && have.tags?.some((t) => same$6(t.name, old))) leftOver.push(`#${name}`);
15660
16212
  if (have.botThreadsError) botProblems.push(`#${name}: could not read the bot's permissions (${shown$6(have.botThreadsError)})`);
15661
16213
  else if (have.botThreads) {
15662
16214
  if (!have.botThreads.post) botProblems.push(`#${name}: the bot cannot start posts or reply in it`);
@@ -15664,11 +16216,13 @@ function forumFeedChecks(input, spec) {
15664
16216
  } else botProblems.push(`#${name}: the provider did not report the bot's permissions`);
15665
16217
  }
15666
16218
  const ok = `${fed.length} of ${fed.length} as declared`;
15667
- return [
16219
+ const rows = [
15668
16220
  resultRow(spec.ids.forum, forumTitle, forumProblems, ok),
15669
16221
  resultRow(spec.ids.tags, tagsTitle, tagProblems, ok),
15670
16222
  resultRow(spec.ids.bot, botTitle, botProblems, ok)
15671
16223
  ];
16224
+ 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`));
16225
+ return rows;
15672
16226
  }
15673
16227
  // src/commands/notifications-setup/layout-picture-problem/layout-picture-problem.ts
15674
16228
  /** The first reason a picture in the layout (`webhookAvatar`, a channel's `webhook.avatar`) cannot work, or undefined. */
@@ -16179,10 +16733,17 @@ const PR_FEED_TAGS = [
16179
16733
  "failing",
16180
16734
  "changes requested",
16181
16735
  "ready",
16182
- "waiting",
16736
+ "in review",
16183
16737
  "merged",
16184
16738
  "closed"
16185
16739
  ];
16740
+ /** The idle times, in minutes, Discord allows a forum's posts before they are archived. */
16741
+ const AUTO_ARCHIVE_MINUTES = [
16742
+ 60,
16743
+ 1440,
16744
+ 4320,
16745
+ 10080
16746
+ ];
16186
16747
  /** The states an incident's post can be tagged with, so a forum with `feeds.incidents` must have all of them (lower case). */
16187
16748
  const INCIDENT_FEED_TAGS = [
16188
16749
  "investigating",
@@ -16206,6 +16767,7 @@ function forumLayoutProblem(layout) {
16206
16767
  const where = `channel \`${channel.name}\``;
16207
16768
  if (channel.kind !== "forum") {
16208
16769
  if (channel.tags) return `${where}: \`tags\` belong to a forum -- set \`kind: "forum"\` or remove them`;
16770
+ if (channel.autoArchiveMinutes !== void 0) return `${where}: \`autoArchiveMinutes\` belongs to a forum -- set \`kind: "forum"\` or remove it`;
16209
16771
  if (channel.defaultReaction || channel.starterReactions) return `${where}: reactions belong to a forum -- set \`kind: "forum"\` or remove them`;
16210
16772
  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`;
16211
16773
  if (channel.feeds?.incidents) return `${where}: \`feeds.incidents\` belongs to a forum, where each incident is a post -- set \`kind: "forum"\` or remove it`;
@@ -16220,6 +16782,9 @@ function forumLayoutProblem(layout) {
16220
16782
  const problem = reactionProblem("a starter reaction", reaction);
16221
16783
  if (problem) return `${where}: ${problem}`;
16222
16784
  }
16785
+ 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)}`;
16786
+ const retain = typeof channel.feeds?.prs === "object" ? channel.feeds.prs.retainDays : void 0;
16787
+ 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)}`;
16223
16788
  const seen = /* @__PURE__ */ new Set();
16224
16789
  for (const tag of channel.tags ?? []) {
16225
16790
  const name = tag.name.trim().toLowerCase();
@@ -16671,6 +17236,7 @@ async function runNotificationsSetup(input$1) {
16671
17236
  ...channel.kind ? { kind: channel.kind } : {},
16672
17237
  ...channel.tags ? { tags: channel.tags } : {},
16673
17238
  ...channel.defaultReaction ? { defaultReaction: channel.defaultReaction } : {},
17239
+ ...channel.autoArchiveMinutes ? { autoArchiveMinutes: channel.autoArchiveMinutes } : {},
16674
17240
  ...webhook ? { webhook } : {},
16675
17241
  ...channel.feeds?.monitoring || channel.feeds?.errors || relayFeedsOf(channel).length > 0 ? { feeds: {
16676
17242
  ...channel.feeds?.monitoring ? { monitoring: {
@@ -17637,7 +18203,11 @@ function prFeedChecks(input) {
17637
18203
  bot: "pr-feed-bot"
17638
18204
  },
17639
18205
  label: "pull request feed",
17640
- tags: PR_FEED_TAGS
18206
+ tags: PR_FEED_TAGS,
18207
+ retired: {
18208
+ id: "pr-feed-retired-tag",
18209
+ tag: "waiting"
18210
+ }
17641
18211
  });
17642
18212
  }
17643
18213
  // src/commands/relay-checks/relay-checks.ts
@@ -18007,6 +18577,7 @@ async function runDoctorNotifications(input) {
18007
18577
  else if (isForum) {
18008
18578
  const wantReaction = channel.defaultReaction ? reactionSpelling(channel.defaultReaction) : void 0;
18009
18579
  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)}"`);
18580
+ 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}`);
18010
18581
  for (const tag of channel.tags ?? []) {
18011
18582
  const have = match.tags?.find((t) => same$2(t.name, tag.name));
18012
18583
  if (!have) channelProblems.push(`#${shown(channel.name)}: tag "${shown(tag.name)}" is missing`);
@@ -30837,7 +31408,7 @@ async function promptEffort() {
30837
31408
  }
30838
31409
  // src/commands/new-work/read-git-config/read-git-config.ts
30839
31410
  /** One `git config --get` value in a directory, or `undefined` when the key is unset or git fails. */
30840
- function readGitConfig(cwd, key, run = runGit) {
31411
+ function readGitConfig(cwd, key, run = runGit$1) {
30841
31412
  try {
30842
31413
  return run([
30843
31414
  "config",
@@ -41089,7 +41660,7 @@ function planIncidentFeed(input) {
41089
41660
  // src/commands/render-incident/render-incident.ts
41090
41661
  /** Discord's message limit is 2000; an update's text is cut well short of it, leaving room for its heading and marker. */
41091
41662
  const UPDATE_TEXT_LIMIT = 1500;
41092
- const TITLE_LIMIT = 100;
41663
+ const TITLE_LIMIT$1 = 100;
41093
41664
  const IMPACT_WORDS = {
41094
41665
  maintenance: "under maintenance",
41095
41666
  degraded: "degraded",
@@ -41137,7 +41708,7 @@ function renderIncident(incident, statusPage) {
41137
41708
  lines.push(statusPage.url ? `Status page: [${statusPage.name}](<${statusPage.url}>)` : `Status page: ${statusPage.name}`);
41138
41709
  lines.push(incidentMarker(incident.id));
41139
41710
  return {
41140
- title: clip(incident.title, TITLE_LIMIT),
41711
+ title: clip(incident.title, TITLE_LIMIT$1),
41141
41712
  body: lines.join("\n"),
41142
41713
  tag
41143
41714
  };
@@ -41156,9 +41727,9 @@ function renderIncident(incident, statusPage) {
41156
41727
  */
41157
41728
  const DEFAULT_SINCE = "2d";
41158
41729
  /** How many of a post's messages are read to find the markers of its updates (Discord's limit per read). */
41159
- const MESSAGES = 100;
41730
+ const MESSAGES$1 = 100;
41160
41731
  /** The channel carrying the feed, and the name of the status page it follows. */
41161
- function feedOf(notifications, pages) {
41732
+ function feedOf$1(notifications, pages) {
41162
41733
  const fed = (notifications.layout?.categories ?? []).flatMap((c) => c.channels ?? []).filter((c) => c.feeds?.incidents);
41163
41734
  if (fed.length === 0) return { problem: "no forum in the layout has `feeds.incidents`" };
41164
41735
  if (fed.length > 1) return { problem: `several forums have \`feeds.incidents\` (${fed.map((c) => `\`${c.name}\``).join(", ")})` };
@@ -41200,7 +41771,7 @@ async function runSyncIncidents(input) {
41200
41771
  }
41201
41772
  const monitoring = loader.has("monitoring") ? loader.get("monitoring") : void 0;
41202
41773
  if (!monitoring?.listIncidents) return stop("skip", "no `monitoring` provider that lists status page incidents");
41203
- const feed = feedOf(notifications, monitoring.statusPages ?? []);
41774
+ const feed = feedOf$1(notifications, monitoring.statusPages ?? []);
41204
41775
  if ("problem" in feed) return stop(feed.problem.startsWith("no forum") ? "skip" : "fail", feed.problem);
41205
41776
  const { channel, page } = feed;
41206
41777
  const statusPage = {
@@ -41243,7 +41814,7 @@ async function runSyncIncidents(input) {
41243
41814
  incident,
41244
41815
  rendered,
41245
41816
  post,
41246
- messages: post ? await notifications.readDiscussionMessages(channel, key, MESSAGES) : []
41817
+ messages: post ? await notifications.readDiscussionMessages(channel, key, MESSAGES$1) : []
41247
41818
  });
41248
41819
  plans.push(plan);
41249
41820
  if (plan.steps.length === 0) {
@@ -41316,11 +41887,11 @@ async function apply(notifications, channel, key, rendered, plan) {
41316
41887
  quiet: true
41317
41888
  })).created) {
41318
41889
  if (await notifications.dedupeDiscussion(channel, key, { refresh: true }) > 0) {
41319
- const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES));
41890
+ const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES$1));
41320
41891
  append = append.filter((u) => !posted.has(u.id));
41321
41892
  }
41322
41893
  } else {
41323
- const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES));
41894
+ const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES$1));
41324
41895
  append = append.filter((u) => !posted.has(u.id));
41325
41896
  }
41326
41897
  } else if (plan.rewrite || plan.retag || plan.close === false) await notifications.updateDiscussion(channel, key, {
@@ -41628,6 +42199,443 @@ const syncIssuesCommand = {
41628
42199
  })).status === "fail") process.exitCode = 1;
41629
42200
  }
41630
42201
  };
42202
+ // src/pull-request-post/pr-key/pr-key.ts
42203
+ /** The key a pull request's post is found by: `owner/repo#123`. */
42204
+ function prKey(repo, number) {
42205
+ return `${repo}#${number}`;
42206
+ }
42207
+ // src/pull-request-post/pull-request-tag/pull-request-tag.ts
42208
+ /** The tag of a pull request: the first that applies of merged, closed, draft, conflicts, failing, changes requested, ready, in review. */
42209
+ function pullRequestTag(state) {
42210
+ if (state.merged) return "merged";
42211
+ if (state.closed) return "closed";
42212
+ if (state.draft) return "draft";
42213
+ if (state.mergeable === "conflicting") return "conflicts";
42214
+ if (state.ci === "failing") return "failing";
42215
+ if (state.review === "changes_requested") return "changes requested";
42216
+ if (state.review === "approved" && state.ci === "passing") return "ready";
42217
+ return "in review";
42218
+ }
42219
+ // src/pull-request-post/age-text/age-text.ts
42220
+ const MINUTE = 6e4;
42221
+ const HOUR = 60 * MINUTE;
42222
+ const DAY$1 = 24 * HOUR;
42223
+ /** How long ago something happened, in the largest whole unit: `just now`, `5 minutes ago`, `1 hour ago`, `3 days ago`. */
42224
+ function ageText(createdAt, now) {
42225
+ const elapsed = Math.max(0, now.getTime() - new Date(createdAt).getTime());
42226
+ if (elapsed < MINUTE) return "just now";
42227
+ const [value, unit] = elapsed >= DAY$1 ? [Math.floor(elapsed / DAY$1), "day"] : elapsed >= HOUR ? [Math.floor(elapsed / HOUR), "hour"] : [Math.floor(elapsed / MINUTE), "minute"];
42228
+ return `${value} ${unit}${value === 1 ? "" : "s"} ago`;
42229
+ }
42230
+ /** What Sourcery writes between its start and end markers, e.g. the reviewer's guide. */
42231
+ const SOURCERY_BLOCK = /<!--\s*Generated by sourcery-ai[^>]*?start\s+(\w+)\s*-->[\s\S]*?<!--\s*Generated by sourcery-ai[^>]*?end\s+\1\s*-->/gi;
42232
+ /** Sourcery's auto-generated summary starts at this marker and runs to the end of the description. */
42233
+ const SOURCERY_SUMMARY = /<!--\s*This is an auto-generated description by sourcery-ai\.?\s*-->[\s\S]*$/i;
42234
+ /** A command someone typed to Sourcery (`@sourcery-ai summary`). */
42235
+ const SOURCERY_COMMAND = /^.*@sourcery-ai\b.*$/gim;
42236
+ /** Drops each heading that names Sourcery with its section, up to the next heading of the same or a higher level. */
42237
+ function withoutSourcerySections(text) {
42238
+ const kept = [];
42239
+ let skipping = 0;
42240
+ for (const line of text.split("\n")) {
42241
+ const heading = /^(#{1,6})\s/.exec(line);
42242
+ if (heading) {
42243
+ const level = heading[1].length;
42244
+ if (/sourcery/i.test(line)) {
42245
+ skipping = level;
42246
+ continue;
42247
+ }
42248
+ if (skipping > 0 && level <= skipping) skipping = 0;
42249
+ }
42250
+ if (skipping === 0) kept.push(line);
42251
+ }
42252
+ return kept.join("\n");
42253
+ }
42254
+ /**
42255
+ * `text` without its HTML comments, repeated until none is left: taking one out can join the pieces around it into a new
42256
+ * one (`<!<!-- x -->-- y -->`), which a single pass would leave in the post.
42257
+ */
42258
+ function withoutHtmlComments(text) {
42259
+ let current = text;
42260
+ for (;;) {
42261
+ const next = current.replace(/<!--[\s\S]*?-->/g, "");
42262
+ if (next === current) return next;
42263
+ current = next;
42264
+ }
42265
+ }
42266
+ /**
42267
+ * The part of a pull request's description worth showing in its post: the text the author wrote. Sourcery's summary,
42268
+ * reviewer's guide and commands are removed, and so is every HTML comment (a template's hints), the blank runs they
42269
+ * leave are closed up, and what is left is cut to {@link DESCRIPTION_LIMIT} characters with an ellipsis. A description
42270
+ * with nothing left, or none, is an empty string.
42271
+ */
42272
+ function prDescription(body) {
42273
+ if (!body) return "";
42274
+ 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();
42275
+ return text.length <= 1500 ? text : `${text.slice(0, 1499).trimEnd()}…`;
42276
+ }
42277
+ // src/pull-request-post/render-pull-request/render-pull-request.ts
42278
+ /** Discord's limit on a post's title. */
42279
+ const TITLE_LIMIT = 100;
42280
+ const CI_TEXT = {
42281
+ passing: "passing",
42282
+ failing: "failing",
42283
+ pending: "running",
42284
+ none: "no result yet"
42285
+ };
42286
+ function cut(text) {
42287
+ return text.length <= TITLE_LIMIT ? text : `${text.slice(0, 99)}…`;
42288
+ }
42289
+ function reviewText(state) {
42290
+ if (state.review === "approved") return "approved";
42291
+ if (state.review === "changes_requested") return "changes requested";
42292
+ if (state.requestedReviewers.length > 0) return `waiting on review from ${state.requestedReviewers.join(", ")}`;
42293
+ return "waiting on review";
42294
+ }
42295
+ /**
42296
+ * The post for a pull request: its title (`repo#123: title`, plain text, because a forum post's title is not
42297
+ * markdown), the summary that is the first message (edited in place, no footer: a link to the pull request without
42298
+ * 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.
42299
+ */
42300
+ function renderPullRequest(state, now) {
42301
+ const tag = pullRequestTag(state);
42302
+ const name = state.repo.slice(state.repo.indexOf("/") + 1);
42303
+ const author = state.authorIsBot ? `${state.author} (bot)` : state.author;
42304
+ const status = state.merged ? "merged" : state.closed ? "closed" : state.draft ? "draft" : reviewText(state);
42305
+ const lines = [
42306
+ `**[${state.repo}#${state.number}](${state.url})**`,
42307
+ `by ${author} into \`${state.base}\`, opened ${ageText(state.createdAt, now)}`,
42308
+ `Status: ${status}`,
42309
+ `CI: ${CI_TEXT[state.ci]}`
42310
+ ];
42311
+ if (state.mergeable === "conflicting") lines.push(`Conflicts with \`${state.base}\``);
42312
+ const description = prDescription(state.body);
42313
+ const body = description ? `${lines.join("\n")}\n\n${description}` : lines.join("\n");
42314
+ return {
42315
+ title: cut(`${name}#${state.number}: ${state.title}`),
42316
+ body,
42317
+ tag
42318
+ };
42319
+ }
42320
+ // src/commands/first-message-body/first-message-body.ts
42321
+ /**
42322
+ * The text of a post's first message without the footer the provider ends it with (`-# sync: <key> | <state>`), found
42323
+ * among its recent messages (newest first) by that footer; `undefined` when the message is not among them, as when the
42324
+ * thread is longer than one read.
42325
+ */
42326
+ function firstMessageBody(messages, key) {
42327
+ const footer = `-# sync: ${key} |`;
42328
+ for (const message of messages) {
42329
+ const at = message.lastIndexOf(`\n\n${footer}`);
42330
+ if (at >= 0) return message.slice(0, at);
42331
+ }
42332
+ }
42333
+ // src/commands/plan-pull-request-post/plan-pull-request-post.ts
42334
+ /** The age in the summary's second line (`opened 5 minutes ago`), which changes by the minute and so is not a difference. */
42335
+ const AGE = /, opened (?:just now|\d+ (?:minute|hour|day)s? ago)/;
42336
+ /** 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. */
42337
+ function bodyDiffers(existing, wanted) {
42338
+ if (existing === void 0) return false;
42339
+ const had = existing.replace(AGE, ", opened");
42340
+ const want = wanted.replace(AGE, ", opened");
42341
+ if (had === want) return false;
42342
+ return !(had.endsWith("…") && want.startsWith(had.slice(0, -1)));
42343
+ }
42344
+ /**
42345
+ * What a pull request's post needs: its tag (set back when a person changed it: Discord never sets a pull request's
42346
+ * state), its title, the text of its first message and whether it is archived. Pure, and the one comparison
42347
+ * `holocron sync prs` uses. Messages the feed appends (the CI and lifecycle lines) are never part of it.
42348
+ */
42349
+ function planPullRequestPost(input) {
42350
+ const { rendered, post } = input;
42351
+ const steps = [];
42352
+ const patch = {};
42353
+ if (post.state !== rendered.tag) {
42354
+ steps.push(post.state === void 0 ? `tag set to \`${rendered.tag}\`` : `tag set back to \`${rendered.tag}\` (was \`${post.state}\`)`);
42355
+ patch.state = rendered.tag;
42356
+ }
42357
+ if (post.title !== void 0 && post.title !== rendered.title) {
42358
+ steps.push("title updated");
42359
+ patch.title = rendered.title;
42360
+ }
42361
+ if (bodyDiffers(input.firstBody, rendered.body)) {
42362
+ steps.push("first message updated");
42363
+ patch.body = rendered.body;
42364
+ }
42365
+ if ((post.closed ?? false) !== input.closed) {
42366
+ steps.push(input.closed ? "archived and locked" : "opened again");
42367
+ patch.closed = input.closed;
42368
+ }
42369
+ return {
42370
+ steps,
42371
+ patch
42372
+ };
42373
+ }
42374
+ // src/commands/pull-request-post-expired/pull-request-post-expired.ts
42375
+ const DAY = 864e5;
42376
+ /**
42377
+ * Whether a closed pull request's post is past `feeds.prs.retainDays`: closed more than that many days before `now`. A
42378
+ * pull request with no known close time, or a feed with no `retainDays`, never is.
42379
+ */
42380
+ function pullRequestPostExpired(closedAt, retainDays, now) {
42381
+ if (retainDays === void 0 || closedAt === void 0) return false;
42382
+ return now.getTime() - new Date(closedAt).getTime() > retainDays * DAY;
42383
+ }
42384
+ // src/commands/sync-prs/map-in-batches/map-in-batches.ts
42385
+ /** Runs `fn` over `items`, `size` at a time, and returns the results in the order of the items. */
42386
+ async function mapInBatches(items, size, fn) {
42387
+ const results = [];
42388
+ for (let i = 0; i < items.length; i += size) results.push(...await Promise.all(items.slice(i, i + size).map(fn)));
42389
+ return results;
42390
+ }
42391
+ // src/commands/sync-prs/run-sync-prs/run-sync-prs.ts
42392
+ /**
42393
+ * `holocron sync prs` -- keep the pull request forum's posts in step with GitHub (spec `tech-discord-notifications-v2`,
42394
+ * step 3, #2853).
42395
+ *
42396
+ * Sentinel's feed writes a post on each webhook delivery; a missed delivery, an outage or a hand-changed tag leaves a
42397
+ * post wrong until the next event. This reads the repository's open pull requests, each as `Source.readPullRequestState`
42398
+ * gives it, and the forum's posts, and puts each post's tag, title and first message right through the same
42399
+ * `renderPullRequest()` the feed uses, and archives the post of a pull request that is closed or merged. Discord does
42400
+ * 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
42401
+ * gone and a key with several posts are reported and left alone; a missing post is left to the feed. When
42402
+ * `feeds.prs.retainDays` is set, the post of a pull request closed longer ago than that is deleted, unless a person
42403
+ * wrote in it. The messages the feed appends (CI and lifecycle lines) are never touched. It reads state, so a second run
42404
+ * changes nothing. A rate limit (429) stops the run and the next one continues. It writes, so it asks first; `--yes`
42405
+ * skips the question and, without a terminal, a run with neither `--yes` nor `--dry-run` refuses.
42406
+ */
42407
+ /** How many of a post's messages are read to find its first one (Discord's limit per read). */
42408
+ const MESSAGES = 100;
42409
+ /** How many pull requests are read from GitHub and Discord at once. */
42410
+ const BATCH = 4;
42411
+ /** The forum that carries the pull request feed, or why there is none. */
42412
+ function feedOf(notifications) {
42413
+ const fed = (notifications.layout?.categories ?? []).flatMap((c) => c.channels ?? []).filter((c) => c.feeds?.prs);
42414
+ if (fed.length === 0) return { problem: "no forum in the layout has `feeds.prs`" };
42415
+ if (fed.length > 1) return { problem: `several forums have \`feeds.prs\` (${fed.map((c) => `\`${c.name}\``).join(", ")})` };
42416
+ return { channel: fed[0] };
42417
+ }
42418
+ async function runSyncPrs(input) {
42419
+ const print = input.print ?? ((line) => console.log(line));
42420
+ const row = (status, ...parts) => print(statusRow$1(status, ["sync prs", ...parts]));
42421
+ const stop = (status, reason) => {
42422
+ row(status, reason);
42423
+ return {
42424
+ status,
42425
+ reason
42426
+ };
42427
+ };
42428
+ const now = input.now ?? /* @__PURE__ */ new Date();
42429
+ const dryRun = Boolean(input.context.dryRun);
42430
+ /* v8 ignore next -- the real loader is only built outside tests, which always inject one */
42431
+ const loader = input.loader ?? new PluginLoader(input.loaded.resolved, input.context);
42432
+ await loader.load();
42433
+ assertPluginsResolvable(loader, "sync prs");
42434
+ let notifications;
42435
+ try {
42436
+ notifications = pickDiscussionProvider(notificationProviders(loader), input.provider);
42437
+ } catch (err) {
42438
+ return stop("skip", errorMessage(err));
42439
+ }
42440
+ if (!notifications.listDiscussions || !notifications.readDiscussionMessages) return stop("fail", `the \`${notifications.providerName}\` provider cannot list or read discussion posts`);
42441
+ const feed = feedOf(notifications);
42442
+ if ("problem" in feed) return stop(feed.problem.startsWith("no forum") ? "skip" : "fail", feed.problem);
42443
+ const channel = feed.channel.name;
42444
+ const prsFeed = feed.channel.feeds.prs;
42445
+ const retainDays = typeof prsFeed === "object" ? prsFeed.retainDays : void 0;
42446
+ const exclude = typeof prsFeed === "object" ? prsFeed.exclude : void 0;
42447
+ if (retainDays !== void 0 && !notifications.deleteDiscussion) return stop("fail", `\`feeds.prs.retainDays\` is set but the \`${notifications.providerName}\` provider cannot delete a post`);
42448
+ const source = loader.has("source") ? loader.get("source") : void 0;
42449
+ if (!source) return stop("skip", "no `source` provider to read pull requests from");
42450
+ if (!source.listPullRequests || !source.readPullRequestState) return stop("fail", `the \`${source.providerName}\` provider cannot read a pull request's state`);
42451
+ const repo = input.context.repo ?? (input.context.org && input.loaded.resolved.name ? `${input.context.org}/${input.loaded.resolved.name}` : void 0);
42452
+ if (!repo) return stop("fail", "cannot tell which repository this is; run it from a checkout with a name and an org");
42453
+ if (exclude?.repos?.includes(repo)) return stop("skip", `\`feeds.prs.exclude\` leaves ${repo} out`);
42454
+ const excludedAuthors = new Set((exclude?.authors ?? []).map((a) => a.toLowerCase()));
42455
+ const counts = {
42456
+ updated: 0,
42457
+ deleted: 0,
42458
+ unchanged: 0,
42459
+ reported: 0,
42460
+ failed: 0,
42461
+ left: 0
42462
+ };
42463
+ let posts;
42464
+ let open;
42465
+ let required;
42466
+ try {
42467
+ if (aggregatePoster({ ci: input.loaded.resolved.ci }) === "none") required = (await resolveRequiredChecks({
42468
+ source,
42469
+ config: input.loaded.resolved
42470
+ })).required;
42471
+ [posts, open] = await Promise.all([notifications.listDiscussions(channel), source.listPullRequests("open", repo)]);
42472
+ } catch (err) {
42473
+ return stop("fail", `reading the pull requests and #${channel}: ${describeError(err)}`);
42474
+ }
42475
+ const prefix = prKey(repo, 0).slice(0, -1);
42476
+ const mine = /* @__PURE__ */ new Map();
42477
+ for (const post of posts) {
42478
+ const rest = post.key?.startsWith(prefix) ? post.key.slice(prefix.length) : "";
42479
+ if (/^\d+$/.test(rest)) mine.set(Number(rest), post);
42480
+ }
42481
+ for (const post of mine.values()) if (post.duplicates) {
42482
+ counts.reported++;
42483
+ row("skip", post.key, `${post.duplicates} more post(s) carry this key; \`holocron cleanup posts\` removes them`);
42484
+ }
42485
+ const finished = (post) => post.closed && (post.state === "merged" || post.state === "closed");
42486
+ const numbers = [.../* @__PURE__ */ new Set([...open.map((p) => p.number), ...mine.keys()])].filter((n) => {
42487
+ if (open.some((p) => p.number === n) || retainDays !== void 0) return true;
42488
+ if (finished(mine.get(n))) {
42489
+ counts.unchanged++;
42490
+ return false;
42491
+ }
42492
+ return true;
42493
+ });
42494
+ let limited = false;
42495
+ const looked = await mapInBatches(numbers, BATCH, async (number) => {
42496
+ const key = prKey(repo, number);
42497
+ if (limited) return { kind: "left" };
42498
+ try {
42499
+ const state = await source.readPullRequestState(number, repo, required);
42500
+ if (!state) return {
42501
+ kind: "gone",
42502
+ key
42503
+ };
42504
+ if (excludedAuthors.has(state.author.toLowerCase())) return { kind: "excluded" };
42505
+ const post = mine.get(number);
42506
+ if (!post) return {
42507
+ kind: "no-post",
42508
+ key
42509
+ };
42510
+ if (state.closed && pullRequestPostExpired(state.closedAt, retainDays, now)) return {
42511
+ kind: "work",
42512
+ work: {
42513
+ key,
42514
+ steps: [`deleted (closed more than ${retainDays} day(s) ago)`],
42515
+ patch: {},
42516
+ remove: true
42517
+ }
42518
+ };
42519
+ const messages = await notifications.readDiscussionMessages(channel, key, MESSAGES);
42520
+ const plan = planPullRequestPost({
42521
+ rendered: renderPullRequest(state, now),
42522
+ closed: state.closed,
42523
+ post,
42524
+ firstBody: firstMessageBody(messages, key)
42525
+ });
42526
+ return plan.steps.length === 0 ? { kind: "same" } : {
42527
+ kind: "work",
42528
+ work: {
42529
+ key,
42530
+ steps: plan.steps,
42531
+ patch: plan.patch
42532
+ }
42533
+ };
42534
+ } catch (err) {
42535
+ if (rateLimitedFor(err) !== void 0) {
42536
+ limited = true;
42537
+ return { kind: "left" };
42538
+ }
42539
+ return {
42540
+ kind: "fail",
42541
+ key,
42542
+ reason: describeError(err)
42543
+ };
42544
+ }
42545
+ });
42546
+ const work = [];
42547
+ for (const item of looked) if (item.kind === "work") work.push(item.work);
42548
+ else if (item.kind === "same") counts.unchanged++;
42549
+ else if (item.kind === "left") counts.left++;
42550
+ else if (item.kind === "gone") {
42551
+ counts.reported++;
42552
+ row("skip", item.key, "its pull request was not found; the post is left alone");
42553
+ } else if (item.kind === "no-post") {
42554
+ counts.reported++;
42555
+ row("skip", item.key, "has no post yet; the feed makes it on the pull request's next event");
42556
+ } else if (item.kind === "fail") {
42557
+ counts.failed++;
42558
+ row("fail", item.key, `reading it: ${item.reason}`);
42559
+ }
42560
+ if (dryRun) {
42561
+ for (const w of work) row("skip", w.key, `would be: ${w.steps.join("; ")}`);
42562
+ row("skip", `dry run, nothing written; ${work.length} post(s) would change, ${counts.unchanged} in step`);
42563
+ return {
42564
+ status: counts.failed > 0 ? "fail" : "ok",
42565
+ counts
42566
+ };
42567
+ }
42568
+ if (work.length > 0 && !input.yes) {
42569
+ 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`);
42570
+ if (!await (input.confirm ?? ((message) => confirm({
42571
+ message,
42572
+ default: false
42573
+ })))(`Change ${work.length} pull request post(s) in #${channel}?`)) {
42574
+ row("skip", "cancelled; nothing was changed");
42575
+ return {
42576
+ status: "cancelled",
42577
+ counts
42578
+ };
42579
+ }
42580
+ }
42581
+ for (const [index, w] of work.entries()) try {
42582
+ if (w.remove) {
42583
+ if (await notifications.deleteDiscussion(channel, w.key)) {
42584
+ counts.deleted++;
42585
+ row("ok", w.key, w.steps.join("; "));
42586
+ } else {
42587
+ counts.reported++;
42588
+ row("skip", w.key, "kept past `retainDays`: a person has written in it");
42589
+ }
42590
+ } else {
42591
+ await notifications.updateDiscussion(channel, w.key, w.patch);
42592
+ counts.updated++;
42593
+ row("ok", w.key, w.steps.join("; "));
42594
+ }
42595
+ } catch (err) {
42596
+ if (rateLimitedFor(err) !== void 0) {
42597
+ counts.left += work.length - index;
42598
+ break;
42599
+ }
42600
+ counts.failed++;
42601
+ row("fail", w.key, describeError(err));
42602
+ }
42603
+ if (counts.left > 0) row("skip", `stopped: a service is rate limiting; ${counts.left} post(s) are left for the next run`);
42604
+ 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}`);
42605
+ return {
42606
+ status: counts.failed > 0 ? "fail" : "ok",
42607
+ counts
42608
+ };
42609
+ }
42610
+ // src/commands/sync-prs/sync-prs.command.ts
42611
+ const syncPrsCommand = {
42612
+ command: "prs",
42613
+ describe: "Keep the pull request forum's posts in step with GitHub: tag, title and first message, and archive finished ones",
42614
+ builder: (y) => y.option("provider", {
42615
+ type: "string",
42616
+ describe: "The `notifications` provider to write through, when several are configured"
42617
+ }).option("yes", {
42618
+ type: "boolean",
42619
+ describe: "Change the posts without asking (a scheduled run needs it)"
42620
+ }),
42621
+ handler: async (argv) => {
42622
+ const tokens = tokenContext(argv.token);
42623
+ if (!tokens) return;
42624
+ const loaded = await loadConfig(argv.cwd);
42625
+ applyResolvedConfig(argv, loaded.resolved);
42626
+ if ((await runSyncPrs({
42627
+ loaded,
42628
+ context: {
42629
+ repoRoot: argv.cwd,
42630
+ dryRun: argv.dryRun,
42631
+ ...tokens,
42632
+ org: resolveOrg(argv, loaded.resolved)
42633
+ },
42634
+ ...argv.provider ? { provider: argv.provider } : {},
42635
+ ...argv.yes ? { yes: true } : {}
42636
+ })).status === "fail") process.exitCode = 1;
42637
+ }
42638
+ };
41631
42639
  // src/commands/sync-readme/generate-readme.ts
41632
42640
  /** Scripts that are neither a task nor a check: what a contributor runs while working (spec: "the dev scripts"). */
41633
42641
  const DEV_SCRIPTS = [
@@ -41911,6 +42919,77 @@ const syncReadmeCommand = {
41911
42919
  }
41912
42920
  }
41913
42921
  };
42922
+ // src/commands/sync-releases/run-git/run-git.ts
42923
+ /** The most output of one git call, so a long range is read whole and not cut by Node's 1 MiB default. */
42924
+ const MAX_BUFFER = 67108864;
42925
+ /** The real `git`: runs it in `cwd` and returns its output; throws when git fails. */
42926
+ const runGit = (cwd, args) => execFileSync("git", args, {
42927
+ cwd,
42928
+ encoding: "utf8",
42929
+ stdio: [
42930
+ "ignore",
42931
+ "pipe",
42932
+ "ignore"
42933
+ ],
42934
+ maxBuffer: MAX_BUFFER
42935
+ });
42936
+ // src/commands/sync-releases/release-changes/release-changes.ts
42937
+ /** A subject that is not a change worth announcing: the release bot's own commit. */
42938
+ const RELEASE_COMMIT = /^chore\(release\)!?:/i;
42939
+ /** A ticket reference line of a commit body: `Closes #1`, `Refs #2, #3`. Only these lines are read from a body. */
42940
+ const REFERENCE_LINE = /^(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?|refs?)\b[:\s]+(.*)$/i;
42941
+ const TRAILING_PR = /\s*\(#(\d+)\)\s*$/;
42942
+ /**
42943
+ * The changes of a release, newest first: each non-merge commit of `from..to` as its subject and the ticket numbers
42944
+ * it names (a trailing `(#123)` in the subject, and `Closes`/`Fixes`/`Resolves`/`Refs #N` lines of the body; nothing
42945
+ * else of the body is read). The release commits (`chore(release)`) are left out. Local git only, so it needs no
42946
+ * network call. With no `from` (a first release), or when git cannot read the range, there are no changes.
42947
+ *
42948
+ * @param cwd - The repository root.
42949
+ * @param from - The commit the release started from.
42950
+ * @param to - The release commit.
42951
+ * @param git - Runs git; tests pass a fake.
42952
+ */
42953
+ function releaseChanges(cwd, from, to, git = runGit) {
42954
+ if (!from) return [];
42955
+ let out;
42956
+ try {
42957
+ out = git(cwd, [
42958
+ "log",
42959
+ "--no-merges",
42960
+ "-z",
42961
+ "--format=%s%x00%b",
42962
+ `${from}..${to}`
42963
+ ]);
42964
+ } catch {
42965
+ return [];
42966
+ }
42967
+ const changes = [];
42968
+ const fields = out.split("\0");
42969
+ if (fields.length % 2 === 1) fields.push("");
42970
+ for (let at = 0; at < fields.length; at += 2) {
42971
+ const rawSubject = fields[at];
42972
+ const body = fields[at + 1];
42973
+ let subject = rawSubject.trim();
42974
+ if (!subject || RELEASE_COMMIT.test(subject)) continue;
42975
+ const issues = [];
42976
+ const pr = TRAILING_PR.exec(subject);
42977
+ if (pr) {
42978
+ subject = subject.slice(0, pr.index);
42979
+ issues.push(Number(pr[1]));
42980
+ }
42981
+ for (const line of body.split("\n")) {
42982
+ const refs = REFERENCE_LINE.exec(line.trim());
42983
+ if (!refs) continue;
42984
+ for (const m of refs[1].matchAll(/#(\d+)/g)) issues.push(Number(m[1]));
42985
+ }
42986
+ changes.push({
42987
+ subject,
42988
+ issues: [...new Set(issues)]
42989
+ });
42990
+ }
42991
+ return changes;
42992
+ }
41914
42993
  // src/commands/sync-releases/release-marker/release-marker.ts
41915
42994
  /**
41916
42995
  * The marker that ends a release's message: Discord's small-text line, so it is quiet to read, carrying the release id
@@ -42003,6 +43082,20 @@ function releasedPackages(cwd, from, to) {
42003
43082
  }
42004
43083
  return released.sort((a, b) => a.name.localeCompare(b.name));
42005
43084
  }
43085
+ // src/commands/sync-releases/change-line/change-line.ts
43086
+ /**
43087
+ * One change as a list item: its subject (type, scope and emoji kept) and a link per ticket,
43088
+ * `- feat(cli): add x [#1](https://github.com/o/r/issues/1)`. Without a repository the numbers are plain text. An `@`
43089
+ * in the subject is broken so a commit message cannot mention anyone, Markdown characters are escaped so it cannot
43090
+ * make a link or format the line, and `://` is broken so a bare address is not made a link.
43091
+ */
43092
+ function changeLine(change, repo) {
43093
+ return [
43094
+ "-",
43095
+ change.subject.replaceAll("@", "@​").replaceAll("://", ":​//").replace(/[\\[\]*_~`|<>]/g, "\\$&"),
43096
+ ...change.issues.map((n) => repo ? `[#${n}](https://github.com/${repo}/issues/${n})` : `#${n}`)
43097
+ ].join(" ");
43098
+ }
42006
43099
  // src/commands/sync-releases/package-line/package-line.ts
42007
43100
  /** The page of one version of a package on npm. */
42008
43101
  function npmVersionUrl(pkg) {
@@ -42020,21 +43113,40 @@ function packageLine(pkg) {
42020
43113
  // src/commands/sync-releases/render-release/render-release.ts
42021
43114
  /** Discord's limit on a thread's name. */
42022
43115
  const THREAD_NAME_LIMIT = 100;
43116
+ /** Discord's limit on a message, and the most changes the blurb lists. */
43117
+ const MESSAGE_LIMIT = 2e3;
43118
+ const MAX_CHANGES = 8;
42023
43119
  /**
42024
43120
  * The text of a release's announcement: a message with the headline, the link to the GitHub release (when a tag and
42025
43121
  * the repository are known) and the marker last, a thread name, and one list item per package that links to the
42026
- * version's page on npm. Chunking the lines to the provider's limit is the provider's job.
43122
+ * version's page on npm. With `changes`, up to eight of them follow the link (an `and N more` line when some are left
43123
+ * 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.
42027
43124
  */
42028
43125
  function renderRelease(input) {
42029
- const { id, tag, repo, packages } = input;
43126
+ const { id, tag, repo, packages, changes = [] } = input;
42030
43127
  const count = packages.length;
42031
43128
  const tags = [...new Set(packages.map((p) => p.distTag))].join(", ");
43129
+ const head = [`**${tag ?? id}** released: ${count} package${count === 1 ? "" : "s"} on ${tags}`, ...tag && repo ? [`https://github.com/${repo}/releases/tag/${tag}`] : []];
43130
+ const marker = releaseMarker(id);
43131
+ const candidates = changes.slice(0, MAX_CHANGES).map((c) => changeLine(c, repo));
43132
+ const build = (kept) => {
43133
+ const left = changes.length - kept;
43134
+ return [
43135
+ ...head,
43136
+ ...candidates.slice(0, kept),
43137
+ ...left > 0 ? [`- and ${left} more`] : [],
43138
+ marker
43139
+ ].join("\n");
43140
+ };
43141
+ let kept = 0;
43142
+ while (kept < candidates.length && build(kept + 1).length < MESSAGE_LIMIT) kept++;
43143
+ let message = build(kept);
43144
+ if (message.length >= MESSAGE_LIMIT) {
43145
+ const room = MESSAGE_LIMIT - marker.length - 2;
43146
+ message = [head[0].slice(0, room), marker].join("\n");
43147
+ }
42032
43148
  return {
42033
- message: [
42034
- `**${tag ?? id}** released: ${count} package${count === 1 ? "" : "s"} on ${tags}`,
42035
- ...tag && repo ? [`https://github.com/${repo}/releases/tag/${tag}`] : [],
42036
- releaseMarker(id)
42037
- ].join("\n"),
43149
+ message,
42038
43150
  threadName: (tag ?? id).slice(0, THREAD_NAME_LIMIT),
42039
43151
  lines: packages.map(packageLine)
42040
43152
  };
@@ -42082,7 +43194,8 @@ async function runSyncReleases(input) {
42082
43194
  id,
42083
43195
  ...input.tag ? { tag: input.tag } : {},
42084
43196
  ...repo ? { repo } : {},
42085
- packages
43197
+ packages,
43198
+ changes: releaseChanges(input.context.repoRoot, input.from || void 0, input.to)
42086
43199
  });
42087
43200
  const marker = releaseMarker(id);
42088
43201
  if (dryRun) {
@@ -43487,7 +44600,7 @@ async function syncApp(argv) {
43487
44600
  const syncCommand = {
43488
44601
  command: "sync [steps..]",
43489
44602
  describe: "Sync state from config to the provider and local files (labels, properties, teams, topics, keywords, description, homepage, readme, workflows, scripts, wiki)",
43490
- 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),
44603
+ 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),
43491
44604
  handler: async (argv) => {
43492
44605
  if (argv.env !== void 0 || argv.steps?.[0] !== void 0) {
43493
44606
  if (await syncApp(argv)) return;
@@ -44356,6 +45469,8 @@ let finishCommand = () => {};
44356
45469
  /** What ran, for the offer to run it for real after a `--dry-run` of it. */
44357
45470
  let ranWords = [];
44358
45471
  let ranDryRun = false;
45472
+ /** When the command started and what it was run with, for the command log; unset when no command ran (`--help`). */
45473
+ let runLog;
44359
45474
  /** Set by `.fail()` once it has printed an error, so the outer catch doesn't repeat it. */
44360
45475
  let errorReported = false;
44361
45476
  try {
@@ -44395,6 +45510,17 @@ try {
44395
45510
  command: name,
44396
45511
  org: argv.org
44397
45512
  });
45513
+ const cwd = String(argv.cwd);
45514
+ runLog = {
45515
+ startedAt: Date.now(),
45516
+ cwd,
45517
+ run: startThisRun({
45518
+ words: ranWords,
45519
+ args: process.argv.slice(2),
45520
+ cwd,
45521
+ org: argv.org
45522
+ })
45523
+ };
44398
45524
  finishCommand = startCommand$1(name);
44399
45525
  const label = commandProgressLabel(argv._);
44400
45526
  if (label) startCommandProgress(label);
@@ -44421,6 +45547,13 @@ try {
44421
45547
  }
44422
45548
  finishCommand(!process.exitCode);
44423
45549
  endSession();
45550
+ if (runLog) await runLog.run.record({
45551
+ startedAt: runLog.startedAt,
45552
+ cwd: runLog.cwd,
45553
+ words: ranWords,
45554
+ args: process.argv.slice(2),
45555
+ exitCode: Number(process.exitCode ?? 0)
45556
+ });
44424
45557
  const offered = await offerRealRun({
44425
45558
  words: ranWords,
44426
45559
  args: process.argv.slice(2),