Add /newroaster and a configurable default board
- /newroaster builds a new advisor the way the original seven were built: finds and fetches public sources, extracts frameworks, rules, positions, stories, and voice with parallel sub-agents, writes the brain, checks every quote is verbatim, writes the council agent, and registers the seat. - roster.json lists every seat, the default board, and how each council picks its seats (default, ask, or auto). /roast-room board changes it; --seats and --all override it per run. - The room reads the roster: it seats up to nine, picks up new seats without a restart, and draws a talking bust for seats without portraits. - README and CLAUDE.md explain choosing the board and adding an advisor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f5e7b631a1
commit
bc9f45ba0d
21 files changed
+965
-75
No files matched your search
@@ -0,0 +1,157 @@
|
||||
---
|
||||
name: newroaster
|
||||
description: Use when someone wants to add a new advisor to the Roast Room, says "/newroaster", "add a roaster", "add a seat", "add [name] to the council", "build a seat for [name]", "I want [name] on my board", or wants their own advisor (themselves, a mentor, or any public figure) built from public work. Builds the seat the same way the original seven were built. It finds and fetches the person's public sources, extracts their frameworks, rules, positions, stories, and voice with parallel sub-agents, writes the brain, checks every quote is verbatim, writes the council agent, and registers the seat in the roster (on the default board if asked). Not for running a council (that is /roast-room).
|
||||
argument-hint: "[full name] [--quick | --deep] [--pillar \"...\"] [--default]"
|
||||
---
|
||||
|
||||
## What this does
|
||||
|
||||
Adds one seat to the Roast Room. A seat is three things, and this skill makes all three:
|
||||
|
||||
1. **A brain**: `.claude/skills/roast-room/brains/<slug>/`, eight files compiled from the person's public work, every quote verbatim with a source id.
|
||||
2. **An agent**: `.claude/agents/council-<key>.md`, the sub-agent that reasons and talks like them from that brain.
|
||||
3. **A roster entry**: one line in `.claude/skills/roast-room/roster.json`, so `/roast-room` and the room know the seat exists.
|
||||
|
||||
The raw sources stay in a local build folder that git ignores. Only the brain ships.
|
||||
|
||||
Build folder: `build/<slug>/` at the project root.
|
||||
|
||||
Read before the first run: `references/brain-spec.md` (the brain layout and its rules), `references/extract-prompt.md` (what each extraction agent gets), `references/agent-template.md` (the seat agent).
|
||||
|
||||
## Who can be a roaster
|
||||
|
||||
- **Public figures with a real body of public work**: essays, letters, books as they teach them in talks, long interviews where they are the main speaker, keynotes, their own channel or podcast. Living or historical.
|
||||
- **The user, or someone who gave consent**: built from material the user provides (their posts, transcripts, notes). Use `--add` in step 3.
|
||||
- **Not**: fictional characters, private people without their consent, or anyone whose public work is too thin. Under about 15 usable sources or 60,000 words, say so and offer `--quick` with a warning, or a different person.
|
||||
|
||||
The seat is a simulation, not the person. The agent says so if asked, and only quotes what is in its brain.
|
||||
|
||||
## Depth
|
||||
|
||||
| Flag | Sources | Words | Extraction agents | Use it for |
|
||||
|---|---|---|---|---|
|
||||
| `--quick` | 12 to 20 | 80k+ | 2 to 3 | Trying someone out |
|
||||
| default | 30 to 50 | 250k+ | 4 to 6 | A seat you will actually use |
|
||||
| `--deep` | 80+ | 500k+ | 8 to 12, in waves | Matching the original seven |
|
||||
|
||||
Quality beats count: one 90-minute keynote is worth ten 6-minute clips.
|
||||
|
||||
## Step 1: Who and what seat
|
||||
|
||||
From the user's message, get the person's full name. If anything below is missing, ask in one AskUserQuestion batch (at most four questions), offering your best guess as the first option:
|
||||
|
||||
1. **The pillar and the question the seat owns.** Propose one from what the person is known for, worded like the existing seats in `roster.json` (pillar: a few words; question: one plain question a founder would face). If an existing seat already owns that pillar, propose a sharper angle so the two seats argue instead of repeating each other.
|
||||
2. **Default board?** Put them at the table for every council, or keep them on call (`--seats` and `ask`). If the default board already has nine seats, ask who they replace.
|
||||
3. **Depth**: quick, standard, or deep (default standard).
|
||||
|
||||
Then fix the names: `key` (short lowercase, letters only, unique in the roster, usually the surname: `naval`, `drucker`), `slug` (`first-last`), `short` (how the room names them: "Naval"), and the scorecard `dimension` (a few words for what this seat scores, like "Leverage and long-term wealth").
|
||||
|
||||
Check the roster first: if the person already has a seat, stop and offer to refresh it instead (step 3 onward on the same slug; fetch skips sources already in `sources.json`).
|
||||
|
||||
## Step 2: Find sources
|
||||
|
||||
Use WebSearch to build a source list, best first. Look for:
|
||||
|
||||
- Their own site, blog, essays, newsletter archive, or letters (the richest text, with dates).
|
||||
- Long talks and keynotes where they are the speaker.
|
||||
- Long interviews and podcasts where they are the main guest (their own podcast counts).
|
||||
- Their books as they teach them in public: author talks, interviews about the book, chapters they posted free. Never fetch pirated or paywalled book text.
|
||||
- Recent material (last two years) so `positions.md` reflects current views, and a spread of years so changes of mind show up.
|
||||
|
||||
Skip clips under about 10 minutes, fan compilations, reaction videos, and pieces where someone else does most of the talking. Write the URLs to `<build>/urls.txt`, one per line, with a `# heading` line per group. Aim for the source count of the chosen depth plus about 20 percent, since some will fail.
|
||||
|
||||
## Step 3: Fetch
|
||||
|
||||
```bash
|
||||
node .claude/skills/newroaster/scripts/fetch.mjs <build> --list <build>/urls.txt
|
||||
```
|
||||
|
||||
Each source becomes `<build>/corpus/S001-<title>.md`, logged in `<build>/sources.json`. It prints `ok`, `skip`, `thin` (paywall or a JavaScript page), or `fail` per URL, then a manifest. YouTube uses yt-dlp when installed, otherwise YouTube's own captions. For local material the user gave you:
|
||||
|
||||
```bash
|
||||
node .claude/skills/newroaster/scripts/fetch.mjs <build> --add path/to/file.md --title "..." --date 2024-05-01
|
||||
```
|
||||
|
||||
If a source came back thin or failed, find a different copy (a transcript page, an archive.org copy) or replace it. A PDF without `pdftotext` is saved as `pending-*.pdf`: read it with the Read tool, save the text as a `.md`, then `--add` it. Re-run until the manifest meets the depth target, then open two or three corpus files to confirm they are clean text by the right person. Write the manifest line counts into your notes for the final report.
|
||||
|
||||
## Step 4: Extract (map)
|
||||
|
||||
Split the sources into batches of about 50,000 words each (a 90-minute talk is about 13,000; a long essay 5,000). Spawn one extraction agent per batch, in **one message**, in parallel, foreground: `subagent_type: general-purpose`, `model: sonnet`, with the prompt from `references/extract-prompt.md` (fill in the name, the seat's pillar and question, the batch's source ids and file paths, and the notes file to write). Run at most six at a time; for `--deep`, run them in waves.
|
||||
|
||||
Each agent writes `<build>/notes/batch-NN.md`. Wait until every agent has reported. When all are back, check every note quote:
|
||||
|
||||
```bash
|
||||
node .claude/skills/newroaster/scripts/check_quotes.mjs <build> <build>/notes
|
||||
```
|
||||
|
||||
Fix what it reports: correct a wrong source id, delete a quote it cannot find. Notes with no verifiable quote can stay as paraphrase, marked "inferred from S0xx".
|
||||
|
||||
## Step 5: Write the brain (reduce)
|
||||
|
||||
Create `.claude/skills/roast-room/brains/<slug>/`. Write `sources.md` with the script:
|
||||
|
||||
```bash
|
||||
node .claude/skills/newroaster/scripts/fetch.mjs <build> --sources-md .claude/skills/roast-room/brains/<slug>/sources.md --name "Full Name"
|
||||
```
|
||||
|
||||
Then spawn three writer agents in one message, in parallel (`general-purpose`, default model). Each reads every notes file plus `references/brain-spec.md` and writes its files into the brain folder, following the spec's budgets and rules:
|
||||
|
||||
- Writer A: `frameworks.md`, `principles.md`, and `books.md`.
|
||||
- Writer B: `positions.md` and `stories.md`.
|
||||
- Writer C: `voice.md`.
|
||||
|
||||
Tell each writer the seat's pillar and question, the build folder (so it can open a corpus file to check a quote's context), and that every quote must be copied exactly from the notes with its source id. Writers write only their own files.
|
||||
|
||||
When they are back, write `_hot.md` yourself from the six finished files (the spec lists what goes in it, including "where this lens misfires"). Then check the whole brain:
|
||||
|
||||
```bash
|
||||
node .claude/skills/newroaster/scripts/check_quotes.mjs <build> .claude/skills/roast-room/brains/<slug>
|
||||
```
|
||||
|
||||
Fix until it passes: every quote verbatim, every id right. Read `_hot.md` once more as the agent will: it should tell you how this person decides, in their words, in under 800 words.
|
||||
|
||||
## Step 6: Write the agent
|
||||
|
||||
Write `.claude/agents/council-<key>.md` from `references/agent-template.md`. Fill every bracket from the brain: the lens (five or six questions this person asks of any decision), how they talk (from `voice.md`), how they debate (name their natural opponents among the seats in `roster.json` and what they concede, from "where this lens misfires"), and the never-list. The description names the pillar, the source count and what the brain is built from, and the trigger phrases ("what would [name] say").
|
||||
|
||||
## Step 7: Register the seat
|
||||
|
||||
```bash
|
||||
node .claude/skills/newroaster/scripts/add_seat.mjs --key <key> --name "<Full Name>" --short "<Short>" --slug <slug> --pillar "<pillar>" --question "<question>" --dimension "<dimension>" [--default] [--swap <key>]
|
||||
```
|
||||
|
||||
It refuses if the agent file or a brain file is missing. `--default` adds the seat to the default board; `--swap <key>` takes another seat off it in the same move. Then:
|
||||
|
||||
- Add one or two "natural tension" lines for the new seat to `.claude/skills/roast-room/references/seats.md` (who they will clash with, and over what).
|
||||
|
||||
## Step 8: Test the seat
|
||||
|
||||
New agent files load when Claude Code starts, so test with the fallback the council itself uses: spawn `general-purpose` with `Read .claude/agents/council-<key>.md and follow it as your instructions for this whole task. Only read files; do not write anything.` followed by the single-seat consult prompt from `.claude/skills/roast-room/references/round-prompts.md`, on a short sample decision in the seat's pillar. Then check its answer:
|
||||
|
||||
- It sounds like the person (compare with `voice.md`), speaks in the first person, and never claims to be them.
|
||||
- It names frameworks with source ids, and every quote passes `check_quotes.mjs` (save the answer to `<build>/test-consult.md` and run the checker on it).
|
||||
- It owns its pillar instead of giving generic advice.
|
||||
|
||||
If it fails, fix the agent or `_hot.md` and test again, once.
|
||||
|
||||
## Step 9: Report
|
||||
|
||||
Tell the user, in under 150 words:
|
||||
|
||||
- Who was added, their pillar and question, and whether they are on the default board.
|
||||
- The brain: sources, words, years covered, and the files written.
|
||||
- How to use them now: `/roast-room ask <key> ...` for one answer, `/roast-room --seats <key>,buffett,... ...` to seat them, and `/roast-room board` to change the default board.
|
||||
- One line: restart Claude Code (or open a new session) so the seat loads as its own agent type; until then the council uses the fallback automatically.
|
||||
- One line: the room draws them a simple cartoon bust in their color. For a real portrait, save a square image with a transparent background as `app/public/portraits/<key>-base.png` (`.webp` or `.jpg` also work). Add `-open`, `-mid`, and `-blink` versions of the same image to make the mouth move.
|
||||
|
||||
## Without sub-agents (Codex or a runtime that cannot spawn agents)
|
||||
|
||||
Run steps 4 and 5 yourself, one batch at a time: extract a batch into its notes file, then move to the next. Write the brain files one at a time from the notes. Everything else is the same.
|
||||
|
||||
## Rules
|
||||
|
||||
- Public and lawful sources only. The corpus stays in the build folder and is never committed or shared; the brain holds short quotes (under 45 words) and paraphrase, never book text.
|
||||
- Every quote in the brain is verbatim and passes `check_quotes.mjs`. A line with no source is inference and says so.
|
||||
- Do not touch the other seats' brains or agents. Only `roster.json`'s `"seats"` and `"default"` change, through `add_seat.mjs`.
|
||||
- Plain English in everything you write yourself: short sentences, no em dashes, no filler.
|
||||
- Cost: a standard seat is about 8 to 10 sub-agent runs. Say which depth you used.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Seat agent template
|
||||
|
||||
Write this to `.claude/agents/council-<key>.md`, replacing every bracket. Model it on an existing seat (`.claude/agents/council-graham.md` is a good one to read first). Keep the section headings so every seat has the same shape. The frontmatter `description` must not contain a colon followed by a space.
|
||||
|
||||
```markdown
|
||||
---
|
||||
name: council-[key]
|
||||
description: The [pillar, lowercase] seat on the Roast Room council. Reasons, decides, and talks the way [Full Name] does, grounded in a brain compiled from [N] of [his/her/their] public sources ([what they are, with years]). Use inside /roast-room, or directly when someone asks "what would [Name] say", wants a read on [three or four topics this seat owns], or asks the [Short] seat a question.
|
||||
tools: Read, Grep, Glob
|
||||
maxTurns: 12
|
||||
---
|
||||
|
||||
You hold the **[Pillar]** seat on the Roast Room council. You reason, decide, and talk the way [Full Name] does. You are not [Full Name] and never claim to be; you are a simulation built from [their] public work, and if anyone asks, you say so. Your job on the council: own one question, **"[question]"**, and bring that lens at full strength. The Chair balances the room. You do not.
|
||||
|
||||
## Your brain
|
||||
|
||||
Root: `.claude/skills/roast-room/brains/[slug]/`
|
||||
|
||||
1. Read `_hot.md` first, every time.
|
||||
2. Then at most three more files that fit the decision: `frameworks.md`, `positions.md` ([one note, such as "stances with dates; cite the newer view when they changed"]), `principles.md`, `voice.md` (read it before your first answer in a session), `stories.md`, `books.md`.
|
||||
3. Never look outside your brain folder for facts about [Name]. The brain is your memory.
|
||||
4. Cite every framework or rule you use with its source id from the brain, like ([Framework name], S0xx). Quote only lines that appear verbatim in the brain. Everything else is your reasoning, in your voice, unquoted.
|
||||
|
||||
## Your lens
|
||||
|
||||
- [Five or six questions this person asks of any decision, each one line, from _hot.md's decision loop.]
|
||||
|
||||
## How you talk
|
||||
|
||||
[Three to five sentences from voice.md: sentence length, cadence, the moves they make, signature phrases to use when they fit, how they hedge or don't.]
|
||||
|
||||
- Speak as the seat, in the first person ("I'd kill option A"). Never narrate the expert in the third person ("he says", "by her rule"). Verbatim lines go in quotes with the source id, and that is the only attribution you need.
|
||||
|
||||
## How you debate
|
||||
|
||||
- Argue from your pillar first, with numbers. If the brief lacks the numbers you need, state your assumption and run the math anyway.
|
||||
- Your natural opponents are [two or three seats from roster.json, with what you push them on]. [What you concede, from "where this lens misfires".]
|
||||
- Engage the strongest version of the other seats' arguments. Move only for a better argument or a new fact, and say exactly what moved you.
|
||||
- If everyone agrees with you, attack the weakest part of your own case.
|
||||
- Answer in the exact shape the round prompt asks for. No preamble.
|
||||
|
||||
## Never
|
||||
|
||||
- Claim to be [Full Name], speak for [them] about things outside the brain, or invent a quote, number, or story.
|
||||
- Use em dashes.
|
||||
- Hedge to sound balanced. A clear "no" with a reason is more useful than a soft "it depends".
|
||||
- [One or two misuses specific to this lens, from "where this lens misfires".]
|
||||
```
|
||||
@@ -0,0 +1,30 @@
|
||||
# Brain spec: one seat on the Roast Room council
|
||||
|
||||
Every seat has the same brain layout, so the council agents differ only in content. The original seven follow this spec; new seats must too.
|
||||
|
||||
Folder: `.claude/skills/roast-room/brains/<slug>/`
|
||||
|
||||
## Files
|
||||
|
||||
| File | Budget (standard; `--quick` may run about half) | Contents |
|
||||
|---|---|---|
|
||||
| `_hot.md` | 600 to 800 words | Read on every council call. Who the seat is, the pillar and the question it owns, the corpus in one line, worldview in three sentences, the 8 rules they decide by (each with one short verbatim quote and source id), the 5 frameworks they reach for first, their decision loop (5 or 6 steps), signature questions they ask founders, a voice cheat sheet (5 lines), and **where this lens misfires**. |
|
||||
| `frameworks.md` | 12 to 25 entries | Name (as they name it, or a short name marked *(unnamed)*), what it is, parts or steps, when to use it, how to score a decision with it (scoring guidance from their own thresholds, labeled as guidance), one verbatim quote with source id, and how many sources use it (with ids). Include the frameworks from their books. Most-used first. |
|
||||
| `principles.md` | 15 to 30 entries | Decision rules in one plain sentence, one or two verbatim quotes with source ids, number of supporting sources, confidence (high = 3+ sources, medium = 2, low = 1). |
|
||||
| `positions.md` | 20 to 40 topics | Their stance on common founder questions: pricing, discounting, raising money, debt, first hire, firing, partners, equity, focus versus diversification, side projects, niche, content, paid ads, brand, AI, remote work, work hours, burnout, selling the company, culture, metrics, competition, timing. Verbatim quote, source id, and date. When they changed their mind, record both views side by side with dates. Topics with no evidence say "no recorded position"; never guess. |
|
||||
| `voice.md` | 400 to 700 words | How they talk: sentence length, cadence, signature phrases (verbatim, with how many sources use them), go-to analogies, how they open and close an argument, how they disagree, words and moves they never use. Then 8 to 12 short verbatim voice anchors (under 45 words each, with source ids). |
|
||||
| `stories.md` | 10 to 20 entries | The stories and case studies they reuse, one or two lines each with the lesson and source ids. |
|
||||
| `books.md` | one entry per book | Title, year, core thesis, key frameworks in your own words, which sources teach it. Never reproduce book text. If they have no books, say so in one line and list their major essays or series instead. |
|
||||
| `sources.md` | all | Written by `fetch.mjs --sources-md`: a header with counts and total words, then `id | title | url | date | words` per source. |
|
||||
|
||||
Each file opens with a `# <File>: <Full Name>` heading and one line on what it was built from.
|
||||
|
||||
## Rules
|
||||
|
||||
- Every quote is verbatim from the corpus and carries a source id from `sources.md`, like "..." (S014). Quotes stay under 45 words. `check_quotes.mjs` must pass on the whole folder.
|
||||
- Quotation marks mean verbatim. Signature questions, paraphrases, and your own summaries go without them, so no agent later passes them off as the person's words.
|
||||
- Never attribute a view without a source id. A line that is your reading of several sources says "inferred from S0xx, S0yy".
|
||||
- Plain English. No em dashes. No filler.
|
||||
- The brain describes how the person thinks so an agent can reason like them. It is not a biography and not a fan page: include where they are wrong, inconsistent, or out of their depth.
|
||||
- **Where this lens misfires** is mandatory in `_hot.md`: the situations where this person's advice is known to fit badly (advice built for high-ticket services applied to SaaS, public-equity rules applied to a seed-stage startup, a solo creator's playbook applied to a 50-person company). Use what they say about their own limits first, then the shape of their experience.
|
||||
- Prefer newer sources when views changed, and say so with dates.
|
||||
@@ -0,0 +1,51 @@
|
||||
# Extraction prompt (map step)
|
||||
|
||||
One agent per batch of about 50,000 words. Spawn them in one message, in parallel: `subagent_type: general-purpose`, `model: sonnet`. Replace the bracketed parts.
|
||||
|
||||
```
|
||||
ROAST ROOM SEAT BUILD: EXTRACT NOTES
|
||||
|
||||
You are building the brain for a new Roast Room seat: [Full Name], who will hold the [pillar] seat and own the question "[question]". The brain teaches an agent to reason, decide, and talk like this person. Your job is one batch of their public sources.
|
||||
|
||||
Repo root: [absolute path]
|
||||
Read these source files in full (each opens with its title and "Source: S0xx | url | date"):
|
||||
[one line per source: S0xx | corpus/S0xx-....md | words]
|
||||
|
||||
Write your notes to: [build]/notes/batch-[NN].md
|
||||
Write nothing else. Do not edit the source files.
|
||||
|
||||
For each source, add a section "## S0xx | [title] | [date]" with these parts. Skip a part when the source has nothing for it. Only extract what [Full Name] says; ignore the host, the interviewer, and other guests.
|
||||
|
||||
### Frameworks
|
||||
- **[Name as they call it, or a short name + (unnamed)]**: what it is, its parts or steps, when they use it, and any threshold or number they attach. Quote: "[verbatim]" (S0xx)
|
||||
|
||||
### Rules
|
||||
- [A decision rule in one plain sentence.] Quote: "[verbatim]" (S0xx)
|
||||
|
||||
### Positions
|
||||
- [Topic]: [their stance in one line]. Quote: "[verbatim]" (S0xx)
|
||||
Topics that matter most: pricing, discounting, raising money, debt, hiring, firing, partners, equity, focus, side projects, niche, content, ads, brand, AI, remote work, hours, burnout, selling the company, culture, metrics, competition, timing. Anything they feel strongly about counts too.
|
||||
|
||||
### Stories
|
||||
- [The story in one line]: [the lesson they draw]. (S0xx)
|
||||
|
||||
### Books
|
||||
- [Title]: what they say the book argues, in your words. (S0xx)
|
||||
|
||||
### Voice
|
||||
- Signature phrases, verbatim. Analogies they reach for. How they open, argue, disagree, and close. Words or moves they avoid.
|
||||
- Two or three voice anchors: short verbatim lines (under 45 words) that sound most like them. "[verbatim]" (S0xx)
|
||||
|
||||
### Limits
|
||||
- Anything they say about where their advice does not apply, mistakes they admit, or views they changed (with the date). (S0xx)
|
||||
|
||||
Quote rules, which a script checks against the source files:
|
||||
- Copy quotes character for character from the source file, including their grammar and filler words. Never fix, merge, or paraphrase inside quotation marks.
|
||||
- Every quote is under 45 words and is followed by its source id in parentheses.
|
||||
- A quote may skip words with "..." only inside one passage.
|
||||
- If you cannot find the exact words, write the point as paraphrase with no quotation marks.
|
||||
|
||||
At the end, add "## Batch summary": the five frameworks and five rules that came up most in this batch, with source ids.
|
||||
|
||||
Reply with one line: the notes path, and how many frameworks, rules, positions, and quotes you wrote.
|
||||
```
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env node
|
||||
// Register a finished seat in the Roast Room roster (.claude/skills/roast-room/roster.json).
|
||||
//
|
||||
// node .claude/skills/newroaster/scripts/add_seat.mjs --key naval --name "Naval Ravikant" --short Naval \
|
||||
// --slug naval-ravikant --pillar "Leverage and wealth" --question "Does this build leverage you own?" \
|
||||
// --dimension "Leverage and long-term wealth" [--color "#22b8a0"] [--default] [--swap <key>]
|
||||
//
|
||||
// Checks the agent file and the brain exist first, so a half-built seat never reaches the table.
|
||||
// --default puts the seat on the default board; --swap <key> takes that seat off the board in
|
||||
// the same move (the board holds at most nine). Running it again for the same key updates it.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..");
|
||||
const SKILL = path.join(ROOT, ".claude", "skills", "roast-room");
|
||||
const ROSTER = path.join(SKILL, "roster.json");
|
||||
const MAX_BOARD = 9;
|
||||
const BRAIN_FILES = ["_hot.md", "frameworks.md", "principles.md", "positions.md", "voice.md", "stories.md", "sources.md"];
|
||||
const PALETTE = ["#22b8a0", "#e05d9b", "#c9a227", "#5b7cfa", "#ef7d32", "#2fa4d6", "#a3be3c", "#b06ad9", "#d6543f", "#3fb37f"];
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const opt = (n) => { const i = args.indexOf(`--${n}`); return i >= 0 ? args[i + 1] : undefined; };
|
||||
const fail = (m) => { console.error("add_seat: " + m); process.exit(1); };
|
||||
|
||||
const seat = {
|
||||
key: (opt("key") || "").toLowerCase(),
|
||||
name: opt("name"), short: opt("short"), initials: opt("initials"), slug: opt("slug"),
|
||||
pillar: opt("pillar"), question: opt("question"), dimension: opt("dimension"), color: opt("color"),
|
||||
};
|
||||
for (const f of ["key", "name", "short", "slug", "pillar", "question", "dimension"]) if (!seat[f]) fail(`--${f} is required`);
|
||||
if (!/^[a-z][a-z0-9]{1,15}$/.test(seat.key)) fail("--key must be 2 to 16 lowercase letters or digits, starting with a letter");
|
||||
if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(seat.slug)) fail("--slug must look like first-last");
|
||||
seat.initials ||= seat.name.split(/\s+/).map((w) => w[0]).join("").slice(0, 3).toUpperCase();
|
||||
|
||||
const agent = path.join(ROOT, ".claude", "agents", `council-${seat.key}.md`);
|
||||
if (!fs.existsSync(agent)) fail(`missing agent file ${path.relative(ROOT, agent)}`);
|
||||
const brain = path.join(SKILL, "brains", seat.slug);
|
||||
const missing = BRAIN_FILES.filter((f) => !fs.existsSync(path.join(brain, f)));
|
||||
if (missing.length) fail(`brain ${path.relative(ROOT, brain)} is missing ${missing.join(", ")}`);
|
||||
|
||||
const r = JSON.parse(fs.readFileSync(ROSTER, "utf8"));
|
||||
const others = r.seats.filter((s) => s.key !== seat.key);
|
||||
if (others.some((s) => s.slug === seat.slug)) fail(`slug ${seat.slug} already belongs to another seat`);
|
||||
if (others.some((s) => s.short.toLowerCase() === seat.short.toLowerCase())) fail(`short name ${seat.short} is taken; pick another`);
|
||||
if (!/^#[0-9a-f]{6}$/i.test(seat.color || "")) {
|
||||
const used = new Set(r.seats.map((s) => s.color.toLowerCase()));
|
||||
seat.color = PALETTE.find((c) => !used.has(c)) || PALETTE[r.seats.length % PALETTE.length];
|
||||
}
|
||||
const at = r.seats.findIndex((s) => s.key === seat.key);
|
||||
if (at >= 0) r.seats[at] = seat; else r.seats.push(seat);
|
||||
|
||||
const swap = opt("swap");
|
||||
if (swap) r.default = r.default.filter((k) => k !== swap);
|
||||
if (args.includes("--default") && !r.default.includes(seat.key)) {
|
||||
if (r.default.length >= MAX_BOARD) fail(`the default board already has ${MAX_BOARD} seats; add --swap <key> to take one off`);
|
||||
r.default.push(seat.key);
|
||||
}
|
||||
|
||||
// one seat per line keeps the file easy to read and edit by hand
|
||||
const line = (o) => "{ " + Object.entries(o).map(([k, v]) => `${JSON.stringify(k)}: ${JSON.stringify(v)}`).join(", ") + " }";
|
||||
const out = [
|
||||
"{",
|
||||
` "board": ${JSON.stringify(r.board || "default")},`,
|
||||
` "default": [${r.default.map((k) => JSON.stringify(k)).join(", ")}],`,
|
||||
` "seats": [`,
|
||||
r.seats.map((s) => " " + line(s)).join(",\n"),
|
||||
" ]",
|
||||
"}",
|
||||
].join("\n") + "\n";
|
||||
JSON.parse(out); // never write a file the room cannot read
|
||||
fs.writeFileSync(ROSTER, out);
|
||||
|
||||
console.log(`${at >= 0 ? "Updated" : "Added"} ${seat.name} (${seat.key}) to the roster.`);
|
||||
console.log(`Default board (${r.default.length}): ${r.default.map((k) => r.seats.find((s) => s.key === k)?.short || k).join(", ")}`);
|
||||
console.log(`Board setting: ${r.board || "default"}`);
|
||||
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env node
|
||||
// Check that every quote in a seat's notes or brain is verbatim in the source it cites.
|
||||
//
|
||||
// node .claude/skills/newroaster/scripts/check_quotes.mjs <build dir> <file or folder> [...]
|
||||
//
|
||||
// A quote is text in double quotes followed within a few characters by a source id, like
|
||||
// "..." (S014) or "..." (S014, S020). Each quote must appear in the corpus file of one of
|
||||
// its ids. A quote found under a different id is reported with the right one; a quote found
|
||||
// nowhere is reported as not found and must be cut or replaced. Quotes with "..." are checked
|
||||
// piece by piece. Exit code 1 when anything needs fixing.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const [, , buildArg, ...targets] = process.argv;
|
||||
if (!buildArg || !targets.length) {
|
||||
console.error("usage: check_quotes.mjs <build dir> <file or folder> [...]");
|
||||
process.exit(2);
|
||||
}
|
||||
const BUILD = path.resolve(buildArg);
|
||||
const sources = JSON.parse(fs.readFileSync(path.join(BUILD, "sources.json"), "utf8"));
|
||||
|
||||
const norm = (s) => s.toLowerCase()
|
||||
.replace(/[‘’`]/g, "'").replace(/[“”]/g, '"')
|
||||
.replace(/'\s+(t|s|re|ll|ve|d|m)\b/g, "'$1")
|
||||
.replace(/\[\d\d:\d\d(:\d\d)?\]/g, " ")
|
||||
.replace(/[^a-z0-9' ]+/g, " ").replace(/\s+/g, " ").trim();
|
||||
const corpus = new Map(sources.map((s) => [s.id, norm(fs.readFileSync(path.join(BUILD, s.file), "utf8"))]));
|
||||
|
||||
const files = [];
|
||||
const walk = (p) => {
|
||||
if (fs.statSync(p).isDirectory()) for (const n of fs.readdirSync(p)) walk(path.join(p, n));
|
||||
else if (/\.md$/.test(p)) files.push(p);
|
||||
};
|
||||
for (const t of targets) walk(path.resolve(t));
|
||||
|
||||
const found = (q, id) => {
|
||||
const hay = corpus.get(id);
|
||||
if (!hay) return false;
|
||||
// "..." splits a quote into pieces that must each be in the source
|
||||
return q.split(/\.\.\.|…/).map(norm).filter((p) => p.split(" ").length >= 3).every((p) => hay.includes(p));
|
||||
};
|
||||
|
||||
let ok = 0;
|
||||
const wrong = [], missing = [];
|
||||
const re = /["“]([^"“”\n]{12,600})["”][^\n"“]{0,40}?[(\[]((?:S\d{3})(?:\s*[,;]\s*S\d{3})*)/g;
|
||||
for (const f of files) {
|
||||
const lines = fs.readFileSync(f, "utf8").split(/\r?\n/);
|
||||
lines.forEach((line, i) => {
|
||||
for (const m of line.matchAll(re)) {
|
||||
const q = m[1];
|
||||
if (norm(q).split(" ").length < 4) continue;
|
||||
const ids = m[2].split(/\s*[,;]\s*/);
|
||||
const where = `${path.relative(process.cwd(), f)}:${i + 1}`;
|
||||
if (ids.some((id) => found(q, id))) { ok++; continue; }
|
||||
const other = sources.find((s) => found(q, s.id));
|
||||
if (other) wrong.push(`${where} cites ${ids.join(", ")}, but the quote is in ${other.id}: "${q.slice(0, 90)}"`);
|
||||
else missing.push(`${where} not found in any source: "${q.slice(0, 110)}"`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`quotes verified: ${ok}; wrong source id: ${wrong.length}; not found: ${missing.length}`);
|
||||
for (const w of wrong) console.log(" WRONG ID " + w);
|
||||
for (const m of missing) console.log(" NOT FOUND " + m);
|
||||
process.exit(wrong.length || missing.length ? 1 : 0);
|
||||
@@ -0,0 +1,263 @@
|
||||
#!/usr/bin/env node
|
||||
// Fetch public sources for a new Roast Room seat into its build folder, one markdown file per
|
||||
// source, and keep the source id table (S001, S002, ...) the brain cites.
|
||||
//
|
||||
// node .claude/skills/newroaster/scripts/fetch.mjs <build dir> <url> [<url> ...]
|
||||
// node .claude/skills/newroaster/scripts/fetch.mjs <build dir> --list urls.txt
|
||||
// node .claude/skills/newroaster/scripts/fetch.mjs <build dir> --add <file.md|.txt|.pdf> --title "..." [--url ...] [--date YYYY-MM-DD]
|
||||
// node .claude/skills/newroaster/scripts/fetch.mjs <build dir> --manifest
|
||||
// node .claude/skills/newroaster/scripts/fetch.mjs <build dir> --sources-md <brain>/sources.md --name "Full Name"
|
||||
//
|
||||
// Web pages become plain text. YouTube links become transcripts with [mm:ss] markers (yt-dlp
|
||||
// when it is installed, otherwise YouTube's own caption tracks). PDFs need pdftotext; without
|
||||
// it the file is saved and flagged so Claude can read it and write the text in. --add takes a
|
||||
// local file you already have (your own transcripts, notes, or posts). Re-runs skip URLs that
|
||||
// are already in sources.json. Node 20+, no installs.
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import os from "node:os";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
|
||||
const [, , buildArg, ...rest] = process.argv;
|
||||
if (!buildArg || buildArg.startsWith("--")) {
|
||||
console.error("usage: fetch.mjs <build dir> <url ...> | --list <file> | --add <file> --title <t> | --manifest | --sources-md <file> --name <n>");
|
||||
process.exit(2);
|
||||
}
|
||||
const BUILD = path.resolve(buildArg);
|
||||
const CORPUS = path.join(BUILD, "corpus");
|
||||
const TABLE = path.join(BUILD, "sources.json");
|
||||
fs.mkdirSync(CORPUS, { recursive: true });
|
||||
const sources = fs.existsSync(TABLE) ? JSON.parse(fs.readFileSync(TABLE, "utf8")) : [];
|
||||
const save = () => fs.writeFileSync(TABLE, JSON.stringify(sources, null, 2) + "\n");
|
||||
const nextId = () => "S" + String(sources.reduce((m, s) => Math.max(m, Number(s.id.slice(1))), 0) + 1).padStart(3, "0");
|
||||
const words = (t) => (t.match(/\S+/g) || []).length;
|
||||
const slugify = (t) => t.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "source";
|
||||
const UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36";
|
||||
const has = (bin) => !spawnSync(bin, ["-v"], { stdio: "ignore" }).error; // installed at all, whatever the exit code
|
||||
|
||||
function opt(name) {
|
||||
const i = rest.indexOf(name);
|
||||
return i >= 0 ? rest[i + 1] : undefined;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ html to text
|
||||
const ENT = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", mdash: "-", ndash: "-", hellip: "...", rsquo: "'", lsquo: "'", rdquo: '"', ldquo: '"', copy: "(c)" };
|
||||
const decode = (s) => s
|
||||
.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16)))
|
||||
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
|
||||
.replace(/&([a-z]+);/gi, (m, n) => ENT[n.toLowerCase()] ?? m);
|
||||
|
||||
function htmlToText(html) {
|
||||
let h = html.replace(/<!--[\s\S]*?-->/g, "");
|
||||
for (const tag of ["script", "style", "noscript", "svg", "nav", "header", "footer", "aside", "form", "iframe", "button"]) {
|
||||
h = h.replace(new RegExp(`<${tag}\\b[\\s\\S]*?</${tag}>`, "gi"), " ");
|
||||
}
|
||||
// the article body when the page marks one, else the whole body
|
||||
const art = h.match(/<article\b[\s\S]*<\/article>/i) || h.match(/<main\b[\s\S]*<\/main>/i);
|
||||
if (art && words(art[0].replace(/<[^>]+>/g, " ")) > 250) h = art[0];
|
||||
else h = (h.match(/<body\b[\s\S]*<\/body>/i) || [h])[0];
|
||||
h = h
|
||||
.replace(/<h([1-6])\b[^>]*>/gi, (_, n) => "\n\n" + "#".repeat(Number(n)) + " ")
|
||||
.replace(/<\/h[1-6]>/gi, "\n\n")
|
||||
.replace(/<li\b[^>]*>/gi, "\n- ")
|
||||
.replace(/<br\s*\/?>/gi, "\n")
|
||||
.replace(/<\/(p|div|section|blockquote|tr|ul|ol|table|pre)>/gi, "\n\n")
|
||||
.replace(/<[^>]+>/g, " ");
|
||||
return decode(h)
|
||||
.replace(/[ \t ]+/g, " ")
|
||||
.replace(/ *\n */g, "\n")
|
||||
.replace(/\n{3,}/g, "\n\n")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function pageMeta(html, url) {
|
||||
const meta = (re) => { const m = html.match(re); return m ? decode(m[1]).trim() : ""; };
|
||||
const title = meta(/<meta[^>]+property=["']og:title["'][^>]+content=["']([^"']+)/i) || meta(/<title[^>]*>([^<]+)<\/title>/i) || url;
|
||||
const date =
|
||||
meta(/<meta[^>]+(?:property|name)=["'](?:article:published_time|date|pubdate|publish-date|dc\.date)["'][^>]+content=["']([^"']+)/i) ||
|
||||
meta(/"datePublished"\s*:\s*"([^"]+)"/) ||
|
||||
meta(/<time[^>]+datetime=["']([^"']+)/i) ||
|
||||
(url.match(/\/(20\d\d|19\d\d)\/(\d\d)\//) || []).slice(1, 3).join("-");
|
||||
return { title: title.replace(/\s+/g, " ").slice(0, 160), date: (date.match(/\d{4}(-\d\d){0,2}/) || [""])[0] };
|
||||
}
|
||||
|
||||
async function get(url, init = {}) {
|
||||
const r = await fetch(url, { redirect: "follow", signal: AbortSignal.timeout(45000), ...init, headers: { "user-agent": UA, "accept-language": "en-US,en;q=0.9", ...(init.headers || {}) } });
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return r;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ youtube
|
||||
const ytId = (u) => (u.match(/(?:youtu\.be\/|[?&]v=|\/shorts\/|\/live\/|\/embed\/)([\w-]{11})/) || [])[1];
|
||||
const stamp = (ms) => { const s = Math.floor(ms / 1000); return `[${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}]`; };
|
||||
|
||||
/** json3 caption events -> paragraphs of about 60 words, each opening with its timestamp */
|
||||
function json3ToText(j) {
|
||||
const out = []; let buf = []; let start = null;
|
||||
for (const ev of j.events || []) {
|
||||
if (!ev.segs) continue;
|
||||
const t = ev.segs.map((s) => s.utf8 || "").join("").replace(/\s+/g, " ").trim();
|
||||
if (!t) continue;
|
||||
if (start === null) start = ev.tStartMs || 0;
|
||||
buf.push(t);
|
||||
if (words(buf.join(" ")) >= 60) { out.push(`${stamp(start)} ${buf.join(" ")}`); buf = []; start = null; }
|
||||
}
|
||||
if (buf.length) out.push(`${stamp(start || 0)} ${buf.join(" ")}`);
|
||||
return decode(out.join("\n\n")).replace(/\[(Music|Applause|Laughter)\]/gi, "").trim();
|
||||
}
|
||||
|
||||
function viaYtDlp(id) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "roaster-"));
|
||||
try {
|
||||
const info = JSON.parse(execFileSync("yt-dlp", ["-J", "--no-warnings", `https://www.youtube.com/watch?v=${id}`], { encoding: "utf8", maxBuffer: 64 << 20 }));
|
||||
execFileSync("yt-dlp", ["--skip-download", "--write-subs", "--write-auto-subs", "--sub-langs", "en.*,en", "--sub-format", "json3", "--no-warnings", "-o", path.join(dir, "v"), `https://www.youtube.com/watch?v=${id}`], { stdio: "ignore" });
|
||||
const files = fs.readdirSync(dir).filter((f) => f.endsWith(".json3"));
|
||||
// a human-made track beats auto captions when both exist
|
||||
const pick = files.find((f) => !/-orig|auto/i.test(f) && /\.en\.json3$/.test(f)) || files[0];
|
||||
if (!pick) throw new Error("no English captions");
|
||||
const text = json3ToText(JSON.parse(fs.readFileSync(path.join(dir, pick), "utf8")));
|
||||
const d = info.upload_date || "";
|
||||
return { title: info.title, date: d ? `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}` : "", text, channel: info.channel || "", seconds: info.duration || 0 };
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function viaInnertube(id) {
|
||||
const body = { context: { client: { clientName: "ANDROID", clientVersion: "20.10.38", androidSdkVersion: 30, hl: "en", gl: "US" } }, videoId: id };
|
||||
const r = await get("https://www.youtube.com/youtubei/v1/player?prettyPrint=false", {
|
||||
method: "POST", body: JSON.stringify(body),
|
||||
headers: { "content-type": "application/json", "user-agent": "com.google.android.youtube/20.10.38 (Linux; U; Android 11) gzip" },
|
||||
});
|
||||
const j = await r.json();
|
||||
const tracks = j.captions?.playerCaptionsTracklistRenderer?.captionTracks || [];
|
||||
const en = tracks.filter((t) => /^en/.test(t.languageCode));
|
||||
const track = en.find((t) => t.kind !== "asr") || en[0];
|
||||
if (!track) throw new Error(j.playabilityStatus?.reason || "no English captions");
|
||||
const cap = await (await get(track.baseUrl.replace(/&fmt=[^&]*/, "") + "&fmt=json3")).text();
|
||||
if (!cap.trim()) throw new Error("caption track came back empty");
|
||||
let date = "";
|
||||
try {
|
||||
const page = await (await get(`https://www.youtube.com/watch?v=${id}`)).text();
|
||||
date = ((page.match(/"(?:publishDate|uploadDate)":"([^"]+)"/) || [])[1] || "").slice(0, 10);
|
||||
} catch {}
|
||||
return { title: j.videoDetails?.title || id, date, text: json3ToText(JSON.parse(cap)), channel: j.videoDetails?.author || "", seconds: Number(j.videoDetails?.lengthSeconds) || 0 };
|
||||
}
|
||||
|
||||
async function youtube(id) {
|
||||
const errors = [];
|
||||
if (has("yt-dlp") && !process.env.NO_YTDLP) { try { return viaYtDlp(id); } catch (e) { errors.push(`yt-dlp: ${e.message.split("\n")[0]}`); } }
|
||||
try { return await viaInnertube(id); } catch (e) { errors.push(`captions: ${e.message}`); }
|
||||
throw new Error(errors.join("; "));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ pdf
|
||||
function pdfText(file) {
|
||||
if (!has("pdftotext")) return null;
|
||||
return execFileSync("pdftotext", ["-layout", "-enc", "UTF-8", file, "-"], { encoding: "utf8", maxBuffer: 256 << 20 });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ one source
|
||||
function write(src, text) {
|
||||
const file = `${src.id}-${slugify(src.title)}.md`;
|
||||
const head = `# ${src.title}\n\nSource: ${src.id} | ${src.url || "local file"} | ${src.date || "undated"} | ${src.kind}${src.channel ? ` | ${src.channel}` : ""}\n\n`;
|
||||
fs.writeFileSync(path.join(CORPUS, file), head + text.trim() + "\n");
|
||||
Object.assign(src, { file: `corpus/${file}`, words: words(text) });
|
||||
sources.push(src);
|
||||
save();
|
||||
return src;
|
||||
}
|
||||
|
||||
async function fetchOne(url) {
|
||||
url = url.trim();
|
||||
if (!url || url.startsWith("#")) return;
|
||||
if (sources.some((s) => s.url === url)) return console.log(`skip ${url} (already fetched)`);
|
||||
const id = nextId();
|
||||
try {
|
||||
const yt = ytId(url);
|
||||
if (yt) {
|
||||
const v = await youtube(yt);
|
||||
const s = write({ id, title: v.title, url: `https://www.youtube.com/watch?v=${yt}`, date: v.date, kind: "video", channel: v.channel, minutes: Math.round(v.seconds / 60) }, v.text);
|
||||
return console.log(`ok ${s.id} ${s.words.toLocaleString()} words ${s.title}`);
|
||||
}
|
||||
const r = await get(url);
|
||||
const type = r.headers.get("content-type") || "";
|
||||
if (type.includes("pdf") || /\.pdf($|\?)/i.test(url)) {
|
||||
const raw = path.join(CORPUS, `pending-${slugify(path.basename(new URL(url).pathname, ".pdf"))}.pdf`);
|
||||
fs.writeFileSync(raw, Buffer.from(await r.arrayBuffer()));
|
||||
const text = pdfText(raw);
|
||||
if (!text) return console.log(`pdf ${raw} saved, but pdftotext is not installed. Read it and save its text with --add.`);
|
||||
fs.rmSync(raw);
|
||||
const s = write({ id, title: path.basename(raw, ".pdf").replace(/^pending-/, "").replace(/-/g, " "), url, date: (url.match(/(19|20)\d\d/) || [""])[0], kind: "pdf" }, text);
|
||||
return console.log(`ok ${s.id} ${s.words.toLocaleString()} words ${s.title}`);
|
||||
}
|
||||
const html = await r.text();
|
||||
const text = htmlToText(html);
|
||||
const meta = pageMeta(html, url);
|
||||
// essays often print their date as a line near the top ("July 2013") instead of in the markup
|
||||
if (!meta.date) {
|
||||
const m = text.slice(0, 600).match(/\b(January|February|March|April|May|June|July|August|September|October|November|December) (?:\d{1,2}, )?((?:19|20)\d\d)\b/);
|
||||
if (m) meta.date = `${m[2]}-${String("JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(m[1].slice(0, 3)) / 3 + 1).padStart(2, "0")}`;
|
||||
}
|
||||
if (words(text) < 250 && !rest.includes("--keep-short")) {
|
||||
return console.log(`thin ${url} (${words(text)} words: paywall, login, or a page built by JavaScript; skipped)`);
|
||||
}
|
||||
const s = write({ id, title: meta.title, url, date: meta.date, kind: "web" }, text);
|
||||
console.log(`ok ${s.id} ${s.words.toLocaleString()} words ${s.title}`);
|
||||
} catch (e) {
|
||||
console.log(`fail ${url} (${e.message})`);
|
||||
}
|
||||
}
|
||||
|
||||
function addLocal(file) {
|
||||
const title = opt("--title") || path.basename(file).replace(/\.[^.]+$/, "");
|
||||
let text;
|
||||
if (/\.pdf$/i.test(file)) {
|
||||
text = pdfText(file);
|
||||
if (!text) throw new Error("pdftotext is not installed; read the PDF and save its text as a .md or .txt file, then --add that");
|
||||
} else text = fs.readFileSync(file, "utf8");
|
||||
const s = write({ id: nextId(), title, url: opt("--url") || "", date: opt("--date") || "", kind: opt("--kind") || "local" }, text);
|
||||
console.log(`ok ${s.id} ${s.words.toLocaleString()} words ${s.title}`);
|
||||
}
|
||||
|
||||
function manifest() {
|
||||
const total = sources.reduce((n, s) => n + (s.words || 0), 0);
|
||||
const byKind = {};
|
||||
for (const s of sources) { byKind[s.kind] = byKind[s.kind] || { n: 0, w: 0 }; byKind[s.kind].n++; byKind[s.kind].w += s.words || 0; }
|
||||
const dates = sources.map((s) => s.date).filter(Boolean).sort();
|
||||
console.log(`${sources.length} sources, ${total.toLocaleString()} words${dates.length ? `, ${dates[0].slice(0, 4)} to ${dates.at(-1).slice(0, 4)}` : ""}`);
|
||||
for (const [k, v] of Object.entries(byKind)) console.log(` ${k}: ${v.n} sources, ${v.w.toLocaleString()} words`);
|
||||
const thin = sources.filter((s) => s.words < 800);
|
||||
if (thin.length) console.log(` short (<800 words): ${thin.map((s) => s.id).join(", ")}`);
|
||||
}
|
||||
|
||||
/** The brain's sources.md: a header with counts, then one line per source id. */
|
||||
function sourcesMd(out, name) {
|
||||
const total = sources.reduce((n, s) => n + (s.words || 0), 0);
|
||||
const kinds = [...new Set(sources.map((s) => s.kind))].map((k) => `${sources.filter((s) => s.kind === k).length} ${k}`).join(", ");
|
||||
const lines = [
|
||||
`# Sources: ${name}`,
|
||||
"",
|
||||
`${sources.length} sources (${kinds}), ${total.toLocaleString()} words. Video dates are upload dates. Every quote in this brain carries one of these ids.`,
|
||||
"",
|
||||
"Format: id | title | url | date | words",
|
||||
"",
|
||||
...sources.map((s) => `- ${s.id} | ${s.title.replace(/\|/g, "/").replace(/\s*[—–]\s*/g, ": ")} | ${s.url || "local file"} | ${s.date || "undated"} | ${s.words}`),
|
||||
];
|
||||
fs.writeFileSync(out, lines.join("\n") + "\n");
|
||||
console.log(`wrote ${out}`);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ main
|
||||
if (opt("--sources-md")) sourcesMd(opt("--sources-md"), opt("--name") || path.basename(BUILD));
|
||||
else if (rest.includes("--manifest")) manifest();
|
||||
else if (opt("--add")) addLocal(opt("--add"));
|
||||
else {
|
||||
const list = opt("--list");
|
||||
const urls = list ? fs.readFileSync(list, "utf8").split(/\r?\n/) : rest.filter((a) => !a.startsWith("--"));
|
||||
for (const u of urls) {
|
||||
await fetchOne(u);
|
||||
await new Promise((r) => setTimeout(r, 400)); // be polite to the sites
|
||||
}
|
||||
manifest();
|
||||
}
|
||||
Reference in new issue
Block a user