wetaca-cli 0.2.6 → 0.3.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/AGENTS.md CHANGED
@@ -18,6 +18,7 @@ Non-negotiable rules when acting on a real account:
18
18
  2. Mutations require an explicit summary → confirmation. In non-interactive runs pass `--yes` ONLY when the user asked for that exact operation.
19
19
  3. Prefer `--dry-run` before any mutation that supports it.
20
20
  4. Never touch payments (the CLI cannot either).
21
+ 5. When a command fails with exit 1/6/7, `wetaca report show` (redacted report) and, if the user agrees, `wetaca report create --yes` to file the issue. `report` needs no Wetaca session.
21
22
 
22
23
  ## Working on this codebase
23
24
 
@@ -27,5 +28,11 @@ Non-negotiable rules when acting on a real account:
27
28
  - Contract: every command returns JSON on stdout (pretty/jsonl optional), errors as JSON on stderr with `--error-format json`, stable exit codes (0 ok, 1 unexpected, 2 usage, 3 auth, 4 network, 5 not found, 6 API, 7 contract drift). See `docs/cli-spec.md`.
28
29
  - Mutations must follow the existing pattern: build payload → honor `--dry-run` → `confirm(flags, summary)` unless `--yes` → call `gql()`.
29
30
  - After changing `src/guide.js`, regenerate `docs/agent-guide.md` (they must stay identical).
30
- - Check syntax before committing: `node --check` on every touched file. CI runs the same checks plus smoke tests and cookie-parser tests.
31
+ - Check syntax before committing: `node --check` on every touched file. CI runs the same checks plus
32
+ `npm test` (`node --test test/*.test.mjs`: redaction, argv scrubbing, fingerprints, the report body,
33
+ the error cache and the full `report create` flow against a local GitHub API stub).
34
+ - `report` conventions: keep it dependency-free and offline-safe; every new field that can carry user
35
+ data must pass through `redact()`; never add a code path that posts to GitHub without the
36
+ confirmation step unless `--yes` was passed explicitly; new secrets/PII shapes belong in
37
+ `REDACTIONS` **and** in a test.
31
38
  - Releases: `npm version patch && git push --follow-tags`. The GitHub Actions `Publish to npm` workflow stages the package (`npm stage publish`, OIDC trusted publishing, no token); a maintainer approves it with `npm stage approve <id> --otp <code>`.
package/README.md CHANGED
@@ -38,6 +38,28 @@ wetaca skills get wetaca-usage
38
38
 
39
39
  A portable skill file is also available at [`skill/SKILL.md`](skill/SKILL.md) for platforms with skill directories (Hermes: `hermes skills install https://raw.githubusercontent.com/gorgueugr/wetaca-cli/master/skill/SKILL.md`).
40
40
 
41
+ ## Report a bug (agents included)
42
+
43
+ Every real failure is cached locally with secrets and personal data stripped, so an agent can turn
44
+ "it broke" into a usable issue without ever seeing the user's credentials:
45
+
46
+ ```
47
+ wetaca report show # title + body + pre-filled GitHub URL (no credentials needed)
48
+ wetaca report last # the stored failure, raw
49
+ wetaca report create --yes # files the issue via `gh auth token` / GITHUB_TOKEN
50
+ ```
51
+
52
+ - Redaction happens before anything is written: session JWTs, cookies, `authorization` headers,
53
+ GitHub/npm tokens, e-mail addresses, phone numbers, street addresses, and the values of
54
+ `--token --refresh-token --street --city --zipcode --code` never reach the report.
55
+ - **Deduped by fingerprint**: the same failure always hashes to the same `wf-…` id, so a second run
56
+ returns the open issue (`mode: "existing"`) instead of a duplicate. `--force` files anyway.
57
+ - No GitHub credential? `wetaca report show --open` opens the pre-filled form, and `report_path`
58
+ in the JSON holds the full markdown.
59
+ - `--doctor` attaches `wetaca doctor`, `--notes "…"` adds context, `--error-file F` reports an error
60
+ captured elsewhere (`wetaca … --error-format json 2> err.json`).
61
+ - `report` needs no Wetaca session.
62
+
41
63
  ## Get started
42
64
 
43
65
  ```
@@ -82,6 +104,7 @@ wetaca skills get wetaca-usage
82
104
  | [Extracted operations](docs/api-operations/) | the ~190 GraphQL documents from Wetaca's website |
83
105
  | [Agent guide](docs/agent-guide.md) | `wetaca skills get wetaca-usage` |
84
106
  | [Agent skill](skill/SKILL.md) | portable SKILL.md for skill hubs (Hermes, Claude Code, OpenCode...) |
107
+ | [Spanish guide](docs/GUIA.md) | day-to-day recipes in Spanish |
85
108
 
86
109
  ## Good to know
87
110
 
package/bin/wetaca.js CHANGED
@@ -2,6 +2,7 @@
2
2
  // wetaca-cli — entry point: arg parsing, dispatch, help, error handling.
3
3
  import { CliError, EXIT, printError, loadConfig, configPath, VERSION } from '../src/lib.js';
4
4
  import * as C from '../src/commands.js';
5
+ import { reportCmd, recordLastError } from '../src/report.js';
5
6
  import { GUIDE } from '../src/guide.js';
6
7
 
7
8
  const HELP = `wetaca-cli ${VERSION} — your Wetaca from the terminal.
@@ -39,6 +40,12 @@ COMMANDS
39
40
  wallet show
40
41
  config path | list | get <k> | set <k> <v>
41
42
  doctor diagnostics (node, network, session)
43
+ report show | last | create turn the last failure into a GitHub issue
44
+ show: redacted report + a pre-filled issue URL (no credentials needed)
45
+ last: the stored failure (raw, still redacted)
46
+ create [--yes]: files the issue with gh/GITHUB_TOKEN, deduped by fingerprint
47
+ flags: --title T --notes "..." --expected "..." --repo O/R --error-file F
48
+ --doctor (attach doctor output) --open (open the issue/URL) --force
42
49
  skills get wetaca-usage AI-agent guide (embedded)
43
50
  completion bash | zsh | fish autocompletion script
44
51
 
@@ -58,7 +65,7 @@ GLOBAL FLAGS
58
65
 
59
66
  const COMPLETION = {
60
67
  bash: `_wetaca() {
61
- local cur prev nouns="auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor skills completion"
68
+ local cur prev nouns="auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor report skills completion"
62
69
  COMPREPLY=()
63
70
  cur="\${COMP_WORDS[COMP_CWORD]}"
64
71
  if [ "$COMP_CWORD" -eq 1 ]; then COMPREPLY=( $(compgen -W "$nouns" -- "$cur") ); fi
@@ -66,16 +73,18 @@ const COMPLETION = {
66
73
  }
67
74
  complete -F _wetaca wetaca`,
68
75
  zsh: `#compdef wetaca
69
- _wetaca() { _alternative 'args:command:(auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor skills completion)' }
76
+ _wetaca() { _alternative 'args:command:(auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor report skills completion)' }
70
77
  _wetaca "$@"`,
71
- fish: `complete -c wetaca -n '__fish_use_subcommand' -a 'auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor skills completion'`,
78
+ fish: `complete -c wetaca -n '__fish_use_subcommand' -a 'auth me subscription suggestion deliveries orders addresses vouchers wallet config doctor report skills completion'`,
72
79
  };
73
80
 
74
81
  // ---------- flag parsing ----------
75
- const BOOL_FLAGS = new Set(['yes', 'no-input', 'dry-run', 'debug', 'no-color', 'help', 'version', 'clipboard', 'cookies-stdin']);
82
+ const BOOL_FLAGS = new Set(['yes', 'no-input', 'dry-run', 'debug', 'no-color', 'help', 'version', 'clipboard', 'cookies-stdin',
83
+ 'open', 'force', 'doctor']);
76
84
  const VALUE_FLAGS = new Set(['format', 'error-format', 'profile', 'token', 'refresh-token', 'cookies',
77
85
  'weeks', 'feedback', 'set', 'limit', 'offset', 'suggestion', 'profile-suggestion', 'resume', 'code', 'state',
78
- 'street', 'number', 'floor', 'zipcode', 'city', 'notes', 'firstname', 'lastname', 'phone']);
86
+ 'street', 'number', 'floor', 'zipcode', 'city', 'notes', 'firstname', 'lastname', 'phone',
87
+ 'title', 'expected', 'repo', 'error-file', 'command']);
79
88
 
80
89
  function parseArgs(argv) {
81
90
  const flags = {}, positional = [];
@@ -219,6 +228,9 @@ async function main() {
219
228
  case 'doctor':
220
229
  result = await C.doctor(args, flags, ctx);
221
230
  break;
231
+ case 'report':
232
+ result = await reportCmd(verb, args, flags, ctx, { doctor: C.doctor, confirm: C.confirm });
233
+ break;
222
234
  case 'skills':
223
235
  if (verb === 'get' && args[0] === 'wetaca-usage') { process.stdout.write(GUIDE); return 0; }
224
236
  if (verb === 'list') { result = { skills: [{ id: 'wetaca-usage', description: 'AI-agent usage guide' }] }; break; }
@@ -250,6 +262,9 @@ main()
250
262
  const { flags } = parseArgs(process.argv.slice(2));
251
263
  const errorFormat = flags['error-format'] === 'json' ? 'json' : 'text';
252
264
  const debug = flags.debug === true;
265
+ // Keep the last failure on disk so `wetaca report` can turn it into an issue
266
+ // (secrets and personal data are redacted before it is written).
267
+ recordLastError(err);
253
268
  if (err instanceof CliError) {
254
269
  printError(err, errorFormat, debug);
255
270
  process.exitCode = err.exitCode;
package/docs/GUIA.md CHANGED
@@ -106,6 +106,24 @@ JSON on stdout, JSON errors with `--error-format json`, stable exit codes
106
106
 
107
107
  Golden rule for agents: read a lot, write little, and show a summary before `--yes`.
108
108
 
109
+ ### Reportar un fallo (para agentes y humanos)
110
+
111
+ El CLI guarda el último fallo real en `~/.config/wetaca-cli/last-error.json`, ya redactado:
112
+
113
+ ```bash
114
+ wetaca report show # título + cuerpo + URL de issue prerellenada (sin credenciales)
115
+ wetaca report show --open # abre el formulario de GitHub en el navegador
116
+ wetaca report create --yes # crea el issue con `gh auth token` o GITHUB_TOKEN
117
+ ```
118
+
119
+ - Se redactan antes de escribir nada: JWT de sesión, cookies, cabeceras `authorization`, tokens de
120
+ GitHub/npm, correos, teléfonos, direcciones y los valores de `--token --street --city --zipcode --code`.
121
+ - Mismo fallo → mismo fingerprint `wf-…` → reutiliza el issue abierto (`mode: "existing"`) en vez de duplicarlo.
122
+ - `--doctor` adjunta la salida de `wetaca doctor`; `--notes "…"` añade contexto (no metas datos de la cuenta).
123
+ - `report` no necesita sesión de Wetaca. Sin credencial de GitHub: `report show --open` y pega el
124
+ contenido de `report_path`.
125
+
126
+
109
127
  Automation ideas (cron):
110
128
  - Every Thursday: `suggestion show` → summary via Telegram → you reply with changes → agent applies them with `--yes`.
111
129
  - Every Wednesday: if `suggestion show | jq -r .validUntil` is close and `skip=false`, send a reminder to decide on pausing.
@@ -22,7 +22,24 @@ Every command returns JSON on stdout by default; errors go to stderr.
22
22
  - Stable exit codes: 0 ok · 1 unexpected · 2 usage/validation/confirmation denied · 3 auth ·
23
23
  4 network · 5 not found · 6 the API rejected the operation · 7 contract drift (schema changed).
24
24
  - `reason: "auth_required"` → nothing to retry; the user must log in.
25
- - `reason: "contract_drift"` → don't reinvent the query; open an issue on the repo.
25
+ - `reason: "contract_drift"` → don't reinvent the query; file a report: `wetaca report show` → `wetaca report create --yes`.
26
+
27
+ ## Reporting a bug (exit 1/6/7)
28
+
29
+ The CLI keeps the last real failure (redacted) on disk. `wetaca report show` turns it into a
30
+ GitHub issue: title, repro command, environment, error JSON and the failing project frames.
31
+ No Wetaca session is needed for this.
32
+
33
+ 1. `wetaca report show` — inspect the body. It is already redacted: tokens, cookies, e-mail,
34
+ phone numbers, street addresses and the values of `--token/--street/--city/--zipcode/--code`
35
+ never reach the report.
36
+ 2. `wetaca report create --yes` — opens the issue on github.com/gorgueugr/wetaca-cli using
37
+ `gh auth token` or `GITHUB_TOKEN`. Identical failures are deduped by fingerprint
38
+ (`mode: "existing"` + the open issue instead of a duplicate).
39
+ 3. Without a credential: `wetaca report show --open` opens the pre-filled GitHub form;
40
+ `report_path` in the JSON is the full markdown to paste.
41
+
42
+ Ask the user before filing an issue on their behalf. Never paste account data into `--notes`.
26
43
 
27
44
  ## Rules for operations with real effects
28
45
 
@@ -68,6 +85,7 @@ Every command returns JSON on stdout by default; errors go to stderr.
68
85
  wetaca wallet
69
86
  wetaca config path | list | get <k> | set <k> <v>
70
87
  wetaca doctor
88
+ wetaca report show | last | create [--yes] last failure -> GitHub issue (redacted)
71
89
  wetaca skills get wetaca-usage this guide
72
90
 
73
91
  ## Typical flows
package/docs/cli-spec.md CHANGED
@@ -44,6 +44,9 @@ vouchers list
44
44
  wallet show
45
45
  config path | list | get <k> | set <k> <v>
46
46
  doctor
47
+ report show | last | create [--yes] [--title T] [--notes S] [--expected S]
48
+ [--repo OWNER/REPO] [--error-file F] [--command "noun verb"]
49
+ [--doctor] [--open] [--force] [--dry-run]
47
50
  skills list | get wetaca-usage
48
51
  completion bash | zsh | fish
49
52
  ```
@@ -111,3 +114,47 @@ is unvalidated), new account sign-up with SMS, Google OAuth, weekly survey, acti
111
114
  - The `productId`/`profileSuggestionId` ids are internal; they are obtained from `suggestion show`/`deliveries next`.
112
115
  - The price is returned in cents (the `*Eur` field is already formatted in some responses).
113
116
  - `subscription pause` uses `cancelSubscriptionAccount` with `pausedWeeks`; the API treats it as a temporary pause. Without `--weeks` it is an indefinite pause; reactivate with `subscription resume`.
117
+
118
+ ## 11. Report (`wetaca report`)
119
+
120
+ Turns the last real failure into a GitHub issue, for people and for agents. Needs **no Wetaca session**.
121
+
122
+ **Cache.** Every command that fails with a non-usage error writes `<config>/last-error.json` (0600):
123
+ `{ at, command, argv, cli_version, node, platform, error: { code, category, reason, retryable, message,
124
+ suggested_commands, details?, stack_frames[] } }`. Usage errors, declined confirmations and
125
+ `wetaca report` itself never overwrite it. `WETACA_REPORT_CACHE=0` disables the cache.
126
+ `stack_frames` keeps only frames inside `src/` or `bin/` (`file.js:line`), so it never carries the
127
+ user's paths.
128
+
129
+ **Redaction** runs before anything is written, in the cache and in the report: session JWTs,
130
+ `authorization` headers, `Bearer`/`GitHub`/`npm` tokens, cookie pairs (`refresh-token=…`),
131
+ e-mail addresses, phone numbers (with or without separators), Spanish street lines, postal
132
+ code + city, `$HOME`/`C:\Users\…` paths, and the values of
133
+ `--token --refresh-token --cookies --password --code --street --number --floor --zipcode --city
134
+ --notes --firstname --lastname --phone --email`. Positional names in `profiles pause|resume`,
135
+ `vouchers apply` and `giftcards redeem` are replaced by `«redacted»`; numeric ids are kept.
136
+ `--notes` / `--expected` are user text and are appended **without** redaction: never put account
137
+ data there.
138
+
139
+ **Fingerprint**: `wf-` + the first 10 hex of sha256 over `command | reason | message` after
140
+ lower-casing, replacing ids/digit runs with `#` and truncating to 160 chars. Version-independent, so
141
+ the same failure across releases dedupes to one issue.
142
+
143
+ **Verbs and output.**
144
+ - `show` (default): writes `<config>/reports/report-<fingerprint>.md` and returns
145
+ `{ ok, mode: "manual", fingerprint, title, body, redactions, report_path, repo, issue_url, opened, next }`.
146
+ `issue_url` is the pre-filled `https://github.com/<repo>/issues/new?title=…&body=…&labels=bug`
147
+ (body capped at 6000 chars in the URL; the file always has the whole report).
148
+ - `last`: `{ ok, hasError, path, ...storedRecord }`.
149
+ - `create`: needs a GitHub credential — `GITHUB_TOKEN`/`GH_TOKEN`/`WETACA_REPORT_TOKEN`, else
150
+ `gh auth token`. No credential → exit 3 (`github_auth_required`) with `suggested_commands`.
151
+ Searches `repo:<repo> is:issue in:body "wetaca-report-fingerprint: <fp>"` first and returns
152
+ `mode: "existing"` when the fingerprint is already open (`--force` bypasses). Confirmation shows
153
+ the exact public body unless `--yes`. Returns `{ ok, mode: "created", issue: { number, url, state, labels } }`.
154
+ - `--dry-run` on `create` returns `wouldSend: { repo, title, body, labels }` and performs no network call.
155
+ - Flags: `--title`, `--notes`, `--expected`, `--repo OWNER/REPO` (default: the package's own repo;
156
+ env `WETACA_REPORT_REPO`), `--error-file FILE` (JSON error wrapper from
157
+ `--error-format json`), `--command "noun verb"`, `--doctor`, `--open`, `--force`.
158
+ - `WETACA_GITHUB_API` (or `GITHUB_API_URL`) overrides `https://api.github.com` — GHES and tests.
159
+ - GitHub errors: 401/403 → exit 3 (`github_auth`), 404 → exit 5, other → exit 6
160
+ (`github_http_<status>`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wetaca-cli",
3
- "version": "0.2.6",
3
+ "version": "0.3.0",
4
4
  "description": "Manage your Wetaca from the terminal: subscription, weekly menu, deliveries and orders. Built for people and AI agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -42,5 +42,8 @@
42
42
  "engines": {
43
43
  "node": ">=18"
44
44
  },
45
+ "scripts": {
46
+ "test": "node --test test/*.test.mjs"
47
+ },
45
48
  "license": "MIT"
46
49
  }
package/skill/SKILL.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: wetaca-usage
3
3
  description: Use when the user asks about Wetaca meals or deliveries.
4
- version: 0.2.4
4
+ version: 0.3.0
5
5
  author: Jorge Soler Padial (https://github.com/gorgueugr)
6
6
  license: MIT
7
7
  metadata:
@@ -35,5 +35,17 @@ Every command returns JSON on stdout by default (`--format pretty` for humans);
35
35
  3. Use `--dry-run` on `suggestion edit`, `addresses save`, `deliveries set-option`, `orders cancel` before any real run.
36
36
  4. Never touch payments — the CLI does not either.
37
37
  5. `reason: "auth_required"` → the user must run `wetaca auth login` (cookie-based; no password involved).
38
+ 6. If a command fails with exit 1/6/7, `wetaca report show` renders a redacted bug report (no session needed) and `wetaca report create --yes` files it on GitHub, deduped by fingerprint. Ask the user first; never paste account data into `--notes`.
39
+
40
+ ## Report a bug
41
+
42
+ Every real failure is cached on disk already redacted (tokens, cookies, e-mails, phones, addresses
43
+ and the values of `--token/--street/--city/--zipcode/--code` are removed). `wetaca report` turns it
44
+ into an issue: title, repro command, environment, error JSON and the failing project frames.
45
+
46
+ - `wetaca report show` → body + pre-filled GitHub URL, no credentials needed.
47
+ - `wetaca report create --yes` → files it via `gh auth token`/`GITHUB_TOKEN`; returns
48
+ `mode: "created"` with the issue, or `mode: "existing"` when the same fingerprint is already open.
49
+ - No GitHub credential → exit 3 with `suggested_commands` (`gh auth login`, `report show --open`).
38
50
 
39
51
  Project source: https://github.com/gorgueugr/wetaca-cli
package/src/commands.js CHANGED
@@ -57,7 +57,7 @@ export function extractRefreshToken(text) {
57
57
  return null;
58
58
  }
59
59
 
60
- async function confirm(flags, summary) {
60
+ export async function confirm(flags, summary) {
61
61
  if (flags.yes) return;
62
62
  if (flags.noInput || !process.stdin.isTTY) {
63
63
  throw usageError(
@@ -74,7 +74,7 @@ async function confirm(flags, summary) {
74
74
  }
75
75
 
76
76
  function requireId(v, what) {
77
- if (!v) throw usageError(`Missing <${what}>.`);
77
+ if (!v) throw usageError(`Missing <${String(what).replace(/[<>]/g, '')}>.`);
78
78
  return v;
79
79
  }
80
80
 
package/src/guide.js CHANGED
@@ -23,7 +23,24 @@ Every command returns JSON on stdout by default; errors go to stderr.
23
23
  - Stable exit codes: 0 ok · 1 unexpected · 2 usage/validation/confirmation denied · 3 auth ·
24
24
  4 network · 5 not found · 6 the API rejected the operation · 7 contract drift (schema changed).
25
25
  - \`reason: "auth_required"\` → nothing to retry; the user must log in.
26
- - \`reason: "contract_drift"\` → don't reinvent the query; open an issue on the repo.
26
+ - \`reason: "contract_drift"\` → don't reinvent the query; file a report: \`wetaca report show\` → \`wetaca report create --yes\`.
27
+
28
+ ## Reporting a bug (exit 1/6/7)
29
+
30
+ The CLI keeps the last real failure (redacted) on disk. \`wetaca report show\` turns it into a
31
+ GitHub issue: title, repro command, environment, error JSON and the failing project frames.
32
+ No Wetaca session is needed for this.
33
+
34
+ 1. \`wetaca report show\` — inspect the body. It is already redacted: tokens, cookies, e-mail,
35
+ phone numbers, street addresses and the values of \`--token/--street/--city/--zipcode/--code\`
36
+ never reach the report.
37
+ 2. \`wetaca report create --yes\` — opens the issue on github.com/gorgueugr/wetaca-cli using
38
+ \`gh auth token\` or \`GITHUB_TOKEN\`. Identical failures are deduped by fingerprint
39
+ (\`mode: "existing"\` + the open issue instead of a duplicate).
40
+ 3. Without a credential: \`wetaca report show --open\` opens the pre-filled GitHub form;
41
+ \`report_path\` in the JSON is the full markdown to paste.
42
+
43
+ Ask the user before filing an issue on their behalf. Never paste account data into \`--notes\`.
27
44
 
28
45
  ## Rules for operations with real effects
29
46
 
@@ -69,6 +86,7 @@ Every command returns JSON on stdout by default; errors go to stderr.
69
86
  wetaca wallet
70
87
  wetaca config path | list | get <k> | set <k> <v>
71
88
  wetaca doctor
89
+ wetaca report show | last | create [--yes] last failure -> GitHub issue (redacted)
72
90
  wetaca skills get wetaca-usage this guide
73
91
 
74
92
  ## Typical flows
package/src/report.js ADDED
@@ -0,0 +1,547 @@
1
+ // wetaca-cli — `report`: turn a failure into a ready-to-send GitHub issue.
2
+ // Design rules for this module:
3
+ // - never send a secret (token, cookie, refresh-token) — redact before anything is stored;
4
+ // - never send personal data (email, phone, address, profile name) — redact + scrub argv;
5
+ // - never need a Wetaca session: `report` works offline, from the last stored error;
6
+ // - never publish without consent: `create` confirms and requires a GitHub credential.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import os from 'node:os';
10
+ import crypto from 'node:crypto';
11
+ import child_process from 'node:child_process';
12
+ import { createRequire } from 'node:module';
13
+ import { CliError, EXIT, VERSION, configDir, loadCreds, usageError } from './lib.js';
14
+
15
+ const require = createRequire(import.meta.url);
16
+ const PKG = require('../package.json');
17
+ const REPO_DEFAULT = (() => {
18
+ const m = String(PKG.repository?.url || '').match(/github\.com[:/]([^/]+)\/([^/.]+)/);
19
+ return m ? `${m[1]}/${m[2]}` : 'gorgueugr/wetaca-cli';
20
+ })();
21
+
22
+ const MARKER = 'wetaca-report-fingerprint';
23
+ const REDACTED = '«redacted»';
24
+ const MAX_BODY = 14000;
25
+
26
+ // ---------- redaction ----------
27
+
28
+ // Long strings that look like credentials in any shape we have seen in the wild:
29
+ // session JWTs, authorization headers, GitHub/npm tokens, cookie pairs, and the
30
+ // values of the flags that carry secrets or personal data. Several entries are
31
+ // functions because a replacer *function* does not expand `$1` in its return value.
32
+ const REDACTIONS = [
33
+ [/eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}/g, () => REDACTED],
34
+ [/authorization:\s*(?:bearer|token)\s+\S+/gi, () => `authorization: ${REDACTED}`],
35
+ [/\b(bearer)\s+[A-Za-z0-9._~+/=-]{8,}/gi, (m, p1) => `${p1} ${REDACTED}`],
36
+ [/\b(gh[pousr]_[A-Za-z0-9]{20,}|npm_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, () => REDACTED],
37
+ [/\b((?:refresh-token|auth-token|customer-token|token-voucher-pending)=)[^;\s"']+/gi, (m, p1) => `${p1}${REDACTED}`],
38
+ [/(--(?:token|refresh-token|cookies|password|code)\s+)(?:"[^"]*"|'[^']*'|\S+)/gi, (m, p1) => `${p1}${REDACTED}`],
39
+ [/(--(?:street|number|floor|zipcode|city|notes|firstname|lastname|phone|email)=)[^\s]+/gi, (m, p1) => `${p1}${REDACTED}`],
40
+ [/[\w.+-]+@[\w-]+\.[\w.-]{2,}/g, () => 'user@example.com'],
41
+ // phone numbers with or without separators (+34 612 345 678)
42
+ [/(?:\+34[\s.-]?)?\b[6789]\d{2}[\s.-]?\d{3}[\s.-]?\d{3}\b/g, () => '«phone»'],
43
+ // Spanish street lines: "Calle Mayor 3", "Av. de la Constitución 12"
44
+ [/\b(?:Calle|C\/|Avenida|Av\.|Plaza|Paseo|Camino|Rúa|Carrer|Ctra\.)\s+[^,.;\n«»]{2,40}/gi, () => '«street»'],
45
+ // postal code followed by a city name ("18006 Granada")
46
+ [/\b\d{5}\s+[A-ZÁÉÍÓÚÑ][a-záéíóúñ]{2,}/g, () => '«zip city»'],
47
+ [/\b[A-Za-z0-9_-]{40,}\b/g, () => REDACTED],
48
+ ];
49
+
50
+ function scrubPaths(s) {
51
+ const home = os.homedir();
52
+ if (home && home.length > 3) s = s.split(home).join('~');
53
+ return s.replace(/\b[A-Za-z]:\\Users\\[^\\\s"']+/gi, 'C:\\Users\\~');
54
+ }
55
+
56
+ // Redacts one string; returns { value, count }.
57
+ function redactString(input) {
58
+ let s = String(input);
59
+ let count = 0;
60
+ for (const [re, to] of REDACTIONS) {
61
+ s = s.replace(re, (...args) => {
62
+ count++;
63
+ return typeof to === 'function' ? to(...args) : to;
64
+ });
65
+ }
66
+ return { value: scrubPaths(s), count };
67
+ }
68
+
69
+ // Deep redaction with a size cap. Returns { value, count }.
70
+ export function redact(input) {
71
+ let count = 0;
72
+ const walk = (v, depth) => {
73
+ if (v == null) return v;
74
+ if (typeof v === 'string') {
75
+ const r = redactString(v.length > 4000 ? v.slice(0, 4000) + '…' : v);
76
+ count += r.count;
77
+ return r.value;
78
+ }
79
+ if (typeof v === 'number' || typeof v === 'boolean') return v;
80
+ if (depth > 5) return '«deep»';
81
+ if (Array.isArray(v)) return v.slice(0, 40).map((x) => walk(x, depth + 1));
82
+ if (typeof v === 'object') {
83
+ const out = {};
84
+ for (const [k, x] of Object.entries(v).slice(0, 60)) out[k] = walk(x, depth + 1);
85
+ return out;
86
+ }
87
+ return String(v);
88
+ };
89
+ const value = walk(input, 0);
90
+ return { value, count };
91
+ }
92
+
93
+ // ---------- argv scrubbing ----------
94
+
95
+ const SECRET_FLAGS = new Set(['token', 'refresh-token', 'cookies', 'password', 'code',
96
+ 'street', 'number', 'floor', 'zipcode', 'city', 'notes', 'firstname', 'lastname', 'phone', 'email']);
97
+ // Positional args that are not ids but names / codes.
98
+ const NAME_POSITIONALS = {
99
+ profiles: ['pause', 'resume'],
100
+ vouchers: ['apply'],
101
+ giftcards: ['redeem'],
102
+ };
103
+
104
+ // Rebuild the failing command with secrets and personal values removed, so the
105
+ // report can be pasted in a public issue.
106
+ export function scrubArgv(argv = []) {
107
+ const out = [];
108
+ for (let i = 0; i < argv.length; i++) {
109
+ const a = String(argv[i]);
110
+ if (a.startsWith('--')) {
111
+ const eq = a.indexOf('=');
112
+ const key = (eq === -1 ? a.slice(2) : a.slice(2, eq)).toLowerCase();
113
+ if (SECRET_FLAGS.has(key)) {
114
+ if (eq !== -1) { out.push(`${a.slice(0, eq + 1)}${REDACTED}`); continue; }
115
+ out.push(a);
116
+ if (i + 1 < argv.length && !String(argv[i + 1]).startsWith('--')) { out.push(REDACTED); i++; }
117
+ continue;
118
+ }
119
+ }
120
+ out.push(a);
121
+ }
122
+ const [noun, verb] = out;
123
+ if (NAME_POSITIONALS[noun]?.includes(verb)) {
124
+ for (let i = 2; i < out.length; i++) {
125
+ if (String(out[i]).startsWith('-')) continue;
126
+ if (!/^-?\d+$/.test(String(out[i]))) out[i] = REDACTED;
127
+ break;
128
+ }
129
+ }
130
+ return out.map((x) => redactString(x).value);
131
+ }
132
+
133
+ // ---------- fingerprint ----------
134
+
135
+ const norm = (s) => String(s ?? '')
136
+ .toLowerCase()
137
+ .replace(/[0-9a-f]{8}-[0-9a-f-]{16,}/g, '#')
138
+ .replace(/\d+/g, '#')
139
+ .replace(/\s+/g, ' ')
140
+ .trim()
141
+ .slice(0, 160);
142
+
143
+ // Stable id for "the same failure": command + reason + message shape, version-independent
144
+ // so a fix released as 0.3.1 still dedupes against the 0.3.0 ticket.
145
+ export function fingerprintOf({ command, reason, message } = {}) {
146
+ const seed = [norm(command), norm(reason), norm(message)].join('|');
147
+ return 'wf-' + crypto.createHash('sha256').update(seed).digest('hex').slice(0, 10);
148
+ }
149
+
150
+ // ---------- environment ----------
151
+
152
+ function hostOf(url) {
153
+ try { return new URL(url).host; } catch { return null; }
154
+ }
155
+
156
+ function npmVersion() {
157
+ try {
158
+ return child_process.execFileSync('npm', ['--version'], {
159
+ encoding: 'utf8', timeout: 4000, stdio: ['ignore', 'pipe', 'ignore'],
160
+ shell: process.platform === 'win32', windowsHide: true,
161
+ }).trim() || null;
162
+ } catch { return null; }
163
+ }
164
+
165
+ function installMode() {
166
+ const entry = process.argv[1] || '';
167
+ return /[\\/]node_modules[\\/]/.test(entry) ? 'npm-global' : 'source-checkout';
168
+ }
169
+
170
+ export function collectEnvironment(ctx = {}) {
171
+ const profile = ctx.profile || 'default';
172
+ const creds = (() => { try { return loadCreds().profiles?.[profile] || {}; } catch { return {}; } })();
173
+ const env = {
174
+ cli_version: VERSION,
175
+ install: installMode(),
176
+ node: process.versions.node,
177
+ npm: npmVersion(),
178
+ os: `${process.platform} ${os.release()} (${process.arch})`,
179
+ shell: path.basename(process.env.SHELL || process.env.ComSpec || '') || null,
180
+ locale: process.env.LC_ALL || process.env.LANG || null,
181
+ terminal: !!process.stdin.isTTY,
182
+ profile,
183
+ // booleans only: never the values
184
+ session_token_present: !!creds.token,
185
+ refresh_token_present: !!creds.refreshToken,
186
+ config_dir: configDir(),
187
+ api_url_override: process.env.WETACA_API_URL ? hostOf(process.env.WETACA_API_URL) : null,
188
+ };
189
+ return redact(env).value;
190
+ }
191
+
192
+ function doctorTable(checks = []) {
193
+ if (!Array.isArray(checks) || !checks.length) return null;
194
+ return checks.map((c) => `${c.ok ? 'ok ' : 'FAIL'} ${c.check}: ${c.detail ?? ''}`).join('\n');
195
+ }
196
+
197
+ function projectFrames(err) {
198
+ const out = [];
199
+ for (const line of String(err?.stack || '').split('\n')) {
200
+ const m = line.match(/[\\/](src|bin)[\\/]([\w.-]+\.js):(\d+)(?::\d+)?/);
201
+ if (!m) continue;
202
+ out.push(`${m[2]}:${m[3]}`);
203
+ if (out.length >= 8) break;
204
+ }
205
+ return out;
206
+ }
207
+
208
+ // ---------- last error cache ----------
209
+
210
+ export function lastErrorPath() { return path.join(configDir(), 'last-error.json'); }
211
+
212
+ function categoryOf(code) {
213
+ return Object.entries(EXIT).find(([, v]) => v === code)?.[0]?.toLowerCase() || 'unexpected';
214
+ }
215
+
216
+ export function commandOf(argv = []) {
217
+ const pos = argv.filter((a) => !String(a).startsWith('-'));
218
+ return pos.slice(0, 2).join(' ').trim();
219
+ }
220
+
221
+ // Called from the CLI entry point on every failure. Must never throw and never
222
+ // slow a command down: a single small atomic write.
223
+ export function recordLastError(err, argv = process.argv.slice(2), { disabled = false } = {}) {
224
+ try {
225
+ if (disabled || process.env.WETACA_REPORT_CACHE === '0') return;
226
+ const command = commandOf(argv);
227
+ if (!command || command.startsWith('report')) return;
228
+ const code = err?.exitCode ?? EXIT.UNEXPECTED;
229
+ const reason = err?.extra?.reason || 'unexpected';
230
+ // Usage mistakes and declined confirmations are not bugs: they never become
231
+ // an issue, so they must not overwrite the last real failure.
232
+ if (code === EXIT.USAGE || reason === 'usage' || reason === 'confirmation_required' || reason === 'declined') return;
233
+ const rec = {
234
+ at: new Date().toISOString(),
235
+ command,
236
+ argv: scrubArgv(argv),
237
+ cli_version: VERSION,
238
+ node: process.versions.node,
239
+ platform: `${process.platform} ${process.arch}`,
240
+ error: redact({
241
+ code,
242
+ category: categoryOf(code),
243
+ reason: err?.extra?.reason || 'unexpected',
244
+ retryable: !!err?.extra?.retryable,
245
+ message: err?.message || String(err),
246
+ suggested_commands: err?.extra?.suggested_commands || [],
247
+ details: err?.extra?.details,
248
+ stack_frames: projectFrames(err),
249
+ }).value,
250
+ };
251
+ fs.mkdirSync(configDir(), { recursive: true });
252
+ const tmp = lastErrorPath() + '.tmp';
253
+ fs.writeFileSync(tmp, JSON.stringify(rec, null, 2) + '\n', { mode: 0o600 });
254
+ fs.renameSync(tmp, lastErrorPath());
255
+ } catch { /* the report cache must never break the CLI */ }
256
+ }
257
+
258
+ export function readLastError() {
259
+ try { return JSON.parse(fs.readFileSync(lastErrorPath(), 'utf8')); } catch { return null; }
260
+ }
261
+
262
+ // ---------- issue body ----------
263
+
264
+ function mdTable(rows) {
265
+ const body = rows.filter(([, v]) => v != null && v !== '').map(([k, v]) => `| ${k} | ${String(v).replace(/\|/g, '\\|')} |`);
266
+ return ['| field | value |', '|---|---|', ...body].join('\n');
267
+ }
268
+
269
+ export function buildIssue({ title, failure, notes, expected, env, doctor }) {
270
+ const e = failure?.error || {};
271
+ const command = failure?.command || 'unknown';
272
+ const reason = e.reason || 'unexpected';
273
+ const fp = fingerprintOf({ command, reason, message: e.message });
274
+ const finalTitle = (title || `[report] wetaca ${command} — ${reason} (exit ${e.code ?? 1})`).slice(0, 180);
275
+ const repro = ['wetaca', ...(failure?.argv || [])].join(' ').trim();
276
+
277
+ const sections = [];
278
+ sections.push(`<!-- ${MARKER}: ${fp} -->`);
279
+ sections.push('## What happened');
280
+ sections.push([
281
+ `\`wetaca ${command}\` failed with exit code \`${e.code ?? 1}\` (\`${reason}\`)${e.category ? ` — category \`${e.category}\`` : ''}.`,
282
+ notes ? '\n' + notes : '',
283
+ ].join('\n').trim());
284
+
285
+ if (expected) {
286
+ sections.push('## Expected');
287
+ sections.push(expected);
288
+ }
289
+
290
+ sections.push('## Reproduce');
291
+ sections.push(['```', `$ ${repro}`, '```'].join('\n'));
292
+
293
+ sections.push('## Environment');
294
+ sections.push(mdTable(Object.entries(env || {})));
295
+
296
+ sections.push('## Error');
297
+ sections.push('```json');
298
+ sections.push(JSON.stringify({
299
+ code: e.code, category: e.category, reason: e.reason, retryable: e.retryable,
300
+ message: e.message, suggested_commands: e.suggested_commands,
301
+ ...(e.details ? { details: e.details } : {}),
302
+ }, null, 2));
303
+ sections.push('```');
304
+
305
+ if (e.stack_frames?.length) {
306
+ sections.push('### Project frames');
307
+ sections.push(['```', ...e.stack_frames, '```'].join('\n'));
308
+ }
309
+
310
+ const dt = doctorTable(doctor?.checks);
311
+ if (dt) {
312
+ sections.push('## `wetaca doctor`');
313
+ sections.push(['```', dt, '```'].join('\n'));
314
+ }
315
+
316
+ const draft = sections.join('\n\n');
317
+ const redactedCount = (draft.match(/«redacted»|«phone»|«street»|«zip|user@example\.com|C:\\Users\\~/g) || []).length;
318
+ sections.push('---');
319
+ sections.push(`Reported by \`wetaca report\` from wetaca-cli \`${VERSION}\`${failure?.cli_version && failure.cli_version !== VERSION ? ` (failed on \`${failure.cli_version}\`)` : ''} · fingerprint \`${fp}\` · ${redactedCount} value(s) redacted.`);
320
+ sections.push('Tokens, cookies, authorization headers, e-mail addresses, phone numbers and delivery addresses are removed automatically before the report is written; the command line is scrubbed too (`--street`, `--city`, `--zipcode`, `--token`, voucher codes …).');
321
+
322
+ const body = sections.join('\n\n');
323
+ return { title: finalTitle, body: body.length > MAX_BODY ? body.slice(0, MAX_BODY) + '\n\n… (truncated)' : body, fingerprint: fp, redactions: redactedCount };
324
+ }
325
+
326
+ // ---------- GitHub ----------
327
+
328
+ function repoFromFlags(flags) {
329
+ const repo = String(flags.repo || process.env.WETACA_REPORT_REPO || REPO_DEFAULT).trim();
330
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw usageError(`--repo must look like owner/name (got '${repo}').`);
331
+ return repo;
332
+ }
333
+
334
+ async function githubToken() {
335
+ for (const k of ['GITHUB_TOKEN', 'GH_TOKEN', 'WETACA_REPORT_TOKEN']) {
336
+ if (process.env[k]?.trim()) return process.env[k].trim();
337
+ }
338
+ try {
339
+ const out = child_process.execFileSync('gh', ['auth', 'token'], {
340
+ encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true,
341
+ }).trim();
342
+ if (out) return out;
343
+ } catch { /* gh missing or not logged in */ }
344
+ return null;
345
+ }
346
+
347
+ async function ghApi(method, url, token, body) {
348
+ // GITHUB_API_URL is what GitHub Actions sets on GHES; WETACA_GITHUB_API lets tests
349
+ // (and enterprise installs) point at another API without touching the code.
350
+ const base = process.env.WETACA_GITHUB_API || process.env.GITHUB_API_URL || 'https://api.github.com';
351
+ const target = url.replace(/^https:\/\/api\.github\.com/, base.replace(/\/+$/, ''));
352
+ let res;
353
+ try {
354
+ res = await fetch(target, {
355
+ method,
356
+ headers: {
357
+ accept: 'application/vnd.github+json',
358
+ authorization: 'Bearer ' + token,
359
+ 'x-github-api-version': '2022-11-28',
360
+ 'user-agent': `wetaca-cli/${VERSION}`,
361
+ ...(body ? { 'content-type': 'application/json' } : {}),
362
+ },
363
+ body: body ? JSON.stringify(body) : undefined,
364
+ });
365
+ } catch (e) {
366
+ throw new CliError(EXIT.NETWORK, `Could not reach api.github.com: ${e.cause?.code || e.message}`,
367
+ { reason: 'network', retryable: true });
368
+ }
369
+ const text = await res.text().catch(() => '');
370
+ let json = null;
371
+ try { json = text ? JSON.parse(text) : null; } catch { /* not JSON */ }
372
+ if (res.ok) return json;
373
+ if (res.status === 401 || res.status === 403) {
374
+ throw new CliError(EXIT.AUTH, `GitHub rejected the credentials (HTTP ${res.status})${json?.message ? ': ' + json.message : ''}. ` +
375
+ 'Log in with `gh auth login` (scope repo) or export GITHUB_TOKEN.',
376
+ { reason: 'github_auth', suggested_commands: ['gh auth login', 'GITHUB_TOKEN=… wetaca report create --yes'] });
377
+ }
378
+ if (res.status === 404) {
379
+ throw new CliError(EXIT.NOT_FOUND, `GitHub repo not found or the token cannot see it (HTTP 404).`,
380
+ { reason: 'github_not_found', details: json });
381
+ }
382
+ throw new CliError(EXIT.API, `GitHub refused the request (HTTP ${res.status})${json?.message ? ': ' + json.message : ''}`,
383
+ { reason: 'github_http_' + res.status, retryable: res.status >= 500, details: json });
384
+ }
385
+
386
+ async function existingIssue(repo, fp, token) {
387
+ const q = `repo:${repo} is:issue in:body "${MARKER}: ${fp}"`;
388
+ const url = `https://api.github.com/search/issues?q=${encodeURIComponent(q)}&per_page=5`;
389
+ try {
390
+ const j = await ghApi('GET', url, token);
391
+ const hit = (j?.items || []).find((i) => String(i.body || '').includes(`${MARKER}: ${fp}`)) || (j?.items || [])[0];
392
+ if (hit) return { number: hit.number, url: hit.html_url, state: hit.state, title: hit.title };
393
+ } catch { /* search is best effort: never block filing the issue */ }
394
+ return null;
395
+ }
396
+
397
+ async function labelSet(repo, token, wanted = ['bug']) {
398
+ try {
399
+ const j = await ghApi('GET', `https://api.github.com/repos/${repo}/labels?per_page=100`, token);
400
+ const have = new Set((j || []).map((l) => l.name));
401
+ const ok = wanted.filter((l) => have.has(l));
402
+ return ok.length ? ok : [];
403
+ } catch { return []; }
404
+ }
405
+
406
+ function issueUrl(repo, { title, body, labels }) {
407
+ const params = new URLSearchParams({ title, body });
408
+ if (labels?.length) params.set('labels', labels.join(','));
409
+ return `https://github.com/${repo}/issues/new?${params.toString()}`;
410
+ }
411
+
412
+ function openInBrowser(url) {
413
+ try {
414
+ const { execSync } = child_process;
415
+ if (process.platform === 'win32') execSync(`rundll32 url.dll,FileProtocolHandler ${url}`, { stdio: 'ignore', windowsHide: true });
416
+ else if (process.platform === 'darwin') execSync(`open ${JSON.stringify(url)}`, { stdio: 'ignore' });
417
+ else execSync(`xdg-open ${JSON.stringify(url)}`, { stdio: 'ignore' });
418
+ return true;
419
+ } catch { return false; }
420
+ }
421
+
422
+ function reportFile(fp) {
423
+ const dir = path.join(configDir(), 'reports');
424
+ fs.mkdirSync(dir, { recursive: true });
425
+ return path.join(dir, `report-${fp}.md`);
426
+ }
427
+
428
+ // ---------- command ----------
429
+
430
+ function failureFromFlags(flags) {
431
+ if (flags['error-file']) {
432
+ let raw;
433
+ try { raw = fs.readFileSync(String(flags['error-file']), 'utf8'); } catch (e) {
434
+ throw usageError('Could not read --error-file: ' + e.message);
435
+ }
436
+ let parsed;
437
+ try { parsed = JSON.parse(raw); } catch { throw usageError('--error-file must contain the JSON error wrapper (--error-format json).'); }
438
+ const err = parsed?.error || parsed;
439
+ return {
440
+ command: flags.command ? String(flags.command) : 'unknown',
441
+ argv: Array.isArray(parsed?.argv) ? parsed.argv : (flags.command ? String(flags.command).split(/\s+/) : []),
442
+ cli_version: VERSION,
443
+ error: {
444
+ code: err?.code ?? EXIT.UNEXPECTED, category: err?.category, reason: err?.reason,
445
+ retryable: err?.retryable, message: err?.message, suggested_commands: err?.suggested_commands,
446
+ details: err?.details, stack_frames: [],
447
+ },
448
+ };
449
+ }
450
+ return readLastError();
451
+ }
452
+
453
+ export async function reportCmd(verb, args, flags, ctx, { doctor, confirm } = {}) {
454
+ if (verb === 'last') {
455
+ const rec = readLastError();
456
+ if (!rec) return { ok: true, hasError: false, note: 'No stored failure yet. The cache fills on the next failing command.' };
457
+ return { ok: true, hasError: true, path: lastErrorPath(), ...rec };
458
+ }
459
+ if (![undefined, 'show', 'create'].includes(verb)) {
460
+ throw usageError(`Report verbs: show | last | create (got '${verb}').`, { suggested_commands: ['wetaca report show'] });
461
+ }
462
+
463
+ const failure = failureFromFlags(flags);
464
+ if (!failure && !flags.title && !flags.notes) {
465
+ throw usageError('Nothing to report: no stored failure. Run the failing command first, or pass --error-file FILE / --title T --notes "…".');
466
+ }
467
+ const repo = repoFromFlags(flags);
468
+ const env = collectEnvironment(ctx);
469
+ const doctorData = flags.doctor && typeof doctor === 'function' ? await doctor([], flags, ctx) : null;
470
+
471
+ const issue = buildIssue({
472
+ title: flags.title ? String(flags.title) : undefined,
473
+ failure,
474
+ notes: flags.notes ? String(flags.notes) : undefined,
475
+ expected: flags.expected ? String(flags.expected) : undefined,
476
+ env,
477
+ doctor: doctorData,
478
+ });
479
+ const file = reportFile(issue.fingerprint);
480
+ fs.writeFileSync(file, `# ${issue.title}\n\n${issue.body}\n`, { mode: 0o600 });
481
+
482
+ const base = {
483
+ ok: true,
484
+ fingerprint: issue.fingerprint,
485
+ title: issue.title,
486
+ body: issue.body,
487
+ redactions: issue.redactions,
488
+ report_path: file,
489
+ repo,
490
+ };
491
+
492
+ if (verb !== 'create') {
493
+ const urlBody = issue.body.length > 6000
494
+ ? issue.body.slice(0, 6000) + `\n\n… (body truncated in this URL — full report at ${file})`
495
+ : issue.body;
496
+ const url = issueUrl(repo, { title: issue.title, body: urlBody, labels: ['bug'] });
497
+ if (flags.open) openInBrowser(url);
498
+ return {
499
+ ...base,
500
+ mode: 'manual',
501
+ issue_url: url,
502
+ opened: !!flags.open,
503
+ next: [
504
+ 'wetaca report create --yes (needs gh auth login or GITHUB_TOKEN)',
505
+ 'wetaca report show --open (pre-filled form in the browser, no credentials)',
506
+ ],
507
+ };
508
+ }
509
+
510
+ const payload = { title: issue.title, body: issue.body, labels: ['bug'] };
511
+ if (ctx.dryRun) return { ...base, dryRun: true, wouldSend: { repo, ...payload } };
512
+
513
+ const token = await githubToken();
514
+ if (!token) {
515
+ throw new CliError(EXIT.AUTH,
516
+ 'No GitHub credential found: set GITHUB_TOKEN (or GH_TOKEN), or run `gh auth login` once (scope repo). ' +
517
+ 'Without a credential, use `wetaca report show --open` to file it by hand.',
518
+ { reason: 'github_auth_required', suggested_commands: ['gh auth login', 'wetaca report show --open'] });
519
+ }
520
+
521
+ const dup = flags.force ? null : await existingIssue(repo, issue.fingerprint, token);
522
+ if (dup) {
523
+ if (flags.open) openInBrowser(dup.url);
524
+ return { ...base, mode: 'existing', issue: dup, note: `An issue with fingerprint ${issue.fingerprint} is already open; pass --force to file another.` };
525
+ }
526
+
527
+ // Confirmation shows exactly what would become public.
528
+ const preview = issue.body.length > 2000 ? issue.body.slice(0, 2000) + '\n…' : issue.body;
529
+ await confirmOrThrow(confirm, flags, `Open this issue on github.com/${repo}?\n\n${issue.title}\n\n${preview}\n\n(full report: ${file})`);
530
+
531
+ const labels = await labelSet(repo, token, payload.labels);
532
+ const created = await ghApi('POST', `https://api.github.com/repos/${repo}/issues`, token,
533
+ { title: payload.title, body: payload.body, ...(labels.length ? { labels } : {}) });
534
+ const out = { ...base, mode: 'created', issue: { number: created.number, url: created.html_url, state: created.state, labels: (created.labels || []).map((l) => l.name) } };
535
+ if (flags.open) { openInBrowser(created.html_url); out.opened = true; }
536
+ return out;
537
+ }
538
+
539
+ // `confirm` lives in commands.js; the dispatcher injects it so this module stays
540
+ // usable on its own (no import cycle, no TTY assumptions in tests).
541
+ async function confirmOrThrow(confirm, flags, summary) {
542
+ if (typeof confirm !== 'function') {
543
+ if (flags.yes) return;
544
+ throw usageError('Real-effect operation; confirmation required. Repeat with --yes.');
545
+ }
546
+ return confirm(flags, summary);
547
+ }