@spec-wave/cli 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spec-wave/cli",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Setup spec-driven GitHub workflow with Projects v2, labels, issue templates, and AI-powered Actions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -25,6 +25,17 @@
25
25
  "required": ["fileWrites", "pullRequests", "variables", "automation"],
26
26
  "additionalProperties": true,
27
27
  "properties": {
28
+ "fileReads": {
29
+ "type": "object",
30
+ "description": "Como um arquivo é LIDO. `readFile` é obrigatória e devolve TEXTO decodificado como UTF-8 — a decodificação é lossy, e ler um binário por ela não dá erro: dá mojibake, ou seja uma saída indistinguível da do caso feliz. `bytes: true` acrescenta `readFileBytes`, que devolve os bytes crus, e nesse caso `readFile` passa a ser exatamente ela decodificada, nunca uma segunda rota.\n\nCondicional e não obrigatória porque um SCM que só sirva documento de texto não precisa dela. Mas NÃO é particularidade de fornecedor — GitLab, Azure Repos e Bitbucket servem bytes igual —, e é por isso que ela é operação de contrato em vez de escape hatch do plugin. Ausente vale `false`: um plugin nunca ganha a operação por omissão.",
31
+ "additionalProperties": true,
32
+ "properties": {
33
+ "bytes": {
34
+ "type": "boolean",
35
+ "description": "Este SCM sabe devolver o conteúdo de um arquivo SEM decodificar. Quem precisa disso é evidência visual de QA (vídeo, imagem), que a spec-wave-ui lê. Nenhum comando da CLI lê binário hoje."
36
+ }
37
+ }
38
+ },
28
39
  "fileWrites": {
29
40
  "type": "object",
30
41
  "required": ["mode"],
@@ -137,7 +148,7 @@
137
148
  },
138
149
  "operations": {
139
150
  "type": "array",
140
- "description": "⚠️ OPCIONAL E NÃO NORMATIVA desde a Fase 2 (bloco H), pela mesma razão do tracker: o loader NÃO lê este array — as funções da porta são a declaração, e uma lista paralela é uma segunda fonte que pode afirmar o que a chamada não encontra. Quem verifica é `scmRequiredOperations` + `checkScmPort`, sobre as funções reais. O campo fica como contrato LEGÍVEL (e `test/ports-conditional-parity.test.mjs` compara a prosa das CONDICIONAIS com as tabelas de runtime e com os marcadores `[op]` do JSDoc).\n\nOBRIGATÓRIAS SEMPRE: setup, verify, defaultBranch, isInitialized, readFile, writeFiles, deleteFile, branchHead, compare, deleteBranch, findOpenPullRequest, ensurePullRequest, getPullRequest, listPullRequestCommitMessages, listPullRequestReviews, listOpenPullRequests, mergePullRequest, closingKeyword, fileUrl, listAutomationRuns.\n\n`closingKeyword({ref, trackerKind, prLink, hubLink})` devolve a CLÁUSULA INTEIRA (`Closes #123`) quando SCM e tracker são o mesmo fornecedor, e `null` em qualquer outro caso — a decisão não é uma capability estática porque depende do PAR tracker+SCM, não só do SCM; ver `pullRequests.referenceSearch`. ⚠️ Assinatura corrigida na v1.1: `(ref, trackerKind)` não bastava. Com a RFC-005 (um hub, N repos de código) o PR de uma Story vive num repo e a issue vive no hub, e `closesRef()` (src/commands/implement.mjs:189) já emite hoje a forma QUALIFICADA `owner/repo#n`. Sem `prLink` e `hubLink` a operação não sabe se pode usar a forma curta — e a forma curta num repo de código fecha a issue errada, ou nenhuma.\n\n`fileUrl({link, ref, pathRel})` devolve a URL navegável de um arquivo numa ref. ⚠️ Acrescentada na v1.1: estava faltando, e sem ela `src/lib/repo-links.mjs` continua cravando `https://github.com/<owner>/<repo>/blob/<ref>/<path>` — string que entra em todo comentário de issue e corpo de PR que o fluxo gera. É a operação mais fácil de esquecer justamente porque a função que a implementa hoje é pura e parece neutra.\n\n`listAutomationRuns` devolve `[]` quando `automation: 'none'`, nunca lança. Nota: a CLI não lista runs hoje — quem o faz é a spec-wave-ui (`server/src/services/specReviewService.ts`), que portanto é a implementação de referência desta operação.\n\nCONDICIONAIS: markReadyForReview (pullRequests.draft); setPullRequestBase (pullRequests.retarget); findPullRequestsReferencing (pullRequests.referenceSearch); getVariable/setVariable/deleteVariable (variables: repo); installAutomation (automation != none); dispatch (remoteDispatch.mechanism != none).",
151
+ "description": "⚠️ OPCIONAL E NÃO NORMATIVA desde a Fase 2 (bloco H), pela mesma razão do tracker: o loader NÃO lê este array — as funções da porta são a declaração, e uma lista paralela é uma segunda fonte que pode afirmar o que a chamada não encontra. Quem verifica é `scmRequiredOperations` + `checkScmPort`, sobre as funções reais. O campo fica como contrato LEGÍVEL (e `test/ports-conditional-parity.test.mjs` compara a prosa das CONDICIONAIS com as tabelas de runtime e com os marcadores `[op]` do JSDoc).\n\nOBRIGATÓRIAS SEMPRE: setup, verify, defaultBranch, isInitialized, readFile, writeFiles, deleteFile, branchHead, compare, deleteBranch, findOpenPullRequest, ensurePullRequest, getPullRequest, listPullRequestCommitMessages, listPullRequestReviews, listOpenPullRequests, mergePullRequest, closingKeyword, fileUrl, listAutomationRuns.\n\n`closingKeyword({ref, trackerKind, prLink, hubLink})` devolve a CLÁUSULA INTEIRA (`Closes #123`) quando SCM e tracker são o mesmo fornecedor, e `null` em qualquer outro caso — a decisão não é uma capability estática porque depende do PAR tracker+SCM, não só do SCM; ver `pullRequests.referenceSearch`. ⚠️ Assinatura corrigida na v1.1: `(ref, trackerKind)` não bastava. Com a RFC-005 (um hub, N repos de código) o PR de uma Story vive num repo e a issue vive no hub, e `closesRef()` (src/commands/implement.mjs:189) já emite hoje a forma QUALIFICADA `owner/repo#n`. Sem `prLink` e `hubLink` a operação não sabe se pode usar a forma curta — e a forma curta num repo de código fecha a issue errada, ou nenhuma.\n\n`fileUrl({link, ref, pathRel})` devolve a URL navegável de um arquivo numa ref. ⚠️ Acrescentada na v1.1: estava faltando, e sem ela `src/lib/repo-links.mjs` continua cravando `https://github.com/<owner>/<repo>/blob/<ref>/<path>` — string que entra em todo comentário de issue e corpo de PR que o fluxo gera. É a operação mais fácil de esquecer justamente porque a função que a implementa hoje é pura e parece neutra.\n\n`listAutomationRuns` devolve `[]` quando `automation: 'none'`, nunca lança. Nota: a CLI não lista runs hoje — quem o faz é a spec-wave-ui (`server/src/services/specReviewService.ts`), que portanto é a implementação de referência desta operação.\n\nCONDICIONAIS: readFileBytes (fileReads.bytes); markReadyForReview (pullRequests.draft); setPullRequestBase (pullRequests.retarget); findPullRequestsReferencing (pullRequests.referenceSearch); getVariable/setVariable/deleteVariable (variables: repo); installAutomation (automation != none); dispatch (remoteDispatch.mechanism != none).",
141
152
  "items": { "type": "string", "pattern": "^[a-zA-Z][a-zA-Z0-9]*$" },
142
153
  "minItems": 1,
143
154
  "uniqueItems": true
@@ -627,7 +627,20 @@ export async function listPullRequestCommitMessages(token, owner, repo, prNumber
627
627
 
628
628
  // `ref` é opcional (compatível com os chamadores de 4 argumentos): o modo PR do
629
629
  // `update` precisa ler o .spec-wave.json na BASE, não no que a API escolher.
630
- export async function getFileContent(token, owner, repo, path, ref) {
630
+ /**
631
+ * Os BYTES de um arquivo, sem decodificar. `null` em 404.
632
+ *
633
+ * **É a única rota de leitura de arquivo.** Havia uma `getFileContent` que
634
+ * decodificava para UTF-8 aqui dentro (issue #140) — o ponto mais escondido
635
+ * possível, porque quem lesse o contrato da porta não tinha como saber que a
636
+ * camada HTTP decidia a codificação, e ler um binário devolvia mojibake sem
637
+ * erro nenhum.
638
+ *
639
+ * Ela foi APAGADA em vez de virar irmã desta: duas rotas para o mesmo arquivo
640
+ * divergem no dia em que uma ganhar cache, retry ou tratamento de `ref`. Quem
641
+ * quer texto usa `ScmPort.readFile`, que é esta função decodificada no plugin.
642
+ */
643
+ export async function getFileBytes(token, owner, repo, path, ref) {
631
644
  // Quiet: 404 é resultado esperado aqui (o arquivo pode não existir), e a linha
632
645
  // `GET ... - 404` no stderr parecia falha no meio da saída do `run`.
633
646
  const octokit = makeQuietOctokit(token);
@@ -635,7 +648,7 @@ export async function getFileContent(token, owner, repo, path, ref) {
635
648
  const res = await octokit.rest.repos.getContent({
636
649
  owner, repo, path, ...(ref ? { ref } : {}),
637
650
  });
638
- return Buffer.from(res.data.content, 'base64').toString('utf-8');
651
+ return Buffer.from(res.data.content, 'base64');
639
652
  } catch (err) {
640
653
  if (err.status === 404) return null;
641
654
  throw err;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "spec-wave",
3
3
  "displayName": "Spec Wave",
4
- "version": "1.5.0",
4
+ "version": "1.6.0",
5
5
  "description": "Fluxo spec-driven no GitHub (RFC-001): Projects v2, labels de gatilho, spec/plan gerados por Action, decomposição em duas etapas e implementação orientada a Stories/Tasks.",
6
6
  "author": {
7
7
  "name": "Astratech",
@@ -26,10 +26,11 @@ import {
26
26
  deleteFile,
27
27
  ensurePullRequest,
28
28
  getBranchHead,
29
- getFileContent,
29
+
30
30
  getPR,
31
31
  getRepoDefaultBranch,
32
32
  getRepoNodeId,
33
+ getFileBytes,
33
34
  getRepoVariable,
34
35
  deleteRepoVariable,
35
36
  // Diagnóstico do `verify({deep})` — bloco G leva 2.
@@ -68,6 +69,10 @@ export const SCM_KIND = 'github';
68
69
  * mutada em runtime seria um plugin ganhando poder depois da carga.
69
70
  */
70
71
  export const GITHUB_SCM_CAPABILITIES = Object.freeze({
72
+ // A Contents API devolve base64: os bytes estão lá, e decodificar é decisão de
73
+ // quem chama. Era exatamente o contrário — a coerção para UTF-8 morava dentro
74
+ // da camada HTTP, escondida de quem lia o contrato (issue #140).
75
+ fileReads: Object.freeze({ bytes: true }),
71
76
  fileWrites: Object.freeze({
72
77
  mode: 'tree-commit-ref',
73
78
  atomicMultiFile: true,
@@ -226,16 +231,19 @@ export function createGithubScm({ link, token, prToken, trackerKind = 'github-pr
226
231
 
227
232
  const a = {
228
233
  commitFilesToBranch, compareBranches, deleteBranch, deleteFile, ensurePullRequest,
229
- getBranchHead, getFileContent, getPR, getRepoDefaultBranch, getRepoNodeId,
234
+ getBranchHead, getPR, getRepoDefaultBranch, getRepoNodeId,
230
235
  getRepoVariable, deleteRepoVariable, isRepoInitialized, listPullRequestCommitMessages,
231
236
  listPullRequestReviews, mergePR, findOpenPR, setRepoVariable, updatePRBase, upsertFile,
232
237
  getPRClosingIssues, getRateLimit, listIssuePullRequests, listOpenPullRequests,
233
238
  markPullRequestReadyForReview,
234
239
  getRepoInfo, getRequiredStatusChecks, listActionsSecretNames,
235
- getActionsCanCreatePullRequests,
240
+ getActionsCanCreatePullRequests, getFileBytes,
236
241
  ...api,
237
242
  };
238
243
 
244
+ /** A única rota de leitura de arquivo — ver `readFile`/`readFileBytes`. */
245
+ const lerBytes = (p, ref) => a.getFileBytes(token, owner, repo, p, ref);
246
+
239
247
  return {
240
248
  kind: SCM_KIND,
241
249
  link,
@@ -331,8 +339,17 @@ export function createGithubScm({ link, token, prToken, trackerKind = 'github-pr
331
339
  return a.isRepoInitialized(token, owner, repo);
332
340
  },
333
341
 
334
- readFile({ path: p, ref } = {}) {
335
- return a.getFileContent(token, owner, repo, p, ref);
342
+ // TEXTO: é `readFileBytes` decodificado, e o contrato exige que seja isso e
343
+ // não uma segunda rota (issue #140). As duas saem da MESMA função local —
344
+ // com duas rotas independentes, a que ganhasse cache ou retry deixaria a
345
+ // outra para trás em silêncio.
346
+ async readFile({ path: p, ref } = {}) {
347
+ const bytes = await lerBytes(p, ref);
348
+ return bytes === null ? null : Buffer.from(bytes).toString('utf-8');
349
+ },
350
+
351
+ async readFileBytes({ path: p, ref } = {}) {
352
+ return lerBytes(p, ref);
336
353
  },
337
354
 
338
355
  writeFiles({ branch, base, files, message } = {}) {
package/src/ports/scm.mjs CHANGED
@@ -63,7 +63,32 @@
63
63
  * @property {() => Promise<string>} defaultBranch
64
64
  * @property {() => Promise<boolean>} isInitialized
65
65
  * @property {(o: {path: string, ref?: string}) => Promise<string|null>} readFile
66
- * `null` em 404 — é RESULTADO esperado (o documento pode não existir), não erro.
66
+ * **TEXTO, decodificado como UTF-8.** `null` em 404 — é RESULTADO esperado (o
67
+ * documento pode não existir), não erro.
68
+ *
69
+ * ⚠️ Ler um BINÁRIO por aqui não dá erro: dá mojibake. A decodificação é
70
+ * lossy e irreversível, e a saída do caso quebrado é indistinguível da do caso
71
+ * feliz — exatamente a degradação que o resto deste contrato persegue. Quem
72
+ * precisa dos bytes usa `readFileBytes`, e o plugin declara
73
+ * `fileReads.bytes: true` para oferecê-la.
74
+ *
75
+ * Onde `fileReads.bytes` é `true`, `readFile` **é** `readFileBytes`
76
+ * decodificado — não uma segunda rota. Isso é requisito e não coincidência:
77
+ * duas rotas independentes para o mesmo arquivo divergem no dia em que uma
78
+ * ganhar cache, retry ou tratamento de `ref` que a outra não tem.
79
+ * @property {(o: {path: string, ref?: string}) => Promise<Uint8Array|null>} [readFileBytes]
80
+ * Os BYTES, sem decodificação. `null` em 404, como `readFile`.
81
+ * *(fileReads.bytes)*
82
+ *
83
+ * Condicional, e não obrigatória, porque um SCM que só sirva documento de
84
+ * texto não deve precisar implementá-la. Mas **não é particularidade de
85
+ * fornecedor** — GitLab, Azure Repos e Bitbucket servem bytes igual —, e é por
86
+ * isso que ela é operação de contrato em vez de escape hatch do plugin.
87
+ *
88
+ * Quem a pediu foi a evidência visual de QA (vídeo e imagem), que a
89
+ * `spec-wave-ui` precisa ler. Nenhum comando da CLI lê binário hoje; o risco
90
+ * que ela fecha é o do PRÓXIMO plugin copiar a coerção do nosso `readFile` sem
91
+ * saber que ela existe, e embarcar arquivo corrompido sem sinal nenhum.
67
92
  * @property {(o: {branch: string, base: string, files: FileWrite[], message: string}) => Promise<CommitResult>} writeFiles
68
93
  * Atômico: N arquivos, um commit, ou nada. `fileWrites.mode`
69
94
  * (`tree-commit-ref` × `push`) é detalhe INTERNO do plugin.
@@ -131,6 +156,7 @@ export const SCM_REQUIRED_OPERATIONS = Object.freeze([
131
156
 
132
157
  /** @type {Readonly<Record<string, Readonly<string[]>>>} */
133
158
  export const SCM_CONDITIONAL_OPERATIONS = Object.freeze({
159
+ 'fileReads.bytes=true': Object.freeze(['readFileBytes']),
134
160
  'pullRequests.draft=true': Object.freeze(['markReadyForReview']),
135
161
  'pullRequests.retarget=true': Object.freeze(['setPullRequestBase']),
136
162
  'pullRequests.referenceSearch=true': Object.freeze(['findPullRequestsReferencing']),
@@ -149,7 +175,8 @@ export const SCM_CONDITIONAL_OPERATIONS = Object.freeze({
149
175
  * carregaria conforme e não saberia tirar PR de rascunho.
150
176
  */
151
177
  export const SCM_CAPABILITY_KEYS = Object.freeze([
152
- 'automation', 'fileWrites', 'identity', 'pullRequests', 'remoteDispatch', 'variables',
178
+ 'automation', 'fileReads', 'fileWrites', 'identity', 'pullRequests', 'remoteDispatch',
179
+ 'variables',
153
180
  ]);
154
181
 
155
182
  /**
@@ -162,6 +189,10 @@ export function scmRequiredOperations(capabilities = {}) {
162
189
  const exigidas = new Set(SCM_REQUIRED_OPERATIONS);
163
190
  const pr = capabilities.pullRequests || {};
164
191
  const ligada = {
192
+ // Ausente vale `false`, como toda capability: um plugin que não declara
193
+ // `fileReads.bytes` não ganha a operação por omissão, e o core tem de
194
+ // perguntar antes de oferecer.
195
+ 'fileReads.bytes=true': capabilities.fileReads?.bytes === true,
165
196
  'pullRequests.draft=true': pr.draft === true,
166
197
  'pullRequests.retarget=true': pr.retarget === true,
167
198
  'pullRequests.referenceSearch=true': pr.referenceSearch === true,