@snack-ai/opencode 0.1.2 → 1.0.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/README.md CHANGED
@@ -1,11 +1,30 @@
1
1
  # @snack-ai/opencode
2
2
 
3
- Live metadata capture for [SNACK](https://github.com/Duck1201/snack), an OpenCode plugin that
4
- records what happened to each prompt — never what was in it.
3
+ Live metadata capture for [SNACK](https://github.com/Duck1201/snack) — an OpenCode plugin that
4
+ records what happened to each prompt, and never what was in it.
5
5
 
6
- ## You do not install this yourself
6
+ [English](#english) · [Português](#português)
7
7
 
8
- This package is registered in OpenCode's own configuration by the SNACK CLI:
8
+ ---
9
+
10
+ ## English
11
+
12
+ ### The friendly version
13
+
14
+ OpenCode already writes down what you did. This plugin watches it happen instead of reading about it
15
+ afterwards.
16
+
17
+ That difference matters more than it sounds. Some things simply do not survive to disk — a prompt
18
+ the provider refuses outright can leave no durable trace in OpenCode's own database, and a refusal
19
+ SNACK cannot see is a refusal it cannot learn from. The plugin catches those as they happen.
20
+
21
+ It is deliberately tiny. It appends one line of JSON per event to a private file and gets out of the
22
+ way. It never opens a database, never imports the SNACK CLI, never phones anywhere, and never —
23
+ under any failure — gets between you and your prompt.
24
+
25
+ ### You do not install this yourself
26
+
27
+ The SNACK CLI registers it in OpenCode's own configuration for you:
9
28
 
10
29
  ```bash
11
30
  npm install -g @snack-ai/cli
@@ -13,14 +32,13 @@ snack setup opencode --install-plugin
13
32
  ```
14
33
 
15
34
  Setup shows the exact configuration change before making it, keeps a backup, and does nothing until
16
- you confirm. `snack doctor` afterwards reports whether the registration is one SNACK can read.
35
+ you confirm. `snack doctor` afterwards tells you whether the registration is one SNACK can read.
17
36
 
18
- SNACK works without this plugin: it can read OpenCode's own database directly. The plugin adds what
19
- a database read cannot give you — outcomes observed as they happen, including restrictions that
20
- leave no durable trace, and optional prompt-size features that are computed and discarded rather
21
- than stored.
37
+ **SNACK works fine without it.** The CLI can read OpenCode's database directly, and that is the
38
+ default. The plugin is the upgrade: outcomes observed live, including the refusals that leave no
39
+ trace, and optional prompt-size features that are computed in memory and thrown away.
22
40
 
23
- ## What it writes
41
+ ### What it writes
24
42
 
25
43
  One line of JSON per event, appended to a private spool directory that setup configured, under a
26
44
  versioned schema (`spool-event-v1`) that both packages ship a byte-identical copy of. Every field is
@@ -38,25 +56,185 @@ With `--enable-prospective-analysis`, each prompt additionally carries a few non
38
56
  features: an estimated token count, a bucketed line count, a bucketed count of fenced code blocks,
39
57
  and how many files were attached. They are derived in memory from text the plugin never writes down.
40
58
 
41
- ## What it will not do
59
+ ### What it will not do
42
60
 
43
61
  **It will not break OpenCode.** Capture failures are swallowed, never thrown into the host, and
44
62
  never allowed to block a prompt. If the spool cannot be written, the plugin warns at most once a
45
- minute and OpenCode carries on as though it were not installed.
63
+ minute and OpenCode carries on exactly as if it were not installed. This is not best-effort
64
+ politeness; it is the plugin's first design constraint, and it is tested by faulting the write path
65
+ and asserting the host never sees an exception.
46
66
 
47
67
  **It will not read what it does not need.** It never opens SQLite, never imports the SNACK CLI, and
48
68
  never touches OpenCode's credentials. It writes to its own spool directory and nowhere else.
49
69
 
50
70
  **It will not guess.** An event that does not validate against the shipped schema is dropped rather
51
71
  than partially interpreted, because a canonical record built from a shape SNACK does not recognize
52
- would carry an invented meaning downstream.
72
+ would carry an invented meaning downstream for as long as it lived.
73
+
74
+ ---
75
+
76
+ ### Under the hood
77
+
78
+ #### The spool
79
+
80
+ Events are appended as NDJSON to segment files with `0600` permissions in a `0700` directory. Append
81
+ is the only write operation; nothing is ever rewritten in place, which is what makes a crash
82
+ mid-write recoverable rather than corrupting.
83
+
84
+ A line cut short by a crash is exactly what truncation recovery expects: the reader validates each
85
+ line, discards the incomplete one with a sanitized diagnostic, and keeps everything before it. The
86
+ count of refused records surfaces in `snack sync` as `rejected_invalid` rather than disappearing.
87
+
88
+ Segments are removed only after **every configured source has committed past them**. A cursor that
89
+ advanced without its transaction committing would silently drop history, so cursors move only inside
90
+ the committing transaction.
91
+
92
+ #### Reconciliation with backfill
93
+
94
+ The plugin and the database reader will both see most prompts. That is the intended arrangement, not
95
+ a bug to avoid, and SNACK reconciles the two into one canonical record by stable identity, revision
96
+ domain, and finality — never by trusting whichever arrived first.
97
+
98
+ Restrictions are unioned across both paths: a refusal seen by either observer counts. Conflicting
99
+ final revisions that cannot be ordered are excluded rather than resolved by guesswork. Property
100
+ tests assert convergence under duplicates, reordering, and gaps, because "eventually consistent"
101
+ without a proof is just hope.
102
+
103
+ #### Content-free by construction
104
+
105
+ The schema has no field that could carry prompt or response text, so leakage is a schema violation
106
+ rather than a policy failure. The privacy canaries are shared byte-identically between both packages
107
+ and driven through the capture path in tests; a canary reaching any written byte fails the build.
108
+
109
+ The provider's own error **code** is stored on purpose — it is what distinguishes a rate limit from
110
+ a timeout, and classifying that difference correctly is the entire reason SNACK does not treat your
111
+ flaky Wi-Fi as a quota event. The error _message_ is not stored.
112
+
113
+ ### Compatibility
114
+
115
+ Requires Node.js 24 and a `@snack-ai/cli` that accepts `spool-event-v1`. Event `schema_version` is
116
+ `1` and has been stable since the plugin's first release, so a current CLI reads any published
117
+ version of this plugin. `snack doctor` reports a registration pinned at an older version as outdated
118
+ rather than incompatible, and re-running `snack setup opencode --install-plugin` updates the pin.
119
+
120
+ Apache-2.0. Security reports go through the private channel in
121
+ [SECURITY.md](https://github.com/Duck1201/snack/blob/main/SECURITY.md).
122
+
123
+ ---
124
+
125
+ ## Português
126
+
127
+ ### A versão amigável
128
+
129
+ O OpenCode já anota o que você fez. Este plugin assiste isso acontecer, em vez de ler sobre depois.
130
+
131
+ Essa diferença importa mais do que parece. Algumas coisas simplesmente não sobrevivem até o disco —
132
+ um prompt que o provedor recusa de cara pode não deixar rastro durável no banco do próprio OpenCode,
133
+ e uma recusa que o SNACK não enxerga é uma recusa com a qual ele não aprende. O plugin pega essas no
134
+ ato.
135
+
136
+ Ele é propositalmente minúsculo. Acrescenta uma linha de JSON por evento num arquivo privado e sai
137
+ da frente. Nunca abre banco, nunca importa a CLI do SNACK, nunca liga para lugar nenhum, e nunca —
138
+ sob falha alguma — entra entre você e o seu prompt.
139
+
140
+ ### Você não instala isto por conta própria
141
+
142
+ A CLI do SNACK registra o plugin na configuração do próprio OpenCode para você:
143
+
144
+ ```bash
145
+ npm install -g @snack-ai/cli
146
+ snack setup opencode --install-plugin
147
+ ```
148
+
149
+ O setup mostra a mudança exata de configuração antes de fazê-la, guarda um backup, e não faz nada
150
+ até você confirmar. Depois, `snack doctor` diz se o registro é um que o SNACK consegue ler.
151
+
152
+ **O SNACK funciona bem sem ele.** A CLI lê o banco do OpenCode diretamente, e esse é o padrão. O
153
+ plugin é o upgrade: desfechos observados ao vivo, incluindo as recusas que não deixam rastro, e
154
+ features opcionais de tamanho de prompt calculadas em memória e descartadas.
155
+
156
+ ### O que ele escreve
157
+
158
+ Uma linha de JSON por evento, acrescentada a um diretório de spool privado que o setup configurou,
159
+ sob um schema versionado (`spool-event-v1`) do qual os dois pacotes carregam uma cópia
160
+ byte-idêntica. Todo campo é metadado:
161
+
162
+ - a qual prompt e sessão pertence, por identificador;
163
+ - o provedor e o modelo, e quando aconteceu;
164
+ - como terminou: completado, cancelado, um erro operacional, ou uma restrição observada e sua
165
+ classe;
166
+ - contagens de tokens e custo, como o provedor reportou.
167
+
168
+ Não existe campo para texto de prompt nem de resposta, e o schema recusa campos desconhecidos de
169
+ forma categórica.
170
+
171
+ Com `--enable-prospective-analysis`, cada prompt carrega também algumas features não semânticas de
172
+ formato: contagem estimada de tokens, contagem de linhas em faixas, contagem de blocos de código em
173
+ faixas, e quantos arquivos foram anexados. São derivadas em memória de um texto que o plugin nunca
174
+ escreve.
175
+
176
+ ### O que ele não vai fazer
177
+
178
+ **Não vai quebrar o OpenCode.** Falhas de captura são engolidas, nunca lançadas para dentro do host,
179
+ e nunca podem bloquear um prompt. Se o spool não puder ser escrito, o plugin avisa no máximo uma vez
180
+ por minuto e o OpenCode segue exatamente como se ele não estivesse instalado. Isso não é gentileza
181
+ de melhor-esforço; é a primeira restrição de projeto do plugin, e é testada injetando falha no
182
+ caminho de escrita e verificando que o host nunca vê exceção.
183
+
184
+ **Não vai ler o que não precisa.** Nunca abre SQLite, nunca importa a CLI do SNACK, nunca toca nas
185
+ credenciais do OpenCode. Escreve no seu próprio diretório de spool e em nenhum outro lugar.
186
+
187
+ **Não vai chutar.** Um evento que não valida contra o schema publicado é descartado em vez de
188
+ interpretado pela metade, porque um registro canônico construído a partir de um formato que o SNACK
189
+ não reconhece carregaria um significado inventado rio abaixo por todo o tempo em que existisse.
190
+
191
+ ---
192
+
193
+ ### Por dentro
194
+
195
+ #### O spool
196
+
197
+ Eventos são acrescentados como NDJSON em arquivos de segmento com permissão `0600` num diretório
198
+ `0700`. Acrescentar é a única operação de escrita; nada é reescrito no lugar, e é isso que torna uma
199
+ queda no meio da escrita recuperável em vez de corruptora.
200
+
201
+ Uma linha cortada por uma queda é exatamente o que a recuperação de truncamento espera: o leitor
202
+ valida cada linha, descarta a incompleta com um diagnóstico sanitizado, e mantém tudo que veio
203
+ antes. A contagem de registros recusados aparece no `snack sync` como `rejected_invalid` em vez de
204
+ sumir.
205
+
206
+ Segmentos só são removidos depois que **toda fonte configurada commitou além deles**. Um cursor que
207
+ avançasse sem sua transação commitar descartaria histórico em silêncio, então cursores só se movem
208
+ dentro da transação que commita.
209
+
210
+ #### Reconciliação com o backfill
211
+
212
+ O plugin e o leitor de banco vão ver a maioria dos prompts. Esse é o arranjo pretendido, não um bug
213
+ a evitar, e o SNACK reconcilia os dois num único registro canônico por identidade estável, domínio
214
+ de revisão e finalidade — nunca confiando em quem chegou primeiro.
215
+
216
+ Restrições são unidas entre os dois caminhos: uma recusa vista por qualquer observador conta.
217
+ Revisões finais conflitantes que não podem ser ordenadas são excluídas em vez de resolvidas no
218
+ chute. Testes de propriedade garantem convergência sob duplicatas, reordenação e lacunas, porque
219
+ "eventualmente consistente" sem prova é só esperança.
220
+
221
+ #### Livre de conteúdo por construção
222
+
223
+ O schema não tem campo capaz de carregar texto de prompt ou resposta, então vazamento é violação de
224
+ schema, não falha de política. As strings-canário de privacidade são compartilhadas byte a byte
225
+ entre os dois pacotes e empurradas pelo caminho de captura nos testes; um canário chegando a
226
+ qualquer byte escrito quebra o build.
227
+
228
+ O **código** de erro do provedor é armazenado de propósito — é o que distingue um rate limit de um
229
+ timeout, e classificar essa diferença corretamente é a razão inteira de o SNACK não tratar o seu
230
+ Wi-Fi instável como evento de quota. A _mensagem_ de erro não é armazenada.
53
231
 
54
- ## Compatibility
232
+ ### Compatibilidade
55
233
 
56
- Requires Node.js 24 and a `@snack-ai/cli` that accepts `spool-event-v1`. Every `0.1.x` of this
57
- plugin emits that contract, so a CLI on the MVP line reads any of them; `snack doctor` reports a
58
- registration pinned at a different `0.1.x` as outdated rather than incompatible, and re-running
59
- `snack setup opencode --install-plugin` updates the pin.
234
+ Requer Node.js 24 e uma `@snack-ai/cli` que aceite `spool-event-v1`. O `schema_version` do evento é
235
+ `1` e está estável desde a primeira release do plugin, então uma CLI atual lê qualquer versão
236
+ publicada dele. O `snack doctor` reporta um registro fixado numa versão antiga como desatualizado, e
237
+ não como incompatível; rodar `snack setup opencode --install-plugin` de novo atualiza o pin.
60
238
 
61
- Apache-2.0. Security reports go through the private channel described in
239
+ Apache-2.0. Relatos de segurança vão pelo canal privado descrito em
62
240
  [SECURITY.md](https://github.com/Duck1201/snack/blob/main/SECURITY.md).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snack-ai/opencode",
3
- "version": "0.1.2",
3
+ "version": "1.0.0",
4
4
  "description": "Fail-open OpenCode metadata capture for SNACK",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -23,21 +23,65 @@
23
23
  "restrictions"
24
24
  ],
25
25
  "properties": {
26
- "schema_version": { "const": 1 },
27
- "event_id": { "type": "string", "minLength": 1, "maxLength": 200 },
28
- "installation_id": { "type": "string", "minLength": 1, "maxLength": 200 },
29
- "event_type": { "enum": ["prompt_started", "session_idle", "session_error"] },
30
- "source_prompt_id": { "type": "string", "minLength": 1, "maxLength": 200 },
31
- "source_session_id": { "type": "string", "minLength": 1, "maxLength": 200 },
32
- "revision": { "type": "string", "minLength": 1, "maxLength": 200 },
33
- "revision_domain": { "const": "opencode-plugin-v1" },
34
- "parser_version": { "const": "opencode-plugin-v1" },
35
- "occurred_at": { "type": "string", "format": "date-time" },
36
- "provider": { "type": ["string", "null"], "maxLength": 100 },
37
- "model": { "type": ["string", "null"], "maxLength": 200 },
38
- "completion": { "enum": ["provisional", "completed"] },
39
- "outcome": { "enum": ["success", "restricted", "excluded"] },
40
- "usage_slices": { "type": "array", "maxItems": 0 },
26
+ "schema_version": {
27
+ "const": 1
28
+ },
29
+ "event_id": {
30
+ "type": "string",
31
+ "minLength": 1,
32
+ "maxLength": 200
33
+ },
34
+ "installation_id": {
35
+ "type": "string",
36
+ "minLength": 1,
37
+ "maxLength": 200
38
+ },
39
+ "event_type": {
40
+ "enum": ["prompt_started", "session_idle", "session_error"]
41
+ },
42
+ "source_prompt_id": {
43
+ "type": "string",
44
+ "minLength": 1,
45
+ "maxLength": 200
46
+ },
47
+ "source_session_id": {
48
+ "type": "string",
49
+ "minLength": 1,
50
+ "maxLength": 200
51
+ },
52
+ "revision": {
53
+ "type": "string",
54
+ "minLength": 1,
55
+ "maxLength": 200
56
+ },
57
+ "revision_domain": {
58
+ "const": "opencode-plugin-v1"
59
+ },
60
+ "parser_version": {
61
+ "const": "opencode-plugin-v1"
62
+ },
63
+ "occurred_at": {
64
+ "type": "string",
65
+ "format": "date-time"
66
+ },
67
+ "provider": {
68
+ "type": ["string", "null"],
69
+ "maxLength": 100
70
+ },
71
+ "model": {
72
+ "type": ["string", "null"],
73
+ "maxLength": 200
74
+ },
75
+ "completion": {
76
+ "enum": ["provisional", "completed"]
77
+ },
78
+ "outcome": {
79
+ "enum": ["success", "restricted", "excluded"]
80
+ },
81
+ "usage_slices": {
82
+ "type": "array",
83
+ "maxItems": 0
84
+ },
41
85
  "restrictions": {
42
86
  "type": "array",
43
87
  "maxItems": 20,
@@ -49,9 +93,18 @@
49
93
  "class": {
50
94
  "enum": ["rate_limit", "usage_limit", "capacity_policy", "other_explicit_limit"]
51
95
  },
52
- "source_code": { "type": "string", "minLength": 1, "maxLength": 100 },
53
- "observed_at": { "type": "string", "format": "date-time" },
54
- "classifier_version": { "const": "opencode-plugin-error-v1" }
96
+ "source_code": {
97
+ "type": "string",
98
+ "minLength": 1,
99
+ "maxLength": 100
100
+ },
101
+ "observed_at": {
102
+ "type": "string",
103
+ "format": "date-time"
104
+ },
105
+ "classifier_version": {
106
+ "const": "opencode-plugin-error-v1"
107
+ }
55
108
  }
56
109
  }
57
110
  },
@@ -66,53 +119,119 @@
66
119
  "attachment_count"
67
120
  ],
68
121
  "properties": {
69
- "analyzer_version": { "const": "opencode-input-v1" },
70
- "estimated_input_tokens": { "type": "integer", "minimum": 0 },
71
- "line_count_bucket": { "enum": ["0", "1-10", "11-50", "51-200", "201+"] },
72
- "code_block_count_bucket": { "enum": ["0", "1", "2-4", "5+"] },
73
- "attachment_count": { "type": "integer", "minimum": 0 }
122
+ "analyzer_version": {
123
+ "const": "opencode-input-v1"
124
+ },
125
+ "estimated_input_tokens": {
126
+ "type": "integer",
127
+ "minimum": 0
128
+ },
129
+ "line_count_bucket": {
130
+ "enum": ["0", "1-10", "11-50", "51-200", "201+"]
131
+ },
132
+ "code_block_count_bucket": {
133
+ "enum": ["0", "1", "2-4", "5+"]
134
+ },
135
+ "attachment_count": {
136
+ "type": "integer",
137
+ "minimum": 0
138
+ }
74
139
  }
75
140
  }
76
141
  },
77
142
  "allOf": [
78
143
  {
79
- "if": { "properties": { "event_type": { "const": "prompt_started" } } },
144
+ "if": {
145
+ "properties": {
146
+ "event_type": {
147
+ "const": "prompt_started"
148
+ }
149
+ },
150
+ "type": "object"
151
+ },
80
152
  "then": {
81
153
  "properties": {
82
- "completion": { "const": "provisional" },
83
- "outcome": { "const": "excluded" },
84
- "restrictions": { "maxItems": 0 }
85
- }
154
+ "completion": {
155
+ "const": "provisional"
156
+ },
157
+ "outcome": {
158
+ "const": "excluded"
159
+ },
160
+ "restrictions": {
161
+ "maxItems": 0,
162
+ "type": "array"
163
+ }
164
+ },
165
+ "type": "object"
86
166
  }
87
167
  },
88
168
  {
89
- "if": { "properties": { "event_type": { "const": "session_idle" } } },
169
+ "if": {
170
+ "properties": {
171
+ "event_type": {
172
+ "const": "session_idle"
173
+ }
174
+ },
175
+ "type": "object"
176
+ },
90
177
  "then": {
91
178
  "properties": {
92
- "completion": { "const": "completed" },
93
- "outcome": { "const": "success" },
94
- "restrictions": { "maxItems": 0 }
95
- }
179
+ "completion": {
180
+ "const": "completed"
181
+ },
182
+ "outcome": {
183
+ "const": "success"
184
+ },
185
+ "restrictions": {
186
+ "maxItems": 0,
187
+ "type": "array"
188
+ }
189
+ },
190
+ "type": "object"
96
191
  }
97
192
  },
98
193
  {
99
- "if": { "properties": { "event_type": { "const": "session_error" } } },
194
+ "if": {
195
+ "properties": {
196
+ "event_type": {
197
+ "const": "session_error"
198
+ }
199
+ },
200
+ "type": "object"
201
+ },
100
202
  "then": {
101
- "properties": { "completion": { "const": "completed" } },
203
+ "properties": {
204
+ "completion": {
205
+ "const": "completed"
206
+ }
207
+ },
102
208
  "oneOf": [
103
209
  {
104
210
  "properties": {
105
- "outcome": { "const": "restricted" },
106
- "restrictions": { "minItems": 1 }
107
- }
211
+ "outcome": {
212
+ "const": "restricted"
213
+ },
214
+ "restrictions": {
215
+ "minItems": 1,
216
+ "type": "array"
217
+ }
218
+ },
219
+ "type": "object"
108
220
  },
109
221
  {
110
222
  "properties": {
111
- "outcome": { "const": "excluded" },
112
- "restrictions": { "maxItems": 0 }
113
- }
223
+ "outcome": {
224
+ "const": "excluded"
225
+ },
226
+ "restrictions": {
227
+ "maxItems": 0,
228
+ "type": "array"
229
+ }
230
+ },
231
+ "type": "object"
114
232
  }
115
- ]
233
+ ],
234
+ "type": "object"
116
235
  }
117
236
  }
118
237
  ]