Skip to content

A Codex skill that finds evidence-backed potential first customers from recent public signals.

feat: upgrade First Customer Finder v2 workflow

Kappaemme-gitd3f6964bd989
diff --git a/.gitignore b/.gitignore
index 8480c79..44d4df5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,3 +3,6 @@ node_modules/
*.tgz
__pycache__/
*.pyc
+outputs/
+.demo-output/
+*.lock
diff --git a/README.md b/README.md
index 6080256..84a3cff 100644
--- a/README.md
+++ b/README.md
@@ -1,90 +1,195 @@
-# Codex First Customer Finder Skill
+# First Customer Finder
-A Codex skill that turns a startup URL or product idea into a qualified shortlist of potential first customers using recent public pain, demand, and timing signals.
+**Find people with a public reason to care about your product — and know your next manual step.**
-It defines the ideal customer profile, researches public sources, links the evidence behind every prospect, ranks fit and timing, drafts a source-based opener, and creates a polished HTML report. It never sends outreach automatically.
+Give Codex your product URL, repository, or a short description. This skill researches accessible public demand signals, qualifies potential customers, verifies suitable public contact routes, and creates a report you can open directly in Codex.
-## What It Does
+Tell it which prospects fit. The next search uses your explicit feedback and local history.
-- Analyzes a startup URL, repository, or product description
-- Defines the primary and adjacent ideal customer profiles
-- Finds explicit demand, pain, workaround, switching, and timing signals
-- Qualifies prospects with an evidence-based score
-- Links every primary prospect to the original public source
-- Drafts respectful, source-based outreach openers
-- Creates a responsive standalone HTML report
-- Keeps all outreach manual by default
-- Avoids private contact enrichment and sensitive personal data
+> These are potential customers based on public evidence, not confirmed buyers. The skill never sends outreach automatically.
-## Installation
+## What's new in v2
+
+- **Concrete outreach:** target role, observed/inferred label, verified public route or an honest missing-route warning, realistic next step, and a specific CTA.
+- **Feedback-driven searches:** keep, maybe, or reject candidates; refine the target profile with explicit preferences.
+- **Product-local history:** stable prospect IDs, duplicate exclusion, previously seen labels, and manually recorded contact outcomes.
+- **Native Markdown + CSV:** evidence and next steps in Codex, with a spreadsheet-friendly export. Standalone HTML is still available.
+- **Stronger checks:** weighted scores are computed, missing dates/routes reduce their relevant dimensions, and malformed or incomplete qualified records are rejected.
+- **Recoverable upgrades:** the installer preserves your previous skill folder outside the active skills directory.
+
+“Learning” means saved search preferences, not model training. Public route verification means Codex inspected the page, not that the recipient consented to promotion.
+
+## Install or update
```bash
npx --yes codex-first-customer-finder-skill@latest
```
-This installs the skill into:
+Installs into `$CODEX_HOME/skills/first-customer-finder` or `~/.codex/skills/first-customer-finder`. Restart Codex after an update so it loads the new instructions. Re-running the command installs the version currently published on npm; source changes are not available there until a release is published.
+
+Custom directory:
+
+```bash
+npx --yes codex-first-customer-finder-skill@latest --skills-dir /path/to/skills
+```
+
+**Requirements:** Node.js for the installer, Python 3.9+ for the local helpers, and a Codex environment with web search or browser access for live research. No third-party Python dependencies, data-broker subscription, or skill-specific API key is required. Codex usage and external platform access remain subject to your own account and tools.
+
+## Try it
+
+Start with a product:
```text
-~/.codex/skills/first-customer-finder
+Use $first-customer-finder to find 5 potential customers for [PRODUCT URL].
```
-Restart Codex after installation.
+Then refine the results:
-## Usage
+```text
+P1 and P3 fit. Focus on owner-led small businesses, avoid enterprise teams, and find 5 more.
+```
-Find the first ten potential customers:
+Record a real outcome:
```text
-Use $first-customer-finder to find ten evidence-backed potential first customers for https://example.com and create the final HTML report.
+I contacted P1. Remember that and exclude it from the next search.
```
-Find design partners:
+Ranks such as P1 belong to the report you are discussing. The saved history uses stable IDs, so ranks cannot silently point to a different prospect in another report.
+
+Other useful requests:
+
+```text
+Use $first-customer-finder in design-partners mode for [PRODUCT URL].
+```
```text
-Use $first-customer-finder in design-partners mode for this startup: [URL]. Prioritize people publicly describing the problem and likely to give product feedback.
+Use $first-customer-finder to find developers publicly asking for an alternative to [TOOL], for my product [URL].
```
-B2B research:
+```text
+Refresh the existing shortlist, recheck the sources, and include the HTML report.
+```
+
+## How a search works
+
+1. **Understand the product.** Identify the outcome, buyer, use case, geography, alternatives, and disqualifiers. Ask a concise question only when a material ambiguity remains.
+2. **Read the current project history.** Apply explicit preferences and avoid excluded candidates. A different product gets a separate history.
+3. **Research public signals.** Discover and open original sources: requests for tools, manual workarounds, unresolved pain, switching intent, and relevant business events.
+4. **Qualify and challenge.** Attribute the evidence correctly, check for resolved problems or poor fit, calculate the score, and consolidate duplicate entities.
+5. **Make the next step concrete.** Identify the relevant function, verify a suitable official/public route when possible, and draft a short message with an actionable CTA.
+6. **Deliver and refine.** Save a Markdown report, CSV, and local history. On request, use your feedback for the next search or refresh.
+
+Search may use accessible public X posts, GitHub issues, forums, product reviews, company pages, and search engines. It does not promise access to every platform, bypass login walls, or qualify candidates from snippets alone. Blocked sources are reported as coverage gaps.
+
+## What you receive
+
+| Output | Purpose |
+| --- | --- |
+| `report.md` | Native Codex report with ranked candidates, source links/dates, roles, contact routes, drafts, and cautions |
+| `prospects.csv` | Spreadsheet-safe snapshot of the included shortlist and its next steps |
+| `report.html` (optional) | Responsive standalone visual report |
+| `state.json` | Product-scoped local history, explicit preferences, feedback, and reported outcomes |
+| `analysis.json` | The run's structured evidence, retained in the workspace unless using an ephemeral workflow |
+
+Example workspace layout:
```text
-Use $first-customer-finder in b2b mode for [URL]. Find public business triggers, qualify the relevant companies, and draft one opener per prospect without sending anything.
+outputs/first-customer-finder/my-product/
+├── state.json
+├── run-01/
+│ ├── analysis.json
+│ ├── report.md
+│ └── prospects.csv
+└── run-02/
+ ├── analysis.json
+ ├── report.md
+ └── prospects.csv
```
-## Output
+History is kept in the chosen workspace, not uploaded, synced, or stored inside the installed skill. Ask for a run without saved history to omit it. Existing report files remain independent snapshots. Keep the research folder out of version control; remove that exact product folder yourself when you no longer want the stored data.
+
+CSV edits are not automatically imported. Tell Codex which outcomes to record.
+
+## Feedback and repeat searches
+
+- **Keep / maybe / reject:** save your assessment and reason for a specific prospect.
+- **Prefer / avoid:** save explicit general criteria. Rejecting one company does not automatically reject its entire industry.
+- **Find more:** exclude all previously seen entities, as well as rejected or already-contacted records.
+- **Refresh:** revisit eligible existing prospects and inspect their current evidence. Preserve feedback and contact status.
+- **Contact outcomes:** `new`, `contacted`, `replied`, `not_interested`, or `customer`; entered only from your report, never inferred from a generated draft.
+
+No background monitoring is started. No follow-up is sent. An empty shortlist is a valid result when there are no additional qualified matches.
+
+## Qualification
-The report includes:
+| Dimension | Weight |
+| --- | ---: |
+| Pain strength | 25% |
+| Product fit | 25% |
+| Timing | 20% |
+| Public reachability | 15% |
+| Evidence quality | 15% |
-1. Early-customer verdict
-2. Primary ICP and disqualifiers
-3. Highest-confidence prospect
-4. Evidence-backed prospect shortlist
-5. Fit and timing scores
-6. Source links and signal dates
-7. Personalized outreach openers
-8. Repeated pain patterns
-9. Seven-day manual outreach plan
-10. Research limitations
+Each dimension runs from 0 to 5. The helper calculates the weighted total. Scores are research priorities, **not conversion probabilities**. Numerical scores cannot override missing, contradictory, or misattributed evidence.
-Prospects are hypotheses based on public signals, not confirmed customers or guaranteed buyers.
+Every primary prospect needs an inspected original source. Unknown signal dates cap timing at 2/5; no suitable verified contact route caps reachability at 1/5. The report distinguishes publication date from the date the source was checked.
## Modes
-- `quick`: up to five strong prospects
-- `standard`: up to ten prospects across several source types
-- `deep`: up to twenty prospects and repeated-pattern analysis
+- `quick`: up to 5 prospects
+- `standard`: up to 10, default
+- `deep`: up to 20 plus repeated-pattern analysis
- `design-partners`: feedback-oriented early adopters
-- `b2b`: companies and public business triggers
+- `b2b`: companies, business triggers, and buyer functions
- `community`: explicit requests and public discussion signals
-## Manual Installation
+Requested counts are limits, not quotas. The skill should return fewer candidates when evidence is weak.
+
+## Privacy and limits
+
+- Public, intentionally shared professional/business information only.
+- No private email discovery, phone enrichment, data brokers, sensitive-trait targeting, or private-group access.
+- No messages, form submissions, follows, comments, or CRM changes from a prospect-search request.
+- A found route is not permission to advertise; platform/community rules still matter.
+- A local preference profile is not autonomous learning or proof of demand.
+- The scripts validate structure and consistency; they cannot prove a public statement true or replace judgment about outreach suitability.
+
+## Run the fictional demo
+
+This offline fixture tests the report and history workflow. **Every prospect, statement, and route is fictional.** It is not a live research benchmark.
```bash
git clone https://github.com/Kappaemme-git/codex-first-customer-finder-skill.git
-mkdir -p ~/.codex/skills
-cp -R codex-first-customer-finder-skill/first-customer-finder ~/.codex/skills/first-customer-finder
+cd codex-first-customer-finder-skill
+python3 first-customer-finder/scripts/generate_report.py examples/demo.json outputs/demo/run-01/report.md --csv outputs/demo/run-01/prospects.csv --html outputs/demo/run-01/report.html --state outputs/demo/state.json
```
-Restart Codex after installation.
+Try a repeat run: it should not invent new prospects or repackage old ones as new.
+
+```bash
+python3 first-customer-finder/scripts/generate_report.py examples/demo.json outputs/demo/run-02/report.md --state outputs/demo/state.json --new-only
+```
+
+Demo history cannot be mixed with real research. The fixture is not shipped in the npm install.
+
+## Local development and tests
+
+Install a source checkout for testing before publishing:
+
+```bash
+node scripts/install.js
+npm test
+npm pack --dry-run
+```
+
+Tests cover score calculation, stable identities, product isolation, feedback, outcome retention, repeated-search exclusions, missing routes, unsafe links, CSV formula escaping, legacy HTML, demo labels, history locking, output protection, and recoverable installation.
+
+The package version is `0.2.0`; “v2” describes the second workflow generation.
+
+## Community input
+
+The outreach improvements address [issue #2](https://github.com/Kappaemme-git/codex-first-customer-finder-skill/issues/2) and incorporate the direction proposed in [PR #3](https://github.com/Kappaemme-git/codex-first-customer-finder-skill/pull/3) and [PR #5](https://github.com/Kappaemme-git/codex-first-customer-finder-skill/pull/5). Those proposals motivated concrete contact routes and manual CTAs; this update also adds local feedback/history and native exports.
## License
diff --git a/examples/demo.json b/examples/demo.json
new file mode 100644
index 0000000..a2193f6
--- /dev/null
+++ b/examples/demo.json
@@ -0,0 +1,140 @@
+{
+ "schema_version": 2,
+ "demo": true,
+ "project_key": "demo-membership-tool",
+ "title": "First Customer Finder · Product demo",
+ "product": "MembershipFlow (fictional)",
+ "product_url": "https://example.com/product",
+ "target_customer": "Independent gym owners",
+ "search_scope": "Fictional fixture; no live research",
+ "generated_at": "2026-07-12",
+ "verdict": "Three fictional studios illustrate strong fit, weaker fit, and a missing contact route.",
+ "prospects": [
+ {
+ "name": "Northside Movement (fictional)",
+ "entity_url": "https://example.com/northside",
+ "type": "Company",
+ "stage": "Problem aware",
+ "pain_signal": "Fictional owner describes manual membership follow-ups.",
+ "evidence": "Invented demo evidence, not a real public statement.",
+ "evidence_status": "verified",
+ "why_fit": "The demo product addresses the described workflow.",
+ "why_now": "The fictional scenario concerns a recent request.",
+ "source_title": "Fictional membership workflow discussion",
+ "source_url": "https://example.com/northside/billing-question",
+ "source_type": "Fictional public forum",
+ "signal_date": "2026-07-10",
+ "checked_at": "2026-07-12",
+ "target_role": "Owner responsible for membership billing",
+ "role_basis": "inferred",
+ "suggested_channel": "Relevant public discussion, if its rules permit",
+ "contact_route": {
+ "status": "verified",
+ "label": "Demo public discussion",
+ "url": "https://example.com/northside/billing-question",
+ "source_url": "https://example.com/northside/billing-question",
+ "checked_at": "2026-07-12",
+ "note": "Demo-only route, not a real contact channel."
+ },
+ "next_step": "Offer a two-minute walkthrough of the membership reminder workflow.",
+ "cta": "Should I send a two-minute walkthrough?",
+ "opener": "You mentioned manual membership follow-ups. We are testing a reminder workflow for small gyms. Should I send a two-minute walkthrough?",
+ "caution": "Fictional example. In a real run verify that the problem is still unresolved.",
+ "dimensions": {
+ "pain_strength": 5,
+ "product_fit": 5,
+ "timing": 4,
+ "reachability": 4,
+ "evidence_quality": 4
+ }
+ },
+ {
+ "name": "Harbor Yoga (fictional)",
+ "entity_url": "https://example.com/harbor-yoga",
+ "type": "Company",
+ "stage": "Problem aware",
+ "pain_signal": "Fictional studio describes weekly spreadsheet checks for failed recurring payments.",
+ "evidence": "Invented scenario: the owner asks how to reduce manual payment chasing.",
+ "evidence_status": "verified",
+ "why_fit": "The demo product addresses the described workflow.",
+ "why_now": "The fictional scenario concerns a recent request.",
+ "source_title": "Fictional membership workflow discussion",
+ "source_url": "https://example.com/harbor-yoga/payment-question",
+ "source_type": "Fictional public forum",
+ "signal_date": "2026-07-10",
+ "checked_at": "2026-07-12",
+ "target_role": "Owner responsible for membership billing",
+ "role_basis": "inferred",
+ "suggested_channel": "Relevant public discussion, if its rules permit",
+ "contact_route": {
+ "status": "verified",
+ "label": "Demo public discussion",
+ "url": "https://example.com/harbor-yoga/payment-question",
+ "source_url": "https://example.com/harbor-yoga/payment-question",
+ "checked_at": "2026-07-12",
+ "note": "Demo-only route, not a real contact channel."
+ },
+ "next_step": "Offer a two-minute walkthrough of the membership reminder workflow.",
+ "cta": "Should I send a two-minute walkthrough?",
+ "opener": "You mentioned manual membership follow-ups. We are testing a reminder workflow for small gyms. Should I send a two-minute walkthrough?",
+ "caution": "Fictional example. In a real run verify that the problem is still unresolved.",
+ "dimensions": {
+ "pain_strength": 4,
+ "product_fit": 4,
+ "timing": 4,
+ "reachability": 4,
+ "evidence_quality": 4
+ }
+ },
+ {
+ "name": "Pulse Coaching (fictional)",
+ "entity_url": "https://example.com/pulse-coaching",
+ "type": "Company",
+ "stage": "Problem aware",
+ "pain_signal": "Fictional owner describes manual membership follow-ups.",
+ "evidence": "Invented demo evidence, not a real public statement.",
+ "evidence_status": "verified",
+ "why_fit": "The demo product addresses the described workflow.",
+ "why_now": "The fictional scenario concerns a recent request.",
+ "source_title": "Fictional membership workflow discussion",
+ "source_url": "https://example.com/pulse-coaching/workflow-story",
+ "source_type": "Fictional public forum",
+ "signal_date": "2026-07-10",
+ "checked_at": "2026-07-12",
+ "target_role": "Owner responsible for membership billing",
+ "role_basis": "inferred",
+ "suggested_channel": "Relevant public discussion, if its rules permit",
+ "contact_route": {
+ "status": "not_found",
+ "note": "The fictional scenario contains no suitable public business contact route."
+ },
+ "next_step": "Find an official public business contact route and confirm suitability before using the draft.",
+ "cta": "Who handles membership billing for the studio?",
+ "opener": "Your workflow description mentions manual payment follow-ups. Who handles membership billing for the studio?",
+ "caution": "No contact route verified. Do not invent an email or contact a similarly named person.",
+ "dimensions": {
+ "pain_strength": 4,
+ "product_fit": 4,
+ "timing": 3,
+ "reachability": 1,
+ "evidence_quality": 4
+ }
+ }
+ ],
+ "patterns": [
+ {
+ "title": "Manual membership follow-ups",
+ "count": 3,
+ "insight": "Fictional examples all describe a recurring operational task; no real market conclusion can be drawn."
+ }
+ ],
+ "outreach_plan": {
+ "angle": "Validate the workflow before pitching.",
+ "first_step": "Review the strongest signal and confirm a suitable route.",
+ "follow_up": "Offer a walkthrough only after interest is expressed.",
+ "success": "A useful conversation is a validation target, not a promised outcome."
+ },
+ "limits": [
+ "All identities, statements, and routes in this fixture are fictional."
+ ]
+}
diff --git a/first-customer-finder/SKILL.md b/first-customer-finder/SKILL.md
index 451922e..cf263b9 100644
--- a/first-customer-finder/SKILL.md
+++ b/first-customer-finder/SKILL.md
@@ -1,13 +1,15 @@
---
name: first-customer-finder
-description: Find and qualify evidence-backed potential first customers, early adopters, design partners, or beta users for a startup using recent public pain and buying signals. Use when Codex needs to analyze a product URL or idea, define an ideal customer profile, research public discussions and business pages, identify first-user prospects, rank lead fit and timing, prepare source-based outreach drafts, or create a shareable early-customer prospecting report without sending messages automatically.
+description: Find evidence-backed potential first customers, beta users, or design partners from public demand signals. Use for product-specific prospect research, qualified shortlists, source-grounded outreach drafts, and follow-up searches refined by the user's feedback and local prospect history. Does not send outreach automatically.
---
# First Customer Finder
Turn a startup URL or product description into a short, evidence-backed list of plausible first customers. Use public signals, preserve privacy, and distinguish a prospect from a confirmed buyer.
-Read [references/research-framework.md](references/research-framework.md) before researching or scoring prospects. Read [references/report-artifact.md](references/report-artifact.md) before creating the final report.
+Read [references/research-framework.md](references/research-framework.md) before researching or scoring prospects and [references/report-artifact.md](references/report-artifact.md) before creating the final report. For saved history, feedback, or a repeat search, also read [references/feedback-and-history.md](references/feedback-and-history.md).
+
+Use English by default; follow an explicit language request. Keep the chat handoff short and put the useful detail in the report. Research requires available web search/browser tools; the bundled Python helpers only validate, export, and manage local files. If live browsing is unavailable, report that limitation instead of inventing leads.
## Workflow
@@ -17,6 +19,7 @@ Read [references/research-framework.md](references/research-framework.md) before
- Identify the product, outcome, buyer, user, price or buying motion, geography, and strongest use case.
- Define one primary ICP, one adjacent ICP, pain triggers, positive signals, and disqualifiers.
- Infer missing context when safe and label the inference. Ask one concise question only when ambiguity would materially change the search.
+- Use one stable product-specific workspace folder. If its history exists, inspect the saved preferences and excluded prospects before searching. Never load another product's history just because it is nearby. State briefly where history will be saved; respect requests for no saved history.
### 2. Build a public-signal search plan
@@ -28,7 +31,7 @@ Search current public sources for:
- migration, churn, or competitor-frustration signals
- public company changes that create timing, such as hiring, launching, expanding, or adopting a relevant workflow
-Use multiple query angles and source types. Prefer original pages over search snippets. Record the source URL, source type, publication date when visible, and the exact evidence supporting qualification.
+Use multiple query angles and source types, including accessible public X discussions, GitHub issues, forums, reviews, and company pages when relevant. Search engines are discovery aids, not evidence. Open original pages, record publication date separately from the date checked, and attribute the signal to its actual author/company. If a source is blocked or only a snippet is available, keep it outside the qualified shortlist and explain coverage gaps. Do not imply every platform was searched.
### 3. Research safely
@@ -49,36 +52,45 @@ Score each prospect using the bundled framework:
- public reachability
- evidence quality
-Remove duplicates and weak matches. A prospect without a cited pain, need, or timing signal is only a speculative fit and must not appear in the primary shortlist.
+Remove duplicates and weak matches. Use a verified company homepage or public professional profile as `entity_url`, not a name alone or the shared platform homepage. One entity may have several signals. A prospect without a cited pain, need, or timing signal is only a speculative fit and must not appear in the primary shortlist.
+
+Check whether the problem was already resolved, the author is selling rather than buying, the product lacks a required capability, or the buyer is outside the requested profile. Put material counter-evidence in the caution or exclude the candidate. A high numerical score cannot override contradictory evidence. Never fill a requested quota with weak matches.
Never claim that a prospect is interested, has consented, or will buy. Label the output “potential customer based on public signals.”
### 5. Draft outreach, never send it
-- Recommend the most natural public or professional channel already associated with the source.
-- Write one short opener grounded only in the cited public context.
+- Identify the target role/function and label it observed or inferred. Do not invent a named decision-maker.
+- Verify a concrete official/public contact route: relevant public thread, published business contact page, or public professional profile. Record its URL and why it is suitable. A visible route is not permission to promote there; inspect relevant community rules. If no appropriate route is found, say so and give a manual research next step, not a guessed address.
+- Write one short opener in the buyer's problem language with a specific, low-friction CTA that can be accepted, declined, or forwarded. Offer a realistic next step such as a workflow review, checklist, or demo. Do not claim an asset, integration, customer result, or capability already exists unless verified.
- Avoid pretending to know the person, overstating familiarity, or mentioning unrelated personal details.
- Do not send messages, submit forms, connect, follow, comment, or create CRM records unless the user separately requests and authorizes that action.
-### 6. Produce the report
+### 6. Produce the report and save the next search's context
Lead with the most actionable evidence. Use this order:
1. **Verdict** — whether the startup has reachable early-customer signals.
2. **ICP** — buyer, job, trigger, and disqualifiers.
3. **Top prospect** — strongest evidence-backed candidate and why now.
-4. **Prospect shortlist** — source, pain signal, fit score, stage, why now, channel, and opener.
+4. **Prospect shortlist** — stable ID, source/date, score, why now, target role, verified contact route (or missing route), concrete next step, CTA, opener, and caution.
5. **Repeated patterns** — pains and triggers appearing across prospects.
6. **Seven-day outreach plan** — a manual, low-volume validation sequence.
7. **Limits** — missing evidence and what must be confirmed through real conversations.
-Create a standalone HTML report unless the user explicitly requests chat-only output:
+Create a native Markdown report and CSV by default. Preserve the standalone HTML option; generate it when requested. Respect explicit chat-only or format preferences:
1. Write structured JSON using `references/report-artifact.md`.
-2. Run `scripts/generate_report.py <analysis.json> <report.html>`.
-3. Save the report in the workspace `outputs/` directory.
-4. Verify prospect cards, source links, scores, patterns, outreach plan, and limitations.
-5. Return a clickable absolute file link in the final response so it opens from Codex.
+2. Run the bundled generator with explicit output paths and, unless declined, the product's local state path. It computes scores, validates v2 data, exports Markdown/CSV/optional HTML, and saves a compact history. Use a fresh run folder so previous reports remain intact.
+3. Verify the report, citations, actual number of included prospects, contact routes, and drafts. CSV export does not send anything or synchronize a CRM.
+4. Return an absolute Markdown file link; when the Codex file-opening tool is available, open the report in the current task. Do not require that tool on other installations.
+5. Invite short feedback using the displayed IDs, for example: “P1 and P3 are a fit; avoid enterprise buyers.” Do not delay the first report waiting for feedback.
+
+### 7. Refine when the user responds
+
+Save explicit keep/maybe/reject feedback with its reason. Translate an explicit general preference into updated search criteria and state what changed before a new search. A rejection of one company is not a rule against its entire industry; ask briefly if that distinction matters. “Learning” means a visible local preference update, not model training.
+
+On a request for more/new prospects, use `--new-only`, retain the product scope, and exclude previously seen entities plus contacted/rejected records. Revalidate saved sources when the user requests a refresh instead. Only mark someone contacted, replied, or a customer when the user supplies that outcome. Never treat generating a draft as contacting someone. Do not start a scheduled monitor from an ordinary follow-up search.
## Modes
@@ -99,3 +111,4 @@ Use `standard` by default.
- Personalize from the source, not from invented assumptions.
- Keep outreach manual and respectful.
- Treat the shortlist as a research hypothesis, not a customer database.
+- Keep local histories and research outputs out of the skill repository and npm package. Demo fixtures must be clearly labeled fictional in every output format.
diff --git a/first-customer-finder/agents/openai.yaml b/first-customer-finder/agents/openai.yaml
index efa3af8..6af6238 100644
--- a/first-customer-finder/agents/openai.yaml
+++ b/first-customer-finder/agents/openai.yaml
@@ -1,4 +1,4 @@
interface:
display_name: "First Customer Finder"
short_description: "Find evidence-backed early customer prospects"
- default_prompt: "Use $first-customer-finder to find ten evidence-backed potential first customers for this startup and create the final HTML report."
+ default_prompt: "Use $first-customer-finder to find potential first customers for this product, verify public contact routes, and create a Markdown report with CSV export."
diff --git a/first-customer-finder/references/feedback-and-history.md b/first-customer-finder/references/feedback-and-history.md
new file mode 100644
index 0000000..d4aa416
--- /dev/null
+++ b/first-customer-finder/references/feedback-and-history.md
@@ -0,0 +1,57 @@
+# Feedback and local history
+
+Read this for saved history, repeat searches, and feedback. No network service, account, background job, or CRM is involved.
+
+## Scope and storage
+
+Use `outputs/first-customer-finder/<product-slug>/state.json` inside the user's chosen workspace. Put each report and its analysis JSON under a fresh run subfolder, such as `2026-09-19-01/`. Do not save research in the installed skill, its distribution repo, or a shared global database. Offer an ephemeral run when the user does not want history: omit `--state` and keep analysis JSON temporary. Explain that old reports contain their own snapshots even if history is later removed.
+
+Set `project_key` to a stable, explicit product identifier (normally its canonical product URL; otherwise a user-recognizable slug). Reuse it on subsequent runs. The helper rejects a different product key in an existing state file. Never silently merge or switch histories. Two products from one company still need separate keys/folders.
+
+Stable prospect IDs derive from `entity_url`: a public official company homepage or the specific public professional/project profile, never the shared host alone. Strip tracking and fragments, normalize www/trailing slashes, and treat twitter.com/x.com as aliases. Different legitimate paths remain different. Do not merge entities by name or guess that two profiles are the same person. Resolve identity manually when evidence establishes a match.
+
+State retains the latest concise prospect snapshot, source/contact URLs, first/last seen times, user feedback/outcome, and explicit preferred/avoided search criteria. No entire scraped threads, private contact lists, tracking pixels, or secrets. Do not commit, upload, or publish it. Users can remove this exact product folder themselves to remove its reports and history; never delete it without a separate explicit request.
+
+## Commands
+
+Paths below are examples; resolve `scripts/` from this skill, and use absolute paths in actual tool calls.
+
+Inspect the saved project before researching:
+
+```bash
+python3 scripts/prospect_history.py --state /workspace/outputs/first-customer-finder/example/state.json show
+```
+
+After the user selects an ID from the report, save only their stated judgment:
+
+```bash
+python3 scripts/prospect_history.py --state /workspace/outputs/first-customer-finder/example/state.json feedback p_0123456789abcd keep --reason "Relevant owner-led business"
+python3 scripts/prospect_history.py --state /workspace/outputs/first-customer-finder/example/state.json feedback p_abcdef01234567 reject --reason "This company is too large"
+```
+
+The stable `p_...` ID appears alongside the convenient report rank P1/P2. Resolve ranks from the specific report being discussed; never reuse a rank across reports without checking its ID.
+
+Only after an explicit general preference, update the search profile:
+
+```bash
+python3 scripts/prospect_history.py --state /workspace/outputs/first-customer-finder/example/state.json profile --prefer "Owner-led small teams" --avoid "Enterprise procurement"
+```
+
+Each supplied flag replaces that entire list; omitted flags preserve their existing list. Multiple flags are allowed. Read the current profile first and retain preferences the user did not change. Use `--clear-prefer` / `--clear-avoid` only when the user requests clearing that list. Reasons on individual feedback records are not automatically generalized.
+
+Only after a user-reported outcome:
+
+```bash
+python3 scripts/prospect_history.py --state /workspace/outputs/first-customer-finder/example/state.json status p_0123456789abcd contacted
+```
+
+Allowed outcomes: `new`, `contacted`, `replied`, `not_interested`, `customer`. All but `new` are excluded from new outreach shortlists; rejecting an entity also excludes it. An explicit `keep` changes feedback but does not reset contact status. Correct a wrongly entered status only at the user's direction.
+
+## More versus refresh
+
+- **More/new:** inspect history, search with current criteria, then generate with `--state ... --new-only`. Previously seen records cannot reappear as new. Any omitted records are counted in the report.
+- **Refresh existing:** reopen evidence and contact routes, write a new analysis, generate with `--state ...` without `--new-only`. Keep/maybe/new records can return as previously seen. Contacted/rejected records stay excluded.
+- **Review contacted prospects:** inspect `show` or the older reports; do not reset their status just to force them into a prospect shortlist.
+- **No additional matches:** produce an honest empty shortlist with the research limits. Do not relabel old prospects as new, broaden the ICP silently, or retry indefinitely.
+
+State updates use an exclusive file lock and atomic replacement. If another run has the file locked, stop that update and report the conflict. Never delete another run's lock to force access.
diff --git a/first-customer-finder/references/report-artifact.md b/first-customer-finder/references/report-artifact.md
index 14e6ba5..affad72 100644
--- a/first-customer-finder/references/report-artifact.md
+++ b/first-customer-finder/references/report-artifact.md
@@ -1,43 +1,74 @@
-# Report Artifact
+# Report artifact
-Create a standalone HTML report from the final qualified prospect data. Use the bundled generator instead of writing report markup manually.
+Default: native Markdown plus CSV. Optional: the existing standalone HTML report. Use the bundled generator; it validates v2 records, calculates weighted scores, sorts prospects, and exports all formats from the same included shortlist. The scripts require Python 3.9+ and no third-party packages. They do not search the web or verify a URL by themselves: Codex must inspect evidence before writing `verified`.
## Generate
+Resolve scripts from the installed skill folder. Use a fresh run folder; the generator refuses to overwrite existing reports or use the same path for input/output/history.
+
+```bash
+python3 scripts/generate_report.py analysis.json outputs/first-customer-finder/example/run-01/report.md --csv outputs/first-customer-finder/example/run-01/prospects.csv --state outputs/first-customer-finder/example/state.json
+```
+
+Add `--html outputs/first-customer-finder/example/run-01/report.html` for the standalone visual version. Add `--new-only` when looking for additional, previously unseen prospects. For ephemeral research omit `--state` and keep analysis temporary. Keep research files out of version control and public packages.
+
+Legacy invocation remains supported:
+
```bash
-python3 scripts/generate_report.py analysis.json outputs/first-customer-finder-report.html
+python3 scripts/generate_report.py analysis.json report.html
```
-Return a clickable absolute file link in Codex. Keep the JSON in a work or temporary directory unless the user asks for raw data.
+Legacy data without `schema_version: 2` gets an explicit validation warning. It cannot update history. New runs must use v2.
-## JSON schema
+Return the Markdown report as a clickable absolute file link. If the current Codex environment provides a file-opening tool, open that report in the current task. Include CSV/HTML links only when useful; keep the chat handoff concise.
+
+## V2 input example
+
+This example is fictional. Never reuse its identities or evidence in real research. `demo: true` produces a prominent notice in Markdown, HTML, CSV (including an empty CSV), and segregated history. For real research use `demo: false` and actually inspect all sources.
```json
{
- "title": "First Customer Finder",
- "product": "Example product",
- "product_url": "https://example.com",
+ "schema_version": 2,
+ "demo": true,
+ "project_key": "demo-membership-tool",
+ "title": "First Customer Finder · Demo",
+ "product": "Example membership tool",
+ "product_url": "https://example.com/product",
"target_customer": "Independent gym owners",
- "search_scope": "Public English-language sources, last 12 months",
+ "search_scope": "Fictional fixture; no live research",
"generated_at": "2026-07-12",
- "verdict": "The strongest early demand comes from owners manually chasing failed membership payments.",
+ "verdict": "One invented candidate demonstrates the output format.",
"prospects": [
{
- "name": "Example Gym",
+ "name": "Example Gym (fictional)",
+ "entity_url": "https://example.com/gym",
"type": "Company",
"stage": "Problem aware",
- "score": 82,
- "pain_signal": "The owner publicly described manually following up on overdue memberships.",
- "evidence": "A recent public post describes the workflow and time cost.",
- "why_fit": "The product automates the exact reminder and payment step.",
- "why_now": "The post is recent and asks how other owners handle the process.",
- "source_title": "How do you handle failed payments?",
- "source_url": "https://example.com/public-post",
- "source_type": "Public forum",
- "signal_date": "2026-07-01",
- "suggested_channel": "Reply to the public discussion",
- "opener": "Saw your question about failed-payment follow-up...",
- "caution": "Confirm the workflow is still active before pitching.",
+ "pain_signal": "Fictional owner describes manual membership follow-ups.",
+ "evidence": "Invented demo evidence, not a real public statement.",
+ "evidence_status": "verified",
+ "why_fit": "The demo product addresses the described workflow.",
+ "why_now": "The fictional scenario concerns a recent request.",
+ "source_title": "Fictional membership workflow discussion",
+ "source_url": "https://example.com/discussion",
+ "source_type": "Fictional public forum",
+ "signal_date": "2026-07-10",
+ "checked_at": "2026-07-12",
+ "target_role": "Owner responsible for membership billing",
+ "role_basis": "inferred",
+ "suggested_channel": "Relevant public discussion, if its rules permit",
+ "contact_route": {
+ "status": "verified",
+ "label": "Fictional discussion reply",
+ "url": "https://example.com/discussion",
+ "source_url": "https://example.com/discussion",
+ "checked_at": "2026-07-12",
+ "note": "Demo-only route, not a real contact channel."
+ },
+ "next_step": "Offer a short workflow walkthrough after confirming interest.",
+ "cta": "Should I send a two-minute walkthrough?",
+ "opener": "You mentioned manual membership follow-ups. We are testing a reminder workflow for small gyms. Should I send a two-minute walkthrough?",
+ "caution": "Fictional example. In a real run verify that the problem is still unresolved.",
"dimensions": {
"pain_strength": 5,
"product_fit": 5,
@@ -47,24 +78,29 @@ Return a clickable absolute file link in Codex. Keep the JSON in a work or tempo
}
}
],
- "patterns": [
- {
- "title": "Manual follow-up",
- "count": 4,
- "insight": "Owners rely on spreadsheets and messaging apps after payments fail."
- }
- ],
+ "patterns": [],
"outreach_plan": {
- "angle": "Offer a manual concierge test before asking for software adoption.",
- "first_step": "Contact the three highest-scoring prospects with one source-based question.",
- "follow_up": "Share a two-minute mockup only after they confirm the pain.",
- "success": "Three conversations and one design-partner commitment within seven days."
+ "angle": "Validate the workflow before pitching.",
+ "first_step": "Review the strongest signal and confirm a suitable route.",
+ "follow_up": "Offer a walkthrough only after interest is expressed.",
+ "success": "A useful conversation is a validation target, not a promised outcome."
},
- "limits": [
- "These are potential customers inferred from public signals, not confirmed buyers.",
- "Verify current relevance before any outreach and keep contact manual."
- ]
+ "limits": ["All identities, statements, and routes in this fixture are fictional."]
}
```
-Normal mode should contain up to ten qualified prospects. Every primary prospect must include a valid public source URL and a score from 0 to 100.
+## Field rules
+
+- `project_key` is stable and product-specific. A different key cannot write into an existing product's history.
+- `entity_url` establishes the stable `p_...` ID; do not supply a fabricated identity or use a shared platform root. Duplicate identities are rejected rather than silently overwriting evidence. The renderer also adds P1/P2 ranks; they are local to each report.
+- `score` is derived from all five numeric dimensions (0–5); any supplied total is replaced. Below-50 candidates must be kept outside the qualified input.
+- `stage` is `High intent`, `Problem aware`, or `Trigger present`. Incomplete “Potential fit” records belong in limits, not `prospects`.
+- `evidence_status` must be `verified` for primary records, meaning Codex inspected the source. This is not verification of purchase intent. Report blocked sources in `limits` instead.
+- `signal_date` is `YYYY-MM-DD` or null. `checked_at` is the real date inspected; a recent check does not refresh an old signal. Unknown signal dates require timing <= 2/5. Dates cannot be in the future relative to the report/check date.
+- `role_basis` is `observed` or `inferred`. Do not turn an inferred function into a supposedly verified named person.
+- `contact_route.status` is `verified` or `not_found`. A verified route needs its URL, label, supporting public URL, check date, and suitability note. A missing route needs an honest note, no URL, and reachability <= 1/5; retain a concrete manual next step such as finding the official support route. A visible form is not consent or proof of suitability.
+- `next_step`, `cta`, `opener`, and `caution` are required. Include the exact `cta` in `opener`. A draft can be prepared for a missing route but must not imply it is ready to send there.
+- Optional `additional_sources`: array of `{ "url": "https://...", "note": "What this supports" }`. Include corroboration/counter-evidence when it materially affects qualification.
+- Optional `patterns`: `{title, count, insight}` records. Counts refer only to included prospects. If history filtering removes inputs, the generator drops stale pattern counts and resets the plan/verdict to the remaining shortlist; revise the actual analysis if richer conclusions are needed.
+- Reports label missing routes, previously seen entities, history exclusions, and uncertainty. CSV escapes formula-leading values; its `status`/`feedback` columns are snapshots. Editing CSV does not sync changes back: tell Codex the outcome so it can update local history explicitly.
+- The helper validates data structure, not the truth of web statements, legal permission to contact, or semantic quality of drafts. Manually inspect the generated report before handing it off.
diff --git a/first-customer-finder/references/research-framework.md b/first-customer-finder/references/research-framework.md
index 5846202..3a51244 100644
--- a/first-customer-finder/references/research-framework.md
+++ b/first-customer-finder/references/research-framework.md
@@ -72,6 +72,10 @@ Interpretation:
An old explicit request can still be relevant, but reduce timing and label the date. A company that merely matches the industry without an evidenced trigger is not a qualified prospect.
+Record `checked_at` separately from `signal_date`. Checking an old post today does not make its demand new. With an unknown publication date, timing must be at most 2/5 unless another dated, cited signal supports it (use that as the primary source). With no verified suitable contact route, reachability must be at most 1/5. Scores are prioritization judgments, not conversion probabilities. The v2 generator calculates the weighted score from the dimensions.
+
+Only sources actually opened and inspected can have `evidence_status: "verified"`; this means the public source was inspected, not that the person intends to buy. Unavailable, snippet-only, ambiguous-author, resolved, and contradictory signals belong in research limits or rejected candidates, not the primary shortlist. Recheck context and replies when they could show the problem is already solved.
+
## Prospect stages
- **High intent:** publicly requesting a solution or actively switching.
@@ -84,9 +88,13 @@ An old explicit request can still be relevant, but reduce timing and label the d
Draft one opener using this shape:
1. mention the public context naturally
-2. connect it to the exact problem
-3. explain the product in one sentence
-4. ask one low-friction question
+2. connect it to the buyer's exact problem in their language
+3. offer a concrete next step the founder can realistically provide
+4. ask one low-friction CTA that can be accepted, declined, or forwarded
+
+Good: “Should I send a two-minute walkthrough of the reminder workflow?” or “Is the owner the right person to ask about membership billing?” Weak: “Would this be useful?” without saying what happens next. Do not invent a completed teardown, integration, testimonial, or business result to make the offer stronger.
+
+Record the target role/function (`role_basis`: `observed` or `inferred`), a concrete `next_step`, the `cta`, and the likely objection in `caution`. Include the exact CTA in the draft. Prefer a context-appropriate public reply or official contact route; identify the route's URL, supporting page, date checked, and suitability. Community rules can make a visible reply box inappropriate for promotion. Mark `not_found` instead of guessing a business email, URL path, or permission to contact. A generic home page is not evidence of a contact mechanism.
Keep it under 90 words by default. Never claim the message was sent. Do not include private emails, phone numbers, personal addresses, family information, or sensitive traits.
diff --git a/first-customer-finder/scripts/generate_report.py b/first-customer-finder/scripts/generate_report.py
index 16373f7..60eba0e 100755
--- a/first-customer-finder/scripts/generate_report.py
+++ b/first-customer-finder/scripts/generate_report.py
@@ -1,14 +1,17 @@
#!/usr/bin/env python3
-"""Generate a standalone First Customer Finder HTML report from JSON."""
+"""Generate native Markdown, CSV, optional standalone HTML, and local history."""
from __future__ import annotations
import argparse
import html
import json
+from contextlib import nullcontext
from pathlib import Path
from typing import Any
-from urllib.parse import urlparse
+
+from prospect_data import atomic_json, normalize_report, prepare_history, public_url, read_state, state_lock
+from report_exports import DEMO_NOTICE, build_csv, build_markdown
DIMENSIONS = {
@@ -27,7 +30,7 @@ def esc(value: Any) -> str:
def clamp(value: Any, maximum: int = 100) -> int:
try:
number = round(float(value))
- except (TypeError, ValueError):
+ except (TypeError, ValueError, OverflowError):
number = 0
return max(0, min(maximum, number))
@@ -39,9 +42,10 @@ def items(value: Any) -> list[Any]:
def safe_url(value: Any) -> str:
- raw = str(value or "").strip()
- parsed = urlparse(raw)
- return esc(raw) if parsed.scheme in {"http", "https"} and parsed.netloc else "#"
+ try:
+ return esc(public_url(value))
+ except ValueError:
+ return "#"
def stage_class(stage: Any) -> str:
@@ -66,6 +70,11 @@ def render_dimensions(data: dict[str, Any]) -> str:
def render_prospect(prospect: dict[str, Any], index: int) -> str:
score = clamp(prospect.get("score"))
source = safe_url(prospect.get("source_url"))
+ route = prospect.get("contact_route", {})
+ route_html = (f'<a href="{safe_url(route.get("url"))}" target="_blank" rel="noreferrer">{esc(route.get("label", "Open contact route"))} ↗</a>'
+ if route.get("status") == "verified" else "No suitable public route verified")
+ route_proof = (f'<a href="{safe_url(route.get("source_url"))}" target="_blank" rel="noreferrer">Route evidence ↗</a> · {esc(route.get("checked_at"))}'
+ if route.get("status") == "verified" else "")
return f"""
<article class="prospect reveal">
<header class="prospect-head">
@@ -81,13 +90,18 @@ def render_prospect(prospect: dict[str, Any], index: int) -> str:
<div class="prospect-grid">
<div><span>Why it fits</span><p>{esc(prospect.get('why_fit', ''))}</p></div>
<div><span>Why now</span><p>{esc(prospect.get('why_now', ''))}</p></div>
- <div><span>Suggested channel</span><p>{esc(prospect.get('suggested_channel', ''))}</p></div>
+ <div><span>Who · {esc(prospect.get('role_basis', 'Not verified'))}</span><p>{esc(prospect.get('target_role', 'Not recorded'))}</p></div>
+ <div><span>Contact route</span><p>{route_html}</p><p>{esc(route.get('note', ''))}</p><p>{route_proof}</p></div>
+ <div><span>Next step</span><p>{esc(prospect.get('next_step', 'Verify source and route.'))}</p></div>
+ <div><span>CTA</span><p>{esc(prospect.get('cta', 'Not recorded'))}</p></div>
<div><span>Caution</span><p>{esc(prospect.get('caution', 'Confirm current relevance before outreach.'))}</p></div>
</div>
- <blockquote><span>Suggested opener</span>{esc(prospect.get('opener', ''))}</blockquote>
+ <blockquote><span>Draft — not sent</span>{esc(prospect.get('opener', ''))}</blockquote>
+ <p class="chip">P{index} · {esc(prospect.get('id', 'legacy'))} · {esc(prospect.get('history_label', 'History not used'))}</p>
<details>
<summary>Evidence and score breakdown</summary>
- <div class="evidence"><div><span>Evidence</span><p>{esc(prospect.get('evidence', ''))}</p></div><div><span>Source</span><p>{esc(prospect.get('source_type', 'Public source'))} · {esc(prospect.get('signal_date', 'Date unavailable'))}</p><a href="{source}" target="_blank" rel="noreferrer">{esc(prospect.get('source_title', 'Open original source'))} ↗</a></div></div>
+ <div class="evidence"><div><span>Evidence</span><p>{esc(prospect.get('evidence', ''))}</p></div><div><span>Source</span><p>{esc(prospect.get('source_type', 'Public source'))} · Published: {esc(prospect.get('signal_date') or 'Unknown')} · Checked: {esc(prospect.get('checked_at', 'Not recorded'))}</p><a href="{source}" target="_blank" rel="noreferrer">{esc(prospect.get('source_title', 'Open original source'))} ↗</a></div></div>
+ {''.join(f'<p><a href="{safe_url(s.get("url"))}" target="_blank" rel="noreferrer">{esc(s.get("note", "Supporting source"))} ↗</a></p>' for s in prospect.get('additional_sources', []))}
<div class="metrics">{render_dimensions(prospect.get('dimensions') if isinstance(prospect.get('dimensions'), dict) else {})}</div>
</details>
</article>"""
@@ -99,7 +113,7 @@ def render_pattern(pattern: dict[str, Any], index: int) -> str:
def build_html(data: dict[str, Any]) -> str:
- prospects = [x for x in items(data.get("prospects")) if isinstance(x, dict)]
+ prospects = sorted([x for x in items(data.get("prospects")) if isinstance(x, dict)], key=lambda p: -clamp(p.get('score')))
patterns = [x for x in items(data.get("patterns")) if isinstance(x, dict)]
scores = [clamp(x.get("score")) for x in prospects]
high_intent = sum(1 for x in prospects if "high" in str(x.get("stage", "")).lower())
@@ -110,6 +124,16 @@ def build_html(data: dict[str, Any]) -> str:
prospect_html = "".join(render_prospect(x, i) for i, x in enumerate(prospects, 1))
pattern_html = "".join(render_pattern(x, i) for i, x in enumerate(patterns, 1))
product_url = safe_url(data.get("product_url"))
+ notices = []
+ if data.get('demo'):
+ notices.append(DEMO_NOTICE)
+ if data.get('legacy_warning'):
+ notices.append(data['legacy_warning'])
+ if data.get('history_summary'):
+ history = data['history_summary']
+ notices.append('History exclusions: ' + ', '.join(f'{k}: {v}' for k, v in history['excluded'].items()))
+ notices.append('Search profile — ' + '; '.join(f'{k}: {", ".join(v) or "none"}' for k, v in history['profile'].items()))
+ notice_html = ''.join(f'<p class="signal"><strong>{esc(n)}</strong></p>' for n in notices)
return f"""<!doctype html>
<html lang="en">
@@ -139,6 +163,7 @@ def build_html(data: dict[str, Any]) -> str:
<div class="shell">
<header class="top"><div class="brand"><i></i> First Customer Finder</div><div class="meta"><span class="chip">Public signals only</span><button type="button" onclick="window.print()">Print / Save PDF</button></div></header>
<main id="main">
+ {notice_html}
<section class="hero"><div><span class="eyebrow">Early-customer report · {esc(data.get('generated_at', ''))}</span><h1>{esc(data.get('title', 'First Customer Finder'))}</h1><p class="verdict">{esc(data.get('verdict', 'No verdict supplied.'))}</p></div><aside class="hero-card"><span>Qualified prospects</span><strong>{len(prospects)}</strong><p>Potential customers based on public signals.</p></aside></section>
<section class="stats"><div><span>Product</span><strong><a href="{product_url}" target="_blank" rel="noreferrer">{esc(data.get('product', 'Not specified'))}</a></strong></div><div><span>Target customer</span><strong>{esc(data.get('target_customer', 'Not specified'))}</strong></div><div><span>High intent</span><strong>{high_intent}</strong></div><div><span>Average fit score</span><strong>{average}/100</strong></div></section>
<section class="best"><div class="best-label">Highest-confidence prospect</div><div><h2>{esc(top.get('name', 'No qualified prospect'))}</h2><p>{esc(top.get('why_now', top.get('pain_signal', '')))}</p></div><strong>{clamp(top.get('score'))}</strong></section>
@@ -156,17 +181,49 @@ def build_html(data: dict[str, Any]) -> str:
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", type=Path, help="Path to report JSON")
- parser.add_argument("output", type=Path, help="Path to output HTML")
+ parser.add_argument("output", type=Path, help="Path to output .md or .html (legacy command supported)")
+ parser.add_argument("--csv", type=Path, help="Optional spreadsheet-safe CSV output")
+ parser.add_argument("--html", type=Path, help="Optional standalone HTML alongside Markdown")
+ parser.add_argument("--state", type=Path, help="Explicit product-local history path")
+ parser.add_argument("--new-only", action="store_true", help="Exclude every previously seen entity; requires --state")
args = parser.parse_args()
- with args.input.open("r", encoding="utf-8") as handle:
- data = json.load(handle)
- if not isinstance(data, dict):
- raise SystemExit("Input JSON must contain an object at the top level.")
-
- args.output.parent.mkdir(parents=True, exist_ok=True)
- args.output.write_text(build_html(data), encoding="utf-8")
- print(f"Created report: {args.output.resolve()}")
+ try:
+ if args.output.suffix.lower() not in {".md", ".html"}:
+ raise ValueError("Output must have .md or .html extension")
+ if args.new_only and not args.state:
+ raise ValueError("--new-only requires --state")
+ outputs = [p for p in (args.output, args.csv, args.html) if p]
+ reserved = [args.input] + ([args.state, args.state.with_name(args.state.name + '.lock')] if args.state else [])
+ all_paths = [p.resolve() for p in outputs + reserved]
+ if len(all_paths) != len(set(all_paths)):
+ raise ValueError("Input, outputs, state, and lock paths must be distinct")
+ for path in outputs:
+ if path.exists() or path.is_symlink():
+ raise ValueError(f"Output already exists; choose a fresh run path: {path}")
+ with args.input.open(encoding="utf-8") as handle:
+ data = normalize_report(json.load(handle))
+ with state_lock(args.state) if args.state else nullcontext():
+ state = None
+ if args.state:
+ current = read_state(args.state) if args.state.exists() or args.state.is_symlink() else None
+ data, state = prepare_history(data, current, args.new_only)
+ rendered = {args.output: build_html(data) if args.output.suffix.lower() == '.html' else build_markdown(data)}
+ if args.csv:
+ rendered[args.csv] = build_csv(data)
+ if args.html:
+ rendered[args.html] = build_html(data)
+ for path, content in rendered.items():
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open('x', encoding='utf-8', newline='') as handle:
+ handle.write(content)
+ if args.state:
+ atomic_json(args.state, state)
+ for path in rendered:
+ print(f"Created: {path.resolve()}")
+ print(f"Included {len(data.get('prospects', []))} prospects. No outreach sent.")
+ except (ValueError, OSError) as exc:
+ parser.exit(1, f"Error: {exc}\n")
if __name__ == "__main__":
diff --git a/first-customer-finder/scripts/prospect_data.py b/first-customer-finder/scripts/prospect_data.py
new file mode 100644
index 0000000..ce68387
--- /dev/null
+++ b/first-customer-finder/scripts/prospect_data.py
@@ -0,0 +1,295 @@
+"""Validation and local state. Standard library only; never performs network I/O."""
+
+from __future__ import annotations
+
+import copy
+import hashlib
+import json
+import math
+import os
+import tempfile
+from contextlib import contextmanager
+from datetime import date, datetime, timezone
+from pathlib import Path
+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
+
+
+WEIGHTS = {"pain_strength": 25, "product_fit": 25, "timing": 20,
+ "reachability": 15, "evidence_quality": 15}
+STATUSES = ("new", "contacted", "replied", "not_interested", "customer")
+FEEDBACK = ("keep", "maybe", "reject")
+
+
+def timestamp():
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
+
+
+def public_url(value):
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError("Expected an absolute public HTTP(S) URL")
+ raw = value.strip()
+ if any(c.isspace() or ord(c) < 32 for c in raw) or "\\" in raw:
+ raise ValueError("URL contains whitespace, control characters, or backslashes")
+ try:
+ parsed = urlsplit(raw)
+ _ = parsed.port
+ if parsed.scheme.lower() not in {"http", "https"} or not parsed.hostname:
+ raise ValueError("Expected an absolute public HTTP(S) URL")
+ if parsed.username is not None or parsed.password is not None:
+ raise ValueError("Credential-bearing URLs are not allowed")
+ except (ValueError, TypeError) as exc:
+ raise ValueError(f"Invalid public URL: {exc}") from exc
+ return raw
+
+
+def canonical_url(value):
+ parsed = urlsplit(public_url(value))
+ host = parsed.hostname.lower()
+ if host.startswith("www."):
+ host = host[4:]
+ if host in {"twitter.com", "mobile.twitter.com", "mobile.x.com"}:
+ host = "x.com"
+ if ":" in host: # IPv6 literal
+ host = f"[{host}]"
+ port = parsed.port
+ if port and not ((parsed.scheme == "https" and port == 443) or
+ (parsed.scheme == "http" and port == 80)):
+ host += f":{port}"
+ query = [(k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=True)
+ if not k.lower().startswith("utm_") and k.lower() not in {"fbclid", "gclid"}]
+ # Hostnames are insensitive; arbitrary paths/query values need not be.
+ return urlunsplit(("https", host, parsed.path.rstrip("/"), urlencode(sorted(query)), ""))
+
+
+def prospect_id(entity_url):
+ return "p_" + hashlib.sha256(canonical_url(entity_url).encode()).hexdigest()[:14]
+
+
+def text_field(obj, key):
+ value = obj.get(key)
+ if not isinstance(value, str) or not value.strip():
+ raise ValueError(f"{key} must be nonempty text")
+ return value.strip()
+
+
+def iso_date(value, field, ceiling=None):
+ if not isinstance(value, str):
+ raise ValueError(f"{field} must be YYYY-MM-DD")
+ try:
+ parsed = date.fromisoformat(value)
+ except ValueError as exc:
+ raise ValueError(f"{field} must be YYYY-MM-DD") from exc
+ if parsed.isoformat() != value:
+ raise ValueError(f"{field} must be YYYY-MM-DD")
+ if ceiling and parsed > ceiling:
+ raise ValueError(f"{field} cannot be later than {ceiling}")
+ return parsed
+
+
+def normalize_report(raw):
+ if not isinstance(raw, dict):
+ raise ValueError("Input JSON must contain an object")
+ data = copy.deepcopy(raw)
+ if type(data.get("schema_version", 1)) is not int or data.get("schema_version", 1) not in {1, 2}:
+ raise ValueError("Unsupported report schema_version")
+ if not isinstance(data.get("prospects", []), list):
+ raise ValueError("prospects must be an array")
+ if not all(isinstance(p, dict) for p in data.get("prospects", [])):
+ raise ValueError("Each prospect must be an object")
+ if data.get("schema_version", 1) == 1:
+ data["legacy_warning"] = "Legacy input: contact routes and source verification were not validated."
+ return data
+ for field in ("patterns", "limits"):
+ if not isinstance(data.get(field, []), list):
+ raise ValueError(f"{field} must be an array")
+ if not all(isinstance(item, str) for item in data.get("limits", [])):
+ raise ValueError("limits entries must be text")
+ for pattern in data.get("patterns", []):
+ if not isinstance(pattern, dict):
+ raise ValueError("Each pattern must be an object")
+ for field in ("title", "insight"):
+ text_field(pattern, field)
+ count = pattern.get("count")
+ if type(count) is not int or not 1 <= count <= len(data.get("prospects", [])):
+ raise ValueError("Pattern count must refer to included prospects")
+ if not isinstance(data.get("outreach_plan", {}), dict):
+ raise ValueError("outreach_plan must be an object")
+ if not all(isinstance(v, str) for v in data.get("outreach_plan", {}).values()):
+ raise ValueError("outreach_plan values must be text")
+ for field in ("project_key", "product", "target_customer", "search_scope", "verdict"):
+ text_field(data, field)
+ if not isinstance(data.get("demo", False), bool):
+ raise ValueError("demo must be a boolean")
+ generated = iso_date(data.get("generated_at"), "generated_at", date.today())
+ known = set()
+ for index, p in enumerate(data.get("prospects", []), 1):
+ try:
+ for field in ("name", "pain_signal", "evidence", "why_fit", "why_now",
+ "source_title", "source_type", "target_role", "next_step",
+ "cta", "opener", "caution", "suggested_channel"):
+ text_field(p, field)
+ for field in ("entity_url", "source_url"):
+ p[field] = public_url(p.get(field))
+ identity = prospect_id(p["entity_url"])
+ if identity in known:
+ raise ValueError("Duplicate entity; consolidate its signals into one prospect")
+ known.add(identity)
+ p["id"] = identity
+ if p.get("evidence_status") != "verified":
+ raise ValueError("Only inspected original sources belong in the primary shortlist")
+ if p.get("stage") not in {"High intent", "Problem aware", "Trigger present"}:
+ raise ValueError("stage must be High intent, Problem aware, or Trigger present")
+ if p.get("role_basis") not in {"observed", "inferred"}:
+ raise ValueError("role_basis must be observed or inferred")
+ checked = iso_date(p.get("checked_at"), "checked_at", generated)
+ if p.get("signal_date") is not None:
+ iso_date(p["signal_date"], "signal_date", checked)
+ dimensions = p.get("dimensions", {})
+ if not isinstance(dimensions, dict):
+ raise ValueError("dimensions must be an object")
+ for key in WEIGHTS:
+ value = dimensions.get(key)
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 5:
+ raise ValueError(f"{key} must be a finite number from 0 to 5")
+ if p.get("signal_date") is None and dimensions["timing"] > 2:
+ raise ValueError("Undated evidence requires timing <= 2")
+ route = p.get("contact_route")
+ if not isinstance(route, dict) or route.get("status") not in {"verified", "not_found"}:
+ raise ValueError("contact_route.status must be verified or not_found")
+ text_field(route, "note")
+ if route["status"] == "verified":
+ for key in ("url", "source_url"):
+ route[key] = public_url(route.get(key))
+ text_field(route, "label")
+ iso_date(route.get("checked_at"), "contact_route.checked_at", generated)
+ else:
+ if route.get("url") or route.get("source_url"):
+ raise ValueError("not_found route cannot contain a guessed URL")
+ if dimensions["reachability"] > 1:
+ raise ValueError("No verified route requires reachability <= 1")
+ if p["cta"].strip() not in p["opener"]:
+ raise ValueError("opener must include its concrete CTA verbatim")
+ p["score"] = round(sum(dimensions[k] / 5 * w for k, w in WEIGHTS.items()))
+ if p["score"] < 50:
+ raise ValueError("Score below 50: move this candidate outside the primary shortlist")
+ if not isinstance(p.get("additional_sources", []), list):
+ raise ValueError("additional_sources must be an array")
+ for source in p.get("additional_sources", []):
+ if not isinstance(source, dict):
+ raise ValueError("Each additional source must be an object")
+ public_url(source["url"])
+ text_field(source, "note")
+ except (ValueError, KeyError, TypeError) as exc:
+ raise ValueError(f"Prospect {index}: {exc}") from exc
+ data["prospects"] = sorted(data.get("prospects", []), key=lambda p: (-p["score"], p["name"]))
+ return data
+
+
+def read_state(path):
+ if path.is_symlink():
+ raise ValueError("State must be a regular local file, not a symlink")
+ with path.open(encoding="utf-8") as handle:
+ state = json.load(handle)
+ if not isinstance(state, dict) or state.get("schema_version") != 1:
+ raise ValueError("Unsupported or malformed history")
+ text_field(state, "project_key")
+ if not isinstance(state.get("demo", False), bool):
+ raise ValueError("Malformed history demo flag")
+ if not isinstance(state.get("prospects"), dict):
+ raise ValueError("Malformed prospect history")
+ profile = state.get("profile")
+ if not isinstance(profile, dict) or any(not isinstance(profile.get(k), list) or
+ not all(isinstance(x, str) for x in profile[k]) for k in ("prefer", "avoid")):
+ raise ValueError("Malformed search profile")
+ for key, record in state["prospects"].items():
+ if not isinstance(record, dict) or record.get("id") != key or record.get("status") not in STATUSES:
+ raise ValueError("Malformed history record")
+ if record.get("feedback") not in (None, *FEEDBACK):
+ raise ValueError("Malformed history feedback")
+ if not isinstance(record.get("latest"), dict) or prospect_id(record["latest"].get("entity_url")) != key:
+ raise ValueError("History identity mismatch")
+ return state
+
+
+def atomic_json(path, data):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ if path.is_symlink():
+ raise ValueError("Refusing to replace a symlink")
+ fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump(data, handle, indent=2, ensure_ascii=False, allow_nan=False)
+ handle.write("\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(temporary, path)
+ finally:
+ if os.path.exists(temporary):
+ os.unlink(temporary)
+
+
+@contextmanager
+def state_lock(path):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ lock = path.with_name(path.name + ".lock")
+ try:
+ fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
+ except FileExistsError as exc:
+ raise ValueError(f"History is locked by another run: {lock}. No state changed.") from exc
+ try:
+ os.close(fd)
+ yield
+ finally:
+ lock.unlink()
+
+
+def prepare_history(data, state, new_only=False):
+ """Return filtered report and next state, without writing either one."""
+ if data.get("schema_version") != 2:
+ raise ValueError("Saved history requires report schema_version 2")
+ if state is None:
+ state = {"schema_version": 1, "project_key": data["project_key"],
+ "demo": data.get("demo", False), "profile": {"prefer": [], "avoid": []}, "prospects": {}}
+ if state["project_key"] != data["project_key"]:
+ raise ValueError("Product mismatch: use a separate state file for this project_key")
+ if state.get("demo", False) != data.get("demo", False):
+ raise ValueError("Demo and real research cannot share history")
+ state, result = copy.deepcopy(state), copy.deepcopy(data)
+ result["prospects"] = []
+ excluded = {"seen": 0, "rejected": 0, "contacted": 0}
+ now = timestamp()
+ for p in data.get("prospects", []):
+ record = state["prospects"].get(p["id"])
+ reason = None
+ if record and record.get("feedback") == "reject":
+ reason = "rejected"
+ elif record and record["status"] != "new":
+ reason = "contacted"
+ elif record and new_only:
+ reason = "seen"
+ if reason:
+ excluded[reason] += 1
+ continue
+ p = copy.deepcopy(p)
+ p["history_label"] = "Previously seen" if record else "New discovery"
+ p["status"] = record["status"] if record else "new"
+ p["feedback"] = record.get("feedback") if record else None
+ next_record = copy.deepcopy(record) if record else {
+ "id": p["id"], "first_seen": now, "status": "new", "feedback": None}
+ next_record.update({"last_seen": now, "latest": p})
+ state["prospects"][p["id"]] = next_record
+ result["prospects"].append(p)
+ result["history_summary"] = {"excluded": excluded, "new_only": new_only,
+ "profile": copy.deepcopy(state["profile"])}
+ if any(excluded.values()):
+ # Input-level conclusions may refer to removed entities. Avoid presenting them as current.
+ result["verdict"] = f"{len(result['prospects'])} eligible prospects remain after history filtering. Review the included evidence before outreach."
+ result["patterns"] = []
+ result["outreach_plan"] = {
+ "angle": "Validate only the included prospects.",
+ "first_step": "Review their evidence and suitable contact routes; send nothing automatically.",
+ "follow_up": "Choose a next step after a real response.",
+ "success": "Observe whether the stated problem is still relevant; no response is guaranteed."}
+ result.setdefault("limits", []).append("History filtering removed candidates; prior pattern counts and the original outreach plan were omitted to avoid stale conclusions.")
+ state["updated_at"] = now
+ return result, state
diff --git a/first-customer-finder/scripts/prospect_history.py b/first-customer-finder/scripts/prospect_history.py
new file mode 100644
index 0000000..a3b944c
--- /dev/null
+++ b/first-customer-finder/scripts/prospect_history.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python3
+"""Inspect local prospect history or record explicit user feedback/outcomes."""
+
+import argparse
+import json
+from pathlib import Path
+
+from prospect_data import FEEDBACK, STATUSES, atomic_json, read_state, state_lock, timestamp
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--state", type=Path, required=True)
+ commands = parser.add_subparsers(dest="command", required=True)
+ commands.add_parser("show")
+ feedback = commands.add_parser("feedback")
+ feedback.add_argument("id")
+ feedback.add_argument("verdict", choices=FEEDBACK)
+ feedback.add_argument("--reason", required=True)
+ status = commands.add_parser("status")
+ status.add_argument("id")
+ status.add_argument("value", choices=STATUSES)
+ profile = commands.add_parser("profile")
+ for field in ("prefer", "avoid"):
+ group = profile.add_mutually_exclusive_group()
+ group.add_argument(f"--{field}", action="append")
+ group.add_argument(f"--clear-{field}", action="store_true")
+ args = parser.parse_args()
+ try:
+ if args.command == "show":
+ print(json.dumps(read_state(args.state), indent=2, ensure_ascii=False))
+ return
+ with state_lock(args.state):
+ state = read_state(args.state)
+ if args.command == "profile":
+ for field in ("prefer", "avoid"):
+ values = getattr(args, field)
+ if values is not None:
+ if any(not x.strip() for x in values):
+ raise ValueError("Search preferences cannot be empty")
+ state["profile"][field] = list(dict.fromkeys(x.strip() for x in values))
+ elif getattr(args, f"clear_{field}"):
+ state["profile"][field] = []
+ else:
+ if args.id not in state["prospects"]:
+ raise ValueError("Unknown prospect ID; resolve it from the relevant report")
+ record = state["prospects"][args.id]
+ if args.command == "feedback":
+ if not args.reason.strip():
+ raise ValueError("Feedback reason cannot be empty")
+ record.update(feedback=args.verdict, feedback_reason=args.reason.strip(), feedback_at=timestamp())
+ else:
+ record.update(status=args.value, status_updated_at=timestamp())
+ state["updated_at"] = timestamp()
+ atomic_json(args.state, state)
+ print(f"Updated local {args.command}: {args.state.resolve()}. No message was sent.")
+ except (ValueError, OSError) as exc:
+ parser.exit(1, f"Error: {exc}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/first-customer-finder/scripts/report_exports.py b/first-customer-finder/scripts/report_exports.py
new file mode 100644
index 0000000..77dc522
--- /dev/null
+++ b/first-customer-finder/scripts/report_exports.py
@@ -0,0 +1,133 @@
+"""Native Markdown and spreadsheet-safe CSV exports."""
+
+import csv
+import io
+import re
+from urllib.parse import quote
+
+from prospect_data import public_url
+
+
+DEMO_NOTICE = "FICTIONAL DEMO — invented prospects and evidence. Not live customer research."
+
+
+def md(value):
+ text = str(value if value is not None else "")
+ text = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+ text = re.sub(r"([\\`*_{}\[\]()|#!])", r"\\\1", text)
+ return " ".join(text.splitlines())
+
+
+def link(label, url):
+ try:
+ safe = public_url(url)
+ except ValueError:
+ return md(label) + " (no verified link)"
+ return f"[{md(label)}]({quote(safe, safe=':/?=&%#@+;,~.-_')})"
+
+
+def build_markdown(data):
+ prospects = data.get("prospects", [])
+ lines = [f"# {md(data.get('title', 'First Customer Finder'))}", ""]
+ if data.get("demo"):
+ lines += [f"> **{DEMO_NOTICE}**", ""]
+ if data.get("legacy_warning"):
+ lines += [f"> {md(data['legacy_warning'])}", ""]
+ lines += [f"{md(data.get('product'))} · {md(data.get('generated_at'))}", "",
+ f"**{len(prospects)} potential customers · No outreach sent**", "",
+ md(data.get("verdict")), "", "## Search brief", "",
+ f"- **Target:** {md(data.get('target_customer'))}",
+ f"- **Scope:** {md(data.get('search_scope'))}",
+ "- Scores prioritize research; they are not purchase probabilities.", ""]
+ history = data.get("history_summary")
+ if history:
+ excluded = history["excluded"]
+ lines += ["## This round", "",
+ f"Previously seen excluded: {excluded['seen']} · Rejected: {excluded['rejected']} · Already contacted/outcome recorded: {excluded['contacted']}", ""]
+ for kind in ("prefer", "avoid"):
+ if history["profile"][kind]:
+ lines += [f"**{kind.title()}:** {md('; '.join(history['profile'][kind]))}", ""]
+ if prospects:
+ top = prospects[0]
+ lines += ["## Start here", "", f"**{md(top.get('name'))} — {top.get('score', 0)}/100**", "",
+ md(top.get("why_now")), "", f"**Next step:** {md(top.get('next_step', 'Verify the source and contact route.'))}", "",
+ "## Shortlist", "", "| Rank | Prospect | Score | Target role | Contact route |",
+ "| --- | --- | ---: | --- | --- |"]
+ for i, p in enumerate(prospects, 1):
+ route = p.get("contact_route", {})
+ route_label = link(route.get("label", "Open route"), route.get("url")) if route.get("status") == "verified" else "No verified route"
+ lines.append(f"| P{i} | {md(p.get('name'))} | {p.get('score', 0)} | {md(p.get('target_role', 'Not verified'))} | {route_label} |")
+ lines.append("")
+ else:
+ lines += ["## No eligible prospects this round", "", "No placeholders were added. Review the limits before changing the search scope.", ""]
+ for i, p in enumerate(prospects, 1):
+ route = p.get("contact_route", {})
+ lines += [f"## P{i} · {md(p.get('name'))}", "",
+ f"**{p.get('score', 0)}/100 · {md(p.get('stage'))} · {md(p.get('history_label', 'History not used'))}**", "",
+ f"Stable ID: `{p.get('id', 'legacy')}`", "",
+ f"**Public signal:** {md(p.get('pain_signal'))}", "",
+ f"**Observed evidence:** {md(p.get('evidence'))}", "",
+ f"**Source:** {link(p.get('source_title', 'Original source'), p.get('source_url'))} · Published: {md(p.get('signal_date') or 'Unknown')} · Checked: {md(p.get('checked_at') or 'Not recorded')}", "",
+ f"**Why it fits:** {md(p.get('why_fit'))}", "",
+ f"**Why now:** {md(p.get('why_now'))}", "",
+ f"**Who:** {md(p.get('target_role', 'Not verified'))} ({md(p.get('role_basis', 'not recorded'))})", ""]
+ if route.get("status") == "verified":
+ lines += [f"**Where:** {link(route.get('label', 'Contact route'), route.get('url'))}", "",
+ f"Route evidence: {link('Supporting public page', route.get('source_url'))} · Checked: {md(route.get('checked_at'))}", ""]
+ else:
+ lines += ["**Where:** No suitable public contact route verified.", ""]
+ lines += [md(route.get("note")), "", f"**Next step:** {md(p.get('next_step'))}", "",
+ f"**CTA:** {md(p.get('cta'))}", "", "### Draft — not sent", "",
+ f"> {md(p.get('opener'))}", "",
+ f"**Check before contacting:** {md(p.get('caution'))}", ""]
+ if p.get("dimensions"):
+ lines += ["Score breakdown: " + " · ".join(f"{md(k.replace('_', ' '))} {v}/5" for k, v in p["dimensions"].items()), ""]
+ for source in p.get("additional_sources", []):
+ lines += [f"- {link(source.get('note', 'Supporting evidence'), source.get('url'))}"]
+ lines.append("")
+ if data.get("patterns"):
+ lines += ["## Recurring patterns", ""]
+ for pattern in data["patterns"]:
+ lines += [f"- **{md(pattern.get('title'))}** ({md(pattern.get('count'))}): {md(pattern.get('insight'))}"]
+ lines.append("")
+ plan = data.get("outreach_plan", {})
+ if plan:
+ lines += ["## Seven-day manual plan", ""]
+ for key, label in (("angle", "Approach"), ("first_step", "First step"), ("follow_up", "Follow-up"), ("success", "Validation target, not a forecast")):
+ lines += [f"- **{label}:** {md(plan.get(key))}"]
+ lines.append("")
+ lines += ["## Limits", "", "- These are potential customers inferred from public signals, not confirmed buyers.",
+ "- A public contact route is not consent to receive promotion."]
+ lines += [f"- {md(value)}" for value in data.get("limits", [])]
+ lines += ["", "## Refine the next round", "", 'Reply with the ranks from this report, for example: “P1 fits; P2 does not because …”. State any general preference explicitly.', "",
+ "History and status changes stay local. Feedback does not train a model or send messages.", ""]
+ return "\n".join(lines)
+
+
+CSV_FIELDS = ["record_type", "demo", "id", "name", "entity_url", "score", "stage", "target_role", "role_basis",
+ "pain_signal", "source_url", "signal_date", "checked_at", "contact_status", "contact_url",
+ "contact_source_url", "contact_note", "next_step", "cta", "opener", "caution", "status", "feedback"]
+
+
+def csv_cell(value):
+ value = str(value if value is not None else "")
+ # Spreadsheet applications may execute formulas even in quoted CSV fields.
+ if value.lstrip().startswith(("=", "+", "-", "@")) or value.startswith(("\t", "\r", "\n")):
+ return "'" + value
+ return value
+
+
+def build_csv(data):
+ buffer = io.StringIO(newline="")
+ writer = csv.DictWriter(buffer, fieldnames=CSV_FIELDS)
+ writer.writeheader()
+ if data.get("demo"):
+ writer.writerow({"record_type": "notice", "demo": "true", "name": DEMO_NOTICE})
+ for p in data.get("prospects", []):
+ row = {key: p.get(key, "") for key in CSV_FIELDS}
+ route = p.get("contact_route", {})
+ row.update(record_type="prospect", demo=str(data.get("demo", False)).lower(),
+ contact_status=route.get("status", "not_verified"), contact_url=route.get("url", ""),
+ contact_source_url=route.get("source_url", ""), contact_note=route.get("note", ""))
+ writer.writerow({key: csv_cell(value) for key, value in row.items()})
+ return buffer.getvalue()
diff --git a/package.json b/package.json
index bd02cb7..7696d98 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "codex-first-customer-finder-skill",
- "version": "0.1.0",
+ "version": "0.2.0",
"description": "A Codex skill that finds evidence-backed potential first customers from recent public signals.",
"license": "MIT",
"author": "Francesco Mistero",
@@ -15,11 +15,17 @@
"bin": {
"codex-first-customer-finder-skill": "scripts/install.js"
},
+ "scripts": {
+ "test": "python3 -m unittest discover -s tests -v && node --test tests/install.test.js",
+ "prepublishOnly": "npm test"
+ },
"files": [
"first-customer-finder",
"scripts/install.js",
"README.md",
- "LICENSE"
+ "LICENSE",
+ "!**/__pycache__/**",
+ "!**/*.pyc"
],
"keywords": [
"codex",
diff --git a/scripts/install.js b/scripts/install.js
index 450ef23..0839ad4 100755
--- a/scripts/install.js
+++ b/scripts/install.js
@@ -53,6 +53,7 @@ function defaultSkillsDir() {
function copyDirectory(source, destination) {
fs.mkdirSync(destination, { recursive: true });
for (const entry of fs.readdirSync(source, { withFileTypes: true })) {
+ if (entry.name === "__pycache__" || entry.name.endsWith(".pyc")) continue;
const sourcePath = path.join(source, entry.name);
const destinationPath = path.join(destination, entry.name);
if (entry.isDirectory()) copyDirectory(sourcePath, destinationPath);
@@ -73,11 +74,34 @@ function main() {
if (!fs.existsSync(source)) throw new Error(`Cannot find bundled skill at ${source}`);
fs.mkdirSync(skillsDir, { recursive: true });
- fs.rmSync(destination, { recursive: true, force: true });
- copyDirectory(source, destination);
+ let destinationStat;
+ try { destinationStat = fs.lstatSync(destination); }
+ catch (error) { if (error.code !== "ENOENT") throw error; }
+ if (destinationStat && destinationStat.isSymbolicLink()) {
+ throw new Error("The installed skill is a symlink; update its source explicitly instead.");
+ }
+ // Stage first and keep the previous installation recoverable.
+ const stagingRoot = fs.mkdtempSync(path.join(skillsDir, ".first-customer-finder-stage-"));
+ const staged = path.join(stagingRoot, "first-customer-finder");
+ copyDirectory(source, staged);
+ let backup;
+ if (fs.existsSync(destination)) {
+ const backupRoot = path.join(path.dirname(skillsDir), "skill-backups");
+ fs.mkdirSync(backupRoot, { recursive: true });
+ backup = path.join(fs.mkdtempSync(path.join(backupRoot, "first-customer-finder-")), "first-customer-finder");
+ fs.renameSync(destination, backup);
+ }
+ try {
+ fs.renameSync(staged, destination);
+ fs.rmdirSync(stagingRoot);
+ } catch (error) {
+ if (backup && !fs.existsSync(destination)) fs.renameSync(backup, destination);
+ throw error;
+ }
console.log("Installed first-customer-finder skill.");
console.log(`Location: ${destination}`);
+ if (backup) console.log(`Previous installation preserved at: ${backup}`);
console.log("");
console.log("Restart Codex, then run:");
console.log(" Use $first-customer-finder to find ten potential first customers for https://example.com.");
diff --git a/tests/install.test.js b/tests/install.test.js
new file mode 100644
index 0000000..e49a04b
--- /dev/null
+++ b/tests/install.test.js
@@ -0,0 +1,57 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const os = require('node:os');
+const { spawnSync } = require('node:child_process');
+
+const installer = path.resolve(__dirname, '../scripts/install.js');
+
+function withFolder(t) {
+ const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'customer-finder-test-'));
+ t.after(() => fs.rmSync(folder, { recursive: true, force: true }));
+ return folder;
+}
+
+test('fresh install and upgrade preserve custom previous files', (t) => {
+ const root = withFolder(t);
+ const skills = path.join(root, 'skills');
+ const run = () => spawnSync(process.execPath, [installer, '--skills-dir', skills], { encoding: 'utf8' });
+ assert.equal(run().status, 0);
+ const target = path.join(skills, 'first-customer-finder');
+ fs.writeFileSync(path.join(target, 'user-note.txt'), 'preserve me');
+ const upgraded = run();
+ assert.equal(upgraded.status, 0, upgraded.stderr);
+ const backup = upgraded.stdout.match(/Previous installation preserved at: (.+)/)[1];
+ assert.equal(fs.readFileSync(path.join(backup, 'user-note.txt'), 'utf8'), 'preserve me');
+ assert.ok(fs.existsSync(path.join(target, 'scripts/prospect_history.py')));
+ assert.ok(!fs.existsSync(path.join(target, 'scripts/__pycache__')));
+});
+
+test('symlink installation is not replaced or followed', (t) => {
+ const root = withFolder(t);
+ const target = path.join(root, 'first-customer-finder');
+ const external = path.join(root, 'external');
+ fs.mkdirSync(external);
+ fs.symlinkSync(external, target);
+ const run = spawnSync(process.execPath, [installer, '--skills-dir', root], { encoding: 'utf8' });
+ assert.notEqual(run.status, 0);
+ assert.ok(fs.lstatSync(target).isSymbolicLink());
+});
+
+test('dangling symlinks are refused', (t) => {
+ const root = withFolder(t);
+ const target = path.join(root, 'first-customer-finder');
+ fs.symlinkSync(path.join(root, 'missing'), target);
+ const run = spawnSync(process.execPath, [installer, '--skills-dir', root]);
+ assert.notEqual(run.status, 0);
+ assert.ok(fs.lstatSync(target).isSymbolicLink());
+});
+
+test('help does not install and invalid options fail', (t) => {
+ const root = withFolder(t);
+ const run = spawnSync(process.execPath, [installer, '--help', '--skills-dir', path.join(root, 'skills')]);
+ assert.equal(run.status, 0);
+ assert.ok(!fs.existsSync(path.join(root, 'skills')));
+ assert.notEqual(spawnSync(process.execPath, [installer, '--bad']).status, 0);
+});
diff --git a/tests/test_workflow.py b/tests/test_workflow.py
new file mode 100644
index 0000000..f9beaec
--- /dev/null
+++ b/tests/test_workflow.py
@@ -0,0 +1,285 @@
+"""Offline regression tests; fixtures are fictional, never customer evidence."""
+
+import copy
+import csv
+import io
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = ROOT / "first-customer-finder" / "scripts"
+sys.path.insert(0, str(SCRIPTS))
+from prospect_data import (atomic_json, canonical_url, normalize_report, prepare_history,
+ prospect_id, public_url, read_state, state_lock)
+from generate_report import build_html
+from report_exports import DEMO_NOTICE, build_csv, build_markdown
+
+
+def fixture():
+ return json.loads((ROOT / "examples" / "demo.json").read_text())
+
+
+class DataTests(unittest.TestCase):
+ def test_scores_computed_and_sorted(self):
+ raw = fixture()
+ for p in raw["prospects"]:
+ p["score"] = 1
+ result = normalize_report(raw)
+ self.assertEqual(result["prospects"][0]["score"], 90)
+ self.assertEqual([p["score"] for p in result["prospects"]], sorted([p["score"] for p in result["prospects"]], reverse=True))
+ self.assertEqual(raw["prospects"][0]["score"], 1)
+
+ def test_identity_normalization(self):
+ self.assertEqual(prospect_id("http://www.example.com/team/?utm_source=x#reply"), prospect_id("https://example.com/team"))
+ self.assertEqual(prospect_id("https://twitter.com/founder"), prospect_id("https://x.com/founder/"))
+ self.assertNotEqual(prospect_id("https://github.com/a"), prospect_id("https://github.com/b"))
+ self.assertNotEqual(prospect_id("https://example.com/?company=a"), prospect_id("https://example.com/?company=b"))
+
+ def test_duplicate_entities_rejected(self):
+ raw = fixture()
+ raw["prospects"].append(copy.deepcopy(raw["prospects"][0]))
+ with self.assertRaisesRegex(ValueError, "Duplicate"):
+ normalize_report(raw)
+
+ def test_unsafe_urls(self):
+ for value in ("javascript:alert(1)", "file:///etc/passwd", "https://user:[email protected]", "https://example.com\n/path", "https://example.com:bad", "https://example.com\\x"):
+ with self.subTest(value=value), self.assertRaises(ValueError):
+ public_url(value)
+
+ def test_invalid_dimensions(self):
+ for value in (True, float("nan"), float("inf"), -1, 6, "5"):
+ raw = fixture()
+ raw["prospects"][0]["dimensions"]["timing"] = value
+ with self.subTest(value=value), self.assertRaises(ValueError):
+ normalize_report(raw)
+
+ def test_unknown_date_is_not_fresh(self):
+ raw = fixture()
+ raw["prospects"][0]["signal_date"] = None
+ with self.assertRaisesRegex(ValueError, "Undated"):
+ normalize_report(raw)
+ raw["prospects"][0]["dimensions"]["timing"] = 2
+ normalize_report(raw)
+
+ def test_future_dates_rejected(self):
+ raw = fixture()
+ raw["prospects"][0]["signal_date"] = "2099-01-01"
+ with self.assertRaisesRegex(ValueError, "later"):
+ normalize_report(raw)
+
+ def test_unverified_sources_rejected(self):
+ raw = fixture()
+ raw["prospects"][0]["evidence_status"] = "snippet_only"
+ with self.assertRaisesRegex(ValueError, "inspected"):
+ normalize_report(raw)
+
+ def test_missing_contact_route_not_invented(self):
+ raw = fixture()
+ raw["prospects"][0]["contact_route"] = {"status": "not_found", "note": "No suitable route found"}
+ with self.assertRaisesRegex(ValueError, "reachability"):
+ normalize_report(raw)
+ raw["prospects"][0]["dimensions"]["reachability"] = 1
+ normalize_report(raw)
+ raw["prospects"][0]["contact_route"]["url"] = "https://example.com/guess"
+ with self.assertRaisesRegex(ValueError, "guessed"):
+ normalize_report(raw)
+
+ def test_cta_must_appear_in_opener(self):
+ raw = fixture()
+ raw["prospects"][0]["opener"] = "Would this be useful?"
+ with self.assertRaisesRegex(ValueError, "CTA"):
+ normalize_report(raw)
+
+ def test_wrong_product_and_demo_boundaries(self):
+ data = normalize_report(fixture())
+ _, state = prepare_history(data, None)
+ for field, value in (("project_key", "another-product"), ("demo", False)):
+ changed = copy.deepcopy(data)
+ changed[field] = value
+ with self.subTest(field=field), self.assertRaises(ValueError):
+ prepare_history(changed, state)
+
+ def test_repeat_search_excludes_seen(self):
+ data = normalize_report(fixture())
+ _, state = prepare_history(data, None)
+ report, next_state = prepare_history(data, state, new_only=True)
+ self.assertEqual(report["prospects"], [])
+ self.assertEqual(report["history_summary"]["excluded"]["seen"], 3)
+ self.assertEqual(len(next_state["prospects"]), 3)
+ self.assertEqual(report["patterns"], [])
+
+ def test_only_new_entities_enter_next_round(self):
+ raw = fixture()
+ data = normalize_report(raw)
+ _, state = prepare_history(data, None)
+ new = copy.deepcopy(raw["prospects"][0])
+ new["name"] = "Another fictional studio"
+ new["entity_url"] = "https://example.com/another-studio"
+ raw["prospects"].append(new)
+ report, next_state = prepare_history(normalize_report(raw), state, new_only=True)
+ self.assertEqual(len(report["prospects"]), 1)
+ self.assertEqual(report["prospects"][0]["name"], new["name"])
+ self.assertEqual(len(next_state["prospects"]), 4)
+
+ def test_malformed_optional_data_rejected(self):
+ for field, value in (("patterns", ["bad"]), ("limits", "bad"), ("outreach_plan", []), ("schema_version", True)):
+ raw = fixture()
+ raw[field] = value
+ with self.subTest(field=field), self.assertRaises(ValueError):
+ normalize_report(raw)
+ raw = fixture()
+ raw["patterns"][0]["count"] = 1000
+ with self.assertRaisesRegex(ValueError, "Pattern count"):
+ normalize_report(raw)
+
+ def test_outcome_and_rejections_survive_refresh(self):
+ data = normalize_report(fixture())
+ _, state = prepare_history(data, None)
+ ids = [p["id"] for p in data["prospects"]]
+ state["prospects"][ids[0]]["status"] = "contacted"
+ state["prospects"][ids[0]]["feedback"] = "keep"
+ state["prospects"][ids[1]]["feedback"] = "reject"
+ report, next_state = prepare_history(data, state)
+ self.assertEqual([p["id"] for p in report["prospects"]], [ids[2]])
+ self.assertEqual(next_state["prospects"][ids[0]]["status"], "contacted")
+ self.assertEqual(report["prospects"][0]["history_label"], "Previously seen")
+
+ def test_no_history_for_legacy(self):
+ data = normalize_report({"prospects": []})
+ self.assertIn("legacy_warning", data)
+ with self.assertRaises(ValueError):
+ prepare_history(data, None)
+
+
+class ExportTests(unittest.TestCase):
+ def test_all_formats_mark_demo(self):
+ data = normalize_report(fixture())
+ for builder in (build_markdown, build_html, build_csv):
+ with self.subTest(builder=builder.__name__):
+ self.assertIn(DEMO_NOTICE, builder(data))
+ empty = copy.deepcopy(data)
+ empty["prospects"] = []
+ self.assertIn(DEMO_NOTICE, builder(empty))
+
+ def test_markdown_and_html_escape_untrusted_content(self):
+ data = normalize_report(fixture())
+ data["prospects"][0]["name"] = '<script>alert(1)</script> [bad](javascript:x) | row'
+ for builder in (build_markdown, build_html):
+ result = builder(data)
+ self.assertNotIn("<script>", result)
+ self.assertNotIn('href="javascript:', result)
+ self.assertIn("\\| row", build_markdown(data))
+
+ def test_csv_formula_injection(self):
+ data = normalize_report(fixture())
+ data["prospects"][0]["name"] = ' =HYPERLINK("https://evil.example")'
+ rows = list(csv.DictReader(io.StringIO(build_csv(data))))
+ self.assertTrue(rows[1]["name"].startswith("'"))
+ self.assertEqual(rows[1]["record_type"], "prospect")
+
+ def test_route_and_manual_next_step_in_every_format(self):
+ data = normalize_report(fixture())
+ for builder in (build_markdown, build_html, build_csv):
+ result = builder(data)
+ self.assertIn(data["prospects"][0]["contact_route"]["url"], result)
+ self.assertIn(data["prospects"][0]["next_step"], result)
+
+
+class CLITests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.folder = Path(self.temp.name)
+ self.input = self.folder / "analysis.json"
+ self.input.write_text(json.dumps(fixture()))
+ self.state = self.folder / "state.json"
+
+ def run_cli(self, script, *args, success=True):
+ result = subprocess.run([sys.executable, str(SCRIPTS / script), *map(str, args)], capture_output=True, text=True)
+ self.assertEqual(result.returncode == 0, success, result.stdout + result.stderr)
+ return result
+
+ def generate(self, name="report.md", *extra):
+ return self.run_cli("generate_report.py", self.input, self.folder / name, "--state", self.state, *extra)
+
+ def test_report_history_feedback_more_and_refresh(self):
+ self.generate("round1.md", "--csv", self.folder / "leads.csv", "--html", self.folder / "report.html")
+ state = read_state(self.state)
+ ids = list(state["prospects"])
+ self.run_cli("prospect_history.py", "--state", self.state, "feedback", ids[0], "keep", "--reason", "Good fit")
+ self.run_cli("prospect_history.py", "--state", self.state, "feedback", ids[1], "reject", "--reason", "Wrong size")
+ self.run_cli("prospect_history.py", "--state", self.state, "status", ids[0], "contacted")
+ self.run_cli("prospect_history.py", "--state", self.state, "profile", "--prefer", "Owner-led", "--avoid", "Enterprise")
+ self.run_cli("prospect_history.py", "--state", self.state, "profile", "--prefer", "Small studios")
+ state = read_state(self.state)
+ self.assertEqual(state["profile"]["avoid"], ["Enterprise"])
+ self.assertEqual(state["profile"]["prefer"], ["Small studios"])
+ self.generate("round2.md", "--new-only")
+ self.assertIn("0 potential customers", (self.folder / "round2.md").read_text())
+ self.generate("refresh.md")
+ self.assertIn("1 potential customers", (self.folder / "refresh.md").read_text())
+ self.assertEqual(read_state(self.state)["prospects"][ids[0]]["status"], "contacted")
+
+ def test_profile_changes_only_from_explicit_command(self):
+ self.generate()
+ key = next(iter(read_state(self.state)["prospects"]))
+ self.run_cli("prospect_history.py", "--state", self.state, "feedback", key, "reject", "--reason", "Too big")
+ self.assertEqual(read_state(self.state)["profile"], {"prefer": [], "avoid": []})
+
+ def test_same_output_cannot_overwrite_input_or_history(self):
+ original = self.input.read_bytes()
+ self.run_cli("generate_report.py", self.input, self.input, success=False)
+ self.assertEqual(self.input.read_bytes(), original)
+ self.generate()
+ before = self.state.read_bytes()
+ self.run_cli("generate_report.py", self.input, self.folder / "other.md", "--csv", self.state, "--state", self.state, success=False)
+ self.assertEqual(self.state.read_bytes(), before)
+
+ def test_existing_output_rejected_without_updating_state(self):
+ self.generate()
+ before = self.state.read_bytes()
+ self.run_cli("generate_report.py", self.input, self.folder / "report.md", "--state", self.state, success=False)
+ self.assertEqual(self.state.read_bytes(), before)
+
+ def test_invalid_input_leaves_no_output_or_state(self):
+ raw = fixture()
+ raw["prospects"][0]["evidence_status"] = "unavailable"
+ self.input.write_text(json.dumps(raw))
+ self.run_cli("generate_report.py", self.input, self.folder / "report.md", "--state", self.state, success=False)
+ self.assertFalse(self.state.exists())
+ self.assertFalse((self.folder / "report.md").exists())
+
+ def test_lock_conflict_preserves_state(self):
+ self.generate()
+ before = self.state.read_bytes()
+ with state_lock(self.state):
+ self.run_cli("prospect_history.py", "--state", self.state, "profile", "--avoid", "Enterprise", success=False)
+ self.assertEqual(self.state.read_bytes(), before)
+ self.assertFalse(self.state.with_suffix(".json.lock").exists())
+
+ def test_unknown_id_does_not_modify_history(self):
+ self.generate()
+ before = self.state.read_bytes()
+ self.run_cli("prospect_history.py", "--state", self.state, "status", "p_missing", "contacted", success=False)
+ self.assertEqual(self.state.read_bytes(), before)
+
+ def test_malformed_and_symlink_history_refused(self):
+ self.state.write_text('{"schema_version": 9}')
+ self.run_cli("prospect_history.py", "--state", self.state, "show", success=False)
+ alias = self.folder / "alias.json"
+ alias.symlink_to(self.state)
+ with self.assertRaisesRegex(ValueError, "symlink"):
+ read_state(alias)
+
+ def test_legacy_html_command(self):
+ self.input.write_text(json.dumps({"product": "Legacy", "prospects": []}))
+ self.run_cli("generate_report.py", self.input, self.folder / "legacy.html")
+ self.assertIn("Legacy input", (self.folder / "legacy.html").read_text())
+
+
+if __name__ == "__main__":
+ unittest.main()