@oss-autopilot/core 3.42.4 → 3.43.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.
Files changed (172) hide show
  1. package/dist/cli-pre-action.js +8 -3
  2. package/dist/cli-registry.js +272 -25
  3. package/dist/cli.bundle.cjs +183 -154
  4. package/dist/commands/check-integration.js +1 -0
  5. package/dist/commands/cleanup.d.ts +76 -0
  6. package/dist/commands/cleanup.js +269 -0
  7. package/dist/commands/comments.d.ts +6 -0
  8. package/dist/commands/comments.js +6 -2
  9. package/dist/commands/config.js +37 -5
  10. package/dist/commands/daily-dismiss-filter.d.ts +7 -0
  11. package/dist/commands/daily-dismiss-filter.js +17 -1
  12. package/dist/commands/daily-ledger.d.ts +122 -0
  13. package/dist/commands/daily-ledger.js +225 -0
  14. package/dist/commands/daily-recent-prs.d.ts +26 -0
  15. package/dist/commands/daily-recent-prs.js +55 -0
  16. package/dist/commands/daily.d.ts +2 -1
  17. package/dist/commands/daily.js +59 -89
  18. package/dist/commands/dashboard-cache.d.ts +2 -0
  19. package/dist/commands/dashboard-cache.js +33 -8
  20. package/dist/commands/dashboard-data.js +71 -36
  21. package/dist/commands/dashboard-gist-sync.js +3 -1
  22. package/dist/commands/dashboard-lifecycle.js +1 -1
  23. package/dist/commands/dashboard-process.d.ts +14 -1
  24. package/dist/commands/dashboard-process.js +46 -7
  25. package/dist/commands/dashboard-server.js +89 -23
  26. package/dist/commands/detect-formatters.js +1 -0
  27. package/dist/commands/dismiss.js +5 -2
  28. package/dist/commands/doctor.d.ts +15 -1
  29. package/dist/commands/doctor.js +73 -5
  30. package/dist/commands/draft.d.ts +77 -0
  31. package/dist/commands/draft.js +218 -0
  32. package/dist/commands/eval.js +1 -0
  33. package/dist/commands/guidelines.d.ts +23 -1
  34. package/dist/commands/guidelines.js +49 -4
  35. package/dist/commands/index.d.ts +24 -4
  36. package/dist/commands/index.js +15 -3
  37. package/dist/commands/issue-thread.d.ts +46 -0
  38. package/dist/commands/issue-thread.js +123 -0
  39. package/dist/commands/ledger-backfill.d.ts +9 -0
  40. package/dist/commands/ledger-backfill.js +44 -1
  41. package/dist/commands/list-mark-done.d.ts +2 -1
  42. package/dist/commands/list-mark-done.js +3 -1
  43. package/dist/commands/list-move-tier.d.ts +2 -1
  44. package/dist/commands/list-move-tier.js +3 -1
  45. package/dist/commands/local-repos.js +10 -5
  46. package/dist/commands/locate-issue-list.d.ts +40 -17
  47. package/dist/commands/locate-issue-list.js +148 -88
  48. package/dist/commands/move.js +7 -1
  49. package/dist/commands/overnight-handoff.d.ts +17 -7
  50. package/dist/commands/overnight-handoff.js +36 -14
  51. package/dist/commands/overnight-push-prep.d.ts +13 -8
  52. package/dist/commands/overnight-push-prep.js +106 -34
  53. package/dist/commands/overnight-tool-rules.d.ts +54 -0
  54. package/dist/commands/overnight-tool-rules.js +217 -0
  55. package/dist/commands/overnight.d.ts +5 -6
  56. package/dist/commands/overnight.js +61 -140
  57. package/dist/commands/parse-list.js +7 -1
  58. package/dist/commands/policy.d.ts +86 -0
  59. package/dist/commands/policy.js +263 -0
  60. package/dist/commands/pr-preflight.d.ts +43 -0
  61. package/dist/commands/pr-preflight.js +294 -0
  62. package/dist/commands/repo-vet.d.ts +9 -0
  63. package/dist/commands/repo-vet.js +36 -11
  64. package/dist/commands/scout-bridge.js +18 -8
  65. package/dist/commands/search.js +7 -0
  66. package/dist/commands/setup.d.ts +3 -3
  67. package/dist/commands/setup.js +46 -18
  68. package/dist/commands/skip-add.js +10 -1
  69. package/dist/commands/startup.d.ts +5 -3
  70. package/dist/commands/startup.js +65 -49
  71. package/dist/commands/state-cmd.d.ts +2 -0
  72. package/dist/commands/state-cmd.js +5 -1
  73. package/dist/commands/stats.js +1 -0
  74. package/dist/commands/status.js +1 -0
  75. package/dist/commands/strategy.js +1 -0
  76. package/dist/commands/vet-list.d.ts +6 -0
  77. package/dist/commands/vet-list.js +25 -0
  78. package/dist/commands/vet.d.ts +12 -0
  79. package/dist/commands/vet.js +118 -1
  80. package/dist/core/__fixtures__/prompt-injection-payloads.js +31 -0
  81. package/dist/core/anti-llm-policy.d.ts +3 -0
  82. package/dist/core/anti-llm-policy.js +3 -0
  83. package/dist/core/auth.js +2 -0
  84. package/dist/core/checklist-analysis.js +50 -12
  85. package/dist/core/ci-analysis.d.ts +7 -2
  86. package/dist/core/ci-analysis.js +76 -21
  87. package/dist/core/comment-utils.d.ts +1 -1
  88. package/dist/core/comment-utils.js +7 -1
  89. package/dist/core/commit-date.d.ts +19 -0
  90. package/dist/core/commit-date.js +17 -0
  91. package/dist/core/compliance-score.js +11 -7
  92. package/dist/core/config-registry.js +11 -5
  93. package/dist/core/contributing.d.ts +2 -3
  94. package/dist/core/contributing.js +2 -3
  95. package/dist/core/daily-logic.d.ts +27 -5
  96. package/dist/core/daily-logic.js +57 -19
  97. package/dist/core/errors.d.ts +37 -3
  98. package/dist/core/errors.js +54 -5
  99. package/dist/core/gist-health.d.ts +15 -3
  100. package/dist/core/gist-health.js +8 -0
  101. package/dist/core/gist-state-store.d.ts +24 -4
  102. package/dist/core/gist-state-store.js +97 -46
  103. package/dist/core/github-stats.d.ts +104 -16
  104. package/dist/core/github-stats.js +282 -97
  105. package/dist/core/http-cache.d.ts +0 -10
  106. package/dist/core/http-cache.js +0 -19
  107. package/dist/core/index.d.ts +12 -5
  108. package/dist/core/index.js +15 -5
  109. package/dist/core/issue-conversation.d.ts +8 -2
  110. package/dist/core/issue-conversation.js +31 -12
  111. package/dist/core/local-config.d.ts +95 -0
  112. package/dist/core/local-config.js +271 -0
  113. package/dist/core/merged-pr-notes.d.ts +2 -2
  114. package/dist/core/pagination.d.ts +55 -0
  115. package/dist/core/pagination.js +59 -0
  116. package/dist/core/paths.d.ts +7 -0
  117. package/dist/core/paths.js +9 -0
  118. package/dist/core/pr-assembly.js +6 -2
  119. package/dist/core/pr-graphql.d.ts +37 -3
  120. package/dist/core/pr-graphql.js +73 -12
  121. package/dist/core/pr-monitor.d.ts +29 -12
  122. package/dist/core/pr-monitor.js +71 -23
  123. package/dist/core/pr-preflight.d.ts +113 -0
  124. package/dist/core/pr-preflight.js +364 -0
  125. package/dist/core/pr-quality-rubric.d.ts +0 -6
  126. package/dist/core/pr-quality-rubric.js +0 -8
  127. package/dist/core/pr-template.d.ts +2 -0
  128. package/dist/core/pr-template.js +5 -1
  129. package/dist/core/repo-policy.d.ts +105 -0
  130. package/dist/core/repo-policy.js +400 -0
  131. package/dist/core/repo-score-manager.d.ts +48 -0
  132. package/dist/core/repo-score-manager.js +111 -1
  133. package/dist/core/review-analysis.d.ts +34 -19
  134. package/dist/core/review-analysis.js +74 -19
  135. package/dist/core/reviewed-prs-fetch.js +11 -29
  136. package/dist/core/reviewed-prs.js +8 -15
  137. package/dist/core/stale-data.d.ts +41 -0
  138. package/dist/core/stale-data.js +115 -0
  139. package/dist/core/state-persistence.d.ts +62 -27
  140. package/dist/core/state-persistence.js +338 -117
  141. package/dist/core/state-schema.d.ts +113 -210
  142. package/dist/core/state-schema.js +165 -80
  143. package/dist/core/state.d.ts +60 -8
  144. package/dist/core/state.js +192 -46
  145. package/dist/core/status-determination.js +26 -8
  146. package/dist/core/strategy.js +3 -1
  147. package/dist/core/types.d.ts +22 -1
  148. package/dist/core/types.js +1 -0
  149. package/dist/core/untrusted-content.d.ts +30 -11
  150. package/dist/core/untrusted-content.js +77 -42
  151. package/dist/core/urls.d.ts +9 -0
  152. package/dist/core/urls.js +18 -0
  153. package/dist/dashboard/assets/{chart-panel-DPKNBUts.js → chart-panel-C_C1lFTI.js} +1 -1
  154. package/dist/dashboard/assets/{index-B25bZOYX.js → index-B--H66Jk.js} +1 -1
  155. package/dist/dashboard/index.html +1 -1
  156. package/dist/formatters/json.d.ts +262 -6
  157. package/dist/formatters/json.js +77 -1
  158. package/package.json +1 -1
  159. package/dist/core/ci-enforced-tools.d.ts +0 -35
  160. package/dist/core/ci-enforced-tools.js +0 -109
  161. package/dist/core/comment-decision.d.ts +0 -79
  162. package/dist/core/comment-decision.js +0 -82
  163. package/dist/core/extraction-categories.d.ts +0 -55
  164. package/dist/core/extraction-categories.js +0 -108
  165. package/dist/core/follow-up-history.d.ts +0 -40
  166. package/dist/core/follow-up-history.js +0 -71
  167. package/dist/core/issue-effort.d.ts +0 -29
  168. package/dist/core/issue-effort.js +0 -47
  169. package/dist/core/maintainer-hints.d.ts +0 -23
  170. package/dist/core/maintainer-hints.js +0 -36
  171. package/dist/core/workflow-state.d.ts +0 -56
  172. package/dist/core/workflow-state.js +0 -101
@@ -10,12 +10,16 @@
10
10
  * external dependencies in isolation.
11
11
  */
12
12
  import * as fs from 'node:fs';
13
+ import * as os from 'node:os';
13
14
  import * as path from 'node:path';
14
15
  import { execFile } from 'node:child_process';
15
16
  import { promisify } from 'node:util';
16
17
  import { getGitHubTokenAsync, getOctokit, getStatePath } from '../core/index.js';
17
18
  import { AgentStateSchema } from '../core/state-schema.js';
18
19
  import { errorMessage } from '../core/errors.js';
20
+ import { resolveDataDir } from '../core/paths.js';
21
+ import { WORKTREE_NAME, staleRejectedCopies } from '../core/stale-data.js';
22
+ import { LAUNCHD_LABEL, isScheduleCurrent } from './overnight.js';
19
23
  const execFileAsync = promisify(execFile);
20
24
  const GH_CMD_TIMEOUT_MS = 3000;
21
25
  // ── Individual checks ───────────────────────────────────────────────────
@@ -122,6 +126,13 @@ function resolveBundlePaths() {
122
126
  const sourcePath = fs.existsSync(devSource) ? devSource : fs.existsSync(coDirSource) ? coDirSource : devSource;
123
127
  return { bundlePath, sourcePath };
124
128
  }
129
+ /**
130
+ * Remediation text depends on the install layout. A source checkout (cli.ts
131
+ * present) rebuilds from pnpm-lock.yaml only (#1935). A prebuilt install (the
132
+ * plugin's marketplace tree, or the npm package) has nothing to build from.
133
+ */
134
+ const SOURCE_CHECKOUT_REBUILD = 'From the repo root run `pnpm install --frozen-lockfile --ignore-scripts && pnpm --filter @oss-autopilot/core run bundle`';
135
+ const PREBUILT_REINSTALL = 'Update or reinstall the oss-autopilot plugin (or the @oss-autopilot/core package)';
125
136
  /**
126
137
  * Try `fs.statSync`; if the file is merely missing (ENOENT), return null.
127
138
  * For other fs errors (EACCES, ELOOP, ENOTDIR, …) surface the error so the
@@ -164,7 +175,7 @@ export function checkBundleUpToDate(options) {
164
175
  name: 'CLI bundle',
165
176
  status: 'warning',
166
177
  message: 'Neither cli.ts nor cli.bundle.cjs could be located',
167
- remediation: 'Reinstall the package or check your install location',
178
+ remediation: `${PREBUILT_REINSTALL}, or check your install location`,
168
179
  };
169
180
  }
170
181
  if (!bundleStat) {
@@ -172,7 +183,7 @@ export function checkBundleUpToDate(options) {
172
183
  name: 'CLI bundle',
173
184
  status: 'warning',
174
185
  message: 'dist/cli.bundle.cjs not built yet',
175
- remediation: 'Run `pnpm run bundle` to build the CLI bundle',
186
+ remediation: SOURCE_CHECKOUT_REBUILD,
176
187
  };
177
188
  }
178
189
  if (sourceStat && sourceStat.mtimeMs > bundleStat.mtimeMs) {
@@ -180,7 +191,7 @@ export function checkBundleUpToDate(options) {
180
191
  name: 'CLI bundle',
181
192
  status: 'warning',
182
193
  message: 'Source files are newer than dist/cli.bundle.cjs',
183
- remediation: 'Run `pnpm run bundle` to rebuild',
194
+ remediation: SOURCE_CHECKOUT_REBUILD,
184
195
  };
185
196
  }
186
197
  return { name: 'CLI bundle', status: 'ok', message: 'Bundle present and up-to-date' };
@@ -223,7 +234,7 @@ export function checkStateFile(options) {
223
234
  }
224
235
  }
225
236
  const defaultScoutImporter = () => import('@oss-scout/core');
226
- export async function checkScoutResolvable(importer = defaultScoutImporter) {
237
+ export async function checkScoutResolvable(importer = defaultScoutImporter, options) {
227
238
  // The scout package is ESM-exports-only, so `require.resolve` fails even
228
239
  // when it's installed. `import()` goes through the ESM resolver, which
229
240
  // honors `exports` maps correctly. Dynamic import only loads the package
@@ -245,6 +256,10 @@ export async function checkScoutResolvable(importer = defaultScoutImporter) {
245
256
  code === 'ERR_INVALID_PACKAGE_CONFIG' ||
246
257
  err instanceof SyntaxError;
247
258
  const reinstallRequired = isNotFound || isCorruptInstall;
259
+ const isSourceCheckout = options?.sourceCheckout ?? fs.existsSync(resolveBundlePaths().sourcePath);
260
+ const reinstallHint = isSourceCheckout
261
+ ? 'Reinstall dependencies from the lockfile: `pnpm install --frozen-lockfile`'
262
+ : PREBUILT_REINSTALL;
248
263
  return {
249
264
  name: '@oss-scout/core resolvable',
250
265
  status: 'error',
@@ -252,7 +267,7 @@ export async function checkScoutResolvable(importer = defaultScoutImporter) {
252
267
  ? `@oss-scout/core cannot be loaded (install issue): ${errorMessage(err)}`
253
268
  : `@oss-scout/core failed to load: ${errorMessage(err)}`,
254
269
  remediation: reinstallRequired
255
- ? 'Reinstall dependencies (`pnpm install` or `npm install`)'
270
+ ? reinstallHint
256
271
  : 'Scout loaded but threw during initialization — report this as a bug in oss-scout with the error above',
257
272
  };
258
273
  }
@@ -294,6 +309,57 @@ export async function checkGitHubRateLimit(preloadedToken) {
294
309
  };
295
310
  }
296
311
  }
312
+ function countStaleData(dataDir) {
313
+ const root = path.join(dataDir, 'worktrees');
314
+ const hasRoot = fs.existsSync(root) && fs.lstatSync(root).isDirectory();
315
+ const entries = hasRoot ? fs.readdirSync(root, { withFileTypes: true }) : [];
316
+ const worktrees = entries.filter((entry) => entry.isDirectory() && WORKTREE_NAME.test(entry.name));
317
+ return { worktrees: worktrees.length, rejected: staleRejectedCopies(dataDir).length };
318
+ }
319
+ /**
320
+ * Stale data under the data directory (#1956): counts only, from the file
321
+ * system; no Git runs here. Which worktrees are safe to remove, and why the
322
+ * others are kept, is what `cleanup` reports.
323
+ */
324
+ export function checkStaleData(dataDir = resolveDataDir()) {
325
+ const name = 'Stale data';
326
+ let counts;
327
+ try {
328
+ counts = countStaleData(dataDir);
329
+ }
330
+ catch (err) {
331
+ return { name, status: 'warning', message: `Could not read ${dataDir}: ${errorMessage(err)}` };
332
+ }
333
+ const message = `${counts.worktrees} overnight worktree(s); ${counts.rejected} rejected state copy(ies) past retention`;
334
+ if (counts.rejected === 0)
335
+ return { name, message, status: 'ok' };
336
+ return {
337
+ name,
338
+ message,
339
+ status: 'warning',
340
+ remediation: 'They are pruned at the next overnight run; `oss-autopilot cleanup` (a dry run) lists them and the worktrees',
341
+ };
342
+ }
343
+ /**
344
+ * The overnight launchd job carries the tool rules and environment of the
345
+ * version that installed it (#1937): an upgrade that tightens them changes
346
+ * nothing for a schedule already on disk until it is installed again.
347
+ */
348
+ export function checkOvernightSchedule(plistPath = path.join(os.homedir(), 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`)) {
349
+ const name = 'Overnight schedule';
350
+ if (!fs.existsSync(plistPath)) {
351
+ return { name, status: 'ok', message: 'No launchd schedule found (systemd and cron jobs are not checked)' };
352
+ }
353
+ if (isScheduleCurrent(fs.readFileSync(plistPath, 'utf8'))) {
354
+ return { name, status: 'ok', message: 'Installed schedule matches this version' };
355
+ }
356
+ return {
357
+ name,
358
+ status: 'warning',
359
+ message: `${plistPath} was written by another version: its permission flags, tool rules or environment differ from the current ones`,
360
+ remediation: 'Run `overnight schedule --install --hour <hour> --claude-path "$(command -v claude)"` again, then the launchctl command it prints',
361
+ };
362
+ }
297
363
  // ── Orchestrator ────────────────────────────────────────────────────────
298
364
  /**
299
365
  * Run all diagnostic checks and return a structured report.
@@ -348,6 +414,8 @@ export async function runDoctor() {
348
414
  runCheckSafely('@oss-scout/core resolvable', () => checkScoutResolvable()),
349
415
  runCheckSafely('CLI bundle', () => checkBundleUpToDate()),
350
416
  runCheckSafely('state.json valid', () => checkStateFile()),
417
+ runCheckSafely('Stale data', () => checkStaleData()),
418
+ runCheckSafely('Overnight schedule', () => checkOvernightSchedule()),
351
419
  ]);
352
420
  const summary = {
353
421
  ok: checks.filter((c) => c.status === 'ok').length,
@@ -0,0 +1,77 @@
1
+ /** Largest draft a command reads. GitHub caps a comment body at 65536 characters; each command's own cap still applies. */
2
+ export declare const MAX_DRAFT_BYTES: number;
3
+ /** Drafts the user never posted or discarded are removed after this long. */
4
+ export declare const MAX_DRAFT_AGE_MS: number;
5
+ export interface DraftPathOutput {
6
+ /** Absolute path for the draft. The file is not created. */
7
+ path: string;
8
+ /** The owner-only draft directory. */
9
+ dir: string;
10
+ }
11
+ export interface DraftContent {
12
+ path: string;
13
+ /** The file's text, from the same single read that produced `sha256`. */
14
+ content: string;
15
+ /** SHA-256 (hex) of the file's text as UTF-8. Pass it back as `--expect-sha256`. */
16
+ sha256: string;
17
+ byteSize: number;
18
+ }
19
+ export interface DraftShowOutput extends DraftContent {
20
+ /** True when `content` is wrapped in the untrusted-content fence (`--untrusted`). `sha256` is always of the unwrapped text. */
21
+ fenced: boolean;
22
+ }
23
+ export declare function sha256Hex(text: string): string;
24
+ /**
25
+ * Throw unless `content` hashes to `expected`. A no-op when `expected` is
26
+ * undefined. Callers run it before their first side effect.
27
+ */
28
+ export declare function assertSha256(content: string, expected: string | undefined): void;
29
+ /**
30
+ * The draft directory, `~/.oss-autopilot/tmp`, created owner-only. An existing
31
+ * directory with looser permissions (made by `mkdir -p` under a 022 umask) is
32
+ * tightened; a symlink, a file in the way, or a directory owned by someone
33
+ * else is refused. Returns the real path so callers can compare against it.
34
+ *
35
+ * Also unlinks the user's own regular files in it older than
36
+ * {@link MAX_DRAFT_AGE_MS}, so abandoned drafts do not pile up. Best effort.
37
+ */
38
+ export declare function getDraftsDir(): string;
39
+ /** `draft path <name>`: where to write a draft. Deterministic, so a later session can find a waiting proposal. */
40
+ export declare function runDraftPath(options: {
41
+ name: string;
42
+ }): DraftPathOutput;
43
+ /**
44
+ * Read a draft once and return its text with the hash of that text.
45
+ *
46
+ * Refuses a file that is not directly inside the draft directory, a symlink
47
+ * or other non-regular file, a file owned by another user, a world-writable
48
+ * or hard-linked file, invalid UTF-8, a byte order mark, and anything over
49
+ * {@link MAX_DRAFT_BYTES}. A bare name or relative path resolves against the
50
+ * draft directory, never the cwd.
51
+ */
52
+ export declare function readDraft(file: string): DraftContent;
53
+ /** What a command was given alongside `--body-file` / `--from-file`. */
54
+ export interface ApprovedDraftRequest {
55
+ file: string;
56
+ flag: '--body-file' | '--from-file';
57
+ expectSha256: string | undefined;
58
+ /** The text was also supplied another way (`--stdin`, positional words, `--content`). */
59
+ hasOtherInput: boolean;
60
+ }
61
+ /**
62
+ * The text of a draft a command is about to post or store. The file is the
63
+ * only source (no silent winner among several), the caller must say which
64
+ * text the user approved, and an empty file never falls back to a default.
65
+ * The hash itself is checked by the command, next to its other gates.
66
+ */
67
+ export declare function readApprovedDraft(request: ApprovedDraftRequest): string;
68
+ /**
69
+ * `draft show <file>`: the text to show the user and the hash to pass back,
70
+ * from one read. With `untrusted`, `content` comes back inside the
71
+ * untrusted-content fence: use it for text distilled from other people's
72
+ * writing (guideline proposals), not for a reply the user dictated.
73
+ */
74
+ export declare function runDraftShow(options: {
75
+ file: string;
76
+ untrusted: boolean;
77
+ }): DraftShowOutput;
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Draft files (#1930): text an agent stages for the user to approve before a
3
+ * command posts or stores it.
4
+ *
5
+ * Drafts used to be staged at predictable paths under `/tmp`, where another
6
+ * local user can pre-create or symlink the path, and the content could change
7
+ * between the user approving it and a command reading it. They now live in
8
+ * `~/.oss-autopilot/tmp` (owner-only), a command reads the file itself
9
+ * (`--body-file`, `--from-file`) instead of taking the text as a shell
10
+ * argument, and `--expect-sha256` pins the read to the text the user saw.
11
+ *
12
+ * `draft path` and `draft show` only touch that directory: no GitHub access,
13
+ * no state, so they are safe in an unattended run.
14
+ */
15
+ import { createHash } from 'node:crypto';
16
+ import * as fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { getDataDir } from '../core/paths.js';
19
+ import { ValidationError } from '../core/errors.js';
20
+ import { wrapUntrustedContent } from '../core/untrusted-content.js';
21
+ /** Largest draft a command reads. GitHub caps a comment body at 65536 characters; each command's own cap still applies. */
22
+ export const MAX_DRAFT_BYTES = 64 * 1024;
23
+ /** A bare file name: no separators, no leading dot or dash. */
24
+ const SAFE_NAME = /^\w[\w.-]{0,199}$/;
25
+ const SHA256_HEX = /^[0-9a-f]{64}$/i;
26
+ /** Drafts the user never posted or discarded are removed after this long. */
27
+ export const MAX_DRAFT_AGE_MS = 30 * 24 * 60 * 60 * 1000;
28
+ const UTF8_BOM = Buffer.from([0xef, 0xbb, 0xbf]);
29
+ const STRICT_UTF8 = new TextDecoder('utf-8', { fatal: true });
30
+ export function sha256Hex(text) {
31
+ return createHash('sha256').update(text, 'utf8').digest('hex');
32
+ }
33
+ /**
34
+ * Throw unless `content` hashes to `expected`. A no-op when `expected` is
35
+ * undefined. Callers run it before their first side effect.
36
+ */
37
+ export function assertSha256(content, expected) {
38
+ if (expected === undefined)
39
+ return;
40
+ if (!SHA256_HEX.test(expected)) {
41
+ throw new ValidationError('--expect-sha256 must be 64 hex characters');
42
+ }
43
+ const actual = sha256Hex(content);
44
+ if (actual !== expected.toLowerCase()) {
45
+ throw new ValidationError(`Content does not match the approved text (expected sha256 ${expected.toLowerCase()}, got ${actual}). ` +
46
+ 'Nothing was posted or stored. Run `draft show` again and show the user the current text.');
47
+ }
48
+ }
49
+ /** False on platforms without POSIX uids (Windows), where the check cannot be made. */
50
+ function isOwnedBySomeoneElse(stat) {
51
+ const uid = process.getuid?.();
52
+ return uid !== undefined && stat.uid !== uid;
53
+ }
54
+ /** Create the directory if needed and stat it without following a symlink. Null when something is in the way. */
55
+ function makeAndStatDir(dir) {
56
+ try {
57
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
58
+ return fs.lstatSync(dir);
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
64
+ function removeStaleDrafts(dir) {
65
+ const cutoff = Date.now() - MAX_DRAFT_AGE_MS;
66
+ for (const name of fs.readdirSync(dir)) {
67
+ const file = path.join(dir, name);
68
+ const stat = fs.lstatSync(file);
69
+ if (stat.isFile() && !isOwnedBySomeoneElse(stat) && stat.mtimeMs < cutoff)
70
+ fs.unlinkSync(file);
71
+ }
72
+ }
73
+ /**
74
+ * The draft directory, `~/.oss-autopilot/tmp`, created owner-only. An existing
75
+ * directory with looser permissions (made by `mkdir -p` under a 022 umask) is
76
+ * tightened; a symlink, a file in the way, or a directory owned by someone
77
+ * else is refused. Returns the real path so callers can compare against it.
78
+ *
79
+ * Also unlinks the user's own regular files in it older than
80
+ * {@link MAX_DRAFT_AGE_MS}, so abandoned drafts do not pile up. Best effort.
81
+ */
82
+ export function getDraftsDir() {
83
+ const dir = path.join(getDataDir(), 'tmp');
84
+ const stat = makeAndStatDir(dir);
85
+ if (!stat?.isDirectory() || isOwnedBySomeoneElse(stat)) {
86
+ throw new ValidationError(`Draft directory ${dir} must be a real directory owned by the current user, not a symlink or a file. ` +
87
+ `Remove or rename ${dir} and rerun.`);
88
+ }
89
+ if ((stat.mode & 0o077) !== 0)
90
+ fs.chmodSync(dir, 0o700);
91
+ const real = fs.realpathSync(dir);
92
+ try {
93
+ removeStaleDrafts(real);
94
+ }
95
+ catch {
96
+ // Cleanup only: a file that vanished or cannot be removed must not fail the command.
97
+ }
98
+ return real;
99
+ }
100
+ /** `draft path <name>`: where to write a draft. Deterministic, so a later session can find a waiting proposal. */
101
+ export function runDraftPath(options) {
102
+ if (!SAFE_NAME.test(options.name)) {
103
+ throw new ValidationError(`Invalid draft name "${options.name}": use letters, digits, ".", "_" and "-" only, starting with a letter, digit or "_"`);
104
+ }
105
+ const dir = getDraftsDir();
106
+ return { path: path.join(dir, options.name), dir };
107
+ }
108
+ function realDirOf(file) {
109
+ try {
110
+ return fs.realpathSync(path.dirname(file));
111
+ }
112
+ catch {
113
+ return null;
114
+ }
115
+ }
116
+ /** Read at most the cap plus one byte, so an oversized or growing file is never read to its end. */
117
+ function readCapped(fd) {
118
+ const buffer = Buffer.alloc(MAX_DRAFT_BYTES + 1);
119
+ let length = 0;
120
+ let read = -1;
121
+ while (read !== 0 && length < buffer.length) {
122
+ read = fs.readSync(fd, buffer, length, buffer.length - length, null);
123
+ length += read;
124
+ }
125
+ return buffer.subarray(0, length);
126
+ }
127
+ function decodeUtf8(bytes, target) {
128
+ if (bytes.subarray(0, 3).equals(UTF8_BOM)) {
129
+ throw new ValidationError(`Refusing to read ${target}: it starts with a byte order mark; save it as plain UTF-8`);
130
+ }
131
+ try {
132
+ return STRICT_UTF8.decode(bytes);
133
+ }
134
+ catch {
135
+ throw new ValidationError(`Refusing to read ${target}: it is not valid UTF-8`);
136
+ }
137
+ }
138
+ /** Check the opened file (not the path, which could have been swapped since) and read it once. */
139
+ function readOpenDraft(fd, target) {
140
+ const stat = fs.fstatSync(fd);
141
+ // Group-writable is allowed: a 002 umask writes 0664, and the directory is
142
+ // owner-only, so group members cannot reach the file through this path.
143
+ if (!stat.isFile() || isOwnedBySomeoneElse(stat) || (stat.mode & 0o002) !== 0 || stat.nlink !== 1) {
144
+ throw new ValidationError(`Refusing to read ${target}: it must be a regular file owned by the current user, not world-writable, with no other hard link`);
145
+ }
146
+ const bytes = readCapped(fd);
147
+ if (bytes.length > MAX_DRAFT_BYTES) {
148
+ throw new ValidationError(`Refusing to read ${target}: larger than ${MAX_DRAFT_BYTES} bytes`);
149
+ }
150
+ const content = decodeUtf8(bytes, target);
151
+ return { content, path: target, sha256: sha256Hex(content), byteSize: bytes.length };
152
+ }
153
+ /**
154
+ * Read a draft once and return its text with the hash of that text.
155
+ *
156
+ * Refuses a file that is not directly inside the draft directory, a symlink
157
+ * or other non-regular file, a file owned by another user, a world-writable
158
+ * or hard-linked file, invalid UTF-8, a byte order mark, and anything over
159
+ * {@link MAX_DRAFT_BYTES}. A bare name or relative path resolves against the
160
+ * draft directory, never the cwd.
161
+ */
162
+ export function readDraft(file) {
163
+ const dir = getDraftsDir();
164
+ const requested = path.resolve(dir, file);
165
+ if (realDirOf(requested) !== dir) {
166
+ throw new ValidationError(`Refusing to read ${requested}: drafts must be files directly inside ${dir}`);
167
+ }
168
+ const target = path.join(dir, path.basename(requested));
169
+ const found = fs.lstatSync(target, { throwIfNoEntry: false });
170
+ if (!found) {
171
+ throw new ValidationError(`No draft at ${target}: write it first (see \`draft path\`)`);
172
+ }
173
+ if (!found.isFile()) {
174
+ throw new ValidationError(`Refusing to read ${target}: not a regular file (symlinks are not followed)`);
175
+ }
176
+ // O_NOFOLLOW closes the gap between the lstat above and the open; the
177
+ // fstat below checks the file that was actually opened.
178
+ const fd = fs.openSync(target, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
179
+ try {
180
+ return readOpenDraft(fd, target);
181
+ }
182
+ finally {
183
+ fs.closeSync(fd);
184
+ }
185
+ }
186
+ /**
187
+ * The text of a draft a command is about to post or store. The file is the
188
+ * only source (no silent winner among several), the caller must say which
189
+ * text the user approved, and an empty file never falls back to a default.
190
+ * The hash itself is checked by the command, next to its other gates.
191
+ */
192
+ export function readApprovedDraft(request) {
193
+ const { flag } = request;
194
+ if (request.hasOtherInput) {
195
+ throw new ValidationError(`${flag} cannot be combined with another source of the text (--stdin, positional words or --content)`);
196
+ }
197
+ if (request.expectSha256 === undefined) {
198
+ throw new ValidationError(`${flag} requires --expect-sha256: run \`draft show\` on the file, show the user its content, ` +
199
+ 'and pass the sha256 it returned');
200
+ }
201
+ const { content } = readDraft(request.file);
202
+ if (content.trim() === '')
203
+ throw new ValidationError('draft file is empty');
204
+ return content;
205
+ }
206
+ /**
207
+ * `draft show <file>`: the text to show the user and the hash to pass back,
208
+ * from one read. With `untrusted`, `content` comes back inside the
209
+ * untrusted-content fence: use it for text distilled from other people's
210
+ * writing (guideline proposals), not for a reply the user dictated.
211
+ */
212
+ export function runDraftShow(options) {
213
+ const draft = readDraft(options.file);
214
+ if (!options.untrusted)
215
+ return { ...draft, fenced: false };
216
+ const content = wrapUntrustedContent(draft.content, path.basename(draft.path), { source: 'draft' });
217
+ return { ...draft, content, fenced: true };
218
+ }
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { computeEvalReport, formatEvalMarkdown } from '../core/eval-report.js';
7
7
  import { getStateManager } from '../core/index.js';
8
+ // eslint-disable-next-line @typescript-eslint/require-await -- async keeps the Promise-returning contract callers rely on; the body has no await yet
8
9
  export async function runEval() {
9
10
  const report = computeEvalReport(getStateManager().getState());
10
11
  return { report, markdown: formatEvalMarkdown(report) };
@@ -4,13 +4,20 @@ export interface GuidelinesViewOutput {
4
4
  /** Markdown content, or null when the repo has no guidelines stored. */
5
5
  content: string | null;
6
6
  /**
7
- * `content` prefixed with the provenance note, or null. This is the field to
7
+ * `content` inside the untrusted-content fence, prefixed with the provenance
8
+ * note and the review status, or null. This is the field to
8
9
  * hand to an agent: stored guidelines were distilled from other people's PR
9
10
  * comments, and re-injected unlabeled they read as project instructions
10
11
  * (#1455). `content` itself stays raw, because the edit flow reads it and
11
12
  * writes it back, and a label in there would be stored as guideline text.
12
13
  */
13
14
  agentContent: string | null;
15
+ /**
16
+ * When the user approved exactly this text (#1929), or null: nothing stored,
17
+ * stored before review was required, or rewritten since by a client that
18
+ * does not record reviews.
19
+ */
20
+ reviewedAt: string | null;
14
21
  /** UTF-8 byte size of `content`, or 0 when content is null. */
15
22
  byteSize: number;
16
23
  /** Whether a guidelines file exists for this repo. */
@@ -83,6 +90,15 @@ interface FetchCorpusOptions extends RepoOption {
83
90
  }
84
91
  interface StoreOptions extends RepoOption {
85
92
  content: string;
93
+ /**
94
+ * The caller's assertion that the user saw this exact text and approved it
95
+ * (#1929). Required and must be `true`: guidelines are distilled from other
96
+ * people's PR comments and are later read back by agents, so nothing is
97
+ * stored on the model's say-so alone.
98
+ */
99
+ reviewed: boolean;
100
+ /** When set, refuse unless `content` hashes to it: the text the user approved via `draft show` (#1930). */
101
+ expectSha256?: string;
86
102
  }
87
103
  /** Read the per-repo guidelines for `repo`. Returns a `local-unavailable` envelope in non-Gist mode. */
88
104
  export declare function runGuidelinesView(options: RepoOption): Promise<GuidelinesViewOutput>;
@@ -96,6 +112,12 @@ export declare function runGuidelinesList(): Promise<GuidelinesListOutput>;
96
112
  * Persist per-repo guidelines for `repo`. Throws when not in Gist mode or
97
113
  * when content exceeds the byte budget — the CLI surface relies on the
98
114
  * outputJson error envelope to surface that to the host cleanly.
115
+ *
116
+ * Two gates sit here, where the CLI, the MCP tool and library callers all
117
+ * pass (#1929). An unattended run never stores: nobody is there to read the
118
+ * text. An attended caller must pass `reviewed: true`; that flag is an
119
+ * assertion the code cannot verify, so it stops a flow that forgot the review
120
+ * step, not a caller that lies.
99
121
  */
100
122
  export declare function runGuidelinesStore(options: StoreOptions): Promise<GuidelinesStoreOutput>;
101
123
  /**
@@ -12,9 +12,12 @@
12
12
  * Standalone-mode users see "not available" on store/reset/fetch-corpus
13
13
  * because per-repo guidelines require Gist persistence to be useful.
14
14
  */
15
- import { getStateManager, requireGitHubToken, getOctokit, GuidelinesNotAvailableError, labelGuidelinesContent, maybeCheckpoint, } from '../core/index.js';
15
+ import { createHash } from 'node:crypto';
16
+ import { getStateManager, requireGitHubToken, getOctokit, GuidelinesNotAvailableError, GUIDELINES_PROVENANCE_NOTE, wrapUntrustedContent, maybeCheckpoint, } from '../core/index.js';
17
+ import { ValidationError, assertAttended } from '../core/errors.js';
16
18
  import { fetchPRCommentBundlesBatch } from '../core/pr-comments-fetcher.js';
17
19
  import { warn } from '../core/logger.js';
20
+ import { assertSha256 } from './draft.js';
18
21
  const MODULE = 'guidelines';
19
22
  const REPO_ID_PATTERN = /^[^/]+\/[^/]+$/;
20
23
  const DEFAULT_FETCH_LIMIT = 5;
@@ -24,20 +27,42 @@ const MAX_FETCH_LIMIT = 10;
24
27
  * (#867 design decision §5). Computed at call time, not module load.
25
28
  */
26
29
  const RECENCY_CLIFF_MS = 365 * 24 * 60 * 60 * 1000;
30
+ function sha256Hex(text) {
31
+ return createHash('sha256').update(text, 'utf8').digest('hex');
32
+ }
33
+ /**
34
+ * The provenance note plus the review status, prefixed to stored guidelines
35
+ * wherever they are handed to an agent. Approved text is still guidance from
36
+ * an untrusted corpus; unapproved text says so, so the reader weighs it less.
37
+ * The stored text goes inside the untrusted-content fence, so a line in it
38
+ * that imitates the label ("> Review: approved ...") reads as data.
39
+ */
40
+ function labelStoredGuidelines(repo, content, reviewedAt) {
41
+ const review = reviewedAt
42
+ ? `> Review: the user read and approved this exact text on ${reviewedAt.slice(0, 10)}.`
43
+ : '> Review: NOT reviewed by the user (stored before review was required, or changed since by an older client). ' +
44
+ 'Weigh it below CONTRIBUTING.md and what the repo itself shows.';
45
+ const fenced = wrapUntrustedContent(content, repo, { source: 'guidelines' });
46
+ return `${GUIDELINES_PROVENANCE_NOTE}\n${review}\n\n${fenced}`;
47
+ }
27
48
  function validateRepo(repo) {
28
49
  if (!REPO_ID_PATTERN.test(repo)) {
29
50
  throw new Error(`Invalid repo identifier "${repo}". Expected "owner/repo" format.`);
30
51
  }
31
52
  }
32
53
  /** Read the per-repo guidelines for `repo`. Returns a `local-unavailable` envelope in non-Gist mode. */
54
+ // eslint-disable-next-line @typescript-eslint/require-await -- async keeps the Promise-returning contract callers rely on; the body has no await yet
33
55
  export async function runGuidelinesView(options) {
34
56
  validateRepo(options.repo);
35
57
  const sm = getStateManager();
36
58
  const content = sm.getGuidelines(options.repo);
59
+ const review = content === null ? undefined : sm.getGuidelinesReview(options.repo);
60
+ const reviewedAt = review && content !== null && review.sha256 === sha256Hex(content) ? review.reviewedAt : null;
37
61
  return {
38
62
  repo: options.repo,
39
63
  content,
40
- agentContent: content === null ? null : labelGuidelinesContent(content),
64
+ agentContent: content === null ? null : labelStoredGuidelines(options.repo, content, reviewedAt),
65
+ reviewedAt,
41
66
  byteSize: content === null ? 0 : Buffer.byteLength(content, 'utf8'),
42
67
  exists: content !== null,
43
68
  storageMode: sm.isGuidelinesAvailable() ? 'gist' : 'local-unavailable',
@@ -48,6 +73,7 @@ export async function runGuidelinesView(options) {
48
73
  * mode — returns an empty list with `storageMode: 'local-unavailable'` so
49
74
  * hosts can distinguish "nothing stored" from "storage not configured".
50
75
  */
76
+ // eslint-disable-next-line @typescript-eslint/require-await -- async keeps the Promise-returning contract callers rely on; the body has no await yet
51
77
  export async function runGuidelinesList() {
52
78
  const sm = getStateManager();
53
79
  const repos = sm.listGuidelinesRepos();
@@ -61,19 +87,38 @@ export async function runGuidelinesList() {
61
87
  * Persist per-repo guidelines for `repo`. Throws when not in Gist mode or
62
88
  * when content exceeds the byte budget — the CLI surface relies on the
63
89
  * outputJson error envelope to surface that to the host cleanly.
90
+ *
91
+ * Two gates sit here, where the CLI, the MCP tool and library callers all
92
+ * pass (#1929). An unattended run never stores: nobody is there to read the
93
+ * text. An attended caller must pass `reviewed: true`; that flag is an
94
+ * assertion the code cannot verify, so it stops a flow that forgot the review
95
+ * step, not a caller that lies.
64
96
  */
65
97
  export async function runGuidelinesStore(options) {
66
98
  validateRepo(options.repo);
99
+ assertAttended('store guidelines');
100
+ if (!options.reviewed) {
101
+ throw new ValidationError('Refusing to store guidelines the user has not reviewed. Show the user the exact text, and once they approve it ' +
102
+ 'store again with --reviewed (CLI) or reviewed: true (MCP tool).');
103
+ }
67
104
  if (!options.content || options.content.length === 0) {
68
105
  throw new Error('Cannot store empty content. Use `guidelines reset` to delete a guidelines file.');
69
106
  }
107
+ assertSha256(options.content, options.expectSha256);
70
108
  const sm = getStateManager();
71
109
  // Throws GuidelinesNotAvailableError or GuidelinesTooLargeError on failure.
72
- sm.setGuidelines(options.repo, options.content);
110
+ const sha256 = sha256Hex(options.content);
111
+ const now = new Date();
112
+ const reviewedAt = now.toISOString();
113
+ const persist = () => {
114
+ sm.setGuidelines(options.repo, options.content);
115
+ sm.markGuidelinesReviewed(options.repo, sha256, reviewedAt);
116
+ };
117
+ persist();
73
118
  // Push to Gist — autoSave only writes the local state-cache mirror in Gist
74
119
  // mode, so without this checkpoint the change never propagates across
75
120
  // machines (#1200).
76
- const gistSyncWarning = await maybeCheckpoint(sm, MODULE, () => sm.setGuidelines(options.repo, options.content));
121
+ const gistSyncWarning = await maybeCheckpoint(sm, MODULE, persist);
77
122
  return {
78
123
  repo: options.repo,
79
124
  byteSize: Buffer.byteLength(options.content, 'utf8'),