@skilldeck/outreach 0.0.0-stage → 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.
@@ -0,0 +1,880 @@
1
+ #!/usr/bin/env node
2
+ // outreach / reddit.mjs
3
+ //
4
+ // Careful, capped Reddit engagement from one account. Searches threads, reads
5
+ // subreddit rules, checks drafts (length, links, disclosure, near-duplicates) and
6
+ // posts a reply only when the hard limits in this file allow it:
7
+ //
8
+ // - a daily cap (rolling 24h), a per-subreddit daily cap and a cooldown
9
+ // - never twice in the same thread
10
+ // - review mode: the user's per-draft approval token (--approve <draftId>)
11
+ // - auto mode: a one-time recorded confirmation (config confirm-auto)
12
+ //
13
+ // State lives in ./.outreach/ (config.json, ledger.json, drafts/). Secrets are
14
+ // read from env vars only and never written to disk or printed.
15
+ //
16
+ // node reddit.mjs <command> [args] [--json] [--dir <state dir>]
17
+ //
18
+ // Exit 0 ok, 1 refused or failed, 2 usage or missing environment.
19
+ // Zero dependencies. Node 20+.
20
+
21
+ import { realpathSync } from 'node:fs'
22
+ import { fileURLToPath } from 'node:url'
23
+ import fs from 'node:fs'
24
+ import path from 'node:path'
25
+ import crypto from 'node:crypto'
26
+
27
+ const VERSION = '0.1.0'
28
+
29
+ const HELP = `reddit: capped, approval-gated Reddit engagement
30
+
31
+ node reddit.mjs <command> [args] [--json] [--dir <state dir>]
32
+
33
+ Commands
34
+ doctor check env vars, token, /api/v1/me (read-only fallback if no creds)
35
+ config get [key] show config (or one dotted key)
36
+ config set <key> <value> mode | caps.* | product.* | disclosure | subreddits | keywords
37
+ config confirm-auto record the user's one-time confirmation for auto mode
38
+ search <query> [--sub r] [--limit N] [--time hour|day|week|month|year|all] [--sort new|relevance|top|comments]
39
+ rules <sub> subreddit rules + self-promotion verdict
40
+ thread <id|url> post, state, skip verdict, whether you already replied
41
+ draft-check <file> | --text "..." --thread <id> [--sub r]
42
+ length, links, disclosure, dedupe; prints a draftId when it passes
43
+ post --thread <id> --draft <draftId> [--approve <draftId>] [--dry-run]
44
+ post a checked draft, within caps
45
+ ledger list | today what has been posted
46
+
47
+ Env: REDDIT_CLIENT_ID REDDIT_CLIENT_SECRET REDDIT_USERNAME REDDIT_PASSWORD REDDIT_USER_AGENT
48
+ State: ./.outreach/ (override with --dir or OUTREACH_DIR)
49
+ Exit: 0 ok, 1 refused or failed, 2 usage or environment
50
+ `
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // Defaults and limits
54
+ // ---------------------------------------------------------------------------
55
+
56
+ export const DEFAULT_CONFIG = {
57
+ mode: null, // 'review' | 'auto'
58
+ autoConfirmedAt: null,
59
+ caps: {
60
+ perDay: 5,
61
+ perSubPerDay: 1,
62
+ cooldownMinutes: 30,
63
+ maxThreadAgeDays: 14,
64
+ minChars: 80,
65
+ maxChars: 3000,
66
+ similarity: 0.5,
67
+ },
68
+ product: { name: '', aliases: [], url: '' },
69
+ disclosure: '',
70
+ subreddits: [],
71
+ keywords: [],
72
+ }
73
+
74
+ /** Hard ceilings no config can exceed. Raising volume past these is spam, whatever the config says. */
75
+ export const HARD_LIMITS = {
76
+ perDay: { min: 1, max: 20 },
77
+ perSubPerDay: { min: 1, max: 3 },
78
+ cooldownMinutes: { min: 10, max: 1440 },
79
+ maxThreadAgeDays: { min: 1, max: 180 },
80
+ minChars: { min: 20, max: 2000 },
81
+ maxChars: { min: 200, max: 10000 },
82
+ similarity: { min: 0.2, max: 0.9 },
83
+ }
84
+
85
+ const DAY_MS = 24 * 60 * 60 * 1000
86
+ const LIST_KEYS = new Set(['subreddits', 'keywords', 'product.aliases'])
87
+ const STRING_KEYS = new Set(['product.name', 'product.url', 'disclosure'])
88
+
89
+ export class UsageError extends Error {
90
+ constructor(msg) {
91
+ super(msg)
92
+ this.code = 2
93
+ }
94
+ }
95
+
96
+ // ---------------------------------------------------------------------------
97
+ // State files
98
+ // ---------------------------------------------------------------------------
99
+
100
+ export function stateDir(opts = {}) {
101
+ return path.resolve(opts.dir ?? process.env.OUTREACH_DIR ?? path.join(process.cwd(), '.outreach'))
102
+ }
103
+
104
+ function readJson(file, fallback) {
105
+ try {
106
+ return JSON.parse(fs.readFileSync(file, 'utf8'))
107
+ } catch (e) {
108
+ if (e.code === 'ENOENT') return fallback
109
+ throw new Error(`${file}: ${e.message}`)
110
+ }
111
+ }
112
+
113
+ function writeJson(file, value) {
114
+ fs.mkdirSync(path.dirname(file), { recursive: true })
115
+ const tmp = `${file}.${process.pid}.tmp`
116
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n')
117
+ fs.renameSync(tmp, file)
118
+ }
119
+
120
+ function merge(base, over) {
121
+ const out = { ...base }
122
+ for (const [k, v] of Object.entries(over ?? {})) {
123
+ out[k] = v && typeof v === 'object' && !Array.isArray(v) && base[k] && typeof base[k] === 'object' ? merge(base[k], v) : v
124
+ }
125
+ return out
126
+ }
127
+
128
+ export function loadConfig(dir) {
129
+ return merge(DEFAULT_CONFIG, readJson(path.join(dir, 'config.json'), {}))
130
+ }
131
+
132
+ export function saveConfig(dir, config) {
133
+ writeJson(path.join(dir, 'config.json'), config)
134
+ }
135
+
136
+ export function loadLedger(dir) {
137
+ const l = readJson(path.join(dir, 'ledger.json'), {})
138
+ return { entries: l.entries ?? [], rateLimitedUntil: l.rateLimitedUntil ?? null }
139
+ }
140
+
141
+ export function saveLedger(dir, ledger) {
142
+ writeJson(path.join(dir, 'ledger.json'), ledger)
143
+ }
144
+
145
+ export function loadDrafts(dir) {
146
+ const d = path.join(dir, 'drafts')
147
+ if (!fs.existsSync(d)) return []
148
+ return fs
149
+ .readdirSync(d)
150
+ .filter((f) => f.endsWith('.json'))
151
+ .map((f) => readJson(path.join(d, f), null))
152
+ .filter(Boolean)
153
+ }
154
+
155
+ function draftFile(dir, id) {
156
+ if (!/^d_[0-9a-f]{12}$/.test(id ?? '')) throw new UsageError(`not a draft id: ${id}`)
157
+ return path.join(dir, 'drafts', `${id}.json`)
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // Config
162
+ // ---------------------------------------------------------------------------
163
+
164
+ function getPath(obj, key) {
165
+ return key.split('.').reduce((o, k) => (o == null ? undefined : o[k]), obj)
166
+ }
167
+
168
+ /** Apply `config set key value` and return the new config. Pure; throws UsageError on bad input. */
169
+ export function setConfigValue(config, key, raw) {
170
+ const next = structuredClone(config)
171
+ if (key === 'autoConfirmedAt') throw new UsageError('autoConfirmedAt is set only by "config confirm-auto", after the user confirms')
172
+ if (key === 'mode') {
173
+ if (raw !== 'review' && raw !== 'auto') throw new UsageError('mode must be "review" or "auto"')
174
+ if (next.mode !== raw) next.autoConfirmedAt = null // switching modes always needs a fresh confirmation
175
+ next.mode = raw
176
+ return next
177
+ }
178
+ if (key.startsWith('caps.')) {
179
+ const name = key.slice(5)
180
+ const lim = HARD_LIMITS[name]
181
+ if (!lim) throw new UsageError(`unknown cap "${name}" (known: ${Object.keys(HARD_LIMITS).join(', ')})`)
182
+ const n = Number(raw)
183
+ if (!Number.isFinite(n)) throw new UsageError(`${key} must be a number`)
184
+ if (n < lim.min || n > lim.max) throw new UsageError(`${key} must be between ${lim.min} and ${lim.max}`)
185
+ next.caps[name] = name === 'similarity' ? n : Math.round(n)
186
+ if (next.mode === 'auto') next.autoConfirmedAt = null // changed limits need re-confirmation
187
+ return next
188
+ }
189
+ if (LIST_KEYS.has(key)) {
190
+ const list = String(raw)
191
+ .split(',')
192
+ .map((s) => s.trim())
193
+ .filter(Boolean)
194
+ .map((s) => (key === 'subreddits' ? s.replace(/^\/?r\//i, '') : s))
195
+ if (key === 'product.aliases') next.product.aliases = list
196
+ else next[key] = list
197
+ return next
198
+ }
199
+ if (STRING_KEYS.has(key)) {
200
+ const [a, b] = key.split('.')
201
+ if (b) next[a][b] = String(raw)
202
+ else next[a] = String(raw)
203
+ return next
204
+ }
205
+ throw new UsageError(`unknown config key "${key}"`)
206
+ }
207
+
208
+ export function confirmAuto(config, now = Date.now()) {
209
+ if (config.mode !== 'auto') throw new UsageError('set mode to auto first: config set mode auto')
210
+ return { ...config, autoConfirmedAt: new Date(now).toISOString(), autoConfirmedCaps: { ...config.caps } }
211
+ }
212
+
213
+ // ---------------------------------------------------------------------------
214
+ // Text checks
215
+ // ---------------------------------------------------------------------------
216
+
217
+ const URL_RE = /\bhttps?:\/\/[^\s)\]>]+|\bwww\.[^\s)\]>]+/gi
218
+
219
+ /** Lowercase, drop URLs and markdown/punctuation, collapse whitespace. */
220
+ export function normalizeText(text) {
221
+ return String(text)
222
+ .toLowerCase()
223
+ .replace(URL_RE, ' ')
224
+ .replace(/[^\p{L}\p{N}\s']/gu, ' ')
225
+ .replace(/'/g, '')
226
+ .replace(/\s+/g, ' ')
227
+ .trim()
228
+ }
229
+
230
+ /** Word n-gram shingles of normalized text. Short texts fall back to single words. */
231
+ export function shingles(text, n = 3) {
232
+ const words = normalizeText(text).split(' ').filter(Boolean)
233
+ const out = new Set()
234
+ if (words.length < n) {
235
+ for (const w of words) out.add(w)
236
+ return out
237
+ }
238
+ for (let i = 0; i + n <= words.length; i++) out.add(words.slice(i, i + n).join(' '))
239
+ return out
240
+ }
241
+
242
+ export function jaccard(a, b) {
243
+ if (a.size === 0 && b.size === 0) return 1
244
+ let inter = 0
245
+ for (const x of a) if (b.has(x)) inter++
246
+ return inter / (a.size + b.size - inter)
247
+ }
248
+
249
+ export function similarity(textA, textB) {
250
+ return jaccard(shingles(textA), shingles(textB))
251
+ }
252
+
253
+ function escapeRe(s) {
254
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
255
+ }
256
+
257
+ function hostOf(url) {
258
+ try {
259
+ return new URL(/^https?:/i.test(url) ? url : `https://${url}`).hostname.replace(/^www\./, '')
260
+ } catch {
261
+ return ''
262
+ }
263
+ }
264
+
265
+ /** Does the text mention the configured product (name, aliases, or its domain)? */
266
+ export function mentionsProduct(text, product = {}) {
267
+ const names = [product.name, ...(product.aliases ?? [])].filter((s) => s && s.trim().length > 1)
268
+ for (const n of names) if (new RegExp(`(^|[^\\p{L}\\p{N}])${escapeRe(n.trim())}($|[^\\p{L}\\p{N}])`, 'iu').test(text)) return true
269
+ const host = product.url ? hostOf(product.url) : ''
270
+ return Boolean(host && text.toLowerCase().includes(host.toLowerCase()))
271
+ }
272
+
273
+ const GENERIC_DISCLOSURE =
274
+ /\b(disclosure|full disclosure|disclaimer|i'?m affiliated|i am affiliated|affiliated with|i (work|worked) (on|at|for)|we (built|make|made|run)|i (built|made|created|founded|maintain|run)|i'?m (the|a|one of the) (founder|co-?founder|developer|dev|maker|author|maintainer|creator|team)|(my|our) (company|product|startup|tool|app|project))\b/i
275
+
276
+ /** Disclosure present: the configured disclosure text (normalized), or a plain first-person affiliation statement. */
277
+ export function hasDisclosure(text, disclosure = '') {
278
+ const d = normalizeText(disclosure)
279
+ if (d && normalizeText(text).includes(d)) return true
280
+ return GENERIC_DISCLOSURE.test(text)
281
+ }
282
+
283
+ export function linkStats(text) {
284
+ const links = String(text).match(URL_RE) ?? []
285
+ const mdLinks = String(text).match(/\[[^\]]*\]\([^)]+\)/g) ?? []
286
+ const words = normalizeText(String(text).replace(/\[([^\]]*)\]\([^)]+\)/g, '$1')).split(' ').filter(Boolean)
287
+ return { links: links.length, mdLinks: mdLinks.length, words: words.length }
288
+ }
289
+
290
+ export function hashText(text) {
291
+ return crypto.createHash('sha256').update(String(text)).digest('hex')
292
+ }
293
+
294
+ export function draftIdFor(thread, text) {
295
+ return 'd_' + hashText(`${thread}\n${text}`).slice(0, 12)
296
+ }
297
+
298
+ /**
299
+ * Check a draft reply. Pure: pass the config, ledger entries and existing drafts.
300
+ * Returns { ok, draftId?, checks: [{name, ok, detail}], similar: [...], mentionsProduct }.
301
+ */
302
+ export function checkDraft(text, { thread, config = DEFAULT_CONFIG, ledger = { entries: [] }, drafts = [] } = {}) {
303
+ const caps = { ...DEFAULT_CONFIG.caps, ...config.caps }
304
+ const checks = []
305
+ const add = (name, ok, detail) => checks.push({ name, ok, detail })
306
+ const body = String(text ?? '').trim()
307
+ const id = draftIdFor(thread, body)
308
+
309
+ add('length', body.length >= caps.minChars && body.length <= caps.maxChars, `${body.length} chars (allowed ${caps.minChars}-${caps.maxChars})`)
310
+
311
+ const ls = linkStats(body)
312
+ const linkCount = Math.max(ls.links, ls.mdLinks)
313
+ add('not-links-only', ls.words >= 25 || linkCount === 0, `${ls.words} words of text around ${linkCount} link(s); a reply must help on its own`)
314
+ add('link-count', linkCount <= 2, `${linkCount} link(s) (max 2)`)
315
+
316
+ const product = mentionsProduct(body, config.product)
317
+ add(
318
+ 'disclosure',
319
+ !product || hasDisclosure(body, config.disclosure),
320
+ product ? 'mentions the product, so it must disclose your affiliation' : 'no product mention',
321
+ )
322
+
323
+ const already = ledger.entries.find((e) => e.thread === thread)
324
+ add('not-already-replied', !already, already ? `already replied in this thread at ${already.postedAt}` : 'no prior reply in ledger')
325
+
326
+ const similar = []
327
+ for (const e of ledger.entries) {
328
+ const s = similarity(body, e.text ?? '')
329
+ if (s >= caps.similarity) similar.push({ source: 'ledger', thread: e.thread, subreddit: e.subreddit, similarity: round(s) })
330
+ }
331
+ for (const d of drafts) {
332
+ if (d.id === id || d.status === 'posted') continue
333
+ const s = similarity(body, d.text ?? '')
334
+ if (s >= caps.similarity) similar.push({ source: 'draft', draftId: d.id, thread: d.thread, similarity: round(s) })
335
+ }
336
+ add('not-duplicate', similar.length === 0, similar.length ? `${similar.length} near-duplicate(s) at >= ${caps.similarity} similarity; write for this thread` : 'unique')
337
+
338
+ const ok = checks.every((c) => c.ok)
339
+ return { ok, draftId: ok ? id : undefined, checks, similar, mentionsProduct: product, chars: body.length }
340
+ }
341
+
342
+ const round = (n) => Math.round(n * 100) / 100
343
+
344
+ // ---------------------------------------------------------------------------
345
+ // Rules, threads, caps
346
+ // ---------------------------------------------------------------------------
347
+
348
+ const PROMO_BANNED = [
349
+ /\bno\s+(self[-\s]?promo(tion|ting)?|promo(tion)?|advertis(ing|ements?)|spam(ming)?|marketing|solicitation|commercial|plugs?|shilling)\b/i,
350
+ /\bself[-\s]?promo(tion)?\b[^.]{0,40}\b(not allowed|prohibited|banned|forbidden|will be removed|is not permitted)\b/i,
351
+ /\b(advertising|promotion|promoting)\b[^.]{0,40}\b(not allowed|prohibited|banned|forbidden|will be removed)\b/i,
352
+ /\bdo not (promote|advertise|self[-\s]?promote|plug)\b/i,
353
+ /\bdon'?t (promote|advertise|self[-\s]?promote|plug)\b/i,
354
+ ]
355
+ const PROMO_LIMITED = [/\b10\s?%|\b9:1\b|\bratio\b/i, /\bself[-\s]?promo(tion)?\b/i, /\bpromot(e|ion|ing)\b/i, /\badvertis/i, /\baffiliat/i, /\breferral/i]
356
+
357
+ /** Read a subreddit's rules and decide how it treats self-promotion. */
358
+ export function assessRules(rules = []) {
359
+ const matched = { banned: [], limited: [] }
360
+ for (const r of rules) {
361
+ const text = `${r.short_name ?? ''}. ${r.description ?? ''} ${r.violation_reason ?? ''}`
362
+ if (PROMO_BANNED.some((re) => re.test(text))) matched.banned.push(r.short_name ?? text.slice(0, 80))
363
+ else if (PROMO_LIMITED.some((re) => re.test(text))) matched.limited.push(r.short_name ?? text.slice(0, 80))
364
+ }
365
+ const selfPromo = matched.banned.length ? 'banned' : matched.limited.length ? 'limited' : 'unspecified'
366
+ return { selfPromo, matched: matched.banned.length ? matched.banned : matched.limited, ruleCount: rules.length }
367
+ }
368
+
369
+ /** Accept a bare id, t3_ fullname, or any reddit comments URL. */
370
+ export function parseThreadId(input) {
371
+ const s = String(input ?? '').trim()
372
+ const m = s.match(/\/comments\/([a-z0-9]+)/i) ?? s.match(/^t3_([a-z0-9]+)$/i) ?? s.match(/^([a-z0-9]{4,12})$/i)
373
+ if (!m) throw new UsageError(`not a thread id or URL: ${input}`)
374
+ return m[1].toLowerCase()
375
+ }
376
+
377
+ export function normalizeSub(s) {
378
+ const v = String(s ?? '').trim().replace(/^\/?r\//i, '')
379
+ if (!/^[A-Za-z0-9_]{2,21}$/.test(v)) throw new UsageError(`not a subreddit name: ${s}`)
380
+ return v
381
+ }
382
+
383
+ function postSummary(d, now = Date.now()) {
384
+ return {
385
+ id: d.id,
386
+ subreddit: d.subreddit,
387
+ title: d.title,
388
+ author: d.author,
389
+ createdUtc: d.created_utc,
390
+ ageHours: d.created_utc ? Math.round((now / 1000 - d.created_utc) / 360) / 10 : null,
391
+ numComments: d.num_comments,
392
+ score: d.score,
393
+ locked: Boolean(d.locked),
394
+ archived: Boolean(d.archived),
395
+ removed: Boolean(d.removed_by_category) || d.selftext === '[removed]',
396
+ over18: Boolean(d.over_18),
397
+ permalink: d.permalink ? `https://www.reddit.com${d.permalink}` : undefined,
398
+ }
399
+ }
400
+
401
+ function flattenComments(children = [], out = []) {
402
+ for (const c of children) {
403
+ if (c?.kind !== 't1') continue
404
+ out.push({ id: c.data.id, author: c.data.author, body: c.data.body, createdUtc: c.data.created_utc })
405
+ if (c.data.replies && typeof c.data.replies === 'object') flattenComments(c.data.replies.data?.children, out)
406
+ }
407
+ return out
408
+ }
409
+
410
+ /** Parse the /comments/<id> response into { post, comments }. */
411
+ export function parseThread(json, now = Date.now()) {
412
+ if (!Array.isArray(json) || !json[0]?.data?.children?.[0]) throw new Error('unexpected thread response')
413
+ const post = postSummary(json[0].data.children[0].data, now)
414
+ post.selftext = json[0].data.children[0].data.selftext ?? ''
415
+ const comments = flattenComments(json[1]?.data?.children)
416
+ return { post, comments }
417
+ }
418
+
419
+ /** Should we skip this thread? Pure. */
420
+ export function assessThread({ post, comments = [] }, { username, maxAgeDays = DEFAULT_CONFIG.caps.maxThreadAgeDays, ledger = { entries: [] }, now = Date.now() } = {}) {
421
+ const reasons = []
422
+ if (post.locked) reasons.push('locked')
423
+ if (post.archived) reasons.push('archived')
424
+ if (post.removed) reasons.push('removed')
425
+ if (post.createdUtc && now - post.createdUtc * 1000 > maxAgeDays * DAY_MS) reasons.push(`older than ${maxAgeDays} days`)
426
+ const me = username?.toLowerCase()
427
+ if (me && (post.author?.toLowerCase() === me || comments.some((c) => c.author?.toLowerCase() === me))) reasons.push('you already posted in this thread')
428
+ if (ledger.entries.some((e) => e.thread === post.id)) reasons.push('already in the ledger')
429
+ return { skip: reasons.length > 0, reasons }
430
+ }
431
+
432
+ /**
433
+ * Hard caps. Pure. `subreddit` may be undefined for the pre-network pass.
434
+ * Returns a list of refusal reasons (empty means allowed).
435
+ */
436
+ export function checkCaps(ledger, { thread, subreddit, now = Date.now(), caps = DEFAULT_CONFIG.caps } = {}) {
437
+ const c = { ...DEFAULT_CONFIG.caps, ...caps }
438
+ const reasons = []
439
+ const entries = ledger.entries ?? []
440
+ if (ledger.rateLimitedUntil && now < Date.parse(ledger.rateLimitedUntil)) reasons.push(`Reddit rate limit in effect until ${ledger.rateLimitedUntil}`)
441
+ if (thread && entries.some((e) => e.thread === thread)) reasons.push('already replied in this thread (never twice in one thread)')
442
+ const recent = entries.filter((e) => now - Date.parse(e.postedAt) < DAY_MS)
443
+ if (recent.length >= c.perDay) reasons.push(`daily cap reached: ${recent.length}/${c.perDay} in the last 24h`)
444
+ if (subreddit) {
445
+ const inSub = recent.filter((e) => e.subreddit?.toLowerCase() === subreddit.toLowerCase())
446
+ if (inSub.length >= c.perSubPerDay) reasons.push(`subreddit cap reached: ${inSub.length}/${c.perSubPerDay} in r/${subreddit} in the last 24h`)
447
+ }
448
+ const last = entries.reduce((m, e) => Math.max(m, Date.parse(e.postedAt) || 0), 0)
449
+ const waitMs = last + c.cooldownMinutes * 60000 - now
450
+ if (last && waitMs > 0) reasons.push(`cooldown: wait ${Math.ceil(waitMs / 60000)} more minute(s) (cooldown ${c.cooldownMinutes}m)`)
451
+ return reasons
452
+ }
453
+
454
+ export function todaySummary(ledger, { now = Date.now(), caps = DEFAULT_CONFIG.caps } = {}) {
455
+ const c = { ...DEFAULT_CONFIG.caps, ...caps }
456
+ const recent = ledger.entries.filter((e) => now - Date.parse(e.postedAt) < DAY_MS)
457
+ const bySub = {}
458
+ for (const e of recent) bySub[e.subreddit] = (bySub[e.subreddit] ?? 0) + 1
459
+ const last = ledger.entries.reduce((m, e) => Math.max(m, Date.parse(e.postedAt) || 0), 0)
460
+ const nextAt = last ? Math.max(now, last + c.cooldownMinutes * 60000) : now
461
+ return { window: 'last 24h', posted: recent.length, cap: c.perDay, remaining: Math.max(0, c.perDay - recent.length), bySubreddit: bySub, perSubCap: c.perSubPerDay, nextAllowedAt: new Date(nextAt).toISOString(), entries: recent }
462
+ }
463
+
464
+ // ---------------------------------------------------------------------------
465
+ // Reddit client (fetch injectable)
466
+ // ---------------------------------------------------------------------------
467
+
468
+ export const ENV_KEYS = ['REDDIT_CLIENT_ID', 'REDDIT_CLIENT_SECRET', 'REDDIT_USERNAME', 'REDDIT_PASSWORD', 'REDDIT_USER_AGENT']
469
+ const READONLY_UA = `node:skilldeck-outreach:${VERSION} (read-only)`
470
+
471
+ export function envStatus(env = process.env) {
472
+ const missing = ENV_KEYS.filter((k) => !env[k])
473
+ const ua = env.REDDIT_USER_AGENT ?? ''
474
+ const uaOk = /\S+:\S+:\S+.*\(by \/?u\/[A-Za-z0-9_-]+\)/i.test(ua)
475
+ return { complete: missing.length === 0, missing, userAgentOk: uaOk, readOnly: missing.length > 0 }
476
+ }
477
+
478
+ export class RedditError extends Error {
479
+ constructor(msg, { status, retryAfterSec } = {}) {
480
+ super(msg)
481
+ this.status = status
482
+ this.retryAfterSec = retryAfterSec
483
+ }
484
+ }
485
+
486
+ function rateInfo(res) {
487
+ const h = (k) => res.headers?.get?.(k)
488
+ const num = (v) => (v == null || v === '' ? undefined : Number(v))
489
+ return { remaining: num(h('x-ratelimit-remaining')), used: num(h('x-ratelimit-used')), resetSec: num(h('x-ratelimit-reset')), retryAfterSec: num(h('retry-after')) }
490
+ }
491
+
492
+ export function createClient({ fetch: f = globalThis.fetch, env = process.env } = {}) {
493
+ const st = envStatus(env)
494
+ const ua = env.REDDIT_USER_AGENT || READONLY_UA
495
+ let token = null
496
+ let lastRate = {}
497
+
498
+ async function call(url, init = {}) {
499
+ const res = await f(url, { ...init, headers: { 'User-Agent': ua, ...(init.headers ?? {}) } })
500
+ lastRate = rateInfo(res)
501
+ if (res.status === 429) {
502
+ const wait = lastRate.retryAfterSec ?? lastRate.resetSec ?? 60
503
+ throw new RedditError(`Reddit rate limit (429); retry after ${Math.ceil(wait)}s`, { status: 429, retryAfterSec: wait })
504
+ }
505
+ if (lastRate.remaining !== undefined && lastRate.remaining < 1 && lastRate.resetSec) {
506
+ // Out of budget: say so; the next call would 429.
507
+ lastRate.exhausted = true
508
+ }
509
+ const text = await res.text()
510
+ let json
511
+ try {
512
+ json = text ? JSON.parse(text) : {}
513
+ } catch {
514
+ json = undefined
515
+ }
516
+ if (!res.ok) {
517
+ const msg = json?.message ?? json?.error ?? text.slice(0, 200)
518
+ throw new RedditError(`${init.method ?? 'GET'} ${new URL(url).pathname} -> ${res.status} ${msg}`, { status: res.status })
519
+ }
520
+ if (json === undefined) throw new RedditError(`non-JSON response from ${new URL(url).pathname}`, { status: res.status })
521
+ return json
522
+ }
523
+
524
+ async function auth() {
525
+ if (token) return token
526
+ if (!st.complete) throw new UsageError(`missing env: ${st.missing.join(', ')} (see the reddit-setup skill)`)
527
+ const basic = Buffer.from(`${env.REDDIT_CLIENT_ID}:${env.REDDIT_CLIENT_SECRET}`).toString('base64')
528
+ const body = new URLSearchParams({ grant_type: 'password', username: env.REDDIT_USERNAME, password: env.REDDIT_PASSWORD })
529
+ const json = await call('https://www.reddit.com/api/v1/access_token', {
530
+ method: 'POST',
531
+ headers: { Authorization: `Basic ${basic}`, 'Content-Type': 'application/x-www-form-urlencoded' },
532
+ body: body.toString(),
533
+ })
534
+ if (!json.access_token) throw new RedditError(`token request failed: ${json.error ?? 'no access_token'} (check app type is "script" and the credentials)`, { status: 401 })
535
+ token = { access: json.access_token, scope: json.scope, expiresIn: json.expires_in }
536
+ return token
537
+ }
538
+
539
+ /** GET a listing path. Uses OAuth when creds exist, public .json otherwise. */
540
+ async function get(p, params = {}) {
541
+ const qs = new URLSearchParams({ raw_json: '1', ...Object.fromEntries(Object.entries(params).filter(([, v]) => v !== undefined && v !== '')) })
542
+ if (st.complete) {
543
+ const t = await auth()
544
+ return call(`https://oauth.reddit.com${p}?${qs}`, { headers: { Authorization: `bearer ${t.access}` } })
545
+ }
546
+ return call(`https://www.reddit.com${p}.json?${qs}`)
547
+ }
548
+
549
+ async function post(p, form) {
550
+ const t = await auth()
551
+ return call(`https://oauth.reddit.com${p}`, {
552
+ method: 'POST',
553
+ headers: { Authorization: `bearer ${t.access}`, 'Content-Type': 'application/x-www-form-urlencoded' },
554
+ body: new URLSearchParams(form).toString(),
555
+ })
556
+ }
557
+
558
+ return { get, post, auth, env: st, rate: () => lastRate, username: env.REDDIT_USERNAME }
559
+ }
560
+
561
+ // ---------------------------------------------------------------------------
562
+ // Commands (each returns { code, data, text })
563
+ // ---------------------------------------------------------------------------
564
+
565
+ export async function doctor(ctx) {
566
+ const st = envStatus(ctx.env)
567
+ const data = { env: { present: ENV_KEYS.filter((k) => !st.missing.includes(k)), missing: st.missing }, userAgentOk: st.userAgentOk }
568
+ if (!st.complete) {
569
+ data.mode = 'read-only'
570
+ data.note = 'Without all five env vars only public .json reads work (search, rules, thread). Posting is disabled.'
571
+ return { code: 2, data, text: `read-only: missing ${st.missing.join(', ')}\n${data.note}` }
572
+ }
573
+ const client = createClient(ctx)
574
+ try {
575
+ const t = await client.auth()
576
+ const me = await client.get('/api/v1/me')
577
+ data.mode = 'authenticated'
578
+ data.scope = t.scope
579
+ data.me = { name: me.name, commentKarma: me.comment_karma, linkKarma: me.link_karma, created: me.created_utc ? new Date(me.created_utc * 1000).toISOString().slice(0, 10) : undefined, verifiedEmail: me.has_verified_email }
580
+ data.rate = client.rate()
581
+ const warn = []
582
+ if (!st.userAgentOk) warn.push('REDDIT_USER_AGENT should look like "<platform>:<app id>:<version> (by /u/<username>)"')
583
+ if (me.name && me.name.toLowerCase() !== ctx.env.REDDIT_USERNAME.toLowerCase()) warn.push('token belongs to a different user than REDDIT_USERNAME')
584
+ data.warnings = warn
585
+ return { code: 0, data, text: [`ok: authenticated as u/${me.name} (scope: ${t.scope ?? '*'})`, `karma: ${me.comment_karma ?? '?'} comment / ${me.link_karma ?? '?'} link`, ...warn.map((w) => `warning: ${w}`)].join('\n') }
586
+ } catch (e) {
587
+ data.mode = 'error'
588
+ data.error = e.message
589
+ return { code: e instanceof UsageError ? 2 : 1, data, text: `failed: ${e.message}` }
590
+ }
591
+ }
592
+
593
+ export async function search(ctx, query, { sub, limit = 25, time = 'week', sort = 'new' } = {}) {
594
+ if (!query) throw new UsageError('search needs a query')
595
+ const client = createClient(ctx)
596
+ const p = sub ? `/r/${normalizeSub(sub)}/search` : '/search'
597
+ const json = await client.get(p, { q: query, restrict_sr: sub ? '1' : undefined, sort, t: time, limit: String(Math.min(100, Number(limit) || 25)), type: 'link' })
598
+ const ledger = loadLedger(ctx.dir)
599
+ const posts = (json?.data?.children ?? []).filter((c) => c.kind === 't3').map((c) => ({ ...postSummary(c.data, ctx.now), inLedger: ledger.entries.some((e) => e.thread === c.data.id) }))
600
+ const lines = posts.map((p) => `${p.id} r/${p.subreddit} ${p.ageHours}h ${p.numComments}c${p.locked ? ' LOCKED' : ''}${p.archived ? ' ARCHIVED' : ''}${p.inLedger ? ' REPLIED' : ''} ${p.title}`)
601
+ return { code: 0, data: { query, sub, posts }, text: lines.join('\n') || 'no results' }
602
+ }
603
+
604
+ export async function rules(ctx, sub) {
605
+ const name = normalizeSub(sub)
606
+ const client = createClient(ctx)
607
+ const json = await client.get(`/r/${name}/about/rules`)
608
+ const list = (json.rules ?? []).map((r) => ({ short_name: r.short_name, description: r.description, kind: r.kind, violation_reason: r.violation_reason }))
609
+ const verdict = assessRules(list)
610
+ const text = [`r/${name}: self-promotion ${verdict.selfPromo}${verdict.matched.length ? ` (${verdict.matched.join('; ')})` : ''}`, ...list.map((r, i) => `${i + 1}. ${r.short_name}`)].join('\n')
611
+ return { code: 0, data: { subreddit: name, rules: list, ...verdict }, text }
612
+ }
613
+
614
+ export async function thread(ctx, input) {
615
+ const id = parseThreadId(input)
616
+ const client = createClient(ctx)
617
+ const json = await client.get(`/comments/${id}`, { limit: '200', depth: '3' })
618
+ const t = parseThread(json, ctx.now)
619
+ const config = loadConfig(ctx.dir)
620
+ const verdict = assessThread(t, { username: ctx.env.REDDIT_USERNAME, maxAgeDays: config.caps.maxThreadAgeDays, ledger: loadLedger(ctx.dir), now: ctx.now })
621
+ const p = t.post
622
+ const text = [
623
+ `${p.id} r/${p.subreddit} ${p.ageHours}h old ${p.numComments} comments`,
624
+ p.title,
625
+ p.permalink,
626
+ verdict.skip ? `SKIP: ${verdict.reasons.join('; ')}` : 'ok to consider',
627
+ '',
628
+ p.selftext.slice(0, 1500),
629
+ '',
630
+ ...t.comments.slice(0, 15).map((c) => `- u/${c.author}: ${String(c.body).replace(/\s+/g, ' ').slice(0, 200)}`),
631
+ ].join('\n')
632
+ return { code: 0, data: { ...t, ...verdict }, text }
633
+ }
634
+
635
+ export function draftCheck(ctx, text, { thread: threadInput, sub } = {}) {
636
+ if (!threadInput) throw new UsageError('draft-check needs --thread <id>')
637
+ if (!text || !String(text).trim()) throw new UsageError('draft-check needs a file or --text')
638
+ const thread = parseThreadId(threadInput)
639
+ const config = loadConfig(ctx.dir)
640
+ const ledger = loadLedger(ctx.dir)
641
+ const drafts = loadDrafts(ctx.dir)
642
+ const body = String(text).trim()
643
+ const r = checkDraft(body, { thread, config, ledger, drafts })
644
+ if (r.ok) {
645
+ writeJson(draftFile(ctx.dir, r.draftId), {
646
+ id: r.draftId,
647
+ thread,
648
+ subreddit: sub ? normalizeSub(sub) : undefined,
649
+ text: body,
650
+ hash: hashText(body),
651
+ mentionsProduct: r.mentionsProduct,
652
+ status: 'ready',
653
+ checkedAt: new Date(ctx.now).toISOString(),
654
+ })
655
+ }
656
+ const lines = r.checks.map((c) => `${c.ok ? 'pass' : 'FAIL'} ${c.name.padEnd(20)} ${c.detail}`)
657
+ lines.push(r.ok ? `draftId: ${r.draftId}` : 'not saved: fix the failures and re-run')
658
+ return { code: r.ok ? 0 : 1, data: { thread, ...r }, text: lines.join('\n') }
659
+ }
660
+
661
+ /** Post a checked draft. Every gate here is enforced in code, regardless of what the agent was told. */
662
+ export async function postDraft(ctx, { thread: threadInput, draft: draftId, approve, dryRun = false } = {}) {
663
+ if (!threadInput || !draftId) throw new UsageError('post needs --thread <id> --draft <draftId>')
664
+ const thread = parseThreadId(threadInput)
665
+ const config = loadConfig(ctx.dir)
666
+ const refuse = (reasons, extra = {}) => ({ code: 1, data: { posted: false, refused: true, reasons, ...extra }, text: `refused:\n${reasons.map((r) => ` - ${r}`).join('\n')}` })
667
+
668
+ // 1. Mode gate
669
+ if (config.mode !== 'review' && config.mode !== 'auto') return refuse(['no mode chosen: ask the user, then "config set mode review|auto"'])
670
+ if (config.mode === 'review' && approve !== draftId) return refuse([`review mode: needs the user's explicit approval of this exact draft (--approve ${draftId})`])
671
+ if (config.mode === 'auto' && !config.autoConfirmedAt) return refuse(['auto mode is not confirmed: show the user the caps and run "config confirm-auto" only after they agree'])
672
+
673
+ // 2. Draft integrity
674
+ const file = draftFile(ctx.dir, draftId)
675
+ const d = readJson(file, null)
676
+ if (!d) return refuse([`no checked draft ${draftId}: run draft-check first`])
677
+ if (d.thread !== thread) return refuse([`draft ${draftId} was checked for thread ${d.thread}, not ${thread}`])
678
+ if (d.status === 'posted') return refuse([`draft ${draftId} was already posted`])
679
+ if (hashText(d.text) !== d.hash) return refuse([`draft ${draftId} changed after it was checked: re-run draft-check`])
680
+
681
+ // 3. Caps before any network
682
+ const ledger = loadLedger(ctx.dir)
683
+ const pre = checkCaps(ledger, { thread, now: ctx.now, caps: config.caps })
684
+ if (pre.length) return refuse(pre)
685
+
686
+ // 4. Thread state, per-subreddit cap and rules (network, read-only)
687
+ const st = envStatus(ctx.env)
688
+ if (!st.complete) return { code: 2, data: { posted: false, missing: st.missing }, text: `cannot post: missing env ${st.missing.join(', ')}` }
689
+ const client = createClient(ctx)
690
+ let t
691
+ let verdict
692
+ try {
693
+ t = parseThread(await client.get(`/comments/${thread}`, { limit: '200', depth: '3' }), ctx.now)
694
+ const r = await client.get(`/r/${t.post.subreddit}/about/rules`)
695
+ verdict = assessRules(r.rules ?? [])
696
+ } catch (e) {
697
+ return handleNetError(ctx, e)
698
+ }
699
+ const reasons = [
700
+ ...assessThread(t, { username: ctx.env.REDDIT_USERNAME, maxAgeDays: config.caps.maxThreadAgeDays, ledger, now: ctx.now }).reasons,
701
+ ...checkCaps(ledger, { thread, subreddit: t.post.subreddit, now: ctx.now, caps: config.caps }),
702
+ ]
703
+ if (d.mentionsProduct && verdict.selfPromo === 'banned') reasons.push(`r/${t.post.subreddit} bans self-promotion (${verdict.matched.join('; ')}) and this draft mentions the product`)
704
+ const unique = [...new Set(reasons)]
705
+ if (unique.length) return refuse(unique, { subreddit: t.post.subreddit })
706
+
707
+ if (dryRun) return { code: 0, data: { posted: false, dryRun: true, thread, subreddit: t.post.subreddit, draftId, mode: config.mode }, text: `dry run: would post ${draftId} to r/${t.post.subreddit} thread ${thread}` }
708
+
709
+ // 5. Post
710
+ let res
711
+ try {
712
+ res = await client.post('/api/comment', { api_type: 'json', thing_id: `t3_${thread}`, text: d.text })
713
+ } catch (e) {
714
+ return handleNetError(ctx, e)
715
+ }
716
+ const errors = res?.json?.errors ?? []
717
+ if (errors.length) {
718
+ const rl = errors.find((x) => x[0] === 'RATELIMIT')
719
+ if (rl) recordRateLimit(ctx, parseRateLimitMessage(rl[1]))
720
+ return refuse(errors.map((x) => `reddit: ${x[0]} ${x[1] ?? ''}`.trim()))
721
+ }
722
+ const thing = res?.json?.data?.things?.[0]?.data ?? {}
723
+ const entry = {
724
+ thread,
725
+ subreddit: t.post.subreddit,
726
+ draftId,
727
+ commentId: thing.id ?? thing.name,
728
+ permalink: thing.permalink ? `https://www.reddit.com${thing.permalink}` : undefined,
729
+ text: d.text,
730
+ mode: config.mode,
731
+ approvedBy: config.mode === 'review' ? 'user' : 'auto-confirmed',
732
+ postedAt: new Date(ctx.now).toISOString(),
733
+ }
734
+ const fresh = loadLedger(ctx.dir)
735
+ fresh.entries.push(entry)
736
+ saveLedger(ctx.dir, fresh)
737
+ writeJson(file, { ...d, status: 'posted', postedAt: entry.postedAt, commentId: entry.commentId })
738
+ return { code: 0, data: { posted: true, ...entry }, text: `posted ${draftId} to r/${entry.subreddit}: ${entry.permalink ?? entry.commentId}` }
739
+ }
740
+
741
+ export function parseRateLimitMessage(msg = '') {
742
+ const m = String(msg).match(/(\d+)\s*(second|minute|hour)/i)
743
+ if (!m) return 600
744
+ const n = Number(m[1])
745
+ return /hour/i.test(m[2]) ? n * 3600 : /minute/i.test(m[2]) ? n * 60 : n
746
+ }
747
+
748
+ function recordRateLimit(ctx, seconds) {
749
+ const l = loadLedger(ctx.dir)
750
+ l.rateLimitedUntil = new Date(ctx.now + seconds * 1000).toISOString()
751
+ saveLedger(ctx.dir, l)
752
+ }
753
+
754
+ function handleNetError(ctx, e) {
755
+ if (e instanceof UsageError) return { code: 2, data: { posted: false, error: e.message }, text: e.message }
756
+ if (e.status === 429) recordRateLimit(ctx, e.retryAfterSec ?? 60)
757
+ return { code: 1, data: { posted: false, error: e.message, status: e.status }, text: `failed: ${e.message}` }
758
+ }
759
+
760
+ export function ledgerCmd(ctx, sub = 'list') {
761
+ const ledger = loadLedger(ctx.dir)
762
+ const config = loadConfig(ctx.dir)
763
+ if (sub === 'today') {
764
+ const s = todaySummary(ledger, { now: ctx.now, caps: config.caps })
765
+ const text = [`${s.posted}/${s.cap} in the last 24h, ${s.remaining} left; next allowed ${s.nextAllowedAt}`, ...Object.entries(s.bySubreddit).map(([k, v]) => ` r/${k}: ${v}/${s.perSubCap}`)].join('\n')
766
+ return { code: 0, data: s, text }
767
+ }
768
+ if (sub !== 'list') throw new UsageError('ledger list | today')
769
+ const text = ledger.entries.map((e) => `${e.postedAt} r/${e.subreddit} ${e.thread} ${e.mode} ${e.permalink ?? e.commentId ?? ''}`).join('\n') || 'ledger is empty'
770
+ return { code: 0, data: ledger, text }
771
+ }
772
+
773
+ export function configCmd(ctx, [action = 'get', key, ...rest]) {
774
+ const config = loadConfig(ctx.dir)
775
+ if (action === 'get') {
776
+ const v = key ? getPath(config, key) : config
777
+ return { code: 0, data: v ?? null, text: typeof v === 'object' ? JSON.stringify(v, null, 2) : String(v ?? '') }
778
+ }
779
+ if (action === 'set') {
780
+ if (!key || rest.length === 0) throw new UsageError('config set <key> <value>')
781
+ const next = setConfigValue(config, key, rest.join(' '))
782
+ saveConfig(ctx.dir, next)
783
+ const note = config.autoConfirmedAt && !next.autoConfirmedAt ? ' (auto confirmation cleared: confirm again with the user)' : ''
784
+ return { code: 0, data: next, text: `${key} = ${JSON.stringify(getPath(next, key))}${note}` }
785
+ }
786
+ if (action === 'confirm-auto') {
787
+ const next = confirmAuto(config, ctx.now)
788
+ saveConfig(ctx.dir, next)
789
+ const c = next.caps
790
+ return { code: 0, data: next, text: `auto mode confirmed at ${next.autoConfirmedAt}: max ${c.perDay}/24h, ${c.perSubPerDay}/subreddit/24h, ${c.cooldownMinutes}m cooldown` }
791
+ }
792
+ throw new UsageError('config get [key] | set <key> <value> | confirm-auto')
793
+ }
794
+
795
+ // ---------------------------------------------------------------------------
796
+ // CLI
797
+ // ---------------------------------------------------------------------------
798
+
799
+ const VALUED = new Set(['--sub', '--limit', '--time', '--sort', '--thread', '--draft', '--approve', '--text', '--dir'])
800
+
801
+ export function parseCli(argv) {
802
+ const flags = {}
803
+ const pos = []
804
+ for (let i = 0; i < argv.length; i++) {
805
+ const a = argv[i]
806
+ if (VALUED.has(a)) {
807
+ if (i + 1 >= argv.length) throw new UsageError(`${a} needs a value`)
808
+ flags[a.slice(2)] = argv[++i]
809
+ } else if (a.startsWith('--')) flags[a.slice(2)] = true
810
+ else pos.push(a)
811
+ }
812
+ return { flags, pos }
813
+ }
814
+
815
+ export async function run(argv, { fetch: f = globalThis.fetch, env = process.env, now = Date.now(), out = process.stdout, err = process.stderr } = {}) {
816
+ let json = argv.includes('--json')
817
+ try {
818
+ if (!argv.length || argv[0] === '--help' || argv[0] === '-h' || argv[0] === 'help') {
819
+ out.write(HELP)
820
+ return argv.length ? 0 : 2
821
+ }
822
+ if (argv[0] === '--version') {
823
+ out.write(VERSION + '\n')
824
+ return 0
825
+ }
826
+ const { flags, pos } = parseCli(argv)
827
+ json = Boolean(flags.json)
828
+ const [cmd, ...args] = pos
829
+ const ctx = { fetch: f, env, now, dir: stateDir({ dir: flags.dir }) }
830
+ let r
831
+ switch (cmd) {
832
+ case 'doctor':
833
+ r = await doctor(ctx)
834
+ break
835
+ case 'config':
836
+ r = configCmd(ctx, args)
837
+ break
838
+ case 'search':
839
+ r = await search(ctx, args.join(' '), { sub: flags.sub, limit: flags.limit, time: flags.time, sort: flags.sort })
840
+ break
841
+ case 'rules':
842
+ if (!args[0]) throw new UsageError('rules <subreddit>')
843
+ r = await rules(ctx, args[0])
844
+ break
845
+ case 'thread':
846
+ if (!args[0]) throw new UsageError('thread <id|url>')
847
+ r = await thread(ctx, args[0])
848
+ break
849
+ case 'draft-check': {
850
+ const text = flags.text ?? (args[0] ? fs.readFileSync(args[0], 'utf8') : undefined)
851
+ r = draftCheck(ctx, text, { thread: flags.thread, sub: flags.sub })
852
+ break
853
+ }
854
+ case 'post':
855
+ r = await postDraft(ctx, { thread: flags.thread, draft: flags.draft, approve: flags.approve, dryRun: Boolean(flags['dry-run']) })
856
+ break
857
+ case 'ledger':
858
+ r = ledgerCmd(ctx, args[0])
859
+ break
860
+ default:
861
+ throw new UsageError(`unknown command "${cmd}" (try --help)`)
862
+ }
863
+ out.write(json ? JSON.stringify({ ok: r.code === 0, ...(r.data && typeof r.data === 'object' && !Array.isArray(r.data) ? r.data : { value: r.data }) }, null, 2) + '\n' : r.text + '\n')
864
+ return r.code
865
+ } catch (e) {
866
+ const code = e instanceof UsageError || e.code === 2 ? 2 : 1
867
+ if (json) out.write(JSON.stringify({ ok: false, error: e.message }) + '\n')
868
+ else err.write(`reddit: ${e.message}\n`)
869
+ return code
870
+ }
871
+ }
872
+
873
+ // Run only when this file is the entry point. Real paths are compared because
874
+ // the path Node was given can be a symlink (macOS /tmp and /var, a linked
875
+ // skills folder), and then it never equals the module's own URL.
876
+ function isEntryPoint(url) {
877
+ try { return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(url)) } catch { return false }
878
+ }
879
+
880
+ if (isEntryPoint(import.meta.url)) process.exitCode = await run(process.argv.slice(2))