@morning-start/dsh-code-toolkit 0.0.0-stage → 0.27.1
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/CHANGELOG.md +375 -0
- package/LICENSE +35 -0
- package/README.md +252 -2
- package/agents/caption/AGENT.md +165 -0
- package/agents/caption/examples/dispatch.md +83 -0
- package/agents/caption/examples/loop.md +66 -0
- package/agents/caption/examples/theater.md +40 -0
- package/agents/caption/references/dispatch.md +128 -0
- package/agents/caption/references/evidence.md +82 -0
- package/agents/caption/references/experts.md +141 -0
- package/agents/caption/references/flows.md +97 -0
- package/agents/caption/references/loop.md +75 -0
- package/agents/pua/AGENT.md +66 -0
- package/agents/pua/examples/run.md +41 -0
- package/agents/pua/references/flavors.md +33 -0
- package/agents/pua/references/methodology.md +32 -0
- package/agents/review/AGENT.md +112 -0
- package/agents/review/examples/clean.md +40 -0
- package/agents/review/examples/findings.md +49 -0
- package/agents/review/references/evidence.md +33 -0
- package/agents/review/references/output.md +59 -0
- package/agents/review/references/rubric.md +43 -0
- package/agents/review/references/severity.md +45 -0
- package/agents/scrub/AGENT.md +130 -0
- package/agents/scrub/examples/clean.md +70 -0
- package/agents/scrub/examples/report.md +66 -0
- package/agents/scrub/references/false-positives.md +92 -0
- package/agents/scrub/references/patterns.md +52 -0
- package/agents/scrub/references/redaction.md +53 -0
- package/agents/simplify/AGENT.md +160 -0
- package/agents/simplify/examples/apply.md +60 -0
- package/agents/simplify/examples/plan.md +65 -0
- package/agents/simplify/references/anti-patterns.md +45 -0
- package/agents/simplify/references/behavior-preservation.md +41 -0
- package/agents/simplify/references/conventions.md +34 -0
- package/agents/simplify/references/operations.md +51 -0
- package/agents/simplify/references/verification.md +74 -0
- package/cordis.patch.yml +23 -0
- package/icon.svg +8 -0
- package/index.js +207 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +62 -4
- package/src/command.js +328 -0
- package/src/delivery.js +48 -0
- package/src/i18n.js +164 -0
- package/src/journal.js +56 -0
- package/src/pua.js +48 -0
- package/src/report.js +202 -0
- package/src/runtime.js +94 -0
- package/src/selection.js +258 -0
package/src/report.js
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turn what the review agent returned into something the session can render.
|
|
3
|
+
*
|
|
4
|
+
* The agent is asked for one JSON object (Codex's review schema). Models do not
|
|
5
|
+
* always comply: some wrap it in a fence, some add prose, some answer in
|
|
6
|
+
* Markdown. A JSON report gets structured rendering with file links; anything
|
|
7
|
+
* else is passed through unchanged, because a slightly ugly report is worth
|
|
8
|
+
* more than a lost one.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
function findingList(value) {
|
|
12
|
+
if (Array.isArray(value)) return value
|
|
13
|
+
return value && typeof value === 'object' ? [value] : []
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function priorityOf(value) {
|
|
17
|
+
if (typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 3) return value
|
|
18
|
+
if (typeof value !== 'string') return null
|
|
19
|
+
const match = /^(?:\[?\s*P\s*)?([0-3])\]?$/i.exec(value.trim())
|
|
20
|
+
return match ? Number(match[1]) : null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function linesOf(raw) {
|
|
24
|
+
if (typeof raw === 'number' && Number.isInteger(raw) && raw >= 0) return { start: raw, end: raw }
|
|
25
|
+
if (raw && typeof raw === 'object' && Number.isInteger(raw.start) && Number.isInteger(raw.end)) {
|
|
26
|
+
return { start: raw.start, end: raw.end }
|
|
27
|
+
}
|
|
28
|
+
if (typeof raw !== 'string' || !raw.trim()) return undefined
|
|
29
|
+
const [from, to] = raw.split(/\s*[-–]\s*/)
|
|
30
|
+
const start = Number(from)
|
|
31
|
+
const end = Number(to ?? from)
|
|
32
|
+
return Number.isInteger(start) && Number.isInteger(end) && start >= 0 && end >= 0
|
|
33
|
+
? { start, end }
|
|
34
|
+
: undefined
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function textOf(value) {
|
|
38
|
+
return typeof value === 'string' ? value.trim() : ''
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Accept Codex's field names, plus the aliases models reach for. */
|
|
42
|
+
function decode(raw) {
|
|
43
|
+
const value = JSON.parse(raw)
|
|
44
|
+
if (!value || typeof value !== 'object') return undefined
|
|
45
|
+
|
|
46
|
+
const findings = findingList(value.findings).flatMap((item) => {
|
|
47
|
+
if (!item || typeof item !== 'object') return []
|
|
48
|
+
const title = textOf(item.title)
|
|
49
|
+
const body = textOf(item.body)
|
|
50
|
+
if (!title || !body) return []
|
|
51
|
+
const location = item.code_location && typeof item.code_location === 'object' ? item.code_location : {}
|
|
52
|
+
const lines = linesOf(location.line_range) ?? linesOf(location.line) ?? linesOf(item.line)
|
|
53
|
+
const path =
|
|
54
|
+
textOf(location.absolute_file_path) ||
|
|
55
|
+
textOf(location.file) ||
|
|
56
|
+
textOf(location.path) ||
|
|
57
|
+
textOf(item.file) ||
|
|
58
|
+
textOf(item.path)
|
|
59
|
+
const confidence = typeof item.confidence_score === 'number' ? item.confidence_score : undefined
|
|
60
|
+
return [{
|
|
61
|
+
title,
|
|
62
|
+
body,
|
|
63
|
+
priority: priorityOf(item.priority),
|
|
64
|
+
path,
|
|
65
|
+
start: lines?.start ?? 0,
|
|
66
|
+
end: lines?.end ?? 0,
|
|
67
|
+
...(confidence === undefined ? {} : { confidence }),
|
|
68
|
+
}]
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
const summary = textOf(value.overall_explanation)
|
|
72
|
+
if (!summary && !findings.length) return undefined
|
|
73
|
+
|
|
74
|
+
const limitations = Array.isArray(value.limitations)
|
|
75
|
+
? value.limitations.filter((item) => typeof item === 'string' && item.trim()).map((item) => item.trim())
|
|
76
|
+
: []
|
|
77
|
+
|
|
78
|
+
const fixed = Array.isArray(value.fixed)
|
|
79
|
+
? value.fixed.flatMap((item) => {
|
|
80
|
+
if (!item || typeof item !== 'object') return []
|
|
81
|
+
const title = textOf(item.title)
|
|
82
|
+
if (!title) return []
|
|
83
|
+
return [{
|
|
84
|
+
title,
|
|
85
|
+
file: textOf(item.file),
|
|
86
|
+
change: textOf(item.change),
|
|
87
|
+
verifiedBy: textOf(item.verified_by),
|
|
88
|
+
}]
|
|
89
|
+
})
|
|
90
|
+
: []
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
findings,
|
|
94
|
+
fixed,
|
|
95
|
+
summary,
|
|
96
|
+
limitations,
|
|
97
|
+
format: 'structured',
|
|
98
|
+
...(typeof value.overall_correctness === 'string' ? { correctness: value.overall_correctness } : {}),
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Walk the text and return the JSON objects that look like a report.
|
|
104
|
+
* Braces inside strings (e.g. `src/{a,b}` in an explanation) must not confuse
|
|
105
|
+
* the scanner, otherwise one brace in prose hides the report behind it.
|
|
106
|
+
*/
|
|
107
|
+
function objectsIn(raw) {
|
|
108
|
+
const found = []
|
|
109
|
+
for (let i = 0; i < raw.length; i++) {
|
|
110
|
+
if (raw[i] !== '{') continue
|
|
111
|
+
const slice = objectAt(raw, i)
|
|
112
|
+
if (!slice) continue
|
|
113
|
+
if (slice.includes('"findings"') && slice.includes('"overall_')) found.push(slice)
|
|
114
|
+
i += slice.length - 1
|
|
115
|
+
}
|
|
116
|
+
return found
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function objectAt(raw, start) {
|
|
120
|
+
let depth = 0
|
|
121
|
+
let inString = false
|
|
122
|
+
let escape = false
|
|
123
|
+
for (let i = start; i < raw.length; i++) {
|
|
124
|
+
const ch = raw[i]
|
|
125
|
+
if (inString) {
|
|
126
|
+
if (escape) escape = false
|
|
127
|
+
else if (ch === '\\') escape = true
|
|
128
|
+
else if (ch === '"') inString = false
|
|
129
|
+
continue
|
|
130
|
+
}
|
|
131
|
+
if (ch === '"') inString = true
|
|
132
|
+
else if (ch === '{') depth++
|
|
133
|
+
else if (ch === '}') {
|
|
134
|
+
depth--
|
|
135
|
+
if (depth === 0) return raw.slice(start, i + 1)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return undefined
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Parse a review reply into either a structured report or a text fallback. */
|
|
142
|
+
export function parseReport(raw) {
|
|
143
|
+
const candidates = objectsIn(raw)
|
|
144
|
+
for (let i = candidates.length - 1; i >= 0; i--) {
|
|
145
|
+
try {
|
|
146
|
+
const report = decode(candidates[i])
|
|
147
|
+
if (report) return report
|
|
148
|
+
} catch {
|
|
149
|
+
/* field types wrong — try the next candidate */
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { findings: [], summary: raw.trim(), limitations: [], format: 'text' }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function fileLink(path, start, end) {
|
|
156
|
+
const range = start || end ? `:${start}–${end}` : ''
|
|
157
|
+
const destination = encodeURI(path.replaceAll('\\', '/'))
|
|
158
|
+
.replaceAll('?', '%3F')
|
|
159
|
+
.replaceAll('#', '%23')
|
|
160
|
+
.replaceAll(')', '%29')
|
|
161
|
+
const fragment = start || end ? `#L${start}${end !== start ? `-L${end}` : ''}` : ''
|
|
162
|
+
return `[${`${path}${range}`.replaceAll(']', '\\]')}](${destination}${fragment})`
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** A finding as its own Markdown section: tag, location, body. */
|
|
166
|
+
function renderFinding(finding) {
|
|
167
|
+
const tagged = /^\[P[0-3]\]/.test(finding.title) || finding.priority === null
|
|
168
|
+
? finding.title
|
|
169
|
+
: `[P${finding.priority}] ${finding.title}`
|
|
170
|
+
const location = finding.path ? fileLink(finding.path, finding.start, finding.end) : ''
|
|
171
|
+
return [`### ${tagged}`, location, finding.body].filter(Boolean).join('\n\n')
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** A fix the reviewer made: what changed, where, and how it was verified. */
|
|
175
|
+
function renderFix(fix, t) {
|
|
176
|
+
const location = fix.file ? fileLink(fix.file, 0, 0) : ''
|
|
177
|
+
const verified = fix.verifiedBy ? `${t('report.verifiedBy')}${fix.verifiedBy}` : ''
|
|
178
|
+
return [`### ${fix.title}`, location, fix.change, verified].filter(Boolean).join('\n\n')
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Render a parsed report as Markdown. `t` translates the few chrome labels;
|
|
183
|
+
* finding text is never translated — it is the agent's own words.
|
|
184
|
+
*/
|
|
185
|
+
export function renderReport(report, t) {
|
|
186
|
+
if (report.format === 'text') return report.summary
|
|
187
|
+
|
|
188
|
+
const limits = report.limitations.map((item) => `- ${t('report.limitation')}${item}`)
|
|
189
|
+
const empty = !report.findings.length ? t('report.noFindings') : ''
|
|
190
|
+
const fixed = report.fixed ?? []
|
|
191
|
+
|
|
192
|
+
return [
|
|
193
|
+
report.summary,
|
|
194
|
+
report.correctness ? `${t('report.verdict')}${report.correctness}` : '',
|
|
195
|
+
empty,
|
|
196
|
+
...report.findings.map(renderFinding),
|
|
197
|
+
fixed.length ? `## ${t('report.fixed')}\n\n${fixed.map((fix) => renderFix(fix, t)).join('\n\n')}` : '',
|
|
198
|
+
limits.length ? limits.join('\n') : '',
|
|
199
|
+
]
|
|
200
|
+
.filter(Boolean)
|
|
201
|
+
.join('\n\n')
|
|
202
|
+
}
|
package/src/runtime.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
/** System-prompt section that carries an agent's persona prefix. */
|
|
4
|
+
const PERSONA_SECTION = 'DEPLOYMENT_PERSONA_PREFIX'
|
|
5
|
+
|
|
6
|
+
/** Delegation tools a review/simplify child must not call: it must not fan out again. */
|
|
7
|
+
const DELEGATE_TOOLS = [
|
|
8
|
+
'subagent',
|
|
9
|
+
'subagent_fork',
|
|
10
|
+
'workflow',
|
|
11
|
+
'list_agents',
|
|
12
|
+
'send_message',
|
|
13
|
+
'wait_agent',
|
|
14
|
+
'interrupt_agent',
|
|
15
|
+
'summon_expert',
|
|
16
|
+
'summon_experts',
|
|
17
|
+
'list_experts',
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Run one isolated subagent with an injected persona.
|
|
22
|
+
*
|
|
23
|
+
* Requires the native `spawn` provider, whose `inheritsParentContext` is false:
|
|
24
|
+
* the child must read the code itself instead of inheriting this conversation.
|
|
25
|
+
* Without that, a review only sees what the main agent already believes.
|
|
26
|
+
*/
|
|
27
|
+
export async function runIsolatedAgent(ctx, parent, options) {
|
|
28
|
+
const { persona, prompt, label, signal, model, t } = options
|
|
29
|
+
|
|
30
|
+
const subagents = ctx.subagents
|
|
31
|
+
if (!subagents) throw new Error(t('error.noProvider'))
|
|
32
|
+
if (typeof subagents.startActivation !== 'function') throw new Error(t('error.noActivation'))
|
|
33
|
+
|
|
34
|
+
const provider = subagents.getProvider('spawn')
|
|
35
|
+
if (!provider) throw new Error(t('error.noProvider'))
|
|
36
|
+
if (provider.inheritsParentContext) throw new Error(t('error.noProvider'))
|
|
37
|
+
|
|
38
|
+
const childId = randomUUID()
|
|
39
|
+
const deny = DELEGATE_TOOLS.filter((name) => ctx.tools.get(name, parent) !== undefined)
|
|
40
|
+
|
|
41
|
+
let activation
|
|
42
|
+
const stopWatching = ctx.on('agent/created', ({ agent }) => {
|
|
43
|
+
if (agent.id !== childId) return
|
|
44
|
+
agent.ctx.systemPrompt.section({
|
|
45
|
+
name: PERSONA_SECTION,
|
|
46
|
+
order: agent.ctx.systemPrompt.getSectionOrder(PERSONA_SECTION),
|
|
47
|
+
text: persona,
|
|
48
|
+
})
|
|
49
|
+
if (deny.length) agent.ctx.tools.restrict({ deny })
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
try {
|
|
53
|
+
// 0.2.2-rc.1 takes a nested `request`; rc.2+ takes a flat spec and exposes
|
|
54
|
+
// `rootOf`. Keep both so the declared engine range stays honest.
|
|
55
|
+
const flat = typeof subagents.rootOf === 'function'
|
|
56
|
+
const request = {
|
|
57
|
+
parent,
|
|
58
|
+
prompt: [{ type: 'text', text: prompt }],
|
|
59
|
+
...(model ? { agentOptions: { model } } : {}),
|
|
60
|
+
}
|
|
61
|
+
activation = await subagents.startActivation({
|
|
62
|
+
provider: 'spawn',
|
|
63
|
+
label,
|
|
64
|
+
childId,
|
|
65
|
+
signal,
|
|
66
|
+
delivery: 'caller',
|
|
67
|
+
...(flat ? request : { request }),
|
|
68
|
+
})
|
|
69
|
+
} finally {
|
|
70
|
+
stopWatching()
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
const result = await activation.result
|
|
75
|
+
if (signal.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError' })
|
|
76
|
+
if (result.stopReason !== 'completed') {
|
|
77
|
+
const detail = result.diagnostic ? ` — ${result.diagnostic}` : ''
|
|
78
|
+
throw new Error(`${t('error.noResult')} (${result.stopReason}${detail})`)
|
|
79
|
+
}
|
|
80
|
+
const text = result.output
|
|
81
|
+
.filter((block) => block.type === 'text')
|
|
82
|
+
.map((block) => block.text)
|
|
83
|
+
.join('')
|
|
84
|
+
.trim()
|
|
85
|
+
if (!text) throw new Error(t('error.noResult'))
|
|
86
|
+
return text
|
|
87
|
+
} finally {
|
|
88
|
+
try {
|
|
89
|
+
await activation.dispose()
|
|
90
|
+
} catch {
|
|
91
|
+
/* the session may already be gone */
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
package/src/selection.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { promisify } from 'node:util'
|
|
3
|
+
|
|
4
|
+
const execFileAsync = promisify(execFile)
|
|
5
|
+
|
|
6
|
+
const GIT_MAX_BUFFER = 8 * 1024 * 1024
|
|
7
|
+
|
|
8
|
+
/** Run git in a working directory and return trimmed stdout. */
|
|
9
|
+
export async function git(cwd, args, signal) {
|
|
10
|
+
try {
|
|
11
|
+
const { stdout } = await execFileAsync('git', args, {
|
|
12
|
+
cwd,
|
|
13
|
+
signal,
|
|
14
|
+
maxBuffer: GIT_MAX_BUFFER,
|
|
15
|
+
windowsHide: true,
|
|
16
|
+
env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' },
|
|
17
|
+
})
|
|
18
|
+
return stdout.trim()
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (error?.name === 'AbortError') throw error
|
|
21
|
+
const detail = (error?.stderr || error?.message || String(error)).toString().trim()
|
|
22
|
+
throw new Error(`git ${args.join(' ')} failed: ${detail}`)
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Resolve a ref to a commit, returning undefined when it does not exist. */
|
|
27
|
+
async function resolveRef(cwd, ref, signal) {
|
|
28
|
+
try {
|
|
29
|
+
return await git(cwd, ['rev-parse', '--verify', '--end-of-options', ref], signal)
|
|
30
|
+
} catch {
|
|
31
|
+
signal?.throwIfAborted()
|
|
32
|
+
return undefined
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Find the commit a branch comparison should start from.
|
|
38
|
+
*
|
|
39
|
+
* The interesting case is a local base branch that is behind its upstream: the
|
|
40
|
+
* diff a reviewer cares about is against the upstream, not the stale local tip.
|
|
41
|
+
*/
|
|
42
|
+
export async function mergeBase(cwd, ref, signal) {
|
|
43
|
+
const head = await resolveRef(cwd, 'HEAD', signal)
|
|
44
|
+
let base = await resolveRef(cwd, ref, signal)
|
|
45
|
+
if (!head || !base) return undefined
|
|
46
|
+
|
|
47
|
+
const upstream = await resolveRef(cwd, `${ref}@{upstream}`, signal)
|
|
48
|
+
if (upstream) {
|
|
49
|
+
try {
|
|
50
|
+
const counts = (await git(cwd, ['rev-list', '--left-right', '--count', `${base}...${upstream}`], signal))
|
|
51
|
+
.split(/\s+/)
|
|
52
|
+
if (Number(counts[1]) > 0) base = upstream
|
|
53
|
+
} catch {
|
|
54
|
+
/* no upstream to compare against */
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
return await git(cwd, ['merge-base', head, base], signal)
|
|
60
|
+
} catch {
|
|
61
|
+
return undefined
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Split the modifier tokens off the command line.
|
|
67
|
+
*
|
|
68
|
+
* `sub` routes the task to an isolated agent; `report` asks for a plan instead of
|
|
69
|
+
* an edit. Both are optional and positional, so `sub report --base main` works.
|
|
70
|
+
*/
|
|
71
|
+
export function splitFlags(rawInput) {
|
|
72
|
+
const tokens = String(rawInput ?? '').trim().split(/\s+/).filter(Boolean)
|
|
73
|
+
const flags = { sub: false, report: false }
|
|
74
|
+
const rest = []
|
|
75
|
+
for (const token of tokens) {
|
|
76
|
+
const lower = token.toLowerCase()
|
|
77
|
+
if (lower === 'sub') { flags.sub = true; continue }
|
|
78
|
+
if (lower === 'report') { flags.report = true; continue }
|
|
79
|
+
rest.push(token)
|
|
80
|
+
}
|
|
81
|
+
return { ...flags, rest: rest.join(' ') }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function parseArgs(rawInput) {
|
|
85
|
+
const tokens = rawInput.trim().split(/\s+/).filter(Boolean)
|
|
86
|
+
let apply = false
|
|
87
|
+
const rest = []
|
|
88
|
+
for (const token of tokens) {
|
|
89
|
+
if (token === '--apply') {
|
|
90
|
+
apply = true
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
rest.push(token)
|
|
94
|
+
}
|
|
95
|
+
const line = rest.join(' ')
|
|
96
|
+
if (!line) return { scope: null, apply }
|
|
97
|
+
|
|
98
|
+
const files = line.match(/^--files\s+(.+)$/)
|
|
99
|
+
if (files) {
|
|
100
|
+
const paths = files[1].split(/[,;]/).map((item) => item.trim()).filter(Boolean)
|
|
101
|
+
if (paths.length) return { scope: { mode: 'files', paths }, apply }
|
|
102
|
+
}
|
|
103
|
+
// `--branch <ref>` compares against a branch other than the default base;
|
|
104
|
+
// `--base` is the same thing under the older name.
|
|
105
|
+
const base = line.match(/^--(?:base|branch)\s+(.+)$/)
|
|
106
|
+
if (base) return { scope: { mode: 'base', ref: base[1].trim() }, apply }
|
|
107
|
+
const commit = line.match(/^--commit\s+(.+)$/)
|
|
108
|
+
if (commit) return { scope: { mode: 'commit', ref: commit[1].trim() }, apply }
|
|
109
|
+
|
|
110
|
+
return { scope: { mode: 'instructions', text: line }, apply }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The repository's default branch, ignoring a ref that already equals HEAD. */
|
|
114
|
+
async function defaultBase(cwd, signal) {
|
|
115
|
+
const head = await resolveRef(cwd, 'HEAD', signal)
|
|
116
|
+
for (const ref of ['origin/HEAD', 'origin/main', 'origin/master', 'main', 'master']) {
|
|
117
|
+
const resolved = await resolveRef(cwd, ref, signal)
|
|
118
|
+
if (resolved && resolved !== head) return ref
|
|
119
|
+
}
|
|
120
|
+
return undefined
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Turn a symbolic scope into a concrete one.
|
|
125
|
+
*
|
|
126
|
+
* "Current branch" means whatever is not yet in the base branch, and the
|
|
127
|
+
* uncommitted work is the part the person is still working on. So: a dirty tree
|
|
128
|
+
* reviews the working tree; a clean tree reviews what the branch adds on top of
|
|
129
|
+
* its base; a branch with no base reviews the recent commits.
|
|
130
|
+
*
|
|
131
|
+
* An explicit `--branch <ref>` is a deliberate choice, so it is honoured even
|
|
132
|
+
* when the tree is dirty — the person asked for that comparison, not for the
|
|
133
|
+
* working tree.
|
|
134
|
+
*/
|
|
135
|
+
export async function resolveScope(scope, { cwd, signal } = {}) {
|
|
136
|
+
if (scope.mode !== 'branch' || !cwd) return scope
|
|
137
|
+
try {
|
|
138
|
+
if ((await git(cwd, ['status', '--porcelain'], signal)).length > 0) return { mode: 'worktree' }
|
|
139
|
+
} catch {
|
|
140
|
+
/* not a repository — fall through to the window */
|
|
141
|
+
}
|
|
142
|
+
try {
|
|
143
|
+
const ref = await defaultBase(cwd, signal)
|
|
144
|
+
const base = ref ? await mergeBase(cwd, ref, signal) : undefined
|
|
145
|
+
if (base) return { mode: 'base', ref }
|
|
146
|
+
} catch {
|
|
147
|
+
/* not a repository, or no base to find */
|
|
148
|
+
}
|
|
149
|
+
return { mode: 'recent', count: 5 }
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The branches a person can compare against, for the hint and for errors. */
|
|
153
|
+
export async function branchList(cwd, signal) {
|
|
154
|
+
try {
|
|
155
|
+
return (await git(cwd, ['for-each-ref', '--format=%(refname:short)', 'refs/heads', 'refs/remotes'], signal))
|
|
156
|
+
.split('\n')
|
|
157
|
+
.filter((name) => name && !name.endsWith('/HEAD'))
|
|
158
|
+
} catch {
|
|
159
|
+
return []
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Whether this scope has anything to look at; a clean tree is a real answer. */
|
|
164
|
+
export async function scopeHasChanges(scope, { cwd, signal } = {}) {
|
|
165
|
+
if (!cwd) return true
|
|
166
|
+
const changed = async (args) => (await git(cwd, args, signal)).trim().length > 0
|
|
167
|
+
try {
|
|
168
|
+
if (scope.mode === 'worktree') return await changed(['status', '--porcelain'])
|
|
169
|
+
if (scope.mode === 'base') {
|
|
170
|
+
const base = await mergeBase(cwd, scope.ref, signal)
|
|
171
|
+
if (!base) return true
|
|
172
|
+
return (await changed(['diff', '--name-only', base])) || (await changed(['ls-files', '--others', '--exclude-standard']))
|
|
173
|
+
}
|
|
174
|
+
// A commit always has content; a window and a project are never empty.
|
|
175
|
+
return true
|
|
176
|
+
} catch {
|
|
177
|
+
return true
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Resolve the scope. An explicit line wins; otherwise the command's own default
|
|
183
|
+
* applies — no question, because a command with no arguments must do something
|
|
184
|
+
* sensible on its own.
|
|
185
|
+
*/
|
|
186
|
+
export async function selectScope(ctx, agent, rawInput, signal, t, fallback = 'project') {
|
|
187
|
+
const parsed = parseArgs(rawInput)
|
|
188
|
+
if (parsed.scope) return parsed
|
|
189
|
+
return { scope: { mode: fallback }, apply: parsed.apply }
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* The concrete instruction handed to the subagent for a resolved scope.
|
|
194
|
+
* The merge base is resolved here so the child does not have to guess which
|
|
195
|
+
* diff a branch comparison means.
|
|
196
|
+
*/
|
|
197
|
+
export async function scopeInstruction(scope, { cwd, signal } = {}) {
|
|
198
|
+
switch (scope.mode) {
|
|
199
|
+
case 'worktree':
|
|
200
|
+
return 'Scope: the uncommitted changes in this working directory (staged, unstaged, and untracked). Start with `git status --short` and `git diff HEAD`.'
|
|
201
|
+
case 'project':
|
|
202
|
+
return 'Scope: the whole project on the current branch — every source file under the repository root, not only the diff. Start by listing the tree and reading the files you will touch; do not limit yourself to recent changes.'
|
|
203
|
+
case 'branch':
|
|
204
|
+
case 'base': {
|
|
205
|
+
let ref = scope.ref
|
|
206
|
+
let base
|
|
207
|
+
if (cwd) {
|
|
208
|
+
try {
|
|
209
|
+
ref ??= await defaultBase(cwd, signal)
|
|
210
|
+
if (ref) base = await mergeBase(cwd, ref, signal)
|
|
211
|
+
} catch {
|
|
212
|
+
base = undefined
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (base) {
|
|
216
|
+
return `Scope: everything this branch adds on top of \`${ref}\`. The merge base is ${base}; start with \`git diff ${base}\` (and \`git log ${base}..HEAD\` for intent).`
|
|
217
|
+
}
|
|
218
|
+
if (scope.mode === 'branch') {
|
|
219
|
+
return 'Scope: the changes on the current branch. Find the base first (`git merge-base HEAD origin/main`), then diff against it; when the repository has no base branch, fall back to `git diff HEAD`.'
|
|
220
|
+
}
|
|
221
|
+
return `Scope: everything this branch adds on top of \`${scope.ref}\`. Find the merge base first (\`git merge-base HEAD ${scope.ref}\`), then \`git diff <merge-base>\`.`
|
|
222
|
+
}
|
|
223
|
+
case 'recent':
|
|
224
|
+
return `Scope: the last ${scope.count} commits on the current branch (the branch has no base to compare with). Start with \`git log -${scope.count} --oneline\` and \`git diff HEAD~${scope.count}..HEAD\`; if the history is shorter, diff against the root commit.`
|
|
225
|
+
case 'commit':
|
|
226
|
+
return `Scope: the single commit \`${scope.ref}\`${scope.title ? ` (${scope.title})` : ''}. Start with \`git show ${scope.ref}\`.`
|
|
227
|
+
case 'files':
|
|
228
|
+
return `Scope: only these paths — ${scope.paths.map((path) => `\`${path}\``).join(', ')}. Read them directly; do not widen the scope.`
|
|
229
|
+
case 'instructions':
|
|
230
|
+
return `Scope, as described by the user: ${scope.text}`
|
|
231
|
+
default:
|
|
232
|
+
return 'Scope: the uncommitted changes in this working directory.'
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Short human label for a scope, used in the report header. */
|
|
237
|
+
export function scopeLabel(scope) {
|
|
238
|
+
switch (scope.mode) {
|
|
239
|
+
case 'worktree':
|
|
240
|
+
return 'working tree vs HEAD'
|
|
241
|
+
case 'project':
|
|
242
|
+
return 'whole project'
|
|
243
|
+
case 'branch':
|
|
244
|
+
return 'current branch'
|
|
245
|
+
case 'recent':
|
|
246
|
+
return `last ${scope.count} commits`
|
|
247
|
+
case 'base':
|
|
248
|
+
return `HEAD vs ${scope.ref}`
|
|
249
|
+
case 'commit':
|
|
250
|
+
return `commit ${scope.ref.slice(0, 10)}`
|
|
251
|
+
case 'files':
|
|
252
|
+
return scope.paths.join(', ')
|
|
253
|
+
case 'instructions':
|
|
254
|
+
return scope.text.length > 60 ? `${scope.text.slice(0, 60)}…` : scope.text
|
|
255
|
+
default:
|
|
256
|
+
return 'working tree'
|
|
257
|
+
}
|
|
258
|
+
}
|