@sequenceholdings/studio-cli 0.9.20 → 0.9.22
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/README.md +159 -12
- package/dist/app/commands.js +37 -7
- package/dist/app/deploy.js +2 -0
- package/dist/app/lockfile-preflight.d.ts +31 -0
- package/dist/app/lockfile-preflight.js +47 -0
- package/dist/app/repository-index.d.ts +5 -1
- package/dist/app/repository-index.js +9 -3
- package/dist/app/scaffold.d.ts +3 -1
- package/dist/app/scaffold.js +5 -3
- package/dist/auth.d.ts +13 -9
- package/dist/auth.js +98 -20
- package/dist/cli-errors.js +6 -1
- package/dist/command-contract.d.ts +13 -1
- package/dist/command-contract.js +3 -1
- package/dist/command-help.d.ts +1 -1
- package/dist/command-help.js +8 -1
- package/dist/config.d.ts +14 -0
- package/dist/config.js +29 -3
- package/dist/docs/commands.d.ts +16 -0
- package/dist/docs/commands.js +168 -0
- package/dist/docs/help.d.ts +2 -0
- package/dist/docs/help.js +12 -0
- package/dist/envs/commands.js +10 -2
- package/dist/host-token.d.ts +19 -4
- package/dist/host-token.js +50 -10
- package/dist/main.d.ts +1 -0
- package/dist/main.js +20 -2
- package/dist/orm/discover-operations.d.ts +1 -1
- package/dist/orm/discover-operations.js +3 -3
- package/dist/orm/discover-schema.d.ts +0 -5
- package/dist/orm/discover-schema.js +0 -3
- package/dist/pipeline/commands.d.ts +0 -7
- package/dist/pipeline/commands.js +16 -67
- package/dist/pipeline/discovery.d.ts +1 -1
- package/dist/pipeline/discovery.js +6 -6
- package/dist/process/build.d.ts +2 -5
- package/dist/process/build.js +4 -49
- package/dist/repos/commands.d.ts +11 -1
- package/dist/repos/commands.js +78 -11
- package/dist/repos/git-credential.d.ts +12 -5
- package/dist/repos/git-credential.js +63 -36
- package/dist/repos/github-connect-command.d.ts +35 -0
- package/dist/repos/github-connect-command.js +250 -0
- package/dist/repos/github-init-command.d.ts +16 -0
- package/dist/repos/github-init-command.js +116 -0
- package/dist/repos/github-init.d.ts +146 -0
- package/dist/repos/github-init.js +355 -0
- package/dist/repos/init-github.d.ts +50 -0
- package/dist/repos/init-github.js +181 -0
- package/dist/repos/pulls.d.ts +5 -1
- package/dist/repos/pulls.js +31 -9
- package/dist/scaffold-guidance.d.ts +10 -2
- package/dist/scaffold-guidance.js +27 -2
- package/dist/templates/github/pr-type.mjs +285 -0
- package/dist/templates/github/pr-types.json +40 -0
- package/dist/templates/guidance/AGENTS.md +15 -8
- package/package.json +7 -7
- package/release-summary.json +3 -1
- package/templates/github/pr-type.mjs +285 -0
- package/templates/github/pr-types.json +40 -0
- package/templates/guidance/AGENTS.md +15 -8
- package/dist/pipeline/active-orm-contracts.d.ts +0 -16
- package/dist/pipeline/active-orm-contracts.js +0 -36
- package/dist/pipeline/repin-orm.d.ts +0 -2
- package/dist/pipeline/repin-orm.js +0 -207
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
// Enforces exactly one `type: *` label on every pull request, so merged work can
|
|
2
|
+
// be measured by kind (bug / performance / enhancement / feature / chore).
|
|
3
|
+
//
|
|
4
|
+
// When a PR has no type label, Claude picks one from the title, description and
|
|
5
|
+
// changed paths, applies it, and leaves a comment saying how to change it. The
|
|
6
|
+
// check fails only when the PR has more than one type label, or when no label
|
|
7
|
+
// is present and classification is unavailable.
|
|
8
|
+
//
|
|
9
|
+
// The taxonomy is pr-types.json beside this file (PR_TYPES_PATH). The workflow
|
|
10
|
+
// reads both from the trusted base commit, never the PR head, because this job
|
|
11
|
+
// holds a write-scoped token and an API key. `seq-studio repo init` writes this
|
|
12
|
+
// file into GitHub-hosted Sequence repos; the canonical copy is in studio-cli's
|
|
13
|
+
// templates/github.
|
|
14
|
+
|
|
15
|
+
import { readFile } from 'node:fs/promises'
|
|
16
|
+
|
|
17
|
+
const MODEL = 'claude-opus-5-5'
|
|
18
|
+
const MAX_BODY_CHARS = 6_000
|
|
19
|
+
const MAX_FILES = 300
|
|
20
|
+
const COMMENT_MARKER = '<!-- pr-type-check -->'
|
|
21
|
+
|
|
22
|
+
export async function loadTypes(path) {
|
|
23
|
+
const parsed = JSON.parse(await readFile(path, 'utf8'))
|
|
24
|
+
if (!Array.isArray(parsed.types) || parsed.types.length === 0) throw new Error(`${path} has no types`)
|
|
25
|
+
return parsed.types
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Pure decision: which type labels does this PR carry? */
|
|
29
|
+
export function evaluateLabels({ labelNames, types }) {
|
|
30
|
+
const byLabel = new Map(types.map((t) => [t.label.toLowerCase(), t]))
|
|
31
|
+
const found = labelNames.map((name) => byLabel.get(name.toLowerCase())).filter(Boolean)
|
|
32
|
+
if (found.length === 1) return { status: 'ok', type: found[0] }
|
|
33
|
+
if (found.length === 0) return { status: 'missing' }
|
|
34
|
+
return { status: 'multiple', types: found }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function buildPrompt({ types, title, body, files }) {
|
|
38
|
+
const taxonomy = types.map((t) => `- ${t.id}: ${t.description}. ${t.guidance}`).join('\n')
|
|
39
|
+
const fileList = files.slice(0, MAX_FILES).join('\n')
|
|
40
|
+
const more = files.length > MAX_FILES ? `\n(${files.length - MAX_FILES} more files not shown)` : ''
|
|
41
|
+
return [
|
|
42
|
+
'Classify this pull request into exactly one type. The labels feed engineering metrics:',
|
|
43
|
+
'how many bugs we fix over time, how much performance work we do, how often we fill gaps',
|
|
44
|
+
'in existing features, how much net-new feature work we ship, and how much maintenance.',
|
|
45
|
+
'',
|
|
46
|
+
'Types:',
|
|
47
|
+
taxonomy,
|
|
48
|
+
'',
|
|
49
|
+
'Pick by the main intent of the change, not by incidental edits. A fix to something that',
|
|
50
|
+
'was broken is a bug even when it touches infrastructure files. A change that only moves',
|
|
51
|
+
'or tidies code, bumps dependencies, or edits CI/docs is a chore.',
|
|
52
|
+
'',
|
|
53
|
+
`<title>${title}</title>`,
|
|
54
|
+
`<description>${(body ?? '').slice(0, MAX_BODY_CHARS)}</description>`,
|
|
55
|
+
`<changed_files>\n${fileList}${more}\n</changed_files>`,
|
|
56
|
+
].join('\n')
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Validates the structured-output JSON; returns a known type id or throws. */
|
|
60
|
+
export function parseClassification({ text, types }) {
|
|
61
|
+
const parsed = JSON.parse(text)
|
|
62
|
+
const ids = new Set(types.map((t) => t.id))
|
|
63
|
+
if (typeof parsed?.type !== 'string' || !ids.has(parsed.type)) {
|
|
64
|
+
throw new Error(`classifier returned an unknown type: ${JSON.stringify(parsed?.type)}`)
|
|
65
|
+
}
|
|
66
|
+
const reason = typeof parsed.reason === 'string' ? parsed.reason.slice(0, 300) : ''
|
|
67
|
+
return { id: parsed.type, reason }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function classify({ apiKey, types, title, body, files }) {
|
|
71
|
+
const res = await fetch('https://api.anthropic.com/v1/messages', {
|
|
72
|
+
method: 'POST',
|
|
73
|
+
headers: {
|
|
74
|
+
'content-type': 'application/json',
|
|
75
|
+
'x-api-key': apiKey,
|
|
76
|
+
'anthropic-version': '2026-10-21',
|
|
77
|
+
'anthropic-beta': 'server-side-fallback-2026-07-01',
|
|
78
|
+
},
|
|
79
|
+
body: JSON.stringify({
|
|
80
|
+
model: MODEL,
|
|
81
|
+
max_tokens: 2_000,
|
|
82
|
+
fallbacks: 'default',
|
|
83
|
+
output_config: {
|
|
84
|
+
effort: 'low',
|
|
85
|
+
format: {
|
|
86
|
+
type: 'json_schema',
|
|
87
|
+
schema: {
|
|
88
|
+
type: 'object',
|
|
89
|
+
properties: {
|
|
90
|
+
type: { type: 'string', enum: types.map((t) => t.id) },
|
|
91
|
+
reason: { type: 'string' },
|
|
92
|
+
},
|
|
93
|
+
required: ['type', 'reason'],
|
|
94
|
+
additionalProperties: false,
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
messages: [{ role: 'user', content: buildPrompt({ types, title, body, files }) }],
|
|
99
|
+
}),
|
|
100
|
+
})
|
|
101
|
+
if (!res.ok) throw new Error(`Anthropic API ${res.status}: ${(await res.text()).slice(0, 500)}`)
|
|
102
|
+
const message = await res.json()
|
|
103
|
+
if (message?.stop_reason === 'refusal') throw new Error('classifier declined the request')
|
|
104
|
+
const text = Array.isArray(message?.content) ? message.content.find((b) => b?.type === 'text')?.text : undefined
|
|
105
|
+
if (typeof text !== 'string') throw new Error('classifier returned no text block')
|
|
106
|
+
return parseClassification({ text, types })
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function github({ token, repo }) {
|
|
110
|
+
const base = `https://api.github.com/repos/${repo}`
|
|
111
|
+
return async (method, path, body) => {
|
|
112
|
+
const res = await fetch(`${base}${path}`, {
|
|
113
|
+
method,
|
|
114
|
+
headers: {
|
|
115
|
+
authorization: `Bearer ${token}`,
|
|
116
|
+
accept: 'application/vnd.github+json',
|
|
117
|
+
'x-github-api-version': '2022-11-28',
|
|
118
|
+
...(body ? { 'content-type': 'application/json' } : {}),
|
|
119
|
+
},
|
|
120
|
+
...(body ? { body: JSON.stringify(body) } : {}),
|
|
121
|
+
})
|
|
122
|
+
if (!res.ok) {
|
|
123
|
+
const error = new Error(`GitHub ${method} ${path}: ${res.status} ${(await res.text()).slice(0, 300)}`)
|
|
124
|
+
error.status = res.status
|
|
125
|
+
throw error
|
|
126
|
+
}
|
|
127
|
+
return res.status === 204 ? null : res.json()
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Creates or updates every label in the taxonomy. Idempotent. */
|
|
132
|
+
export async function syncLabels({ gh, types }) {
|
|
133
|
+
for (const t of types) {
|
|
134
|
+
const fields = { color: t.color, description: t.description.slice(0, 100) }
|
|
135
|
+
try {
|
|
136
|
+
await gh('PATCH', `/labels/${encodeURIComponent(t.label)}`, fields)
|
|
137
|
+
} catch (error) {
|
|
138
|
+
if (error.status !== 404) throw error
|
|
139
|
+
await gh('POST', '/labels', { name: t.label, ...fields })
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function listFiles({ gh, number }) {
|
|
145
|
+
const files = []
|
|
146
|
+
for (let page = 1; page <= 3; page += 1) {
|
|
147
|
+
const batch = await gh('GET', `/pulls/${number}/files?per_page=100&page=${page}`)
|
|
148
|
+
files.push(...batch.map((f) => f.filename))
|
|
149
|
+
if (batch.length < 100) break
|
|
150
|
+
}
|
|
151
|
+
return files
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const WEEK_MS = 7 * 24 * 60 * 60 * 1000
|
|
155
|
+
|
|
156
|
+
/** Monday 00:00 UTC of the week containing `date`, as YYYY-MM-DD. */
|
|
157
|
+
export function weekStart(date) {
|
|
158
|
+
const day = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()))
|
|
159
|
+
day.setUTCDate(day.getUTCDate() - ((day.getUTCDay() + 6) % 7))
|
|
160
|
+
return day.toISOString().slice(0, 10)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Merged PRs per week per type; PRs without exactly one type label count as `untyped`. */
|
|
164
|
+
export function bucketMergedPulls({ pulls, types, since }) {
|
|
165
|
+
const buckets = new Map()
|
|
166
|
+
for (const pull of pulls) {
|
|
167
|
+
if (!pull.merged_at) continue
|
|
168
|
+
const mergedAt = new Date(pull.merged_at)
|
|
169
|
+
if (mergedAt < since) continue
|
|
170
|
+
const week = weekStart(mergedAt)
|
|
171
|
+
const row = buckets.get(week) ?? Object.fromEntries([...types.map((t) => [t.id, 0]), ['untyped', 0]])
|
|
172
|
+
const verdict = evaluateLabels({ labelNames: (pull.labels ?? []).map((l) => l.name), types })
|
|
173
|
+
row[verdict.status === 'ok' ? verdict.type.id : 'untyped'] += 1
|
|
174
|
+
buckets.set(week, row)
|
|
175
|
+
}
|
|
176
|
+
return [...buckets.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([week, counts]) => ({ week, ...counts }))
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function renderReport({ rows, types }) {
|
|
180
|
+
const columns = [...types.map((t) => t.id), 'untyped']
|
|
181
|
+
const lines = [`| week of | ${columns.join(' | ')} | total | bug share |`, `|---|${columns.map(() => '---:').join('|')}|---:|---:|`]
|
|
182
|
+
for (const row of rows) {
|
|
183
|
+
const total = columns.reduce((sum, c) => sum + row[c], 0)
|
|
184
|
+
const typed = total - row.untyped
|
|
185
|
+
const share = typed > 0 ? `${Math.round((100 * row.bug) / typed)}%` : '—'
|
|
186
|
+
lines.push(`| ${row.week} | ${columns.map((c) => row[c]).join(' | ')} | ${total} | ${share} |`)
|
|
187
|
+
}
|
|
188
|
+
return lines.join('\n')
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Closed PRs updated since `since`, newest first, stopping once a page is entirely older. */
|
|
192
|
+
async function listClosedPulls({ gh, since }) {
|
|
193
|
+
const pulls = []
|
|
194
|
+
for (let page = 1; page <= 50; page += 1) {
|
|
195
|
+
const batch = await gh('GET', `/pulls?state=closed&sort=updated&direction=desc&per_page=100&page=${page}`)
|
|
196
|
+
pulls.push(...batch)
|
|
197
|
+
if (batch.length < 100 || batch.every((p) => new Date(p.updated_at) < since)) break
|
|
198
|
+
}
|
|
199
|
+
return pulls
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function fixInstructions(types) {
|
|
203
|
+
const list = types.map((t) => `\`${t.label}\``).join(', ')
|
|
204
|
+
return `Add exactly one of ${list}, e.g. \`gh pr edit <number> --add-label "${types[0].label}"\`.`
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function main() {
|
|
208
|
+
const types = await loadTypes(process.env.PR_TYPES_PATH ?? '.github/pr-types.json')
|
|
209
|
+
const repo = process.env.GITHUB_REPOSITORY
|
|
210
|
+
const gh = github({ token: process.env.GITHUB_TOKEN, repo })
|
|
211
|
+
|
|
212
|
+
if (process.argv[2] === 'report') {
|
|
213
|
+
const weeksIndex = process.argv.indexOf('--weeks')
|
|
214
|
+
const weeks = weeksIndex > 0 ? Number(process.argv[weeksIndex + 1]) : 12
|
|
215
|
+
if (!Number.isInteger(weeks) || weeks < 1 || weeks > 52) throw new Error('--weeks must be an integer from 1 to 52')
|
|
216
|
+
const since = new Date(`${weekStart(new Date(Date.now() - (weeks - 1) * WEEK_MS))}T00:00:00Z`)
|
|
217
|
+
const rows = bucketMergedPulls({ pulls: await listClosedPulls({ gh, since }), types, since })
|
|
218
|
+
console.log(`Merged PRs on ${repo} by type, weekly (UTC, weeks start Monday). Bug share is of typed PRs.\n`)
|
|
219
|
+
console.log(renderReport({ rows, types }))
|
|
220
|
+
return
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (process.argv[2] === 'sync-labels') {
|
|
224
|
+
await syncLabels({ gh, types })
|
|
225
|
+
console.log(`Synced ${types.length} type labels on ${repo}.`)
|
|
226
|
+
return
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const event = JSON.parse(await readFile(process.env.GITHUB_EVENT_PATH, 'utf8'))
|
|
230
|
+
const number = event.pull_request?.number
|
|
231
|
+
if (!number) throw new Error('This check runs on pull_request events only.')
|
|
232
|
+
|
|
233
|
+
// Re-read labels: the event payload is a snapshot from when the event fired.
|
|
234
|
+
const pull = await gh('GET', `/pulls/${number}`)
|
|
235
|
+
const verdict = evaluateLabels({ labelNames: pull.labels.map((l) => l.name), types })
|
|
236
|
+
|
|
237
|
+
if (verdict.status === 'ok') {
|
|
238
|
+
console.log(`PR #${number} is typed as ${verdict.type.label}.`)
|
|
239
|
+
return
|
|
240
|
+
}
|
|
241
|
+
if (verdict.status === 'multiple') {
|
|
242
|
+
console.error(`PR #${number} has ${verdict.types.length} type labels (${verdict.types.map((t) => t.label).join(', ')}). Keep exactly one.`)
|
|
243
|
+
process.exitCode = 1
|
|
244
|
+
return
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Label events only re-check: classifying on `unlabeled` would race an author
|
|
248
|
+
// who removed one type label to add another.
|
|
249
|
+
if (process.env.PR_TYPE_CLASSIFY !== 'true') {
|
|
250
|
+
console.error(`PR #${number} has no type label. ${fixInstructions(types)}`)
|
|
251
|
+
process.exitCode = 1
|
|
252
|
+
return
|
|
253
|
+
}
|
|
254
|
+
const apiKey = process.env.ANTHROPIC_API_KEY
|
|
255
|
+
if (!apiKey) {
|
|
256
|
+
console.error(`PR #${number} has no type label and no classifier key is available. ${fixInstructions(types)}`)
|
|
257
|
+
process.exitCode = 1
|
|
258
|
+
return
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
let picked
|
|
262
|
+
try {
|
|
263
|
+
picked = await classify({ apiKey, types, title: pull.title, body: pull.body, files: await listFiles({ gh, number }) })
|
|
264
|
+
} catch (error) {
|
|
265
|
+
console.error(`Could not classify PR #${number}: ${error.message}\n${fixInstructions(types)}`)
|
|
266
|
+
process.exitCode = 1
|
|
267
|
+
return
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const type = types.find((t) => t.id === picked.id)
|
|
271
|
+
await syncLabels({ gh, types: [type] })
|
|
272
|
+
await gh('POST', `/issues/${number}/labels`, { labels: [type.label] })
|
|
273
|
+
const others = types.filter((t) => t.id !== type.id).map((t) => `\`${t.label}\``).join(', ')
|
|
274
|
+
await gh('POST', `/issues/${number}/comments`, {
|
|
275
|
+
body: `${COMMENT_MARKER}\nLabelled this PR **\`${type.label}\`**: ${picked.reason}\n\nIf that's wrong, swap it for one of ${others}. Every PR needs exactly one type label; they feed our bug / performance / feature trend metrics.\n\n---\n_Generated by [Claude Code](https://claude.ai/code)_`,
|
|
276
|
+
})
|
|
277
|
+
console.log(`PR #${number} had no type label; applied ${type.label} (${picked.reason}).`)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
281
|
+
main().catch((error) => {
|
|
282
|
+
console.error(error)
|
|
283
|
+
process.exitCode = 1
|
|
284
|
+
})
|
|
285
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$comment": "Every pull request carries exactly one type label. Canonical copy: studio shared/services/studio-cli/templates/github/pr-types.json; Git Service Pulls mirror it in atlas git-service/pull-types.ts (a test enforces it). Add a type, never rename one: renaming splits the trend lines.",
|
|
3
|
+
"types": [
|
|
4
|
+
{
|
|
5
|
+
"id": "bug",
|
|
6
|
+
"label": "type: bug",
|
|
7
|
+
"color": "d73a4a",
|
|
8
|
+
"description": "Fixes behavior that is broken or wrong",
|
|
9
|
+
"guidance": "Something that used to work, or was meant to work, does the wrong thing: an error, a crash, wrong data, a regression."
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
"id": "performance",
|
|
13
|
+
"label": "type: performance",
|
|
14
|
+
"color": "fbca04",
|
|
15
|
+
"description": "Makes something faster, cheaper, or more reliable under load",
|
|
16
|
+
"guidance": "Latency, memory, cost, timeouts, rate limits, query plans, bundle size. Behavior is correct before and after; it is just slow or expensive."
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"id": "enhancement",
|
|
20
|
+
"label": "type: enhancement",
|
|
21
|
+
"color": "a2eeef",
|
|
22
|
+
"description": "Fills a gap in an existing feature",
|
|
23
|
+
"guidance": "A capability that already exists but is missing something users would reasonably expect it to have: a missing filter, an edge case, a missing field, better UX on an existing flow."
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"id": "feature",
|
|
27
|
+
"label": "type: feature",
|
|
28
|
+
"color": "0e8a16",
|
|
29
|
+
"description": "Adds a new capability",
|
|
30
|
+
"guidance": "Something users or developers could not do at all before: a new product surface, app, integration, command, or workflow."
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"id": "chore",
|
|
34
|
+
"label": "type: chore",
|
|
35
|
+
"color": "c5def5",
|
|
36
|
+
"description": "Maintenance with no user-facing behavior change",
|
|
37
|
+
"guidance": "Infrastructure, CI, dependencies, refactors, docs, tests, tooling, config, and agent guides."
|
|
38
|
+
}
|
|
39
|
+
]
|
|
40
|
+
}
|
|
@@ -1,15 +1,22 @@
|
|
|
1
1
|
# Sequence development
|
|
2
2
|
|
|
3
|
-
Before every development task, read the
|
|
4
|
-
target environment.
|
|
5
|
-
|
|
3
|
+
Before every development task, read the Sequence developer docs for this
|
|
4
|
+
project's target environment. They match the platform version that environment
|
|
5
|
+
runs, so prefer them over memory, other repositories, or copied snippets.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
7
|
+
```sh
|
|
8
|
+
seq-studio envs list # find the environment name
|
|
9
|
+
seq-studio docs search "<what you need>" -e <env> # find the right page
|
|
10
|
+
seq-studio docs read <slug> -e <env> # read it in full
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Search before running an unfamiliar `seq-studio` command, and read the matching
|
|
14
|
+
page before changing a manifest. If the CLI cannot reach the docs, open
|
|
15
|
+
`<environment-url>/docs` (index at `/docs/llms.txt`) in the signed-in browser.
|
|
16
|
+
The docs are the single source of truth for platform usage; do not duplicate
|
|
17
|
+
their instructions in this file.
|
|
11
18
|
|
|
12
19
|
After concrete CLI friction costs time or retries, finish the task, then follow
|
|
13
|
-
the
|
|
20
|
+
the `seq-studio/feedback` docs page and run `seq-studio feedback submit`
|
|
14
21
|
before the final response. Include the confirmed receipt ID and ticket URL, or
|
|
15
22
|
the sanitized draft and submission evidence if no receipt is confirmed.
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import type { OrmSyncedTableContract } from '@sequenceholdings/orm';
|
|
2
|
-
import type { ResolvedEnv } from '../config.js';
|
|
3
|
-
type OrmModule = typeof import('@sequenceholdings/orm');
|
|
4
|
-
interface ContractStage {
|
|
5
|
-
readonly satisfies: {
|
|
6
|
-
readonly namespace: string;
|
|
7
|
-
readonly table: string;
|
|
8
|
-
};
|
|
9
|
-
}
|
|
10
|
-
export declare function loadActiveOrmContracts({ env, orm, stages, token, }: {
|
|
11
|
-
env: ResolvedEnv;
|
|
12
|
-
orm: OrmModule;
|
|
13
|
-
stages: readonly ContractStage[];
|
|
14
|
-
token: string;
|
|
15
|
-
}): Promise<Record<string, OrmSyncedTableContract>>;
|
|
16
|
-
export {};
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod';
|
|
2
|
-
import { getJson } from '../atlas-client.js';
|
|
3
|
-
const namespaceResponseSchema = z.object({
|
|
4
|
-
active_definition: z.unknown().nullable(),
|
|
5
|
-
active_definition_format: z.number().int().nullable(),
|
|
6
|
-
});
|
|
7
|
-
export async function loadActiveOrmContracts({ env, orm, stages, token, }) {
|
|
8
|
-
const namespaces = [...new Set(stages.map((stage) => stage.satisfies.namespace))];
|
|
9
|
-
const definitions = new Map();
|
|
10
|
-
await Promise.all(namespaces.map(async (namespace) => {
|
|
11
|
-
const response = namespaceResponseSchema.parse(await getJson({
|
|
12
|
-
baseUrl: env.url,
|
|
13
|
-
token,
|
|
14
|
-
path: `/api/orm/namespaces/${encodeURIComponent(namespace)}`,
|
|
15
|
-
}));
|
|
16
|
-
if (response.active_definition_format !== 2 || response.active_definition === null) {
|
|
17
|
-
throw new Error(`ORM namespace '${namespace}' has no active v2 definition in ${env.name}`);
|
|
18
|
-
}
|
|
19
|
-
definitions.set(namespace, orm.canonicalDefinitionSchema.parse(response.active_definition));
|
|
20
|
-
}));
|
|
21
|
-
const contracts = {};
|
|
22
|
-
for (const stage of stages) {
|
|
23
|
-
const binding = stage.satisfies;
|
|
24
|
-
const key = `${binding.namespace}.${binding.table}`;
|
|
25
|
-
const definition = definitions.get(binding.namespace);
|
|
26
|
-
const table = definition?.tables.find((candidate) => candidate.table === binding.table);
|
|
27
|
-
if (!table) {
|
|
28
|
-
throw new Error(`active ORM definition does not contain synced table '${key}'`);
|
|
29
|
-
}
|
|
30
|
-
contracts[key] = orm.extractOrmSyncedTableContract({
|
|
31
|
-
namespace: binding.namespace,
|
|
32
|
-
table,
|
|
33
|
-
});
|
|
34
|
-
}
|
|
35
|
-
return contracts;
|
|
36
|
-
}
|
|
@@ -1,207 +0,0 @@
|
|
|
1
|
-
import { readFile } from 'node:fs/promises';
|
|
2
|
-
import { join, resolve } from 'node:path';
|
|
3
|
-
import { z } from 'zod';
|
|
4
|
-
import { getAccessToken } from '../auth.js';
|
|
5
|
-
import { resolveConfiguredEnv } from '../config.js';
|
|
6
|
-
import { explicitOrSandboxEnv } from '../env-flags.js';
|
|
7
|
-
import { isSandboxTokenMode } from '../sandbox-auth.js';
|
|
8
|
-
import { loadActiveOrmContracts } from './active-orm-contracts.js';
|
|
9
|
-
import { commitFileWrites } from './atomic-file-writes.js';
|
|
10
|
-
import { resolvePipelineTarget } from './lifecycle.js';
|
|
11
|
-
const LOG = '[seq-studio]';
|
|
12
|
-
const ORM_CONTRACTS_FILENAME = 'orm-contracts.json';
|
|
13
|
-
async function loadModules() {
|
|
14
|
-
return {
|
|
15
|
-
spec: await import('@sequenceholdings/pipeline-spec'),
|
|
16
|
-
orm: await import('@sequenceholdings/orm'),
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
function requestedEnvironment(args) {
|
|
20
|
-
const value = args.flags.e ?? args.flags.env;
|
|
21
|
-
return explicitOrSandboxEnv(typeof value === 'string' ? value : undefined);
|
|
22
|
-
}
|
|
23
|
-
function hasOrmPin(stage) {
|
|
24
|
-
return stage.type === 'serving' && stage.satisfies !== undefined;
|
|
25
|
-
}
|
|
26
|
-
async function loadExistingCatalog({ path, spec, }) {
|
|
27
|
-
let raw;
|
|
28
|
-
try {
|
|
29
|
-
raw = await readFile(path, 'utf8');
|
|
30
|
-
}
|
|
31
|
-
catch (error) {
|
|
32
|
-
if (error instanceof Error && Reflect.get(error, 'code') === 'ENOENT')
|
|
33
|
-
return {};
|
|
34
|
-
throw error;
|
|
35
|
-
}
|
|
36
|
-
const parsed = JSON.parse(raw);
|
|
37
|
-
spec.ormContractCatalogSchema.parse(parsed);
|
|
38
|
-
return z.record(z.string(), z.unknown()).parse(parsed);
|
|
39
|
-
}
|
|
40
|
-
function assertNoUntargetedContractCollisions({ contracts, pinnedStages, target, }) {
|
|
41
|
-
for (const stage of pinnedStages) {
|
|
42
|
-
if (stage.environments.includes(target))
|
|
43
|
-
continue;
|
|
44
|
-
const key = `${stage.satisfies.namespace}.${stage.satisfies.table}`;
|
|
45
|
-
const refreshed = contracts[key];
|
|
46
|
-
if (refreshed && refreshed.content_hash !== stage.satisfies.content_hash) {
|
|
47
|
-
throw new Error(`cannot repin '${key}' for target '${target}': untargeted stage '${stage.stage}' ` +
|
|
48
|
-
`pins ${stage.satisfies.content_hash.slice(0, 12)}… while ${target} requires ` +
|
|
49
|
-
`${refreshed.content_hash.slice(0, 12)}…; align the environments' ORM contracts first`);
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
function environmentNameForTarget(target) {
|
|
54
|
-
if (target === 'dev')
|
|
55
|
-
return 'local';
|
|
56
|
-
if (target === 'staging' || target === 'production' || target === 'banksouth')
|
|
57
|
-
return target;
|
|
58
|
-
return undefined;
|
|
59
|
-
}
|
|
60
|
-
async function assertSharedStageContractsAgree({ contracts, orm, stages, target, }) {
|
|
61
|
-
const otherTargets = new Set(stages.flatMap((stage) => stage.environments.filter((candidate) => candidate !== target)));
|
|
62
|
-
for (const otherTarget of otherTargets) {
|
|
63
|
-
const environmentName = environmentNameForTarget(otherTarget);
|
|
64
|
-
if (!environmentName) {
|
|
65
|
-
throw new Error(`cannot verify shared ORM pins for target '${otherTarget}'; ` +
|
|
66
|
-
'split multi-target stages or use environment-specific pins');
|
|
67
|
-
}
|
|
68
|
-
if (isSandboxTokenMode()) {
|
|
69
|
-
// Every name resolves to the sandbox deployment, which is not this target's.
|
|
70
|
-
throw new Error(`cannot verify shared ORM pins for target '${otherTarget}' from an agent sandbox; ` +
|
|
71
|
-
'it reaches only its own deployment');
|
|
72
|
-
}
|
|
73
|
-
const otherEnv = await resolveConfiguredEnv({ requested: environmentName });
|
|
74
|
-
const otherToken = await getAccessToken({ env: otherEnv.name, targetUrl: otherEnv.url });
|
|
75
|
-
const sharedStages = stages.filter((stage) => stage.environments.includes(otherTarget));
|
|
76
|
-
const otherContracts = await loadActiveOrmContracts({
|
|
77
|
-
env: otherEnv,
|
|
78
|
-
orm,
|
|
79
|
-
stages: sharedStages,
|
|
80
|
-
token: otherToken,
|
|
81
|
-
});
|
|
82
|
-
for (const stage of sharedStages) {
|
|
83
|
-
const key = `${stage.satisfies.namespace}.${stage.satisfies.table}`;
|
|
84
|
-
if (contracts[key]?.content_hash !== otherContracts[key]?.content_hash) {
|
|
85
|
-
throw new Error(`cannot repin shared stage '${stage.stage}': active ORM contract '${key}' ` +
|
|
86
|
-
`differs between targets '${target}' and '${otherTarget}'`);
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
function replacePinnedHash({ contents, currentHash, nextHash, file, }) {
|
|
92
|
-
const pattern = new RegExp(`(^\\s*content_hash:\\s*)(["']?)${currentHash}\\2(\\s*(?:#.*)?$)`, 'gm');
|
|
93
|
-
const matches = [...contents.matchAll(pattern)];
|
|
94
|
-
if (matches.length !== 1) {
|
|
95
|
-
throw new Error(`${file}: expected exactly one satisfies.content_hash value '${currentHash}', found ${matches.length}`);
|
|
96
|
-
}
|
|
97
|
-
return contents.replace(pattern, `$1$2${nextHash}$2$3`);
|
|
98
|
-
}
|
|
99
|
-
export async function pipelineRepinOrmCommand(args) {
|
|
100
|
-
const requested = requestedEnvironment(args);
|
|
101
|
-
if (!requested) {
|
|
102
|
-
console.error('usage: seq-studio pipeline repin-orm [dir] -e <env> [--target <id>] [--dry-run]');
|
|
103
|
-
return 1;
|
|
104
|
-
}
|
|
105
|
-
const dirArg = args.positional[0] ?? '.';
|
|
106
|
-
const dir = resolve(dirArg);
|
|
107
|
-
const dryRun = args.flags['dry-run'] === true || args.flags['dry-run'] === 'true';
|
|
108
|
-
try {
|
|
109
|
-
const { spec, orm } = await loadModules();
|
|
110
|
-
const pipeline = await spec.loadSpecDirectory(dir);
|
|
111
|
-
const allPinnedStages = pipeline.stages.filter(hasOrmPin);
|
|
112
|
-
if (allPinnedStages.length === 0) {
|
|
113
|
-
console.log(`${LOG} no ORM satisfies pins found in ${dirArg}`);
|
|
114
|
-
return 0;
|
|
115
|
-
}
|
|
116
|
-
const env = await resolveConfiguredEnv({ requested });
|
|
117
|
-
const token = await getAccessToken({ env: env.name, targetUrl: env.url });
|
|
118
|
-
const target = (await resolvePipelineTarget({ args, env, token })).id;
|
|
119
|
-
const pinnedStages = allPinnedStages.filter((stage) => stage.environments.includes(target));
|
|
120
|
-
if (pinnedStages.length === 0) {
|
|
121
|
-
console.log(`${LOG} no ORM satisfies pins target ${target} in ${dirArg}`);
|
|
122
|
-
return 0;
|
|
123
|
-
}
|
|
124
|
-
const contracts = await loadActiveOrmContracts({ env, orm, stages: pinnedStages, token });
|
|
125
|
-
const nextHashes = new Map();
|
|
126
|
-
for (const stage of pinnedStages) {
|
|
127
|
-
const binding = stage.satisfies;
|
|
128
|
-
const key = `${binding.namespace}.${binding.table}`;
|
|
129
|
-
const contract = contracts[key];
|
|
130
|
-
if (!contract)
|
|
131
|
-
throw new Error(`missing active ORM contract for '${key}'`);
|
|
132
|
-
nextHashes.set(stage.stage, contract.content_hash);
|
|
133
|
-
}
|
|
134
|
-
await assertSharedStageContractsAgree({
|
|
135
|
-
contracts,
|
|
136
|
-
orm,
|
|
137
|
-
stages: pinnedStages,
|
|
138
|
-
target,
|
|
139
|
-
});
|
|
140
|
-
assertNoUntargetedContractCollisions({
|
|
141
|
-
contracts,
|
|
142
|
-
pinnedStages: allPinnedStages,
|
|
143
|
-
target,
|
|
144
|
-
});
|
|
145
|
-
const catalogPath = join(dir, ORM_CONTRACTS_FILENAME);
|
|
146
|
-
const existingContracts = await loadExistingCatalog({ path: catalogPath, spec });
|
|
147
|
-
const mergedContracts = { ...existingContracts, ...contracts };
|
|
148
|
-
const catalog = spec.ormContractCatalogSchema.parse(mergedContracts);
|
|
149
|
-
const compatibilityErrors = pinnedStages.flatMap((stage) => {
|
|
150
|
-
const contentHash = nextHashes.get(stage.stage);
|
|
151
|
-
if (!contentHash)
|
|
152
|
-
throw new Error(`missing active ORM contract for stage '${stage.stage}'`);
|
|
153
|
-
const key = `${stage.satisfies.namespace}.${stage.satisfies.table}`;
|
|
154
|
-
return spec
|
|
155
|
-
.checkServingSatisfiesOrmContract({
|
|
156
|
-
projection: {
|
|
157
|
-
columns: spec.requireResolvedColumns(stage.projection.columns, `${stage.stage}.projection.columns`),
|
|
158
|
-
primary_key: stage.projection.primary_key,
|
|
159
|
-
},
|
|
160
|
-
satisfies: { ...stage.satisfies, content_hash: contentHash },
|
|
161
|
-
contract: catalog[key],
|
|
162
|
-
})
|
|
163
|
-
.filter((finding) => finding.severity === 'error');
|
|
164
|
-
});
|
|
165
|
-
if (compatibilityErrors.length > 0) {
|
|
166
|
-
compatibilityErrors.forEach((finding) => console.error(`error(${finding.code}): ${finding.message}`));
|
|
167
|
-
console.error(`${LOG} refusing to repin: active ORM contracts are incompatible`);
|
|
168
|
-
return 1;
|
|
169
|
-
}
|
|
170
|
-
const writes = [];
|
|
171
|
-
for (const stage of pinnedStages) {
|
|
172
|
-
const file = pipeline.files.find((candidate) => {
|
|
173
|
-
const basename = candidate.split('/').at(-1);
|
|
174
|
-
return basename === `${stage.stage}.stage.yml` || basename === `${stage.stage}.stage.yaml`;
|
|
175
|
-
});
|
|
176
|
-
if (!file)
|
|
177
|
-
throw new Error(`could not find the source file for stage '${stage.stage}'`);
|
|
178
|
-
const current = await readFile(join(dir, file), 'utf8');
|
|
179
|
-
const nextHash = nextHashes.get(stage.stage);
|
|
180
|
-
if (!nextHash)
|
|
181
|
-
throw new Error(`missing active ORM contract for stage '${stage.stage}'`);
|
|
182
|
-
writes.push({
|
|
183
|
-
path: join(dir, file),
|
|
184
|
-
contents: replacePinnedHash({
|
|
185
|
-
contents: current,
|
|
186
|
-
currentHash: stage.satisfies.content_hash,
|
|
187
|
-
nextHash,
|
|
188
|
-
file,
|
|
189
|
-
}),
|
|
190
|
-
});
|
|
191
|
-
}
|
|
192
|
-
writes.push({
|
|
193
|
-
path: catalogPath,
|
|
194
|
-
contents: `${JSON.stringify(mergedContracts, null, 2)}\n`,
|
|
195
|
-
});
|
|
196
|
-
if (!dryRun) {
|
|
197
|
-
await commitFileWrites({ writes });
|
|
198
|
-
}
|
|
199
|
-
const changed = pinnedStages.filter((stage) => stage.satisfies.content_hash !== nextHashes.get(stage.stage)).length;
|
|
200
|
-
console.log(`${LOG} ${dryRun ? 'would repin' : 'repinned'} ${changed} of ${pinnedStages.length} ORM contract pin(s) from ${env.name}`);
|
|
201
|
-
return 0;
|
|
202
|
-
}
|
|
203
|
-
catch (error) {
|
|
204
|
-
console.error(`${LOG} ORM repin failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
205
|
-
return 1;
|
|
206
|
-
}
|
|
207
|
-
}
|