@theholocron/cli 5.0.0-alpha.593 → 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",
@@ -2230,6 +2231,15 @@ const syncIssuesEntry = {
2230
2231
  skipOptions: ["yes"],
2231
2232
  supportsDryRun: true
2232
2233
  };
2234
+ // src/commands/sync-prs/sync-prs.entry.ts
2235
+ const syncPrsEntry = {
2236
+ name: "sync prs",
2237
+ description: "Keep the pull request forum's posts in step with GitHub",
2238
+ positionals: [],
2239
+ options: [],
2240
+ skipOptions: ["provider", "yes"],
2241
+ supportsDryRun: true
2242
+ };
2233
2243
  // src/commands/sync-readme/sync-readme.entry.ts
2234
2244
  const syncReadmeEntry = {
2235
2245
  name: "sync readme",
@@ -2495,6 +2505,7 @@ const registry = createCommandRegistry([
2495
2505
  syncGithubEntry,
2496
2506
  syncIssuesEntry,
2497
2507
  syncIncidentsEntry,
2508
+ syncPrsEntry,
2498
2509
  syncReleasesEntry,
2499
2510
  ideasSyncEntry,
2500
2511
  syncToolingEntry,
@@ -2786,7 +2797,7 @@ function withoutDryRun(args) {
2786
2797
  return [...own.filter((arg) => arg !== "--dry-run" && !arg.startsWith("--dry-run=")), ...rest];
2787
2798
  }
2788
2799
  // src/commands/offer-real-run/offer-real-run.ts
2789
- const INFO_FLAGS = /* @__PURE__ */ new Set([
2800
+ const INFO_FLAGS$1 = /* @__PURE__ */ new Set([
2790
2801
  "--help",
2791
2802
  "-h",
2792
2803
  "--version",
@@ -2804,11 +2815,90 @@ const INFO_FLAGS = /* @__PURE__ */ new Set([
2804
2815
  async function offerRealRun(input) {
2805
2816
  if (!input.dryRun || input.exitCode !== 0) return void 0;
2806
2817
  if (!input.interactive || input.ci || input.preview) return void 0;
2807
- if (input.args.some((arg) => INFO_FLAGS.has(arg))) return void 0;
2818
+ if (input.args.some((arg) => INFO_FLAGS$1.has(arg))) return void 0;
2808
2819
  if (!input.supportsDryRun(input.words)) return void 0;
2809
2820
  if (!await input.confirm("Dry run complete — run it for real?")) return void 0;
2810
2821
  return input.spawn(withoutDryRun(input.args));
2811
2822
  }
2823
+ // src/observability/format-log-line/format-log-line.ts
2824
+ /** The longest message a thread line keeps, in characters. */
2825
+ const MAX_MESSAGE_CHARS = 300;
2826
+ /** The most numeric fields a thread line names. */
2827
+ const MAX_FIELDS = 6;
2828
+ /**
2829
+ * One log call as a single line for a Discord thread: `[warn] message (count=3, status=200)`. Only what is safe to show
2830
+ * by name: the level, the message (scrubbed with the logger's own token-shape `redact()`, collapsed to one line and cut
2831
+ * to 300 characters) and the names and values of the numeric fields; a string, an object or a flag value in the context
2832
+ * is never read. A call with no message, and the step 6 `command_run` event (the thread ends with its own status line),
2833
+ * give no line.
2834
+ *
2835
+ * @param level - `info`, `warn` or `error`.
2836
+ * @param objOrMsg - The call's context object, or its bare message.
2837
+ * @param msg - The message that goes with a context object.
2838
+ */
2839
+ function formatLogLine(level, objOrMsg, msg) {
2840
+ const context = typeof objOrMsg === "string" ? {} : objOrMsg;
2841
+ const message = typeof objOrMsg === "string" ? objOrMsg : msg;
2842
+ if (!message || context.event === "command_run") return void 0;
2843
+ const text = redact(message).replace(/\s+/g, " ").trim().slice(0, MAX_MESSAGE_CHARS);
2844
+ if (!text) return void 0;
2845
+ const fields = Object.entries(context).filter(([, value]) => typeof value === "number" && Number.isFinite(value)).slice(0, MAX_FIELDS).map(([name, value]) => `${name.replace(/[^\w.-]/g, "_")}=${String(value)}`);
2846
+ return `[${level}] ${text}${fields.length > 0 ? ` (${fields.join(", ")})` : ""}`;
2847
+ }
2848
+ // src/observability/log-tap/log-tap.ts
2849
+ /** Where the CLI's own log lines are copied to while a command thread is open; `undefined` when none is. */
2850
+ let sink;
2851
+ /**
2852
+ * Start (or, with `undefined`, stop) copying the CLI logger's formatted lines to `next` (spec
2853
+ * `tech-discord-notifications-v2`, step 7). There is one at a time: a process runs one command.
2854
+ *
2855
+ * @param next - Receives each line the logger writes at `info` or above; `undefined` stops the copy.
2856
+ */
2857
+ function setLogTap(next) {
2858
+ sink = next;
2859
+ }
2860
+ /**
2861
+ * Hand one formatted line to the tap, if one is set. A tap that throws is ignored: the logger must not be affected.
2862
+ *
2863
+ * @param line - The line, from `formatLogLine()`.
2864
+ */
2865
+ function pushToLogTap(line) {
2866
+ try {
2867
+ sink?.(line);
2868
+ } catch {}
2869
+ }
2870
+ // src/observability/tap-logger/tap-logger.ts
2871
+ /**
2872
+ * Wrap a logger so that each `info`, `warn` and `error` call is also copied, as one formatted line, to the log tap
2873
+ * (`setLogTap()`), which a command thread streams to Discord (spec `tech-discord-notifications-v2`, step 7). The
2874
+ * wrapped logger writes exactly what the original writes; a child is wrapped too, so a line from any module is seen.
2875
+ * `debug` is never copied.
2876
+ *
2877
+ * @param inner - The logger to wrap.
2878
+ */
2879
+ function tapLogger(inner) {
2880
+ const copy = (level, objOrMsg, msg) => {
2881
+ const line = formatLogLine(level, objOrMsg, msg);
2882
+ if (line) pushToLogTap(line);
2883
+ };
2884
+ return {
2885
+ debug: (objOrMsg, msg) => inner.debug(objOrMsg, msg),
2886
+ info: (objOrMsg, msg) => {
2887
+ inner.info(objOrMsg, msg);
2888
+ copy("info", objOrMsg, msg);
2889
+ },
2890
+ warn: (objOrMsg, msg) => {
2891
+ inner.warn(objOrMsg, msg);
2892
+ copy("warn", objOrMsg, msg);
2893
+ },
2894
+ error: (objOrMsg, msg) => {
2895
+ inner.error(objOrMsg, msg);
2896
+ copy("error", objOrMsg, msg);
2897
+ },
2898
+ child: (bindings) => tapLogger(inner.child(bindings)),
2899
+ flush: () => inner.flush()
2900
+ };
2901
+ }
2812
2902
  // src/observability/logger/logger.ts
2813
2903
  /**
2814
2904
  * CLI-side wiring for `@theholocron/observability/logger`.
@@ -2861,89 +2951,199 @@ const logger = createCliLogger({
2861
2951
  * rebuilt at most once more when a handler supplies `holocron.config` context.
2862
2952
  * See `createCliLogger` in `@theholocron/kyber/observability`.
2863
2953
  */
2864
- const buildCliLogger = logger.buildCliLogger;
2954
+ const buildCliLogger = (argv, opts) => {
2955
+ const built = logger.buildCliLogger(argv, opts);
2956
+ return {
2957
+ ...built,
2958
+ logger: tapLogger(built.logger)
2959
+ };
2960
+ };
2865
2961
  /** Lazily-memoized `Logger` for call sites with no `argv` in scope (yargs' `.fail()`). */
2866
- const getLogger = logger.getLogger;
2962
+ const getLogger = () => tapLogger(logger.getLogger());
2867
2963
  /** Report a fatal, command-ending CLI error: printed with `style.fail` and logged. */
2868
- const reportError = logger.reportError;
2964
+ const reportError = (message, log = getLogger()) => logger.reportError(message, log);
2869
2965
  /** The current root logger's correlation id, if a root has been built. */
2870
2966
  const getRunId = logger.getRunId;
2871
2967
  logger.resetCliLogger;
2872
2968
  logger.resolveLogLevel;
2873
- // src/observability/resolve-telemetry/resolve-telemetry.ts
2874
- const env$10 = holocronEnv();
2969
+ // src/credentials-environments/derives-environment/derives-environment.ts
2970
+ /** The providers whose `credentials` entry may leave `environment` out and have it derived (#2063). */
2971
+ const DERIVING = /* @__PURE__ */ new Set(["1password"]);
2972
+ /** Whether a `credentials` provider with no `environment` option derives its Environment names. */
2973
+ function derivesEnvironment(provider) {
2974
+ return DERIVING.has(provider);
2975
+ }
2976
+ // src/credentials-environments/layer-environment/layer-environment.ts
2977
+ /** The layer words, in the order the docs list them. */
2978
+ const ENVIRONMENT_LAYERS = [
2979
+ "local",
2980
+ "dev",
2981
+ "ci",
2982
+ "prod",
2983
+ "preview",
2984
+ "agent"
2985
+ ];
2986
+ /** Whether `value` is exactly one of the layer words (case-sensitive: `Prod` is a literal Environment name). */
2987
+ function isEnvironmentLayer(value) {
2988
+ return typeof value === "string" && ENVIRONMENT_LAYERS.includes(value);
2989
+ }
2875
2990
  /**
2876
- * Holocron-specific credential resolution for the telemetry sinks — the env
2877
- * chain plus Holocron's own shipped fallbacks. This is **CLI policy**, not part
2878
- * of the portable adapter set: `sentry-sink.ts` / `posthog-sink.ts` take a
2879
- * resolved DSN / key and never read the environment. When the adapters move to
2880
- * `@theholocron/observability` (#635) this module stays here.
2881
- *
2882
- * errors: HOLOCRON_SENTRY_DSN → SENTRY_DSN → FALLBACK_DSN
2883
- * analytics: HOLOCRON_POSTHOG_PROJECT_TOKEN → POSTHOG_PROJECT_TOKEN → FALLBACK_POSTHOG_PROJECT_TOKEN
2884
- * host: HOLOCRON_POSTHOG_HOST → POSTHOG_HOST → DEFAULT_POSTHOG_HOST
2885
- *
2886
- * The `SENTRY_DSN` / `POSTHOG_PROJECT_TOKEN` fallbacks are the vendor-native
2887
- * names a consumer repo sets to route CLI telemetry to its own project. The
2888
- * built-in fallbacks are ingest-only keys — publishable by design, same risk
2889
- * model as ADR-0007 / ADR-0008.
2991
+ * The Environment a layer of a repository is kept in: `<org/repo> - <layer>`. The one place the name is built, for the
2992
+ * `credentials` providers (`environmentLayers()`) and for the config entries that name a `layer`.
2890
2993
  */
2891
- /** Holocron's own Sentry project — the fallback when no env var points elsewhere. */
2892
- const FALLBACK_DSN = "https://95cbb72ad5636c94e119a5405ee8f55f@o4508238154104832.ingest.us.sentry.io/4511810950791168";
2893
- /** Holocron's own PostHog project write key — ingest-only. */
2894
- const FALLBACK_POSTHOG_PROJECT_TOKEN = "phc_AC4vFCvYzwnzmG7Vg5nEc3PZKZztoPyfKp4Lb9BbXcLK";
2895
- const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";
2896
- /** Resolve the Sentry DSN. `""` → error telemetry disabled. */
2897
- function resolveDsn() {
2898
- return env$10.get("SENTRY_DSN") ?? FALLBACK_DSN;
2994
+ function layerEnvironment(slug, layer) {
2995
+ return `${slug} - ${layer}`;
2899
2996
  }
2900
- /** Resolve the PostHog project key. `""` → usage analytics disabled. */
2901
- function resolvePostHogKey() {
2902
- return env$10.get("POSTHOG_PROJECT_TOKEN") ?? FALLBACK_POSTHOG_PROJECT_TOKEN;
2997
+ // src/credentials-environments/environment-layers/environment-layers.ts
2998
+ /** The suffix each layer's Environment carries: `<org/repo> - <suffix>`. `test` and `preview` have none. */
2999
+ const SUFFIX = {
3000
+ local: "local",
3001
+ development: "dev",
3002
+ ci: "ci",
3003
+ production: "prod",
3004
+ agent: "agent"
3005
+ };
3006
+ /**
3007
+ * The Environments a layer reads, in the order they are tried (#2063, #2058). A machine (`local`) reads
3008
+ * `<slug> - local` and then `<slug> - dev`: that is the only fallback there is. `development` reads `- dev`, `ci`
3009
+ * reads `- ci` and `production` reads `- prod`; a missing name is a missing name. `agent` (an agent's process, spec
3010
+ * `tech-agent-secrets`) reads `- agent` and nothing else, not `- local` or `- dev`, so an agent never sees a value that
3011
+ * belongs to a person's layer. `test` and `preview` read none (a preview deployment gets its values from the
3012
+ * deployment, not from a vault). Only `- local` is optional.
3013
+ */
3014
+ function environmentLayers(slug, layer) {
3015
+ if (layer === "test" || layer === "preview") return [];
3016
+ const candidate = (suffix, optional) => ({
3017
+ name: layerEnvironment(slug, suffix),
3018
+ optional
3019
+ });
3020
+ return layer === "local" ? [candidate(SUFFIX.local, true), candidate(SUFFIX.development, false)] : [candidate(SUFFIX[layer], false)];
2903
3021
  }
2904
- /** Resolve the PostHog ingest host. */
2905
- function resolvePostHogHost() {
2906
- return env$10.get("POSTHOG_HOST") ?? DEFAULT_POSTHOG_HOST;
3022
+ // src/credentials-environments/repo-slug/repo-slug.ts
3023
+ /**
3024
+ * The `<org>/<repo>` of the repository at `cwd`, from its `origin` remote. A remote that is missing or cannot be
3025
+ * parsed is a `ConfigError` that names the `environment` option as the fix.
3026
+ */
3027
+ async function repoSlug(cwd, exec) {
3028
+ const remote = await readGitRemote(cwd, exec ? { exec } : {});
3029
+ if (!remote) throw new ConfigError$1(`cannot derive the 1Password Environment name: the \`origin\` remote of ${cwd} is missing or not an owner/repo URL. Give the \`credentials\` provider an \`environment\` option to name it.`);
3030
+ return remote.slug;
2907
3031
  }
2908
- // src/observability/telemetry/telemetry.ts
3032
+ // src/credentials-environments/resolve-environments/resolve-environments.ts
2909
3033
  /**
2910
- * CLI self-telemetry — errors (Sentry), usage analytics (PostHog).
3034
+ * The Environments one `credentials` entry reads. An explicit name (the entry's `environment` option, else the shared
3035
+ * `credentials.environment`) is the only candidate and wins. Otherwise a deriving provider gets the names of its layer
3036
+ * (`environmentLayers()`) from the repo's `origin` and `detectEnvironment()`. Nothing is read from a provider here. An empty list means there is nothing to read (the `test` layer).
3037
+ */
3038
+ async function resolveEnvironments(provider, explicit, input) {
3039
+ if (explicit !== void 0) return [{
3040
+ name: explicit,
3041
+ optional: false
3042
+ }];
3043
+ if (!derivesEnvironment(provider)) return [];
3044
+ const layer = detectEnvironment(input.env);
3045
+ if (layer === "test") return [];
3046
+ return environmentLayers(await repoSlug(input.repoRoot, input.gitExec), layer);
3047
+ }
3048
+ // src/credentials-environments/try-environments/try-environments.ts
3049
+ /** A provider's "no such Environment": its API error with status 404 (`ProviderApiError`, matched by shape). */
3050
+ function isNotFound(err) {
3051
+ return typeof err === "object" && err !== null && err.status === 404;
3052
+ }
3053
+ /**
3054
+ * Calls `attempt` for each candidate and sorts the answers into found and missing. A 404 is a miss; any other error
3055
+ * is thrown. A missing optional Environment is silent; a missing required one is reported by name.
3056
+ */
3057
+ async function tryEnvironments(candidates, attempt) {
3058
+ const found = [];
3059
+ const missing = [];
3060
+ for (const candidate of candidates) try {
3061
+ found.push({
3062
+ name: candidate.name,
3063
+ result: await attempt(candidate.name)
3064
+ });
3065
+ } catch (err) {
3066
+ if (!isNotFound(err)) throw err;
3067
+ if (!candidate.optional) missing.push(candidate.name);
3068
+ }
3069
+ return {
3070
+ found,
3071
+ missing
3072
+ };
3073
+ }
3074
+ // src/credentials-environments/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.
2911
3090
  *
2912
- * The orchestration is `createCliTelemetry` in `@theholocron/kyber/observability`
2913
- * (no vendor SDK import here either: the sinks live in `@theholocron/observability`).
2914
- * This module binds it to Holocron's values: the `HOLOCRON` env prefix, the
2915
- * credentials resolved by `resolve-telemetry.ts`, and the logger's run id.
2916
- * The single kill switch is `HOLOCRON_TELEMETRY=false` (legacy alias
2917
- * `NO_HOLOCRON_TELEMETRY`); see ADR-0007 / ADR-0008.
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.
2918
3093
  */
2919
- const telemetry = createCliTelemetry({
2920
- envPrefix: PREFIX$1,
2921
- dsn: resolveDsn,
2922
- posthogKey: resolvePostHogKey,
2923
- posthogHost: resolvePostHogHost,
2924
- getRunId: () => getRunId()
2925
- });
2926
- /** Install the live sinks unless telemetry is opted out or a credential is empty. */
2927
- const init = telemetry.init;
2928
- /** Apply the `telemetry` config block; it only ever narrows what `init` turned on. */
2929
- const applyConfig = telemetry.applyConfig;
2930
- /** Capture a PostHog event, scrubbed of secrets. */
2931
- const event = telemetry.event;
2932
- /** Start a command span; call the returned function with the outcome. */
2933
- const startCommand$1 = telemetry.startCommand;
2934
- /** Report an error to Sentry. */
2935
- const captureException = telemetry.captureException;
2936
- /** End the Sentry session. */
2937
- const endSession = telemetry.endSession;
2938
- /** Drain both sinks and return to the no-ops. */
2939
- const flush = telemetry.flush;
2940
- telemetry.resetTelemetry;
2941
- // src/credentials-environments/derives-environment/derives-environment.ts
2942
- /** The providers whose `credentials` entry may leave `environment` out and have it derived (#2063). */
2943
- const DERIVING = /* @__PURE__ */ new Set(["1password"]);
2944
- /** Whether a `credentials` provider with no `environment` option derives its Environment names. */
2945
- function derivesEnvironment(provider) {
2946
- return DERIVING.has(provider);
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;
2947
3147
  }
2948
3148
  // src/plugin/capabilities/capabilities.ts
2949
3149
  /** How many providers each capability resolves to: one (`"single"`) or several active at once (`"many"`). */
@@ -3054,26 +3254,44 @@ function splitAgent(raw) {
3054
3254
  agentOptions: options
3055
3255
  };
3056
3256
  }
3057
- // src/credentials-environments/layer-environment/layer-environment.ts
3058
- /** The layer words, in the order the docs list them. */
3059
- const ENVIRONMENT_LAYERS = [
3060
- "local",
3061
- "dev",
3062
- "ci",
3063
- "prod",
3064
- "preview",
3065
- "agent"
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"
3066
3263
  ];
3067
- /** Whether `value` is exactly one of the layer words (case-sensitive: `Prod` is a literal Environment name). */
3068
- function isEnvironmentLayer(value) {
3069
- return typeof value === "string" && ENVIRONMENT_LAYERS.includes(value);
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)}`);
3070
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
+ ];
3071
3284
  /**
3072
- * The Environment a layer of a repository is kept in: `<org/repo> - <layer>`. The one place the name is built, for the
3073
- * `credentials` providers (`environmentLayers()`) and for the config entries that name a `layer`.
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.
3074
3290
  */
3075
- function layerEnvironment(slug, layer) {
3076
- 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)}`);
3077
3295
  }
3078
3296
  // src/config/validate-environment-choice/validate-environment-choice.ts
3079
3297
  /**
@@ -3341,57 +3559,6 @@ function validateRequiredChecks(checks) {
3341
3559
  seen.add(context);
3342
3560
  });
3343
3561
  }
3344
- // src/credentials-environments/repo-slug/repo-slug.ts
3345
- /**
3346
- * The `<org>/<repo>` of the repository at `cwd`, from its `origin` remote. A remote that is missing or cannot be
3347
- * parsed is a `ConfigError` that names the `environment` option as the fix.
3348
- */
3349
- async function repoSlug(cwd, exec) {
3350
- const remote = await readGitRemote(cwd, exec ? { exec } : {});
3351
- if (!remote) throw new ConfigError$1(`cannot derive the 1Password Environment name: the \`origin\` remote of ${cwd} is missing or not an owner/repo URL. Give the \`credentials\` provider an \`environment\` option to name it.`);
3352
- return remote.slug;
3353
- }
3354
- // src/credentials-environments/unsynced-layer/unsynced-layer.ts
3355
- /**
3356
- * The layers this machine reads for itself (`agent` is the one an agent's process reads, spec `tech-agent-secrets`). They
3357
- * are never synced to GitHub, a deployment or a Worker (#2104).
3358
- */
3359
- const UNSYNCED_LAYERS = [
3360
- "local",
3361
- "dev",
3362
- "agent"
3363
- ];
3364
- /** Whether `layer` is one of {@link UNSYNCED_LAYERS}. */
3365
- function isUnsyncedLayer(layer) {
3366
- return isEnvironmentLayer(layer) && UNSYNCED_LAYERS.includes(layer);
3367
- }
3368
- /**
3369
- * The text of the error for an Environment of an unsynced layer, shared by the command and the config checks.
3370
- *
3371
- * @param what - What names the layer, e.g. "`sync secrets --env dev`" or "a `repo.secrets.sync` entry".
3372
- * @param layer - The unsynced layer.
3373
- */
3374
- function unsyncedLayerMessage(what, layer) {
3375
- return `${what} names the \`${layer}\` layer: \`local\`, \`dev\` and \`agent\` are read by this machine and are never synced. Only ${ENVIRONMENT_LAYERS.filter((l) => !isUnsyncedLayer(l)).map((l) => `\`${String(l)}\``).join(" and ")} can be synced`;
3376
- }
3377
- /**
3378
- * Refuse a sync of an unsynced layer, before anything is read. The argument is a layer word, or the literal name of a
3379
- * layer's Environment (`<org/repo> - dev`, built by `layerEnvironment()` from the `origin` remote). A remote that
3380
- * cannot be read means no literal name can be matched, so only a layer word is checked then.
3381
- *
3382
- * @param id - The environment as given on the command line.
3383
- * @param input - Where the repository is, and optionally how to read its remote.
3384
- * @throws {ConfigError} For an unsynced layer, whatever other flags are given.
3385
- */
3386
- async function assertSyncableLayer(id, input) {
3387
- if (isEnvironmentLayer(id)) {
3388
- if (isUnsyncedLayer(id)) throw new ConfigError$1(unsyncedLayerMessage(`\`sync secrets --env ${id}\``, id));
3389
- return;
3390
- }
3391
- const slug = await repoSlug(input.repoRoot, input.gitExec).catch(() => void 0);
3392
- if (slug === void 0) return;
3393
- for (const layer of UNSYNCED_LAYERS) if (id === layerEnvironment(slug, layer)) throw new ConfigError$1(unsyncedLayerMessage(`\`sync secrets --env\` for ${JSON.stringify(id)}`, layer));
3394
- }
3395
3562
  // src/config/validate-secrets-deploy/validate-secrets-deploy.ts
3396
3563
  /**
3397
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
@@ -3650,6 +3817,8 @@ function resolveConfig(raw) {
3650
3817
  if (raw.issueTypes !== void 0) validateIssueTypes(raw.issueTypes);
3651
3818
  validateRepoLabels(raw.repo?.labels);
3652
3819
  validateRepoViews(raw.repo?.views);
3820
+ validateCommandLog(raw.notifications);
3821
+ validateCommandThreads(raw.notifications);
3653
3822
  validateRepoEnvironments(raw.repo?.environments);
3654
3823
  validateRequiredChecks(raw.repo?.requiredChecks);
3655
3824
  validateVariablesSync(raw.repo?.variables);
@@ -3693,6 +3862,7 @@ function resolveConfig(raw) {
3693
3862
  ideas: raw.ideas,
3694
3863
  log: raw.log,
3695
3864
  telemetry: raw.telemetry,
3865
+ notifications: raw.notifications,
3696
3866
  eslint: raw.eslint
3697
3867
  };
3698
3868
  }
@@ -4027,73 +4197,6 @@ function placeAreas(areas, raw) {
4027
4197
  else if (area.area === "org") result = placeOrg(result, area);
4028
4198
  return result;
4029
4199
  }
4030
- // src/credentials-environments/environment-layers/environment-layers.ts
4031
- /** The suffix each layer's Environment carries: `<org/repo> - <suffix>`. `test` and `preview` have none. */
4032
- const SUFFIX = {
4033
- local: "local",
4034
- development: "dev",
4035
- ci: "ci",
4036
- production: "prod",
4037
- agent: "agent"
4038
- };
4039
- /**
4040
- * The Environments a layer reads, in the order they are tried (#2063, #2058). A machine (`local`) reads
4041
- * `<slug> - local` and then `<slug> - dev`: that is the only fallback there is. `development` reads `- dev`, `ci`
4042
- * reads `- ci` and `production` reads `- prod`; a missing name is a missing name. `agent` (an agent's process, spec
4043
- * `tech-agent-secrets`) reads `- agent` and nothing else, not `- local` or `- dev`, so an agent never sees a value that
4044
- * belongs to a person's layer. `test` and `preview` read none (a preview deployment gets its values from the
4045
- * deployment, not from a vault). Only `- local` is optional.
4046
- */
4047
- function environmentLayers(slug, layer) {
4048
- if (layer === "test" || layer === "preview") return [];
4049
- const candidate = (suffix, optional) => ({
4050
- name: layerEnvironment(slug, suffix),
4051
- optional
4052
- });
4053
- return layer === "local" ? [candidate(SUFFIX.local, true), candidate(SUFFIX.development, false)] : [candidate(SUFFIX[layer], false)];
4054
- }
4055
- // src/credentials-environments/resolve-environments/resolve-environments.ts
4056
- /**
4057
- * The Environments one `credentials` entry reads. An explicit name (the entry's `environment` option, else the shared
4058
- * `credentials.environment`) is the only candidate and wins. Otherwise a deriving provider gets the names of its layer
4059
- * (`environmentLayers()`) from the repo's `origin` and `detectEnvironment()`. Nothing is read from a provider here. An empty list means there is nothing to read (the `test` layer).
4060
- */
4061
- async function resolveEnvironments(provider, explicit, input) {
4062
- if (explicit !== void 0) return [{
4063
- name: explicit,
4064
- optional: false
4065
- }];
4066
- if (!derivesEnvironment(provider)) return [];
4067
- const layer = detectEnvironment(input.env);
4068
- if (layer === "test") return [];
4069
- return environmentLayers(await repoSlug(input.repoRoot, input.gitExec), layer);
4070
- }
4071
- // src/credentials-environments/try-environments/try-environments.ts
4072
- /** A provider's "no such Environment": its API error with status 404 (`ProviderApiError`, matched by shape). */
4073
- function isNotFound(err) {
4074
- return typeof err === "object" && err !== null && err.status === 404;
4075
- }
4076
- /**
4077
- * Calls `attempt` for each candidate and sorts the answers into found and missing. A 404 is a miss; any other error
4078
- * is thrown. A missing optional Environment is silent; a missing required one is reported by name.
4079
- */
4080
- async function tryEnvironments(candidates, attempt) {
4081
- const found = [];
4082
- const missing = [];
4083
- for (const candidate of candidates) try {
4084
- found.push({
4085
- name: candidate.name,
4086
- result: await attempt(candidate.name)
4087
- });
4088
- } catch (err) {
4089
- if (!isNotFound(err)) throw err;
4090
- if (!candidate.optional) missing.push(candidate.name);
4091
- }
4092
- return {
4093
- found,
4094
- missing
4095
- };
4096
- }
4097
4200
  // src/config/resolve-layers/resolve-layers.ts
4098
4201
  /**
4099
4202
  * Turns every `layer` in a loaded config into the `environment` it names (spec `tech-environment-layers`, #2069), so
@@ -4217,46 +4320,6 @@ function resolvedEnvironment(entry) {
4217
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()`);
4218
4321
  return entry.environment;
4219
4322
  }
4220
- // src/commands/resolve-org/resolve-org.ts
4221
- const env$9 = createEnvLookup();
4222
- /**
4223
- * Resolves the active org in priority order:
4224
- * 1. `--org` CLI flag
4225
- * 2. `HOLOCRON_ORG` env var
4226
- * 3. `org` from `holocron.config.ts`
4227
- */
4228
- function resolveOrg(argv, config) {
4229
- return argv.org ?? env$9.get("HOLOCRON_ORG") ?? config.org;
4230
- }
4231
- // src/commands/apply-resolved-config/apply-resolved-config.ts
4232
- /**
4233
- * `buildCliLogger` options derived from a loaded `holocron.config` — the
4234
- * level, the Axiom dataset, and the resolved org for a keyring-backed
4235
- * Axiom token. Used by every handler that has already called `loadConfig`.
4236
- */
4237
- function cliLoggerOpts(argv, resolved) {
4238
- return {
4239
- configLevel: resolved.log?.level,
4240
- configAxiomDataset: resolved.log?.axiom?.dataset,
4241
- org: resolveOrg(argv, resolved)
4242
- };
4243
- }
4244
- /**
4245
- * Fold a loaded `holocron.config` into the running process: reconfigure the
4246
- * logger from `log:`, then apply the `telemetry:` override layer. Every handler
4247
- * that has called `loadConfig` runs this, so a repo's `telemetry.enabled: false`
4248
- * (or `analytics: "none"`) is honoured for that command. Env still wins —
4249
- * `applyConfig` only narrows what `init` already turned on.
4250
- */
4251
- function applyResolvedConfig(argv, resolved) {
4252
- buildCliLogger(argv, cliLoggerOpts(argv, resolved));
4253
- applyConfig(resolved.telemetry);
4254
- }
4255
- // src/commands/token-context/token-context.ts
4256
- /** Parses --token values and returns the context spread, or null on parse error (exits with code 1). */
4257
- function tokenContext(rawTokens) {
4258
- return tokenContext$1(rawTokens, reportError);
4259
- }
4260
4323
  // src/plugin/missing-plugin-hint/missing-plugin-hint.ts
4261
4324
  /**
4262
4325
  * The line that says how to get a plugin package that does not resolve: add it to the `holocron` catalog of
@@ -4537,6 +4600,476 @@ function actionsOf(plugin) {
4537
4600
  ...plugin.whoami ? { whoami: plugin.whoami } : {}
4538
4601
  };
4539
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
+ }
4540
5073
  // src/commands/issue-types/classify-type-error/classify-type-error.ts
4541
5074
  /** Reads a thrown error as one of the four things `ensureIssueTypes()` acts on differently. */
4542
5075
  function classifyTypeError(err) {
@@ -5080,7 +5613,8 @@ async function provisionChannel(deps, spec) {
5080
5613
  ...spec.access ? { access: spec.access } : {},
5081
5614
  ...spec.kind ? { kind: spec.kind } : {},
5082
5615
  ...spec.tags ? { tags: spec.tags } : {},
5083
- ...spec.defaultReaction ? { defaultReaction: spec.defaultReaction } : {}
5616
+ ...spec.defaultReaction ? { defaultReaction: spec.defaultReaction } : {},
5617
+ ...spec.autoArchiveMinutes ? { autoArchiveMinutes: spec.autoArchiveMinutes } : {}
5084
5618
  });
5085
5619
  const changed = channel.created || (channel.updated?.length ?? 0) > 0;
5086
5620
  const verb = channel.created ? "created" : changed ? "updated" : "exists ";
@@ -8290,7 +8824,7 @@ const row$37 = (id, status, detail) => ({
8290
8824
  */
8291
8825
  async function abandonWork(a) {
8292
8826
  const { input, key, source, pullRequest: pr } = a;
8293
- const git = input.git ?? runGit;
8827
+ const git = input.git ?? runGit$1;
8294
8828
  const repoRoot = input.context.repoRoot;
8295
8829
  const dryRun = Boolean(input.context.dryRun);
8296
8830
  const rows = [];
@@ -8902,7 +9436,7 @@ async function readIssueBoards(input) {
8902
9436
  /** The real git and file system {@link runStartWork} runs against; tests pass a fake. */
8903
9437
  function createRealStartWorkIo() {
8904
9438
  return {
8905
- git: runGit,
9439
+ git: runGit$1,
8906
9440
  exists: (path) => existsSync(path),
8907
9441
  read: (path) => readFileSync(path, "utf8"),
8908
9442
  write: (path, text) => {
@@ -10385,7 +10919,7 @@ async function runCloseWork(input) {
10385
10919
  return finish();
10386
10920
  }
10387
10921
  if (!pr) return fail("pull request", `no pull request for ${key} (its branch is <type>/<issue>-<slug>; --pr names one)`);
10388
- const git = input.git ?? runGit;
10922
+ const git = input.git ?? runGit$1;
10389
10923
  const repoRoot = input.context.repoRoot;
10390
10924
  if (pr.state === "closed") {
10391
10925
  if (!pr.merged) {
@@ -15660,6 +16194,7 @@ function forumFeedChecks(input, spec) {
15660
16194
  const forumProblems = [];
15661
16195
  const tagProblems = [];
15662
16196
  const botProblems = [];
16197
+ const leftOver = [];
15663
16198
  for (const { cat, channel } of fed) {
15664
16199
  const name = shown$6(channel.name);
15665
16200
  const have = found.channels.find((c) => same$6(c.name, channel.name) && c.category !== void 0 && same$6(c.category, cat));
@@ -15672,6 +16207,8 @@ function forumFeedChecks(input, spec) {
15672
16207
  continue;
15673
16208
  }
15674
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}`);
15675
16212
  if (have.botThreadsError) botProblems.push(`#${name}: could not read the bot's permissions (${shown$6(have.botThreadsError)})`);
15676
16213
  else if (have.botThreads) {
15677
16214
  if (!have.botThreads.post) botProblems.push(`#${name}: the bot cannot start posts or reply in it`);
@@ -15679,11 +16216,13 @@ function forumFeedChecks(input, spec) {
15679
16216
  } else botProblems.push(`#${name}: the provider did not report the bot's permissions`);
15680
16217
  }
15681
16218
  const ok = `${fed.length} of ${fed.length} as declared`;
15682
- return [
16219
+ const rows = [
15683
16220
  resultRow(spec.ids.forum, forumTitle, forumProblems, ok),
15684
16221
  resultRow(spec.ids.tags, tagsTitle, tagProblems, ok),
15685
16222
  resultRow(spec.ids.bot, botTitle, botProblems, ok)
15686
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;
15687
16226
  }
15688
16227
  // src/commands/notifications-setup/layout-picture-problem/layout-picture-problem.ts
15689
16228
  /** The first reason a picture in the layout (`webhookAvatar`, a channel's `webhook.avatar`) cannot work, or undefined. */
@@ -16194,10 +16733,17 @@ const PR_FEED_TAGS = [
16194
16733
  "failing",
16195
16734
  "changes requested",
16196
16735
  "ready",
16197
- "waiting",
16736
+ "in review",
16198
16737
  "merged",
16199
16738
  "closed"
16200
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
+ ];
16201
16747
  /** The states an incident's post can be tagged with, so a forum with `feeds.incidents` must have all of them (lower case). */
16202
16748
  const INCIDENT_FEED_TAGS = [
16203
16749
  "investigating",
@@ -16221,6 +16767,7 @@ function forumLayoutProblem(layout) {
16221
16767
  const where = `channel \`${channel.name}\``;
16222
16768
  if (channel.kind !== "forum") {
16223
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`;
16224
16771
  if (channel.defaultReaction || channel.starterReactions) return `${where}: reactions belong to a forum -- set \`kind: "forum"\` or remove them`;
16225
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`;
16226
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`;
@@ -16235,6 +16782,9 @@ function forumLayoutProblem(layout) {
16235
16782
  const problem = reactionProblem("a starter reaction", reaction);
16236
16783
  if (problem) return `${where}: ${problem}`;
16237
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)}`;
16238
16788
  const seen = /* @__PURE__ */ new Set();
16239
16789
  for (const tag of channel.tags ?? []) {
16240
16790
  const name = tag.name.trim().toLowerCase();
@@ -16686,6 +17236,7 @@ async function runNotificationsSetup(input$1) {
16686
17236
  ...channel.kind ? { kind: channel.kind } : {},
16687
17237
  ...channel.tags ? { tags: channel.tags } : {},
16688
17238
  ...channel.defaultReaction ? { defaultReaction: channel.defaultReaction } : {},
17239
+ ...channel.autoArchiveMinutes ? { autoArchiveMinutes: channel.autoArchiveMinutes } : {},
16689
17240
  ...webhook ? { webhook } : {},
16690
17241
  ...channel.feeds?.monitoring || channel.feeds?.errors || relayFeedsOf(channel).length > 0 ? { feeds: {
16691
17242
  ...channel.feeds?.monitoring ? { monitoring: {
@@ -17652,7 +18203,11 @@ function prFeedChecks(input) {
17652
18203
  bot: "pr-feed-bot"
17653
18204
  },
17654
18205
  label: "pull request feed",
17655
- tags: PR_FEED_TAGS
18206
+ tags: PR_FEED_TAGS,
18207
+ retired: {
18208
+ id: "pr-feed-retired-tag",
18209
+ tag: "waiting"
18210
+ }
17656
18211
  });
17657
18212
  }
17658
18213
  // src/commands/relay-checks/relay-checks.ts
@@ -18022,6 +18577,7 @@ async function runDoctorNotifications(input) {
18022
18577
  else if (isForum) {
18023
18578
  const wantReaction = channel.defaultReaction ? reactionSpelling(channel.defaultReaction) : void 0;
18024
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}`);
18025
18581
  for (const tag of channel.tags ?? []) {
18026
18582
  const have = match.tags?.find((t) => same$2(t.name, tag.name));
18027
18583
  if (!have) channelProblems.push(`#${shown(channel.name)}: tag "${shown(tag.name)}" is missing`);
@@ -30852,7 +31408,7 @@ async function promptEffort() {
30852
31408
  }
30853
31409
  // src/commands/new-work/read-git-config/read-git-config.ts
30854
31410
  /** One `git config --get` value in a directory, or `undefined` when the key is unset or git fails. */
30855
- function readGitConfig(cwd, key, run = runGit) {
31411
+ function readGitConfig(cwd, key, run = runGit$1) {
30856
31412
  try {
30857
31413
  return run([
30858
31414
  "config",
@@ -41104,7 +41660,7 @@ function planIncidentFeed(input) {
41104
41660
  // src/commands/render-incident/render-incident.ts
41105
41661
  /** Discord's message limit is 2000; an update's text is cut well short of it, leaving room for its heading and marker. */
41106
41662
  const UPDATE_TEXT_LIMIT = 1500;
41107
- const TITLE_LIMIT = 100;
41663
+ const TITLE_LIMIT$1 = 100;
41108
41664
  const IMPACT_WORDS = {
41109
41665
  maintenance: "under maintenance",
41110
41666
  degraded: "degraded",
@@ -41152,7 +41708,7 @@ function renderIncident(incident, statusPage) {
41152
41708
  lines.push(statusPage.url ? `Status page: [${statusPage.name}](<${statusPage.url}>)` : `Status page: ${statusPage.name}`);
41153
41709
  lines.push(incidentMarker(incident.id));
41154
41710
  return {
41155
- title: clip(incident.title, TITLE_LIMIT),
41711
+ title: clip(incident.title, TITLE_LIMIT$1),
41156
41712
  body: lines.join("\n"),
41157
41713
  tag
41158
41714
  };
@@ -41171,9 +41727,9 @@ function renderIncident(incident, statusPage) {
41171
41727
  */
41172
41728
  const DEFAULT_SINCE = "2d";
41173
41729
  /** How many of a post's messages are read to find the markers of its updates (Discord's limit per read). */
41174
- const MESSAGES = 100;
41730
+ const MESSAGES$1 = 100;
41175
41731
  /** The channel carrying the feed, and the name of the status page it follows. */
41176
- function feedOf(notifications, pages) {
41732
+ function feedOf$1(notifications, pages) {
41177
41733
  const fed = (notifications.layout?.categories ?? []).flatMap((c) => c.channels ?? []).filter((c) => c.feeds?.incidents);
41178
41734
  if (fed.length === 0) return { problem: "no forum in the layout has `feeds.incidents`" };
41179
41735
  if (fed.length > 1) return { problem: `several forums have \`feeds.incidents\` (${fed.map((c) => `\`${c.name}\``).join(", ")})` };
@@ -41215,7 +41771,7 @@ async function runSyncIncidents(input) {
41215
41771
  }
41216
41772
  const monitoring = loader.has("monitoring") ? loader.get("monitoring") : void 0;
41217
41773
  if (!monitoring?.listIncidents) return stop("skip", "no `monitoring` provider that lists status page incidents");
41218
- const feed = feedOf(notifications, monitoring.statusPages ?? []);
41774
+ const feed = feedOf$1(notifications, monitoring.statusPages ?? []);
41219
41775
  if ("problem" in feed) return stop(feed.problem.startsWith("no forum") ? "skip" : "fail", feed.problem);
41220
41776
  const { channel, page } = feed;
41221
41777
  const statusPage = {
@@ -41258,7 +41814,7 @@ async function runSyncIncidents(input) {
41258
41814
  incident,
41259
41815
  rendered,
41260
41816
  post,
41261
- messages: post ? await notifications.readDiscussionMessages(channel, key, MESSAGES) : []
41817
+ messages: post ? await notifications.readDiscussionMessages(channel, key, MESSAGES$1) : []
41262
41818
  });
41263
41819
  plans.push(plan);
41264
41820
  if (plan.steps.length === 0) {
@@ -41331,11 +41887,11 @@ async function apply(notifications, channel, key, rendered, plan) {
41331
41887
  quiet: true
41332
41888
  })).created) {
41333
41889
  if (await notifications.dedupeDiscussion(channel, key, { refresh: true }) > 0) {
41334
- const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES));
41890
+ const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES$1));
41335
41891
  append = append.filter((u) => !posted.has(u.id));
41336
41892
  }
41337
41893
  } else {
41338
- const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES));
41894
+ const posted = postedUpdateIds(await notifications.readDiscussionMessages(channel, key, MESSAGES$1));
41339
41895
  append = append.filter((u) => !posted.has(u.id));
41340
41896
  }
41341
41897
  } else if (plan.rewrite || plan.retag || plan.close === false) await notifications.updateDiscussion(channel, key, {
@@ -41643,6 +42199,443 @@ const syncIssuesCommand = {
41643
42199
  })).status === "fail") process.exitCode = 1;
41644
42200
  }
41645
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
+ };
41646
42639
  // src/commands/sync-readme/generate-readme.ts
41647
42640
  /** Scripts that are neither a task nor a check: what a contributor runs while working (spec: "the dev scripts"). */
41648
42641
  const DEV_SCRIPTS = [
@@ -41926,6 +42919,77 @@ const syncReadmeCommand = {
41926
42919
  }
41927
42920
  }
41928
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
+ }
41929
42993
  // src/commands/sync-releases/release-marker/release-marker.ts
41930
42994
  /**
41931
42995
  * The marker that ends a release's message: Discord's small-text line, so it is quiet to read, carrying the release id
@@ -42018,6 +43082,20 @@ function releasedPackages(cwd, from, to) {
42018
43082
  }
42019
43083
  return released.sort((a, b) => a.name.localeCompare(b.name));
42020
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
+ }
42021
43099
  // src/commands/sync-releases/package-line/package-line.ts
42022
43100
  /** The page of one version of a package on npm. */
42023
43101
  function npmVersionUrl(pkg) {
@@ -42035,21 +43113,40 @@ function packageLine(pkg) {
42035
43113
  // src/commands/sync-releases/render-release/render-release.ts
42036
43114
  /** Discord's limit on a thread's name. */
42037
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;
42038
43119
  /**
42039
43120
  * The text of a release's announcement: a message with the headline, the link to the GitHub release (when a tag and
42040
43121
  * the repository are known) and the marker last, a thread name, and one list item per package that links to the
42041
- * version's page on npm. Chunking the lines to the provider's limit is the provider's job.
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.
42042
43124
  */
42043
43125
  function renderRelease(input) {
42044
- const { id, tag, repo, packages } = input;
43126
+ const { id, tag, repo, packages, changes = [] } = input;
42045
43127
  const count = packages.length;
42046
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
+ }
42047
43148
  return {
42048
- message: [
42049
- `**${tag ?? id}** released: ${count} package${count === 1 ? "" : "s"} on ${tags}`,
42050
- ...tag && repo ? [`https://github.com/${repo}/releases/tag/${tag}`] : [],
42051
- releaseMarker(id)
42052
- ].join("\n"),
43149
+ message,
42053
43150
  threadName: (tag ?? id).slice(0, THREAD_NAME_LIMIT),
42054
43151
  lines: packages.map(packageLine)
42055
43152
  };
@@ -42097,7 +43194,8 @@ async function runSyncReleases(input) {
42097
43194
  id,
42098
43195
  ...input.tag ? { tag: input.tag } : {},
42099
43196
  ...repo ? { repo } : {},
42100
- packages
43197
+ packages,
43198
+ changes: releaseChanges(input.context.repoRoot, input.from || void 0, input.to)
42101
43199
  });
42102
43200
  const marker = releaseMarker(id);
42103
43201
  if (dryRun) {
@@ -43502,7 +44600,7 @@ async function syncApp(argv) {
43502
44600
  const syncCommand = {
43503
44601
  command: "sync [steps..]",
43504
44602
  describe: "Sync state from config to the provider and local files (labels, properties, teams, topics, keywords, description, homepage, readme, workflows, scripts, wiki)",
43505
- builder: (y) => syncArgs(y).command(syncGithubCommand).command(syncIssuesCommand).command(syncIncidentsCommand).command(syncReleasesCommand).command(syncReadmeCommand).command(ideasSyncCommand).command(syncToolingCommand).command(syncRequestsCommand).command(specsSyncCommand).command(secretsSyncCommand).command(notificationsSyncRolesCommand),
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),
43506
44604
  handler: async (argv) => {
43507
44605
  if (argv.env !== void 0 || argv.steps?.[0] !== void 0) {
43508
44606
  if (await syncApp(argv)) return;
@@ -44371,6 +45469,8 @@ let finishCommand = () => {};
44371
45469
  /** What ran, for the offer to run it for real after a `--dry-run` of it. */
44372
45470
  let ranWords = [];
44373
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;
44374
45474
  /** Set by `.fail()` once it has printed an error, so the outer catch doesn't repeat it. */
44375
45475
  let errorReported = false;
44376
45476
  try {
@@ -44410,6 +45510,17 @@ try {
44410
45510
  command: name,
44411
45511
  org: argv.org
44412
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
+ };
44413
45524
  finishCommand = startCommand$1(name);
44414
45525
  const label = commandProgressLabel(argv._);
44415
45526
  if (label) startCommandProgress(label);
@@ -44436,6 +45547,13 @@ try {
44436
45547
  }
44437
45548
  finishCommand(!process.exitCode);
44438
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
+ });
44439
45557
  const offered = await offerRealRun({
44440
45558
  words: ranWords,
44441
45559
  args: process.argv.slice(2),