@oss-autopilot/core 3.42.5 → 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 (168) 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/ci-analysis.d.ts +7 -2
  85. package/dist/core/ci-analysis.js +76 -21
  86. package/dist/core/commit-date.d.ts +19 -0
  87. package/dist/core/commit-date.js +17 -0
  88. package/dist/core/config-registry.js +11 -5
  89. package/dist/core/contributing.d.ts +2 -3
  90. package/dist/core/contributing.js +2 -3
  91. package/dist/core/daily-logic.d.ts +27 -5
  92. package/dist/core/daily-logic.js +57 -19
  93. package/dist/core/errors.d.ts +37 -3
  94. package/dist/core/errors.js +54 -5
  95. package/dist/core/gist-health.d.ts +15 -3
  96. package/dist/core/gist-health.js +8 -0
  97. package/dist/core/gist-state-store.d.ts +24 -4
  98. package/dist/core/gist-state-store.js +97 -46
  99. package/dist/core/github-stats.d.ts +104 -16
  100. package/dist/core/github-stats.js +282 -97
  101. package/dist/core/http-cache.d.ts +0 -10
  102. package/dist/core/http-cache.js +0 -19
  103. package/dist/core/index.d.ts +12 -5
  104. package/dist/core/index.js +15 -5
  105. package/dist/core/issue-conversation.d.ts +8 -2
  106. package/dist/core/issue-conversation.js +31 -12
  107. package/dist/core/local-config.d.ts +95 -0
  108. package/dist/core/local-config.js +271 -0
  109. package/dist/core/merged-pr-notes.d.ts +2 -2
  110. package/dist/core/pagination.d.ts +55 -0
  111. package/dist/core/pagination.js +59 -0
  112. package/dist/core/paths.d.ts +7 -0
  113. package/dist/core/paths.js +9 -0
  114. package/dist/core/pr-assembly.js +6 -2
  115. package/dist/core/pr-graphql.d.ts +37 -3
  116. package/dist/core/pr-graphql.js +73 -12
  117. package/dist/core/pr-monitor.d.ts +29 -12
  118. package/dist/core/pr-monitor.js +71 -23
  119. package/dist/core/pr-preflight.d.ts +113 -0
  120. package/dist/core/pr-preflight.js +364 -0
  121. package/dist/core/pr-quality-rubric.d.ts +0 -6
  122. package/dist/core/pr-quality-rubric.js +0 -8
  123. package/dist/core/pr-template.d.ts +2 -0
  124. package/dist/core/pr-template.js +5 -1
  125. package/dist/core/repo-policy.d.ts +105 -0
  126. package/dist/core/repo-policy.js +400 -0
  127. package/dist/core/repo-score-manager.d.ts +48 -0
  128. package/dist/core/repo-score-manager.js +111 -1
  129. package/dist/core/review-analysis.d.ts +34 -19
  130. package/dist/core/review-analysis.js +67 -10
  131. package/dist/core/reviewed-prs-fetch.js +11 -29
  132. package/dist/core/reviewed-prs.js +8 -15
  133. package/dist/core/stale-data.d.ts +41 -0
  134. package/dist/core/stale-data.js +115 -0
  135. package/dist/core/state-persistence.d.ts +62 -27
  136. package/dist/core/state-persistence.js +338 -117
  137. package/dist/core/state-schema.d.ts +113 -210
  138. package/dist/core/state-schema.js +165 -80
  139. package/dist/core/state.d.ts +60 -8
  140. package/dist/core/state.js +192 -46
  141. package/dist/core/status-determination.js +26 -8
  142. package/dist/core/strategy.js +3 -1
  143. package/dist/core/types.d.ts +22 -1
  144. package/dist/core/types.js +1 -0
  145. package/dist/core/untrusted-content.d.ts +30 -11
  146. package/dist/core/untrusted-content.js +77 -42
  147. package/dist/core/urls.d.ts +9 -0
  148. package/dist/core/urls.js +18 -0
  149. package/dist/dashboard/assets/{chart-panel-DPKNBUts.js → chart-panel-C_C1lFTI.js} +1 -1
  150. package/dist/dashboard/assets/{index-B25bZOYX.js → index-B--H66Jk.js} +1 -1
  151. package/dist/dashboard/index.html +1 -1
  152. package/dist/formatters/json.d.ts +262 -6
  153. package/dist/formatters/json.js +77 -1
  154. package/package.json +1 -1
  155. package/dist/core/ci-enforced-tools.d.ts +0 -35
  156. package/dist/core/ci-enforced-tools.js +0 -109
  157. package/dist/core/comment-decision.d.ts +0 -79
  158. package/dist/core/comment-decision.js +0 -82
  159. package/dist/core/extraction-categories.d.ts +0 -55
  160. package/dist/core/extraction-categories.js +0 -108
  161. package/dist/core/follow-up-history.d.ts +0 -40
  162. package/dist/core/follow-up-history.js +0 -71
  163. package/dist/core/issue-effort.d.ts +0 -29
  164. package/dist/core/issue-effort.js +0 -47
  165. package/dist/core/maintainer-hints.d.ts +0 -23
  166. package/dist/core/maintainer-hints.js +0 -36
  167. package/dist/core/workflow-state.d.ts +0 -56
  168. package/dist/core/workflow-state.js +0 -101
@@ -65,6 +65,7 @@ function suggestEntryPoints(newFile, existingFiles) {
65
65
  }
66
66
  return [...new Set(suggestions)];
67
67
  }
68
+ // eslint-disable-next-line @typescript-eslint/require-await -- async keeps the Promise-returning contract callers rely on; the body has no await yet
68
69
  export async function runCheckIntegration(options) {
69
70
  const base = options.base;
70
71
  // Get new files added in this branch vs base
@@ -0,0 +1,76 @@
1
+ /**
2
+ * `cleanup` (#1956): report, and with `--apply` remove, stale data under
3
+ * `~/.oss-autopilot`: overnight worktrees and rejected state copies.
4
+ *
5
+ * Overnight worktrees (`worktrees/<owner>-<repo>-<n>`) are created by the
6
+ * overnight-preparer agent, not by this CLI, and nothing recorded their
7
+ * removal. A worktree is removed only when every check below passes, in this
8
+ * order; a check that fails or errors keeps it, with the reason in the output:
9
+ *
10
+ * 1. it is a direct child of `worktrees/`, a real directory (not a symlink)
11
+ * with a name the preparer creates, and it resolves inside the data dir;
12
+ * 2. it is the root of a linked Git worktree (`.git` is a file);
13
+ * 3. `git status --porcelain --untracked-files=all` is empty: no modified and
14
+ * no untracked files, whatever `status.showUntrackedFiles` says;
15
+ * 4. HEAD is contained in a remote-tracking ref, so no commit lives only here;
16
+ * 5. no rebase, merge, cherry-pick (a leftover `sequencer` included), revert
17
+ * or bisect is in progress;
18
+ * 6. every ignored file sits under a build-output directory
19
+ * ({@link BUILD_OUTPUT}); an ignored `.env`, or an ignored file that is
20
+ * merely named `build`, keeps the worktree;
21
+ * 7. no file is flagged skip-worktree or assume-unchanged, which would hide
22
+ * an edit from 3;
23
+ * 8. every commit in this worktree's HEAD reflog is reachable from a branch,
24
+ * a remote-tracking ref or a tag;
25
+ * 9. nothing touched it for {@link WORKTREE_MIN_AGE_DAYS} days.
26
+ *
27
+ * Each worktree is judged and, with `--apply`, removed at once, so nothing
28
+ * happens to it between the two. Removal is `git worktree remove` without
29
+ * `--force`, which re-checks 3 itself and leaves the branch in the clone. No
30
+ * network access, no `rm`. `--apply` refuses during an unattended run. A
31
+ * check that throws, and a removal Git refuses, are listed in `errors`.
32
+ *
33
+ * Two deliberate differences from the issue text:
34
+ * - PR merged/closed is not checked (that needs the network). A clean,
35
+ * pushed, idle worktree of a still-open PR is removed too; the preparer
36
+ * recreates it on demand.
37
+ * - `doctor` reports counts only, not sizes or ages; the detail is here.
38
+ */
39
+ export declare const WORKTREE_MIN_AGE_DAYS = 14;
40
+ /** Ignored paths under a directory with one of these names are rebuildable, not work. */
41
+ export declare const BUILD_OUTPUT: Set<string>;
42
+ export type WorktreeAction = 'removed' | 'would-remove' | 'kept';
43
+ export interface WorktreeReport {
44
+ path: string;
45
+ /** Whole days since the directory or its index last changed; null when unreadable. */
46
+ ageDays: number | null;
47
+ /** null: the check did not run or errored. */
48
+ clean: boolean | null;
49
+ pushed: boolean | null;
50
+ action: WorktreeAction;
51
+ /** Why it was kept, or why it is safe to remove. */
52
+ reason: string;
53
+ }
54
+ export interface WorktreeScan {
55
+ worktrees: WorktreeReport[];
56
+ /** What went wrong: a scan that threw, a removal that was planned and then refused. */
57
+ errors: string[];
58
+ }
59
+ export interface CleanupOutput extends WorktreeScan {
60
+ /** False: a dry run, nothing was deleted. */
61
+ applied: boolean;
62
+ /** Rejected state copies past retention: removed when `applied`, else listed. */
63
+ rejectedCopies: string[];
64
+ }
65
+ export interface CleanupOptions {
66
+ apply: boolean;
67
+ }
68
+ /** Every direct child of `<dataDir>/worktrees`, judged; removed only with `apply`. Never throws. */
69
+ export declare function cleanWorktrees(dataDir: string, options: CleanupOptions, now?: number): WorktreeScan;
70
+ /**
71
+ * `errors` is non-empty when anything went wrong, in a dry run too; the CLI
72
+ * action turns that into a non-zero exit code, since a scheduler or a script
73
+ * sees only that and a partial `--apply` is not success.
74
+ */
75
+ export declare function runCleanup(options: CleanupOptions): CleanupOutput;
76
+ export declare function printCleanup(data: CleanupOutput): void;
@@ -0,0 +1,269 @@
1
+ /**
2
+ * `cleanup` (#1956): report, and with `--apply` remove, stale data under
3
+ * `~/.oss-autopilot`: overnight worktrees and rejected state copies.
4
+ *
5
+ * Overnight worktrees (`worktrees/<owner>-<repo>-<n>`) are created by the
6
+ * overnight-preparer agent, not by this CLI, and nothing recorded their
7
+ * removal. A worktree is removed only when every check below passes, in this
8
+ * order; a check that fails or errors keeps it, with the reason in the output:
9
+ *
10
+ * 1. it is a direct child of `worktrees/`, a real directory (not a symlink)
11
+ * with a name the preparer creates, and it resolves inside the data dir;
12
+ * 2. it is the root of a linked Git worktree (`.git` is a file);
13
+ * 3. `git status --porcelain --untracked-files=all` is empty: no modified and
14
+ * no untracked files, whatever `status.showUntrackedFiles` says;
15
+ * 4. HEAD is contained in a remote-tracking ref, so no commit lives only here;
16
+ * 5. no rebase, merge, cherry-pick (a leftover `sequencer` included), revert
17
+ * or bisect is in progress;
18
+ * 6. every ignored file sits under a build-output directory
19
+ * ({@link BUILD_OUTPUT}); an ignored `.env`, or an ignored file that is
20
+ * merely named `build`, keeps the worktree;
21
+ * 7. no file is flagged skip-worktree or assume-unchanged, which would hide
22
+ * an edit from 3;
23
+ * 8. every commit in this worktree's HEAD reflog is reachable from a branch,
24
+ * a remote-tracking ref or a tag;
25
+ * 9. nothing touched it for {@link WORKTREE_MIN_AGE_DAYS} days.
26
+ *
27
+ * Each worktree is judged and, with `--apply`, removed at once, so nothing
28
+ * happens to it between the two. Removal is `git worktree remove` without
29
+ * `--force`, which re-checks 3 itself and leaves the branch in the clone. No
30
+ * network access, no `rm`. `--apply` refuses during an unattended run. A
31
+ * check that throws, and a removal Git refuses, are listed in `errors`.
32
+ *
33
+ * Two deliberate differences from the issue text:
34
+ * - PR merged/closed is not checked (that needs the network). A clean,
35
+ * pushed, idle worktree of a still-open PR is removed too; the preparer
36
+ * recreates it on demand.
37
+ * - `doctor` reports counts only, not sizes or ages; the detail is here.
38
+ */
39
+ import * as fs from 'node:fs';
40
+ import path from 'node:path';
41
+ import { assertAttended, errorMessage } from '../core/errors.js';
42
+ import { resolveDataDir } from '../core/paths.js';
43
+ import { DAY_MS, WORKTREE_NAME, isInside, pruneRejectedCopies, staleRejectedCopies } from '../core/stale-data.js';
44
+ import { git } from './overnight-push-prep.js';
45
+ export const WORKTREE_MIN_AGE_DAYS = 14;
46
+ /** Ignored paths under a directory with one of these names are rebuildable, not work. */
47
+ export const BUILD_OUTPUT = new Set(['node_modules', 'dist', 'build', 'target', 'coverage', '.venv']);
48
+ // Every call, the removal included: no index lock for a read, no
49
+ // `core.fsmonitor` program the repo's config names, and untracked files
50
+ // always count (`worktree remove` runs its own status and would otherwise
51
+ // honour `status.showUntrackedFiles=no` and delete them).
52
+ const SAFE_GIT = ['--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'status.showUntrackedFiles=all'];
53
+ const IN_PROGRESS = [
54
+ 'rebase-merge',
55
+ 'rebase-apply',
56
+ 'MERGE_HEAD',
57
+ 'CHERRY_PICK_HEAD',
58
+ 'REVERT_HEAD',
59
+ 'BISECT_LOG',
60
+ 'sequencer',
61
+ ];
62
+ // Deleting a large `node_modules` on a loaded disk outlasts the runner's 60 s.
63
+ const REMOVE_TIMEOUT_MS = 10 * 60_000;
64
+ const MAX_NAMED_PATHS = 3;
65
+ const COMMIT_MESSAGE_SUFFIX = '.commit-msg.txt';
66
+ function gitOut(worktree, args) {
67
+ return git(worktree, [...SAFE_GIT, ...args]).trim();
68
+ }
69
+ function gitDirOf(dir) {
70
+ return gitOut(dir, ['rev-parse', '--absolute-git-dir']);
71
+ }
72
+ function kept(dir, reason) {
73
+ return { path: dir, ageDays: null, clean: null, pushed: null, action: 'kept', reason };
74
+ }
75
+ /** Reason the path is not a worktree this command may judge, or null. */
76
+ function refusal(dataDir, dir) {
77
+ if (!WORKTREE_NAME.test(path.basename(dir)))
78
+ return 'name is not one the overnight preparer creates';
79
+ if (!fs.lstatSync(dir).isDirectory())
80
+ return 'not a real directory (symlink or file)';
81
+ if (!isInside(dataDir, dir))
82
+ return 'resolves outside the data directory';
83
+ const dotGit = path.join(dir, '.git');
84
+ if (!fs.existsSync(dotGit) || !fs.lstatSync(dotGit).isFile())
85
+ return 'not a linked git worktree';
86
+ const toplevel = gitOut(dir, ['rev-parse', '--show-toplevel']);
87
+ if (fs.realpathSync(toplevel) !== fs.realpathSync(dir))
88
+ return 'not the root of its git worktree';
89
+ return null;
90
+ }
91
+ /** Whole days since the directory itself or the worktree's index last changed. */
92
+ function idleDays(dir, now) {
93
+ const index = path.join(gitDirOf(dir), 'index');
94
+ const dirMtime = fs.statSync(dir).mtimeMs;
95
+ const lastTouched = fs.existsSync(index) ? Math.max(dirMtime, fs.statSync(index).mtimeMs) : dirMtime;
96
+ return Math.max(0, Math.floor((now - lastTouched) / DAY_MS));
97
+ }
98
+ function operationInProgress(dir) {
99
+ const gitDir = gitDirOf(dir);
100
+ const found = IN_PROGRESS.filter((name) => fs.existsSync(path.join(gitDir, name)));
101
+ return found.length > 0 ? `operation in progress (${found.join(', ')})` : null;
102
+ }
103
+ /** Directory segments only: an ignored regular file named `build` is not build output. */
104
+ function isBuildOutput(ignoredPath) {
105
+ // A directory entry ends in `/`, so its own name is not the last segment.
106
+ const directories = ignoredPath.split('/').slice(0, -1);
107
+ return directories.some((segment) => BUILD_OUTPUT.has(segment));
108
+ }
109
+ function ignoredOutsideBuildOutput(dir) {
110
+ // `matching` lists an ignored directory once instead of every file in it.
111
+ const status = gitOut(dir, ['status', '--porcelain', '--ignored=matching', '--untracked-files=normal']);
112
+ const ignored = status.split('\n').filter((line) => line.startsWith('!! '));
113
+ const precious = ignored.map((line) => line.slice(3)).filter((ignoredPath) => !isBuildOutput(ignoredPath));
114
+ if (precious.length === 0)
115
+ return null;
116
+ const more = precious.length > MAX_NAMED_PATHS ? `, and ${precious.length - MAX_NAMED_PATHS} more` : '';
117
+ return `ignored files outside build output: ${precious.slice(0, MAX_NAMED_PATHS).join(', ')}${more}`;
118
+ }
119
+ function hiddenEdits(dir) {
120
+ // `ls-files -v` tags: `S` skip-worktree, a lowercase letter assume-unchanged.
121
+ const isFlagged = /^[a-zS] /m.test(gitOut(dir, ['ls-files', '-v']));
122
+ return isFlagged ? 'files flagged skip-worktree or assume-unchanged (edits to them are invisible)' : null;
123
+ }
124
+ function reflogOnlyCommits(dir) {
125
+ // This worktree's own HEAD reflog; `rev-list -g` cannot take `--not`.
126
+ // ponytail: the commits go on the command line; a reflog too long for that
127
+ // makes the spawn fail, and a failed check keeps the worktree.
128
+ const reflog = gitOut(dir, ['reflog', 'show', '--format=%H', 'HEAD']);
129
+ const commits = new Set(reflog.split('\n').filter((sha) => sha !== ''));
130
+ if (commits.size === 0)
131
+ return null;
132
+ const lost = gitOut(dir, ['rev-list', ...commits, '--not', '--branches', '--remotes', '--tags']);
133
+ if (lost === '')
134
+ return null;
135
+ return `${lost.split('\n').length} commit(s) reachable only from this worktree's HEAD reflog`;
136
+ }
137
+ const DEEP_CHECKS = [operationInProgress, ignoredOutsideBuildOutput, hiddenEdits, reflogOnlyCommits];
138
+ /** Why a clean-or-not, pushed-or-not worktree of `ageDays` is kept, or null when it may go. */
139
+ function keepReason(dir, report, ageDays) {
140
+ if (!report.clean)
141
+ return 'uncommitted or untracked files';
142
+ if (!report.pushed)
143
+ return 'HEAD is not on any remote-tracking branch (unpushed work)';
144
+ for (const check of DEEP_CHECKS) {
145
+ const reason = check(dir);
146
+ if (reason)
147
+ return reason;
148
+ }
149
+ if (ageDays < WORKTREE_MIN_AGE_DAYS)
150
+ return `touched ${ageDays} day(s) ago (kept for ${WORKTREE_MIN_AGE_DAYS})`;
151
+ return null;
152
+ }
153
+ function judge(dataDir, dir, now) {
154
+ const refused = refusal(dataDir, dir);
155
+ if (refused)
156
+ return kept(dir, refused);
157
+ const ageDays = idleDays(dir, now);
158
+ const isClean = gitOut(dir, ['status', '--porcelain', '--untracked-files=all']) === '';
159
+ const isPushed = gitOut(dir, ['for-each-ref', '--count=1', '--contains', 'HEAD', 'refs/remotes']) !== '';
160
+ const report = { ...kept(dir, ''), ageDays, clean: isClean, pushed: isPushed };
161
+ const reason = keepReason(dir, report, ageDays);
162
+ if (reason)
163
+ return { ...report, reason };
164
+ return { ...report, action: 'would-remove', reason: `clean, pushed, idle ${ageDays} days` };
165
+ }
166
+ function inspect(dataDir, dir, now) {
167
+ try {
168
+ return { report: judge(dataDir, dir, now) };
169
+ }
170
+ catch (err) {
171
+ const reason = `check failed: ${errorMessage(err)}`;
172
+ return { report: kept(dir, reason), error: `${dir}: ${reason}` };
173
+ }
174
+ }
175
+ function removalFailure(err) {
176
+ if (err?.code === 'ETIMEDOUT')
177
+ return `git worktree remove was killed after ${REMOVE_TIMEOUT_MS / 1000}s; the worktree may be partly removed`;
178
+ return `git worktree remove refused: ${errorMessage(err)}`;
179
+ }
180
+ /** Judged removable and then not removed: an error, not a keep. */
181
+ function remove(report) {
182
+ try {
183
+ git(report.path, [...SAFE_GIT, 'worktree', 'remove', report.path], REMOVE_TIMEOUT_MS);
184
+ }
185
+ catch (err) {
186
+ const reason = removalFailure(err);
187
+ return { report: { ...report, action: 'kept', reason }, error: `${report.path}: ${reason}` };
188
+ }
189
+ // The preparer's commit message file sits beside the worktree and goes with it.
190
+ const message = report.path + COMMIT_MESSAGE_SUFFIX;
191
+ if (isRegularFile(message))
192
+ fs.rmSync(message);
193
+ return { report: { ...report, action: 'removed' } };
194
+ }
195
+ function isRegularFile(file) {
196
+ return fs.existsSync(file) && fs.lstatSync(file).isFile();
197
+ }
198
+ /** `<worktree name>.commit-msg.txt` (agents/overnight-preparer.md): not a worktree, so not judged or reported. */
199
+ function isCommitMessageFile(root, name) {
200
+ if (!name.endsWith(COMMIT_MESSAGE_SUFFIX))
201
+ return false;
202
+ return WORKTREE_NAME.test(name.slice(0, -COMMIT_MESSAGE_SUFFIX.length)) && isRegularFile(path.join(root, name));
203
+ }
204
+ /** Judge one worktree and, with `apply`, remove it straight away if it may go. */
205
+ function judgeAndRemove(dataDir, dir, options, now) {
206
+ const outcome = inspect(dataDir, dir, now);
207
+ return options.apply && outcome.report.action === 'would-remove' ? remove(outcome.report) : outcome;
208
+ }
209
+ function scan(dataDir, root, options, now) {
210
+ // A symlinked `worktrees` would have every child resolve outside the data dir.
211
+ if (!fs.existsSync(root) || !fs.lstatSync(root).isDirectory())
212
+ return { worktrees: [], errors: [] };
213
+ const names = fs.readdirSync(root).filter((name) => !isCommitMessageFile(root, name));
214
+ const outcomes = names.map((name) => judgeAndRemove(dataDir, path.join(root, name), options, now));
215
+ const errors = outcomes.flatMap((outcome) => outcome.error ?? []);
216
+ return { worktrees: outcomes.map((outcome) => outcome.report), errors };
217
+ }
218
+ /** Every direct child of `<dataDir>/worktrees`, judged; removed only with `apply`. Never throws. */
219
+ export function cleanWorktrees(dataDir, options, now = Date.now()) {
220
+ const root = path.join(dataDir, 'worktrees');
221
+ try {
222
+ return scan(dataDir, root, options, now);
223
+ }
224
+ catch (err) {
225
+ return { worktrees: [], errors: [`could not scan ${root}: ${errorMessage(err)}`] };
226
+ }
227
+ }
228
+ function listRejectedCopies(dataDir) {
229
+ try {
230
+ return { removed: staleRejectedCopies(dataDir), errors: [] };
231
+ }
232
+ catch (err) {
233
+ return { removed: [], errors: [`could not list rejected state copies in ${dataDir}: ${errorMessage(err)}`] };
234
+ }
235
+ }
236
+ /**
237
+ * `errors` is non-empty when anything went wrong, in a dry run too; the CLI
238
+ * action turns that into a non-zero exit code, since a scheduler or a script
239
+ * sees only that and a partial `--apply` is not success.
240
+ */
241
+ export function runCleanup(options) {
242
+ if (options.apply)
243
+ assertAttended('remove worktrees and rejected state copies');
244
+ const dataDir = resolveDataDir();
245
+ const rejected = options.apply ? pruneRejectedCopies(dataDir) : listRejectedCopies(dataDir);
246
+ const scanned = cleanWorktrees(dataDir, options);
247
+ const errors = [...scanned.errors, ...rejected.errors];
248
+ return { applied: options.apply, worktrees: scanned.worktrees, rejectedCopies: rejected.removed, errors };
249
+ }
250
+ export function printCleanup(data) {
251
+ const verb = data.applied ? 'Removed' : 'Would remove';
252
+ const going = data.worktrees.filter((w) => w.action !== 'kept');
253
+ const kept = data.worktrees.filter((w) => w.action === 'kept');
254
+ console.log(`${verb} ${going.length} worktree(s), ${data.rejectedCopies.length} rejected state copy(ies)`);
255
+ for (const w of going)
256
+ console.log(` ${w.path}: ${w.reason}`);
257
+ for (const file of data.rejectedCopies)
258
+ console.log(` ${file}`);
259
+ if (kept.length > 0)
260
+ console.log(`Kept ${kept.length} worktree(s):`);
261
+ for (const w of kept)
262
+ console.log(` ${w.path}: ${w.reason}`);
263
+ if (data.errors.length > 0)
264
+ console.log(`${data.errors.length} error(s):`);
265
+ for (const error of data.errors)
266
+ console.log(` ${error}`);
267
+ if (!data.applied && going.length + data.rejectedCopies.length > 0)
268
+ console.log('Re-run with --apply to remove.');
269
+ }
@@ -11,10 +11,14 @@ interface CommentsOptions {
11
11
  interface PostOptions {
12
12
  url: string;
13
13
  message: string;
14
+ /** When set, refuse unless `message` hashes to it: the text the user approved via `draft show` (#1930). */
15
+ expectSha256?: string;
14
16
  }
15
17
  interface ClaimOptions {
16
18
  issueUrl: string;
17
19
  message?: string;
20
+ /** When set, refuse unless the claim message hashes to it (#1930). */
21
+ expectSha256?: string;
18
22
  }
19
23
  /**
20
24
  * Fetch all comments, reviews, and inline review comments for a PR.
@@ -37,6 +41,8 @@ export declare function runComments(options: CommentsOptions): Promise<CommentsO
37
41
  * @throws {ValidationError} If the URL or message is invalid
38
42
  */
39
43
  export declare function runPost(options: PostOptions): Promise<PostOutput>;
44
+ /** The comment `claim` posts when no message is given; the MCP approval form shows this exact text. */
45
+ export declare const DEFAULT_CLAIM_MESSAGE = "Hi! I'd like to work on this issue. Could you assign it to me?";
40
46
  /**
41
47
  * Post a claim comment on a GitHub issue and track it locally.
42
48
  *
@@ -10,6 +10,7 @@ const MODULE = 'comments';
10
10
  import { paginateAllDetailed } from '../core/pagination.js';
11
11
  import { buildStalenessWarning } from '../formatters/json.js';
12
12
  import { validateUrl, validateMessage, validateGitHubUrl, PR_URL_PATTERN, ISSUE_OR_PR_URL_PATTERN, ISSUE_URL_PATTERN, } from './validation.js';
13
+ import { assertSha256 } from './draft.js';
13
14
  /**
14
15
  * Fetch all comments, reviews, and inline review comments for a PR.
15
16
  * Filters out the user's own comments and optionally bot comments.
@@ -158,6 +159,7 @@ export async function runComments(options) {
158
159
  */
159
160
  export async function runPost(options) {
160
161
  assertAttended('post a comment');
162
+ assertSha256(options.message, options.expectSha256);
161
163
  validateUrl(options.url);
162
164
  validateGitHubUrl(options.url, ISSUE_OR_PR_URL_PATTERN, 'issue or PR');
163
165
  if (!options.message.trim()) {
@@ -183,6 +185,8 @@ export async function runPost(options) {
183
185
  url: options.url,
184
186
  };
185
187
  }
188
+ /** The comment `claim` posts when no message is given; the MCP approval form shows this exact text. */
189
+ export const DEFAULT_CLAIM_MESSAGE = "Hi! I'd like to work on this issue. Could you assign it to me?";
186
190
  /**
187
191
  * Post a claim comment on a GitHub issue and track it locally.
188
192
  *
@@ -197,9 +201,9 @@ export async function runClaim(options) {
197
201
  validateUrl(options.issueUrl);
198
202
  validateGitHubUrl(options.issueUrl, ISSUE_URL_PATTERN, 'issue');
199
203
  const token = requireGitHubToken();
200
- // Default claim message or custom
201
- const message = options.message || "Hi! I'd like to work on this issue. Could you assign it to me?";
204
+ const message = options.message || DEFAULT_CLAIM_MESSAGE;
202
205
  validateMessage(message);
206
+ assertSha256(message, options.expectSha256);
203
207
  // Parse URL
204
208
  const parsed = parseGitHubUrl(options.issueUrl);
205
209
  if (!parsed || parsed.type !== 'issues') {
@@ -4,6 +4,7 @@
4
4
  */
5
5
  import { CONFIG_KEY_REGISTRY, formatUnknownKeyError, getStateManager, maybeCheckpoint, } from '../core/index.js';
6
6
  import { ValidationError } from '../core/errors.js';
7
+ import { MACHINE_PATH_KEYS, getMachinePath, getMachinePathSource, getMachineScanPaths, setMachinePath, } from '../core/local-config.js';
7
8
  import { ISSUE_SCOPES, DIFF_TOOLS } from '../core/types.js';
8
9
  import { validateGitHubUsername } from './validation.js';
9
10
  const MODULE = 'config';
@@ -13,6 +14,37 @@ function validateScope(value) {
13
14
  }
14
15
  return value;
15
16
  }
17
+ /**
18
+ * The config as this machine uses it: the two path settings show the value in
19
+ * effect here (local file first, synced value as fallback), not whatever
20
+ * another machine last synced (#1950). `machinePathSources` says where each
21
+ * shown path comes from and is omitted when neither is configured.
22
+ * `localRepoScanPaths` shows this machine's scan roots (source `set` or
23
+ * `adopted`), and is omitted when the defaults are in use (#2010).
24
+ */
25
+ function showConfig(config) {
26
+ const shown = { ...config };
27
+ const sources = {};
28
+ for (const key of MACHINE_PATH_KEYS) {
29
+ const value = getMachinePath(key, config);
30
+ if (value === undefined)
31
+ delete shown[key];
32
+ else
33
+ shown[key] = value;
34
+ const source = getMachinePathSource(key, config);
35
+ if (source)
36
+ sources[key] = source;
37
+ }
38
+ const scanPaths = getMachineScanPaths(config.localRepoScanPaths);
39
+ if (scanPaths) {
40
+ shown.localRepoScanPaths = scanPaths.paths;
41
+ sources.localRepoScanPaths = scanPaths.source;
42
+ }
43
+ else {
44
+ delete shown.localRepoScanPaths;
45
+ }
46
+ return { config: shown, ...(Object.keys(sources).length > 0 && { machinePathSources: sources }) };
47
+ }
16
48
  /**
17
49
  * Read or write user configuration settings.
18
50
  * When called without a key, returns the full config.
@@ -36,7 +68,7 @@ export async function runConfig(options) {
36
68
  const stateManager = getStateManager();
37
69
  if (!options.key) {
38
70
  // Show current config
39
- return { config: stateManager.getState().config };
71
+ return showConfig(stateManager.getState().config);
40
72
  }
41
73
  if (!options.value) {
42
74
  throw new Error('Value required');
@@ -89,12 +121,12 @@ function applyConfigKey(stateManager, key, value) {
89
121
  break;
90
122
  }
91
123
  case 'remove-scope': {
92
- const scope = validateScope(value);
124
+ // Not validated: a stored scope a newer release added must be removable (#2005).
93
125
  const existingScopes = currentConfig.scope ?? [];
94
- if (!existingScopes.includes(scope)) {
126
+ if (!existingScopes.includes(value)) {
95
127
  throw new Error(`Scope "${value}" is not currently set`);
96
128
  }
97
- const filtered = existingScopes.filter((s) => s !== scope);
129
+ const filtered = existingScopes.filter((s) => s !== value);
98
130
  if (filtered.length === 0) {
99
131
  throw new Error('Cannot remove the last scope. Use setup to clear scopes entirely.');
100
132
  }
@@ -172,7 +204,7 @@ function applyConfigKey(stateManager, key, value) {
172
204
  break;
173
205
  }
174
206
  case 'issueListPath': {
175
- stateManager.updateConfig({ issueListPath: value || undefined });
207
+ setMachinePath('issueListPath', value || undefined);
176
208
  break;
177
209
  }
178
210
  case 'diffTool': {
@@ -7,6 +7,13 @@
7
7
  import { getStateManager, type CommentedIssue } from '../core/index.js';
8
8
  import type { DailyWarning } from '../formatters/json.js';
9
9
  type StateManagerLike = Pick<ReturnType<typeof getStateManager>, 'reloadIfChanged' | 'batch' | 'getIssueDismissedAt' | 'undismissIssue'>;
10
+ /**
11
+ * Reload state where the run only wants to pick up a config edit made while
12
+ * it was fetching. A failed reload there is not worth the run (the digest is
13
+ * already saved): it becomes a warning and the run continues on in-memory
14
+ * state. State written by a newer release still stops it (#1951).
15
+ */
16
+ export declare function reloadOrWarn(stateManager: Pick<StateManagerLike, 'reloadIfChanged'>, warnings: DailyWarning[]): void;
10
17
  /**
11
18
  * Run a batch against a baseline that is fresh as of right now.
12
19
  *
@@ -4,10 +4,26 @@
4
4
  * against a real StateManager (dismiss, resurface, reload from disk) without
5
5
  * mocking the whole daily pipeline.
6
6
  */
7
- import { isCoveredByDismiss } from '../core/index.js';
7
+ import { isCoveredByDismiss, NewerStateVersionError } from '../core/index.js';
8
8
  import { warn } from '../core/logger.js';
9
9
  import { recordWarning } from './daily-warnings.js';
10
10
  const MODULE = 'daily';
11
+ /**
12
+ * Reload state where the run only wants to pick up a config edit made while
13
+ * it was fetching. A failed reload there is not worth the run (the digest is
14
+ * already saved): it becomes a warning and the run continues on in-memory
15
+ * state. State written by a newer release still stops it (#1951).
16
+ */
17
+ export function reloadOrWarn(stateManager, warnings) {
18
+ try {
19
+ stateManager.reloadIfChanged();
20
+ }
21
+ catch (err) {
22
+ if (err instanceof NewerStateVersionError)
23
+ throw err;
24
+ recordWarning(warnings, 'state-load', 'reload state before capacity check', err);
25
+ }
26
+ }
11
27
  /**
12
28
  * Run a batch against a baseline that is fresh as of right now.
13
29
  *
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Ledger upkeep the daily run does before it rewrites per-repo counts. Kept
3
+ * out of daily.ts so ledger rules live in one small place.
4
+ */
5
+ import type { Octokit } from '@octokit/rest';
6
+ import { type PRsSinceResult } from '../core/github-stats.js';
7
+ import type { getStateManager } from '../core/index.js';
8
+ import type { RepoMetadata } from '../core/pr-monitor.js';
9
+ import type { ClosedPR, DailyDigest, MergedPR, StoredClosedPR, StoredMergedPR } from '../core/types.js';
10
+ import type { DailyWarning } from '../formatters/json.js';
11
+ type StateManagerLike = ReturnType<typeof getStateManager>;
12
+ type LedgerStateManager = Pick<StateManagerLike, 'getMergedPRs' | 'getClosedPRs' | 'renameRepo' | 'evictClosedPRs'>;
13
+ /**
14
+ * Bring the stored merged/closed ledgers in line with what GitHub reports now.
15
+ * Must run before anything reads or writes repoScores in the same batch.
16
+ *
17
+ * 1. Re-key transferred/renamed repos, so the old name isn't zeroed and then
18
+ * re-bumped from stored PR URLs on the next load (which double counted its
19
+ * merges in getStats).
20
+ * 2. Drop closed-ledger entries that were reopened (now in `openPRs`) or have
21
+ * since merged, so the count reconciliation that follows no longer raises
22
+ * `closedWithoutMergeCount` back to a ledger that still holds them (#1923).
23
+ * This runs every day, so state inflated before the fix heals on the next
24
+ * run, as does an entry another machine's older copy brought back.
25
+ *
26
+ * @param searchedPRs - every merged/closed PR the count searches returned
27
+ * @param openPRs - the user's currently open PRs, as just fetched
28
+ */
29
+ export declare function syncLedgersWithGitHub(stateManager: LedgerStateManager, searchedPRs: ReadonlyArray<{
30
+ url: string;
31
+ title: string;
32
+ }>, openPRs: ReadonlyArray<{
33
+ url: string;
34
+ }>): void;
35
+ /**
36
+ * Write the star counts and languages a repository read returned, then drop
37
+ * what is stored about repositories whose PRs are never tracked (#1924):
38
+ * those in `config.untrackedOrgs`, and those this read reported private.
39
+ * The fetches no longer return either kind; this removes what earlier
40
+ * versions stored, and what another machine's older copy brings back.
41
+ *
42
+ * Only an explicit `isPrivate: true` in `repoMetadata` counts as private. A
43
+ * repository missing from the map (404, network error, aborted chunk, or the
44
+ * whole fetch failing) or with no flag is left alone, so deleted, renamed and
45
+ * transferred repositories keep their rows.
46
+ */
47
+ export declare function applyRepoMetadata(stateManager: Pick<StateManagerLike, 'updateRepoScore' | 'evictExcludedRepos'>, repoMetadata: ReadonlyMap<string, RepoMetadata>, warnings: DailyWarning[]): void;
48
+ /**
49
+ * Zero `closedWithoutMergeCount` for repos the closed-PR count search no
50
+ * longer returns, mirroring the stale reset daily does for merged counts.
51
+ * Without it, a repo whose closed PRs were all reopened or merged leaves the
52
+ * search and keeps its last search-set count for good (#1923). The count
53
+ * reconciliation that follows in the same batch raises each repo back to its
54
+ * closed-ledger count, so only the surplus over the ledger is dropped.
55
+ *
56
+ * Skipped, like the merged reset, when the search returned nothing while state
57
+ * has closed counts (possible transient API failure) or when it hit its
58
+ * pagination cap (an absent repo may still have closed PRs).
59
+ */
60
+ export declare function resetStaleClosedCounts(stateManager: Pick<StateManagerLike, 'getState' | 'updateRepoScore'>, closedCounts: ReadonlyMap<string, number>, wasSearchTruncated: boolean): void;
61
+ /** This run's merged-ledger gap fetch; undefined when the fetch failed. */
62
+ export type MergedLedgerGap = PRsSinceResult<StoredMergedPR> | undefined;
63
+ /** This run's closed-ledger gap fetch; undefined when the fetch failed. */
64
+ export type ClosedLedgerGap = PRsSinceResult<StoredClosedPR> | undefined;
65
+ /**
66
+ * Fetch every merged PR since the ledger's newest entry (#1924). The recent
67
+ * list daily shows covers seven days, so after a longer pause it alone left
68
+ * the merges in between out of the ledger for good. Must run before anything
69
+ * in this run adds to the merged ledger: the watermark is read here.
70
+ *
71
+ * A failed or truncated fetch is recorded in `warnings`, and
72
+ * {@link storeMergedLedger} then stores nothing, so the next run asks for the
73
+ * same range again. Until a run stores them, today's merges are not in the
74
+ * ledger, so the "extract learnings" nudge, which counts ledger rows of
75
+ * recent merges, is also held back for them.
76
+ */
77
+ export declare function fetchMergedLedgerGap(octokit: Octokit, stateManager: Pick<StateManagerLike, 'getState' | 'getMergedPRWatermark'>, warnings: DailyWarning[]): Promise<MergedLedgerGap>;
78
+ /**
79
+ * The closed-ledger mirror of {@link fetchMergedLedgerGap} (#1925). Without
80
+ * it the recent closed list seeded a fresh ledger with last week's closes,
81
+ * and the dashboard's fetch then started from that newest row, so older
82
+ * closed history was never fetched. Must run before anything in this run adds
83
+ * to the closed ledger.
84
+ *
85
+ * A ledger an older version already left short of `allTimeCount` is fetched
86
+ * from the start while it is under the backfill ceiling (see
87
+ * gapFetchWatermark), so it heals without a manual `ledger-backfill`.
88
+ */
89
+ export declare function fetchClosedLedgerGap(octokit: Octokit, stateManager: Pick<StateManagerLike, 'getState' | 'getClosedPRWatermark' | 'getClosedPRs'>, warnings: DailyWarning[], allTimeCount: number | undefined): Promise<ClosedLedgerGap>;
90
+ /** What a store step takes besides the gap. */
91
+ interface StoreLedgerInput {
92
+ /** Previous run's digest: best-effort first-response and review state for the new rows (#1461). */
93
+ previousDigest: DailyDigest | undefined;
94
+ /** GitHub's all-time count from the count search; undefined when unknown. */
95
+ allTimeCount: number | undefined;
96
+ warnings: DailyWarning[];
97
+ }
98
+ /**
99
+ * Add this run's merges to the merged ledger: the gap since its newest entry
100
+ * plus the recent list (which can also fill an older hole inside its window).
101
+ *
102
+ * Nothing is stored unless the gap was fetched whole. The ledger's newest
103
+ * entry is the next run's starting point, so a recent row stored without the
104
+ * rows before it would move that point past merges nobody fetched.
105
+ *
106
+ * Then compares the ledger with GitHub's all-time merged count (see
107
+ * checkLedgerCount).
108
+ */
109
+ export declare function storeMergedLedger(stateManager: Pick<StateManagerLike, 'addMergedPRs' | 'getMergedPRs'>, input: StoreLedgerInput & {
110
+ gap: MergedLedgerGap;
111
+ recentlyMergedPRs: ReadonlyArray<MergedPR>;
112
+ }): void;
113
+ /**
114
+ * The closed-ledger mirror of {@link storeMergedLedger} (#1925): the gap
115
+ * plus the recent closed list, stored only when the gap was fetched whole,
116
+ * then checked against GitHub's all-time closed-without-merge count.
117
+ */
118
+ export declare function storeClosedLedger(stateManager: Pick<StateManagerLike, 'addClosedPRs' | 'getClosedPRs'>, input: StoreLedgerInput & {
119
+ gap: ClosedLedgerGap;
120
+ recentlyClosedPRs: ReadonlyArray<ClosedPR>;
121
+ }): void;
122
+ export {};