@vaultcompass/conductor 0.18.0 → 0.19.0

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.js CHANGED
@@ -14,10 +14,12 @@ import { EXIT_BLOCKED, EXIT_COULD_NOT_RUN, EXIT_OK } from './exit-codes.js';
14
14
  import { absolutePathEntries, createGitShim, pinGitOutside, pinnedGitInside, realPathInside, removeGitShim, runGit, tempInsideTreeMessage, workTreeAbove, } from './git.js';
15
15
  import { applyInit, planInit, renderInitHuman, renderRevertHuman, revertInit, } from './init.js';
16
16
  import { renderSarif } from './output-sarif.js';
17
- import { gateLogLines, jobLogSummary, previewLogLines, proposalLogLines, renderText, verdictToken, versionSkewAnnotations, versionSkewSummaryLines, versionSkewWarnings, } from './output-text.js';
18
- import { GATE_ROLES, GATE_STAGES, POLICY_FILE_NAME, PolicyError, applyCliOverrides, loadPolicy, parsePolicy, } from './policy.js';
17
+ import { findingLogLines, gateLogLines, jobLogSummary, previewLogLines, proposalLogLines, renderText, verdictToken, NO_POLICY_LINE, versionSkewAnnotations, versionSkewSummaryLines, versionSkewWarnings, } from './output-text.js';
18
+ import { GATE_ROLES, GATE_STAGES, MissingPolicyError, POLICY_FILE_NAME, PolicyError, applyCliOverrides, loadPolicy, parsePolicy, } from './policy.js';
19
+ import { refuseAdoptionProposal } from './adoption-proposal.js';
20
+ import { summaryField } from './escape.js';
19
21
  import { diffPolicies, previewPolicy, previewRoles } from './policy-diff.js';
20
- import { refusedTrustBase, runAll } from './run.js';
22
+ import { asProposal, refusedTrustBase, runAll } from './run.js';
21
23
  import { headTreeEqualsBase, withMovedBaseTip, policyDiffers, readFileAtRef, refuseTrustBaseForPullRequest, unreadableBaseRemedy, refuseTrustBaseRef, } from './trust-base.js';
22
24
  const pkgPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
23
25
  const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
@@ -197,13 +199,16 @@ function applyAdvisory(exitCode, advisory) {
197
199
  return advisory && exitCode === EXIT_BLOCKED ? EXIT_OK : exitCode;
198
200
  }
199
201
  /**
200
- * Whether the text report is rendered for a terminal: only when it goes to
201
- * stdout (no --output) and stdout is a TTY. A file, a pipe and the
202
- * --text-report copy never are, so they stay byte for byte as before.
202
+ * A policy parse error as one line for a refusal: its text quotes keys and
203
+ * values from a file the pull request can write, so it is flattened, escaped
204
+ * and capped like any other head-chosen text, and ends in a full stop.
203
205
  */
204
- export function rendersToTerminal(output, stdoutIsTTY) {
205
- return output === undefined && stdoutIsTTY === true;
206
+ function parseErrorLine(error) {
207
+ const line = summaryField(error.message.replace(/\s+/g, ' '), 400);
208
+ return /[.!?]$/.test(line) ? line : `${line}.`;
206
209
  }
210
+ /** No policy at all: what the base of an adoption proposal contributes. */
211
+ const EMPTY_POLICY = { version: 1, gates: {}, report: { format: 'text' } };
207
212
  /**
208
213
  * Reads the policy for one run, from the base ref in pull-request mode.
209
214
  *
@@ -251,7 +256,14 @@ function inventoryFromHead(root, overrides) {
251
256
  */
252
257
  export function policyForRun(root, trustBase, overrides, githubBaseRef, githubActions,
253
258
  /** Whether this run asked for the preview under the proposed rules. */
254
- preview = false) {
259
+ preview = false,
260
+ /**
261
+ * Whether --adoption-proposal was given. Without it a base with no policy
262
+ * is refused exactly as before the flag existed, whoever calls the CLI.
263
+ */
264
+ adoptionProposal = false,
265
+ /** The environment git will run in, for the proposal's own check of it. */
266
+ env = process.env) {
255
267
  if (trustBase === undefined) {
256
268
  // A PULL-REQUEST JOB WITH NO TRUST BASE would take its rules from the
257
269
  // tree being judged. In Actions (GITHUB_ACTIONS and GITHUB_BASE_REF both
@@ -349,24 +361,99 @@ preview = false) {
349
361
  // on the base branch on purpose, and mirrors the no-contract
350
362
  // (discovered, write one) vs contract-waived (imposed, a person already
351
363
  // decided) distinction the intent gate already makes for a missing spec.
352
- const detail = `No ${POLICY_FILE_NAME} on "${trustBase}". On a pull-request run every rule comes from the ` +
353
- 'base ref, so this run has no policy at all and nothing was checked. ' +
354
- (headText === null
355
- ? `Run "conductor init" on the base branch.`
356
- : `The ${POLICY_FILE_NAME} in this pull request is a proposal: it decides what runs ` +
357
- 'once it is on the base branch, and never on the pull request that adds it.');
358
- return {
364
+ //
365
+ // THE ONE WAY OUT OF THE REFUSAL (issue 101) is at the bottom of this
366
+ // block: --adoption-proposal was given, the HEAD blob parses, and
367
+ // refuseAdoptionProposal found no reason to refuse. Every other path
368
+ // through here is the refusal above, exit 2.
369
+ const lead = `No ${POLICY_FILE_NAME} on "${trustBase}". On a pull-request run every rule comes from the ` +
370
+ 'base ref, so this run has no policy at all and nothing was checked. ';
371
+ const refused = (rest, noPolicy = false) => ({
359
372
  kind: 'refused',
360
373
  ref: trustBase,
361
- detail,
374
+ detail: `${lead}${rest}`,
362
375
  inventory: inventoryFromHead(root, overrides),
376
+ ...(noPolicy ? { noPolicy: true } : {}),
377
+ });
378
+ if (headRead.kind === 'error') {
379
+ // UNREADABLE IS NOT ABSENT, on the head as on the base. Not the "run
380
+ // conductor init" sentence: the pull request does carry something at
381
+ // that path, and it is not a file git will hand back.
382
+ return refused(`The ${POLICY_FILE_NAME} in this pull request cannot be read: ${headRead.detail}.`);
383
+ }
384
+ if (headRead.kind === 'absent') {
385
+ return refused(`Run "conductor init" on the base branch.`, true);
386
+ }
387
+ // THE HEAD BLOB, never the file on disk: the working tree can hold an
388
+ // uncommitted edit, and loadPolicy follows a symbolic link.
389
+ let head;
390
+ try {
391
+ head = parsePolicy(headRead.text, `HEAD:${POLICY_FILE_NAME}`);
392
+ }
393
+ catch (error) {
394
+ if (!(error instanceof PolicyError))
395
+ throw error;
396
+ return refused(`The ${POLICY_FILE_NAME} in this pull request is not a policy either: ${parseErrorLine(error)}`);
397
+ }
398
+ if (!adoptionProposal) {
399
+ return refused(`The ${POLICY_FILE_NAME} in this pull request is a proposal: it decides what runs ` +
400
+ 'once it is on the base branch, and never on the pull request that adds it.');
401
+ }
402
+ const whyNot = refuseAdoptionProposal(root, trustBase, env);
403
+ if (whyNot !== null) {
404
+ return refused(`The ${POLICY_FILE_NAME} in this pull request was not run as a proposal: ${whyNot}`);
405
+ }
406
+ // A PROPOSAL. Only enabled, stage and enforce come from the head, over
407
+ // what the policy file gives for each product alone (previewPolicy, the
408
+ // one function that takes a subset of a head policy): never its command,
409
+ // args, options, timeout-seconds, present-on-base or report.format.
410
+ const declared = GATE_ROLES.filter((role) => head.gates[role] !== undefined);
411
+ const proposed = previewPolicy(EMPTY_POLICY, head, declared);
412
+ return {
413
+ kind: 'proposal',
414
+ // --gate as on any primary run (applyCliOverrides), a role the proposed
415
+ // policy does not declare being the same usage error it is there.
416
+ policy: applyCliOverrides(proposed, overrides),
417
+ trustBase: {
418
+ ref: trustBase,
419
+ policyChanged: true,
420
+ refusal: null,
421
+ proposal: { reason: 'no-policy-on-base' },
422
+ // What the head wrote and this run did NOT apply: every key in which
423
+ // the head policy differs from the policy that ran. Compared with
424
+ // that policy and not with an empty one, so a product default the
425
+ // head merely leaves alone is not listed as a change it proposes.
426
+ policyChanges: diffPolicies(proposed, head),
427
+ },
363
428
  };
364
429
  }
365
430
  // Parsed once, before applyCliOverrides, so a --gate override never shows up
366
431
  // as a policy change. The parsed head is never handed to a run: the
367
432
  // comparison reads it, and the preview policy below takes only enabled,
368
433
  // stage and enforce from it.
369
- const baseParsed = parsePolicy(baseText, `${trustBase}:${POLICY_FILE_NAME}`);
434
+ //
435
+ // A BASE POLICY THAT DOES NOT PARSE (an empty file included) IS A REFUSAL
436
+ // WITH A REPORT, like every other base this run cannot be judged against.
437
+ // It used to throw from here, which left one line on stderr and no report
438
+ // at all. Never a proposal: the base has a policy file.
439
+ let baseParsed;
440
+ try {
441
+ baseParsed = parsePolicy(baseText, `${trustBase}:${POLICY_FILE_NAME}`);
442
+ }
443
+ catch (error) {
444
+ if (!(error instanceof PolicyError))
445
+ throw error;
446
+ return {
447
+ kind: 'refused',
448
+ ref: trustBase,
449
+ detail: `The ${POLICY_FILE_NAME} on "${trustBase}" is not a policy this run can use: ` +
450
+ `${parseErrorLine(error)} On a pull-request run every rule comes from the base ` +
451
+ 'ref, so nothing was checked. Fix the file on the base branch; the pull request that does ' +
452
+ 'so is judged against this same base, so it has to be merged by someone allowed to merge ' +
453
+ 'without this check passing.',
454
+ inventory: inventoryFromHead(root, overrides),
455
+ };
456
+ }
370
457
  const policyChanged = headRead.kind === 'error' ? true : policyDiffers(baseText, headText);
371
458
  let headPolicy = null;
372
459
  if (headText !== null) {
@@ -397,6 +484,10 @@ preview = false) {
397
484
  // fail-closed direction: it is never taken to match the base.
398
485
  policyChanged,
399
486
  refusal: null,
487
+ // The base has a policy and HEAD has no policy file at all: this pull
488
+ // request deletes it. Only for a file that is truly absent, never for
489
+ // one git could not read or one that does not parse.
490
+ ...(headRead.kind === 'absent' ? { policyRemoved: true } : {}),
400
491
  ...(policyChanged ? { policyChanges: diffPolicies(baseParsed, headPolicy) } : {}),
401
492
  // Computed AFTER refuseTrustBaseRef has already returned null, on the
402
493
  // one shape that check accepts despite an identical tree: a merge
@@ -634,12 +725,13 @@ export function buildProgram() {
634
725
  .option('--base <ref>', 'measure the intent gate against what this branch changed since <ref>, rather than against the index. In Actions this defaults to the base the action resolved (refs/conductor/trust-base, else refs/remotes/origin/<GITHUB_BASE_REF>, as a commit id) when GITHUB_BASE_REF is set.')
635
726
  .option('--trust-base <ref>', 'pull-request mode: read .guardrails.yaml from this ref instead of from the tree being judged, and pass the same ref to every gate that supports it. A policy change in the pull request is reported as a proposal and never takes effect for the run, so a pull request cannot change the rules it is judged by. In Actions the composite action fetches the base branch and passes its full commit id on a pull_request event, or the commit the merge ref was built from when the fetched tip has the merge ref\'s exact tree.')
636
727
  .option('--output <path>', 'write the report to this file instead of to stdout, for a CI step that uploads it')
637
- .option('--text-report <path>', 'with --format sarif, also write the text report to this file, from the same run: exactly what --format text would have rendered for this result, --verbose, --compact-on-refusal and --advisory respected, and no gate is run a second time. In a full report (any run that is not fully clean, or any run with --verbose) the second line is "verdict-token: <token>"; the one-line summary of a clean run without --verbose has none. The token is a label for this run\'s own exit decision: pass, nothing-checked (exit 0 but nothing was checked: no gate ran, or every gate that ran had nothing to scan, read no packages, had no contract, or was handed an empty change set), advisory-blocked (N), unenforced-findings (N), blocked (N) or could-not-run. Only meaningful with --format sarif: with --format text the text report is already the output, so the combination is a usage error (exit 2).')
728
+ .option('--text-report <path>', 'with --format sarif, also write the text report to this file, from the same run: exactly what --format text would have rendered for this result, --verbose, --compact-on-refusal and --advisory respected, and no gate is run a second time. In a full report (any run that is not fully clean, or any run with --verbose) the second line is "verdict-token: <token>"; the one-line summary of a clean run without --verbose has none. The token is a label for this run\'s own exit decision: pass, nothing-checked (exit 0 but nothing was checked: no gate ran, or every gate that ran had nothing to scan, read no packages, had no contract, or was handed an empty change set), advisory-blocked (N), unenforced-findings (N), blocked (N), could-not-run, or on an --adoption-proposal run that enforced nothing, proposal (N) or proposal-nothing-checked. Only meaningful with --format sarif: with --format text the text report is already the output, so the combination is a usage error (exit 2).')
638
729
  .option('--spec <path>', 'the spec the intent gate imports its contract from, outranking a Spec: line in the pull request body and the branch-name convention. On a pull-request run (--trust-base) the spec is read from the base ref, and a frozen contract on the base takes precedence over it')
639
730
  .option('--verbose', 'print the full per-gate report even when the run is clean. A clean run prints one summary line by default, because a pre-commit hook that prints a screenful on every commit is a hook a team switches off. Text output only; SARIF is unaffected.')
640
731
  .option('--compact-on-refusal', 'when the trust base was refused and no gate ran, print a short body instead of the full refusal report: the version, the verdict, and the refusal reason (with its remedy, when one applies), never the full per-gate report. Built for the pull-request-comment step; every other run is unaffected, whatever --verbose says. Text output only; SARIF is unaffected.')
641
732
  .option('--gate <role>', 'restrict the run to this role; repeatable', (value, previous = []) => [...previous, value])
642
733
  .option('--advisory', 'maps exit 1 (every enabled gate ran and at least one blocked) to exit 0, so a blocking finding never fails this run. A gate that could not run is unaffected and still exits 2: advisory changes what a FINDING does, never what a broken gate does. The report is unchanged and a blocking finding still prints as BLOCKING; only the process exit code and the verdict line, which says findings were advisory, are different.')
734
+ .option('--adoption-proposal', 'pull-request mode only, needs --trust-base, never with --staged: when the trust base has no .guardrails.yaml and this pull request adds one, run the policy it adds as a proposal instead of refusing. Only enabled, stage and enforce are taken from it, from the committed file; every other key is the product default. The run exits 0 whatever the gates find, with the verdict token proposal (N) or proposal-nothing-checked and a line saying nothing was enforced; it exits 2 when a gate the proposed policy enforces could not run. Refused, exit 2 as without the flag, unless all of this holds: the policy file is absent from the trust base, from every merge base of the trust base and HEAD, and from the first-parent history of the trust base; the repository is not shallow; no GIT_ variable outside a short allowlist is set. Pass it only for a pull request into the default branch: the Action does exactly that. On any other run it changes nothing.')
643
735
  .option('--project <dir>', PROJECT_OPTION_HELP)
644
736
  .exitOverride()
645
737
  .action((options) => {
@@ -649,6 +741,16 @@ export function buildProgram() {
649
741
  // finally below on every way out of this action.
650
742
  let gitShim = null;
651
743
  try {
744
+ // USAGE ERRORS, before anything runs. A proposal is a statement about
745
+ // a pull request against a base: the index of a local commit has no
746
+ // base to lack a policy, and without a trust base there is nothing
747
+ // the policy could be absent from.
748
+ if (options.adoptionProposal === true && options.staged === true) {
749
+ throw new PolicyError('--adoption-proposal cannot be combined with --staged: a proposal is about a pull request, never about the index.');
750
+ }
751
+ if (options.adoptionProposal === true && options.trustBase === undefined) {
752
+ throw new PolicyError('--adoption-proposal needs --trust-base: it only decides what a run does when the trust base has no policy.');
753
+ }
652
754
  // BEFORE ANY GIT CALL, including the one that finds the repository.
653
755
  if (options.trustBase !== undefined) {
654
756
  gitShim = pinPathForTrustBase(options.project === undefined ? cwd : path.resolve(cwd, options.project));
@@ -673,8 +775,8 @@ export function buildProgram() {
673
775
  : { gates: parseRoles(options.gate) }),
674
776
  };
675
777
  const stage = parseStage(options.stage);
676
- const source = policyForRun(root, options.trustBase, overrides, process.env.GITHUB_BASE_REF, process.env.GITHUB_ACTIONS, options.preview === true && options.staged !== true);
677
- const policy = source.kind === 'policy' ? source.policy : source.inventory;
778
+ const source = policyForRun(root, options.trustBase, overrides, process.env.GITHUB_BASE_REF, process.env.GITHUB_ACTIONS, options.preview === true && options.staged !== true, options.adoptionProposal === true);
779
+ const policy = source.kind === 'refused' ? source.inventory : source.policy;
678
780
  const format = parseFormat(options.format ?? policy.report.format);
679
781
  // BEFORE ANY GATE RUNS. With --format text the text report already is
680
782
  // the run's output, so a second copy of it in a file is not something
@@ -684,49 +786,58 @@ export function buildProgram() {
684
786
  if (options.textReport !== undefined && format !== 'sarif') {
685
787
  throw new PolicyError('--text-report is only meaningful with --format sarif: with --format text the text report is the output already.');
686
788
  }
789
+ // What every run of the gates is handed, a proposal's included.
790
+ const runOptions = (trustBase) => ({
791
+ repoRoot: root,
792
+ staged: Boolean(options.staged),
793
+ pathValue: process.env.PATH ?? '',
794
+ env: process.env,
795
+ ...(stage === undefined ? {} : { stage }),
796
+ ...(options.base === undefined ? {} : { base: options.base }),
797
+ ...(options.spec === undefined ? {} : { spec: options.spec }),
798
+ ...(trustBase === undefined ? {} : { trustBase: withMovedBaseTip(root, trustBase, process.env.CONDUCTOR_BASE_TIP) }),
799
+ });
687
800
  const result = source.kind === 'refused'
688
801
  ? refusedTrustBase(source.inventory, source.ref, source.detail, {
689
802
  ...(stage === undefined ? {} : { stage }),
690
803
  ...(source.notGiven === true ? { notGiven: true } : {}),
804
+ ...(source.noPolicy === true ? { noPolicy: true } : {}),
691
805
  })
692
- : runAll(source.policy, {
693
- repoRoot: root,
694
- staged: Boolean(options.staged),
695
- pathValue: process.env.PATH ?? '',
696
- env: process.env,
697
- ...(stage === undefined ? {} : { stage }),
698
- ...(options.base === undefined ? {} : { base: options.base }),
699
- ...(options.spec === undefined ? {} : { spec: options.spec }),
700
- ...(source.trustBase === undefined ? {} : { trustBase: withMovedBaseTip(root, source.trustBase, process.env.CONDUCTOR_BASE_TIP) }),
701
- // Only on request, never on --staged, and only with a trust
702
- // base and a preview policy: a head that parsed and changed
703
- // at least one role's enabled or stage.
704
- ...(options.preview === true &&
705
- options.staged !== true &&
706
- source.trustBase !== undefined &&
707
- source.previewPolicy !== null
708
- ? { preview: { policy: source.previewPolicy } }
709
- : {}),
710
- });
806
+ : source.kind === 'proposal'
807
+ ? // THE PRIMARY PATH, WITH THE TRUST BASE, AND NEVER A PREVIEW:
808
+ // every pull-request protection keys on the trust base being
809
+ // set, and a proposal has no preview to pass (see the type).
810
+ // asProposal then writes the exit code, and nothing else does.
811
+ asProposal(runAll(source.policy, runOptions(source.trustBase)))
812
+ : runAll(source.policy, {
813
+ ...runOptions(source.trustBase),
814
+ // Only on request, never on --staged, and only with a trust
815
+ // base and a preview policy: a head that parsed and changed
816
+ // at least one role's enabled or stage.
817
+ ...(options.preview === true &&
818
+ options.staged !== true &&
819
+ source.trustBase !== undefined &&
820
+ source.previewPolicy !== null
821
+ ? { preview: { policy: source.previewPolicy } }
822
+ : {}),
823
+ });
711
824
  const advisory = Boolean(options.advisory);
712
825
  // SARIF carries no verdict line, so --advisory has nothing to say
713
826
  // there: each finding's `properties.blocking` is the gate's own
714
827
  // decision (see output-sarif.ts) and is unaffected by this flag,
715
828
  // exactly as the text report's per-finding BLOCKING marker is.
716
- const renderTextReport = (terminal) => renderText(result, {
829
+ // One rendering for a terminal, a file, a pipe and the --text-report
830
+ // copy: a refused run is the short form on every one of them.
831
+ const renderTextReport = () => renderText(result, {
717
832
  verbose: Boolean(options.verbose),
718
833
  version: pkg.version,
719
834
  compact: Boolean(options.compactOnRefusal),
720
835
  advisory,
721
- ...(terminal ? { terminal: true } : {}),
722
836
  });
723
- // Only a report printed straight to a terminal is told so; a file,
724
- // a pipe and the --text-report copy render exactly as before.
725
- const toTerminal = rendersToTerminal(options.output, process.stdout.isTTY);
726
- const rendered = format === 'sarif' ? `${renderSarif(result, pkg.version)}\n` : renderTextReport(toTerminal);
837
+ const rendered = format === 'sarif' ? `${renderSarif(result, pkg.version)}\n` : renderTextReport();
727
838
  // The SAME result, rendered a second time, never a second run: the
728
839
  // token in this file is for the run that set the exit code below.
729
- const textReport = options.textReport === undefined ? undefined : renderTextReport(false);
840
+ const textReport = options.textReport === undefined ? undefined : renderTextReport();
730
841
  if (options.output === undefined) {
731
842
  process.stdout.write(rendered);
732
843
  }
@@ -772,6 +883,10 @@ export function buildProgram() {
772
883
  // for an unwritable file.
773
884
  const logLines = [
774
885
  ...gateLogLines(result, process.stderr.isTTY === true ? { terminal: true } : {}),
886
+ // The findings by name, only when the report went to a file: then
887
+ // the log is the one place a reader of the job sees them (issue
888
+ // 144). A report on stdout names them itself, directly above.
889
+ ...(options.output === undefined ? [] : findingLogLines(result)),
775
890
  ...proposalLogLines(result),
776
891
  ...previewLogLines(result),
777
892
  ...versionSkewWarnings(result),
@@ -834,6 +949,25 @@ export function buildProgram() {
834
949
  process.exitCode = fail(err instanceof PolicyError
835
950
  ? err.message
836
951
  : `conductor: ${err instanceof Error ? err.message : String(err)}`);
952
+ // NO POLICY FILE AT ALL, IN ACTIONS: the workflow is installed and
953
+ // checks nothing, and a red step with one stderr line was read as a
954
+ // broken tool (issue 101). The same fixed line the refused
955
+ // pull-request run prints goes on the run's page. Only a run with no
956
+ // trust base reaches here with this error (a trust-base run reads the
957
+ // policy from a ref and reports its absence itself). A summary that
958
+ // cannot be written is skipped: the exit code is already 2.
959
+ const summaryFile = process.env.GITHUB_STEP_SUMMARY;
960
+ if (err instanceof MissingPolicyError &&
961
+ process.env.GITHUB_ACTIONS === 'true' &&
962
+ summaryFile !== undefined &&
963
+ summaryFile !== '') {
964
+ try {
965
+ appendFileSync(summaryFile, `${NO_POLICY_LINE}\n\n`);
966
+ }
967
+ catch {
968
+ // The line on stderr above already says there is no policy.
969
+ }
970
+ }
837
971
  }
838
972
  finally {
839
973
  if (gitShim !== null) {
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Every character outside printable ASCII as a \uXXXX escape (an astral
3
+ * character as its two surrogate escapes), so head-chosen text cannot smuggle
4
+ * a bidi override or a zero-width character into the report. Used for a head
5
+ * policy value (renderValue, src/policy-diff.ts), and for every preview line
6
+ * (cleanPreviewLine, src/gate-runner.ts), whose gate text the head's own
7
+ * control files can choose (audit 2026-10-27, N3).
8
+ */
9
+ export declare function escapeNonAscii(text: string): string;
10
+ /**
11
+ * ONE FIELD OF A NAMED-FINDING LINE, made safe for the three places such a
12
+ * line is printed: the job log, the step summary and the pull request
13
+ * comment (issue 144). A finding's rule, path, package name and message are
14
+ * all text a pull request can choose, so every one of them goes through
15
+ * here, and nothing else writes a field of those lines.
16
+ *
17
+ * What comes back is one line of printable ASCII, at most `max` characters:
18
+ *
19
+ * - every character outside printable ASCII is a \uXXXX escape: a newline,
20
+ * a carriage return and a tab cannot start a second line, and a bidi
21
+ * override or a zero-width character is visible;
22
+ * - a backtick, an angle bracket and an ampersand are escaped the same way.
23
+ * The lines are printed inside a fenced code block, where a backtick run
24
+ * is the only thing that could end the fence, and no HTML tag, comment or
25
+ * entity survives outside one either;
26
+ * - "::" and "##[" are broken up with a space, so a job log reader sees no
27
+ * workflow command;
28
+ * - runs of spaces are collapsed and the result is trimmed and cut at `max`
29
+ * with a "..." marker, escapes counted.
30
+ *
31
+ * NOT escaped: the rest of markdown's punctuation (an underscore, a star, a
32
+ * bracket). A path is full of it, and it is inert inside the fence both
33
+ * consumers print these lines in; they check that for themselves and omit a
34
+ * line holding a backtick or anything unprintable.
35
+ */
36
+ export declare function summaryField(raw: string, max: number): string;
package/dist/escape.js ADDED
@@ -0,0 +1,49 @@
1
+ // Pure text sanitizers with no dependency on any other module here, so a
2
+ // renderer or the gate runner can import them without importing the policy
3
+ // diff or anything heavier.
4
+ /**
5
+ * Every character outside printable ASCII as a \uXXXX escape (an astral
6
+ * character as its two surrogate escapes), so head-chosen text cannot smuggle
7
+ * a bidi override or a zero-width character into the report. Used for a head
8
+ * policy value (renderValue, src/policy-diff.ts), and for every preview line
9
+ * (cleanPreviewLine, src/gate-runner.ts), whose gate text the head's own
10
+ * control files can choose (audit 2026-10-27, N3).
11
+ */
12
+ export function escapeNonAscii(text) {
13
+ return text.replace(/[^\x20-\x7e]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`);
14
+ }
15
+ /**
16
+ * ONE FIELD OF A NAMED-FINDING LINE, made safe for the three places such a
17
+ * line is printed: the job log, the step summary and the pull request
18
+ * comment (issue 144). A finding's rule, path, package name and message are
19
+ * all text a pull request can choose, so every one of them goes through
20
+ * here, and nothing else writes a field of those lines.
21
+ *
22
+ * What comes back is one line of printable ASCII, at most `max` characters:
23
+ *
24
+ * - every character outside printable ASCII is a \uXXXX escape: a newline,
25
+ * a carriage return and a tab cannot start a second line, and a bidi
26
+ * override or a zero-width character is visible;
27
+ * - a backtick, an angle bracket and an ampersand are escaped the same way.
28
+ * The lines are printed inside a fenced code block, where a backtick run
29
+ * is the only thing that could end the fence, and no HTML tag, comment or
30
+ * entity survives outside one either;
31
+ * - "::" and "##[" are broken up with a space, so a job log reader sees no
32
+ * workflow command;
33
+ * - runs of spaces are collapsed and the result is trimmed and cut at `max`
34
+ * with a "..." marker, escapes counted.
35
+ *
36
+ * NOT escaped: the rest of markdown's punctuation (an underscore, a star, a
37
+ * bracket). A path is full of it, and it is inert inside the fence both
38
+ * consumers print these lines in; they check that for themselves and omit a
39
+ * line holding a backtick or anything unprintable.
40
+ */
41
+ export function summaryField(raw, max) {
42
+ const flat = escapeNonAscii(raw)
43
+ .replace(/[`<>&]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`)
44
+ .replace(/:(?=:)/g, ': ')
45
+ .replace(/#(?=#\[)/g, '# ')
46
+ .replace(/ {2,}/g, ' ')
47
+ .trim();
48
+ return flat.length > max ? `${flat.slice(0, Math.max(0, max - 3))}...` : flat;
49
+ }
@@ -0,0 +1,38 @@
1
+ import type { GateOutcome } from './gate-runner.js';
2
+ /** What predated the policy: a count, or the policy is not committed yet. */
3
+ export type PredatingFact = {
4
+ kind: 'count';
5
+ count: number;
6
+ } | {
7
+ kind: 'not-committed';
8
+ };
9
+ export interface ExistingFindings {
10
+ /** Blocking findings from the history gate (gitleaks). */
11
+ history: number;
12
+ /** Blocking findings from the vulnerabilities gate (osv-scanner). */
13
+ vulnerabilities: number;
14
+ /** About the history findings only; null when there are none or git could not say. */
15
+ predating: PredatingFact | null;
16
+ /** History findings whose file is not in HEAD's tree; null when git could not say. */
17
+ goneAtHead: number | null;
18
+ /** History findings whose file is in HEAD's tree; null when git could not say. */
19
+ stillAtHead: number | null;
20
+ }
21
+ /**
22
+ * The facts for the message, or null when the gates that block are not the
23
+ * history or the vulnerabilities gate. The caller only calls it on a run with
24
+ * no trust base; the text report checks that again.
25
+ *
26
+ * A history finding counts as predating the policy only when EVERY commit it
27
+ * carries (the kept commit and each alsoIn) is an ancestor of the policy
28
+ * commit's first parent. The kept commit can be the newest, or chosen by a
29
+ * forged date, so it alone proves nothing. Gaming this changes a sentence,
30
+ * never an exit code.
31
+ */
32
+ export declare function collectExistingFindings(outcomes: readonly GateOutcome[], repoRoot: string): ExistingFindings | null;
33
+ /**
34
+ * The report section. Every name in it exists today: the stage split, each
35
+ * tool's own ignore mechanism and each family gate's own baseline. Nothing
36
+ * here points at a conductor command that records findings as known.
37
+ */
38
+ export declare function existingFindingsLines(info: ExistingFindings): string[];