From 23c280e8b15ab5d19ea0355538be28af1ad79a3d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 02:39:43 +0000 Subject: [PATCH 1/2] Add a local agent-native CRM slice with research and a draft spec. The notes cite the Ampersand CRM guide and the Salesforce, HubSpot, Twenty, Attio, Folk, Pipedrive and Close docs. The draft follows the records template and records the ADR 0004 conflict. The slice is a standard-library SQLite store with a JSON command line and MCP server, covered by local tests and no external calls. Co-authored-by: Jake Parker --- docs/research/crm-guide-notes.md | 143 ++++++ docs/specs/agent-native-crm.md | 179 +++++++ products/crm/.gitignore | 5 + products/crm/README.md | 48 ++ products/crm/crm.py | 10 + products/crm/mcp.py | 10 + products/crm/openwiz_crm/__init__.py | 3 + products/crm/openwiz_crm/cli.py | 170 +++++++ products/crm/openwiz_crm/errors.py | 11 + products/crm/openwiz_crm/mcp.py | 333 +++++++++++++ products/crm/openwiz_crm/store.py | 719 +++++++++++++++++++++++++++ products/crm/test_crm.py | 248 +++++++++ 12 files changed, 1879 insertions(+) create mode 100644 docs/research/crm-guide-notes.md create mode 100644 docs/specs/agent-native-crm.md create mode 100644 products/crm/.gitignore create mode 100644 products/crm/README.md create mode 100644 products/crm/crm.py create mode 100644 products/crm/mcp.py create mode 100644 products/crm/openwiz_crm/__init__.py create mode 100644 products/crm/openwiz_crm/cli.py create mode 100644 products/crm/openwiz_crm/errors.py create mode 100644 products/crm/openwiz_crm/mcp.py create mode 100644 products/crm/openwiz_crm/store.py create mode 100644 products/crm/test_crm.py diff --git a/docs/research/crm-guide-notes.md b/docs/research/crm-guide-notes.md new file mode 100644 index 00000000..46f4a7fa --- /dev/null +++ b/docs/research/crm-guide-notes.md @@ -0,0 +1,143 @@ +# CRM guide notes + +Research for the agent-native CRM draft in [docs/specs/agent-native-crm.md](../specs/agent-native-crm.md). The notes were taken from the public pages linked below. The printed book was not in hand. Ampersand's public preview is a seven-part field guide, presented as volume one, for engineers who build software and agents that read from and write to CRMs. The preview's own description is "A field guide for engineers building software and AI agents that read from and write to CRMs." A shorter request-a-copy page carries the foreword and the same table of contents. + +The guide's installation diagram says its counts are illustrative, not measured customer data. Those counts are not repeated here as facts. + +## Sources + +- Preview: +- Request-a-copy page, foreword by Ayan Barua, contents: +- Ampersand Salesforce connector: +- Ampersand subscribe actions: +- Subscribe Actions launch post, 8 May 2025: +- Salesforce objects and fields: +- Salesforce custom fields: +- Salesforce describe global: +- Salesforce sObject describe: +- Salesforce API request limits: +- Salesforce Bulk API limits: +- Salesforce Change Data Capture allocations: +- HubSpot CRM model: +- HubSpot object APIs: +- HubSpot search: +- HubSpot associations: +- HubSpot webhooks: +- HubSpot usage limits: +- Twenty data model: +- Twenty APIs: +- Attio objects and lists: +- Attio standard objects: +- Attio people: +- Attio companies: +- Attio deals: +- Folk custom fields: +- Folk custom objects: +- Pipedrive custom fields: +- Pipedrive API v2 custom fields: +- Pipedrive rate limiting: +- Close overview: +- Close rate limits: + +Launch posts confirm the book exists and state the problem in the authors' words. They are not a substitute for the preview: [Dion Low](https://www.linkedin.com/posts/dionlow_last-week-we-launched-the-book-i-wrote-activity-7516561502812766208-BYfw), [Ampersand](https://www.linkedin.com/posts/withampersand_last-week-we-announced-our-15m-series-a-activity-7516234269929775104-w-Z6). The preview credits Dion Low as primary author, with Anusha Talasila, Jaehyun (Jay) Lim and Joel Theodros. + +## What the guide says a CRM is + +A CRM turns interactions into linked records so sales, marketing, customer success and leadership can ask different questions of one set of records. Sales asks what to do next on a deal. Marketing asks which campaigns produce engagement. Customer success asks whether an account is healthy. Leadership asks how the pipeline is doing. The guide's account-executive interview describes the salesperson's loop as prospecting, qualifying, pitching and closing, and says management, marketing and customer success use the same records for forecast, source and renewal. + +A spreadsheet works for a few people and breaks as columns and editors multiply: conflicting edits, weak permissions, manual reminders, fragile links, slow queries, and history scattered across tabs. The guide maps those to locking, access control, workflows, referential integrity, indexing and retained history. A CRM supplies the mechanisms. It does not decide the business rules. + +The core map in the preview: + +| Business concept | Salesforce | HubSpot | +| --- | --- | --- | +| Organization | Account | Company | +| Person | Contact | Contact | +| Potential sale | Opportunity | Deal | +| Support issue | Case | Ticket | + +Activities are records too. The preview says Salesforce models tasks and calendar events as Task and Event, and that their links depend on the activity. Custom objects are how a business names what the standard model does not: a listing, a job posting, an inventory item. Custom fields such as `Renewal_Tier__c` carry that customer's own words. Two Salesforce customers do not share a schema. + +The guide's engineering consequences: + +- Discover objects, fields and relationships at runtime, then confirm what they mean before mapping them. A fixed set of endpoints is the wrong expectation. +- Application schemas change by review and migration. A customer CRM changes when sales, marketing or customer success adds a step. Oversight varies. Old fields stay because an old report still uses them (`Stage__c` beside `Stage_v2__c` is the preview's example). +- Reading one record is not enough. An agent reconstructs context by walking the graph: person, company, deals, conversations. The guide calls fetching the rest of a thin change "hydration." +- A change notification often carries an id and what changed, not the fields a downstream agent needs. Ampersand's described path is to hydrate, transform and then deliver. +- Writing is a business action. Stages, required fields, assignment and permissions decide what may be written. Some customers want a batch to succeed or fail as a whole. Others want valid rows to land and failures reported. The guide says that choice has to be explicit. +- Production instances do not look like the vendor's test org. Backfills of large orgs run for hours and need a checkpoint that proves progress, or a healthy import and a stuck import look the same. The same HTTP status can mean a transient provider error or a missing permission. People leave, tokens get revoked, and a connection that could read contacts later fails when it first touches accounts. OAuth scopes and CRM permissions are different gates. +- Deploying code into the customer org, such as a Salesforce Apex trigger, can be easy to install and blocked on the way out by the customer's own test coverage. +- Between the record and the agent the preview draws five layers: the record, authorization, transport (rate limits, pagination, retries), shape (mapping and hydration), then the agent. Dead fields should be dropped. Source and time should be kept. +- One integration is an API call. A product that serves many customers needs a per-installation record of auth, schema, mappings, sync checkpoints and errors. The guide treats that management layer as infrastructure, including region separation, and says some failures still need a person. + +Ampersand's connector docs match the book. The Salesforce CRM module supports read (backfill and incremental), write (including bulk write and delete), subscribe, and proxy calls. Account, Campaign, Case, Contact, Event, Lead, Opportunity, Product, Task and User are listed for all three, and the page says all custom objects are too, standard and custom fields included. Subscribe actions reuse a read object's field mapping. HubSpot adds an association-change event. The launch post says Salesforce has no native webhooks, so the practical stream is Change Data Capture, and that each customer needs isolated tokens and adaptive rate limits. + +## Salesforce + +Salesforce describes objects as tables and records as rows. Standard objects ship with the platform. Custom objects are defined in the org, including through the Metadata API. External objects point at data stored outside the org. The concepts page says Account is the central object for companies and organizations, and that an application only sees the objects the running user is allowed to see. Sharing rules and profile permissions are part of the model, not a layer beside it. + +Custom fields and custom objects use an API name ending in `__c` (`Hire_Date__c`, `Issue__c`). A managed package adds a namespace prefix, so `name__c` becomes `prefix__name__c`. Uniqueness and case sensitivity are visible on describe and are not set by a normal data API call. A duplicate unique value returns `DUPLICATE_VALUE`. The custom-fields page lists Account, Campaign, Case, Contact, Contract, Event, Lead, Opportunity, Product2, Solution, Task and User as standard objects that accept custom fields. On that page, Lead, Task and Event accept custom fields and neither master-detail nor lookup relationships. + +Describe global, `GET /services/data/vXX.X/sobjects/`, lists standard and custom objects and the maximum batch size. Describe on one object, `GET /services/data/vXX.X/sobjects/sObject/describe/`, returns fields, URLs and child relationships. Both honor `If-Modified-Since` with `304`. The describe-global page warns that the header also changes when org-wide permissions or profiles change, not only when that object's fields change. A cached schema can go stale because a person changed access. + +API limits are per org, for a rolling 24 hours, not per user. Developer Edition is 15,000 calls. Enterprise Edition, and Professional with API access, is 100,000 plus licenses plus add-ons. The page's example is an Enterprise org with 15 Salesforce licenses: 115,000 calls. Unlimited and Performance use the same 100,000 base, with a Salesforce license counted at 5,000 calls. A full sandbox that is not created from a template is 5,000,000. REST, SOAP, Bulk API, Bulk API 2.0 and most Connect APIs count. Concurrent calls that last 20 seconds or longer are capped at 5 on Developer and trial orgs and 25 on production and sandboxes. REST and SOAP calls time out at 10 minutes, queries aside. The combined URI and headers on a REST call are limited to 16,384 bytes. The limits page points at Composite resources as the way to cut round trips. Usage is visible in the `Sforce-Limit-Info` header and at `/limits`. + +Bulk API 2.0 is the documented path once a job is over 2,000 records. Bulk and Bulk 2.0 share 15,000 batches per rolling 24 hours and 150,000,000 uploaded records. In Bulk 2.0 only ingest jobs consume batches. A Bulk 2.0 ingest job is limited to 150 MB, and the page says to stay under about 100 MB of raw CSV because the body is base64-encoded. Results are kept for 7 days. + +Change Data Capture publishes record changes. The allocations page says a change event message is at most 1 MB. A larger message is not delivered and is replaced by a gap event. The same page says the default cap on selected entities is 5, that an add-on removes that cap, and that delivery to Pub/Sub, CometD, empApi and event relays shares a rolling 24-hour allocation with high-volume platform events. The page's Unlimited example is 50,000 delivered events. Its default-allocations table lists 50,000, 25,000 and 10,000 for Performance and Unlimited, Enterprise, and Developer. Events are retained for 72 hours and can be resumed with a replay id. Apex triggers do not count against the delivery allocation. Exceeding it disconnects the subscriber. + +## HubSpot + +HubSpot's CRM guide defines objects, records, properties and associations. One object API covers the standard objects. The path parameter is an object type id: contacts `0-1`, companies `0-2`, deals `0-3`, tickets `0-5`. Activities are objects too: notes `0-46`, meetings `0-47`, calls `0-48`, emails `0-49`, tasks `0-27`. Custom objects use ids of the form `2-XXX`, discovered from the schemas API. Contacts, companies, deals, tickets and notes also accept a fully qualified name in some APIs. + +Record ids (`hs_object_id`) are unique inside one object. A contact and a company can share the same id. Contacts also dedupe on email, companies on domain, and either object can gain a custom unique property. Batch upsert uses `idProperty`. Deals require `dealname`, `dealstage` and `pipeline` to create. Pipelines and stages are their own API. + +Associations are separate from properties. They can be unlabeled or labeled (the guide's example is Decision maker). Association definitions, including custom labels, are a schema API. The associations guide's limits: Professional and Enterprise accounts get 500,000 association requests per day. Burst limits are 100 requests per 10 seconds on Free and Starter, and 150 on Professional and Enterprise. Batch read accepts 1,000 inputs. Batch create accepts 2,000. + +Search is `POST` on the object search path. The search guide limits it to 5 requests per second per account, 200 records per page, 10,000 results for one query, a 3,000-character query, and at most five filter groups with six filters each and 18 filters in total. New and updated records can take a moment to appear. Archived records do not appear. + +General app limits are separate and stricter APIs opt out of them. The usage guide says a publicly distributed OAuth app is limited to 110 requests per 10 seconds for each installing account, and that this excludes the CRM Search API. The API-limit add-on does not raise that public-app cap. Private apps, per the same page: Free and Starter 100 requests per 10 seconds per app and 250,000 per day per account; Professional 190 per 10 seconds and 625,000 per day; Enterprise 190 per 10 seconds and 1,000,000 per day. The daily cap is shared by private apps in the account. The burst cap is per app. A `429` body includes `policyName` of `DAILY` or the secondly policy. Daily reset follows the account time zone. + +Webhooks are an app-level subscription, not an account-level one. The webhooks guide says the classic endpoints are for legacy public apps, that delivery is HTTPS, that settings can be cached for up to five minutes, and that HubSpot sends at most 10 concurrent requests per installing account, with up to 100 events in one request. Subscriptions need the matching CRM read scope. The guide also says webhooks can subscribe to CRM object events, including contacts, companies, deals, tickets, products and line items. + +## Twenty, Attio, Folk, Pipedrive, Close + +Twenty ships Companies, People, Opportunities, Tasks and Notes, and treats a custom object as a first-class object with the same REST and GraphQL endpoints, views, permissions and workflow triggers. There is no static API reference. Each workspace has its own schema. Records are under `/rest/{object}`. Schema changes go through `/rest/metadata/`. A record read can ask for `fields` and a relation `depth`. Omitting `fields` on an object with more than 200 readable fields returns a default of 200, standard fields before custom ones. Unknown fields and fields the role cannot read return 400. + +Attio separates facts from process. Objects hold records (people and companies exist in every workspace; deal, user and workspace are optional). Lists hold entries that point at those records and can carry attributes that exist only for that process. People are enriched, and the people page says enriched values cannot be overridden by API users and that some enriched attributes are hidden from the API depending on the plan. Creating a person can create or match a company from the email domain. Deals, when an admin enables them, require name, stage and owner. Deals have no unique attribute by default. The deals page says to add one before asserting, because a non-unique match that hits two deals is rejected. The companies page says a custom attribute on Company cannot be given a unique constraint. + +Folk scopes custom fields and custom object types to a group. Two groups can each have a Status field, or a Job Applications object, and they do not share a schema. People and companies are the contacts. An object links people, companies, or both. Writes go through `customFieldValues` keyed by group id. Select options are matched by label, and an unknown label on write creates an option. + +Pipedrive's custom field keys are generated per account. The custom-fields page says the same name and type in two accounts still produce different `key` values, so a key cannot be copied between accounts. API v2 moves those keys under `custom_fields` instead of the v1 root-level hash keys. Leads inherit deal custom fields. Rate limits are a daily token budget: 30,000 base tokens times a plan multiplier (Lite 1, Growth 2, Premium 5, Ultimate 7) times seats, plus purchased top-ups, shared by the company. The page's sample costs include 2 tokens to get one entity, 20 to list, 10 to update, and 40 to search. A burst limit also applies per user on a 2-second window. An empty budget returns 429 until the next server-midnight reset. + +Close inverts the Salesforce lead. A lead is the company or organization and contains contacts, tasks, opportunities and activities. Activities are calls, emails, notes, SMS and meetings. Custom fields sit on leads, contacts, opportunities and custom activities. `PUT` is a patch. The rate-limit page says limits are per endpoint group, per API key, and per organization, and that the organization limit is three times the per-key limit. The 20-versus-60 requests-per-second pair on that page is an illustration of the three-times rule, not a published universal cap. A 429 carries `RateLimit` and `retry-after`. The page says to wait for `rate_reset` rather than use a fixed backoff. Some endpoints can still 429 inside the window. + +## What is good, and what hurts an agent + +The useful ideas, across these systems: + +- One graph of organizations, people, potential sales and activities, with every role reading a different view. +- Custom objects and fields that use the same API as standard ones. Twenty is the clearest statement of this. HubSpot's single object path is the same idea. Salesforce describe is the discovery tool, with the namespace and `__c` suffix as the tax. +- Associations as their own records, with labels, not only a lookup column. HubSpot and Attio both do this. Salesforce AccountContactRelation shows the same need on top of the lookup. +- History, ownership and a stage that can require data before it advances. That is the guide's reason to leave the spreadsheet. +- A stable external id, and an upsert that is idempotent. HubSpot's `idProperty` and Attio's assert-by-unique-attribute are the patterns. The id has to include the object type wherever ids are per object. +- Change streams plus a hydrate step. A thin event is a hint, not context. +- Checkpoints and a visible cursor on long imports. The guide's backfill lesson. +- An error category an agent can branch on, instead of a raw status code. The guide says raw provider errors also waste the agent's context. + +The painful parts, for an engineer or an agent: + +- The schema is owned by admins and drifts. Field names lie. Requiredness depends on stage, profile and validation rules the API does not always put in one document. +- The integration user does not see the CRM the admin sees. Describe and a successful OAuth handshake both overstate what the next call can do. +- Quotas are shared with every other tool in the org, and they are easy to spend by reading one record at a time or by searching. HubSpot search is a separate, much tighter budget. Salesforce counts Bulk calls against the same daily allocation as REST. +- Writes can start workflows, assignment rules and required-field failures. A confident agent that fills every field will clobber a rep's correction and can trip a validation rule it cannot see. +- Providers disagree on the words. Close's lead is a company. Salesforce's lead is a person who has not been converted. HubSpot has both a contact and a lead object (`0-136`). Pipedrive's custom field identity is an opaque hash. Attio will not let an API overwrite enriched facts. +- Lists and groups (Attio, Folk) are a second schema on top of the person. Copying "the contact" without the list loses the process. +- Test orgs do not reproduce production automations, and some of those automations only show up as an opaque status code. +- Event streams have their own caps, drop oversized messages into gap events, and still need a read before the agent can act. + +## Implications for this CRM + +The first slice should be the graph and the agent surface, not a Salesforce client. Standard objects are data, custom objects use the same calls, associations are labeled, activities are records with a source, and a context read returns one hop plus recent changes. Writes are partial, audited, and can require the revision the agent just read. External identity is provider, object type and external id, so a later import does not merge a HubSpot contact with a company that happens to share a number. + +Live sync, webhooks and capture from Slack, email, GitHub and X are later. They need per-installation schema, checkpoints, a written batch policy, and a person in the loop when a provider error is really a permissions change. Those are the parts the guide says teams underestimate. They are also the parts that need approval before any live read. diff --git a/docs/specs/agent-native-crm.md b/docs/specs/agent-native-crm.md new file mode 100644 index 00000000..771c96a2 --- /dev/null +++ b/docs/specs/agent-native-crm.md @@ -0,0 +1,179 @@ +# Agent-native CRM + +This file is a draft spec body. [ADR 0004](../adr/0004-github-layout-for-versions-specs-tickets.md) says the live spec is a parent issue, and a file in the repository was considered and rejected for that job. The draft is here so the research, the cut and the first slice can be reviewed together. It should be copied into a parent issue, and this file removed or reduced to a pointer, once that issue exists. + +The notes behind the design are in [docs/research/crm-guide-notes.md](../research/crm-guide-notes.md). The first slice is [products/crm](../../products/crm/README.md). + +## Problem Statement + +OpenWiz needs a CRM with two users, and they are the same product. + +OpenWiz itself needs to remember people and organizations it deals with: users, contributors, partners, and leads such as a university application or work in an outside repository. The factory already keeps its process on GitHub. It does not keep the relationship around that work: who the person is, which organization they belong to, what was last said, and what should happen next. + +The other user is an agent building or operating some other product. That agent needs a CRM it can call the way it calls a tool: create and search records, log what just happened, and read the linked context back in one response. Today that agent is pointed at Salesforce or HubSpot. Those systems are powerful and they are a poor fit for an agent. The schema belongs to an admin and drifts. A read of one record is not the context. A write is a business action that can fire rules the agent cannot see. Quotas are shared, errors are ambiguous, and the integration user does not see the CRM the admin sees. The research notes collect those limits from the Ampersand guide and from the vendor docs. + +A spreadsheet, or a pile of notes in a repository, fails the test the guide starts from. Several roles add columns, two rows disagree about the owner, and nobody can say what changed. + +## Solution + +Build one local-first CRM whose records are the product, and whose callers are agents. + +The working name in the request was the goat CRM. This draft calls it the agent-native CRM. The public name is an open decision. + +### Who it is for + +- OpenWiz, tracking users, contributors, partners and leads. A lead might be a university application or an outside repository. Those are records and associations, not special tables. +- Other agents, through a skill that tells them to use this CRM for their own relationships. One data model, one tool surface, a separate database per workspace. OpenWiz's own database is just the first workspace. + +People use it by asking an agent. The agent uses the command line or MCP. A human user interface is later. + +### Data model + +Four standard objects, plus custom objects that use the same API: + +| Object | Required fields | What it is | +| --- | --- | --- | +| `person` | `name` | A person. Optional `email` and `role` | +| `company` | `name` | An organization. Optional `domain` | +| `deal` | `name`, `stage` | A potential commitment. Stage is `new`, `qualifying`, `proposal`, `won` or `lost`. Optional `amount` | +| `activity` | `kind`, `summary` | Something that happened. Kind is `note`, `email`, `meeting`, `call`, `slack`, `github`, `x` or `other` | + +Custom objects and custom fields are metadata. Field types are `text`, `number`, `boolean`, `date` and `select`. Adding a field does not migrate a table. A required field cannot be added once records exist, because old rows would already violate it. + +Associations are directed and labeled (`works_at`, `about`). They are not a lookup column hidden inside the record. An activity log creates the activity and links it with `about`. + +Every record has an integer `revision`. An update or delete may pass the revision it read. If the record has moved, the write is refused. That is the optimistic lock the guide lists as the spreadsheet's first failure. Callers that omit it accept a lost update. + +Every create, update, delete and association appends a change row with the actor and the time. Deleted records stay, with `deleted_at` set. Search hides them. Get and context still return them. + +An external binding is `provider` + object type + external id. HubSpot ids are unique per object, so the type is part of the key. The binding is idempotent for the same record and a conflict for a different one. The slice stores the binding. It does not call the provider. + +`context` is the read agents should prefer. It returns the record, one hop of linked records with their fields, and the recent changes. That is the guide's "reading is reconstructing the graph," done locally so the agent does not issue a fan-out of gets. + +### Agent surface + +The slice's surface is the contract for this cut: + +- Command line: `python3 -I products/crm/crm.py --db PATH ...`, one JSON object on stdout. Commands are `init`, `schema`, `object-add`, `field-add`, `record-create`, `record-get`, `record-update`, `record-delete`, `record-search`, `associate`, `activity-log`, `context`, `ref-bind` and `ref-get`. +- MCP: `python3 -I products/crm/mcp.py` with `OPENWIZ_CRM_DB` set. Newline-delimited JSON-RPC. Tools match the commands: `crm_schema`, `crm_object_add`, `crm_field_add`, `crm_record_create`, `crm_record_update`, `crm_record_search`, `crm_record_context`, `crm_associate`, `crm_activity_log`, `crm_ref_bind`. +- Errors an agent can branch on: `validation`, `unknown_object`, `unknown_field`, `not_found`, `conflict`, `object_mismatch`, `internal`. + +A later skill, in the skills sense, is a short instruction file that tells any agent to call these tools, to read `context` before it writes, and to pass `if_revision` when it updates. The skill is not in this slice. + +### Sync and import + +Not in the slice. The design, when a later ticket builds it, is offline-first and then read-only: + +1. Accept a fixture shaped like a Salesforce describe plus records, or a HubSpot properties list plus records. No network. +2. Map provider fields onto our fields only when the mapping names both sides. Unmapped fields are kept on the record as custom fields, not dropped silently and not guessed. +3. Upsert by the external binding. Write a checkpoint the caller can resume. A run that stops must say how far it got. +4. A live read of Salesforce or HubSpot waits for an explicit approval. It uses describe or the properties API first, stores the schema it saw, and treats a later describe change as drift to report, not as a surprise failure on write. +5. Subscriptions come after backfill. Salesforce Change Data Capture and HubSpot webhooks both deliver a hint. The connector hydrates the record, then writes it here. Gap events and webhook retries are checkpoints, not new kinds of record. +6. Writes back to a provider are a separate, later decision. Each writable field has a rule: who may write it, whether a blank overwrites, and whether a rejected row fails the batch or is reported beside the rows that landed. The slice does not write to a provider, and it does not deploy code into a customer org. + +### Activity capture + +Not in the slice, except that an agent can already log an activity with a source and a time. Later capture from Slack, email, GitHub and X creates a proposed activity with the source, the external id of the message, and the records it seems to concern. A rule or a person confirms it before it is treated as fact. Capture that writes straight into the CRM will record the wrong person and then automate on that mistake. + +### What would make it better than the incumbents + +Better for an agent, not a claim that this replaces a sales team's Salesforce. + +| Today | This CRM | +| --- | --- | +| Salesforce and HubSpot schemas are whatever the admin saved, and two customers do not match | The same API creates a custom object and a person. Schema is a tool result | +| A read returns one row. Context is a fan-out the agent has to invent | `context` returns the record and one hop | +| HubSpot ids collide across objects. Pipedrive field keys are per-account hashes | External identity includes the object type, and our own field names are stable api names | +| Writes from an integration are hard to undo and easy to lose against a human edit | Partial update, a revision check, and a change row that names the actor | +| Attio enriched fields cannot be overwritten, and the agent is not told why in a uniform way | Every refusal is a code and a message. Nothing is silently corrected | +| Twenty is the closest open model, and it is a workspace product with its own server | This slice is one file an agent can open, with no account and no token | +| Close, Pipedrive and Folk each pick a different place for "the company" and "the process" | People and companies are facts. A deal stage is the process in the first cut. Attio-style lists, where the same person sits on several processes with different fields, are a later decision rather than a premature table | + +The slice is not best-in-class yet. It has no pipelines as their own object, no permissions, no dedupe beyond the external binding, no full-text index, and no multi-hop query. Those are sequenced below so the first cut stays something an agent can run and a test can prove. + +### MVP cut + +The MVP is the slice in `products/crm`: + +- SQLite file, standard objects, custom objects and fields, labeled associations, activities, change history, revision check, external bindings. +- The command line and the MCP server above. +- Tests in `products/crm/test_crm.py`, synthetic data only. + +The MVP does not import, sync, capture, authenticate, or send a request. It does not add a Rust dependency. + +### Roadmap + +1. **This slice.** Local graph, agent surface, tests. +2. **Offline import.** Fixture files for a Salesforce-shaped and a HubSpot-shaped export. Idempotent upsert, stored mapping, checkpoint. Still no network. +3. **Process.** Pipeline and stage as data, required fields per stage, and a duplicate hint when email or domain matches. Decide whether a list, in the Attio sense, is a real object or whether a deal is enough. +4. **Skill.** The instruction file agents follow, plus any missing tool the skill cannot express with the current surface. +5. **Read-only connectors.** Salesforce and HubSpot, one installation each, after an explicit live-read approval. Schema cache, backfill checkpoint, hydrate-on-event. No write back. +6. **Capture.** GitHub first, then Slack, email and X, as proposed activities with provenance. +7. **Write-back.** Explicit per-field rules and a batch policy. Error categories mapped before the agent sees a provider body. +8. **Many installations.** One record per customer connection: auth health, schema version, checkpoint, last error. Region boundaries if a later product stores customer data in more than one place. + +Each of 2 through 8 is its own spec or a ticket under this one, with its own proof. This draft does not pretend they are built. + +## Changelog headline + +An agent can store people, companies, deals and activities in a local CRM and read a record back with the records linked to it. + +## User Stories + +- An OpenWiz agent can record a person, the organization they belong to, and the last activity, and can read that context back in one call. +- An OpenWiz agent can represent a lead, such as a university application or an outside repository, as a deal or a custom object linked to a person, without a code change. +- A builder agent can add a field or an object at runtime and then write records through the same commands it uses for a person. +- A builder agent can refuse to overwrite a record when the revision it read is no longer current. +- A builder agent can bind a Salesforce or HubSpot id, including the object type, so a later import does not create a second row and does not merge two objects that share a number. +- Another agent's skill can point at a different database and use the same tools. + +## Implementation Decisions + +- The slice lives in `products/crm` and is not a Cargo workspace member. The workspace's approved crates are `serde`, `serde_json` and `rustix`. SQLite comes from the Python standard library, which adds no dependency. A Rust port waits on an approval for a new crate. +- Records are rows in one table. Field definitions and JSON values implement custom fields. The standard objects are seeded rows, not special code paths. +- Associations are their own rows. The first cut is one hop. Deeper queries are a later ticket. +- Activities are records. Capture sources are a field, not a new object per channel. +- The command line and MCP call the same store. MCP is newline-delimited JSON-RPC for the protocol versions named in the README. Tool failures are results with `isError` set, using the same error codes as the command line. +- The database path is chosen by the caller. The repository does not contain a database. Real relationship data stays out of git. +- No network library is imported. A test scans the package for that. +- `products/crm` is outside the paths the changelog check treats as non-product. There is no ticket number for a `changes/.md` line yet. See Further Notes. + +## Testing Decisions + +- `python3 -I products/crm/test_crm.py` is the proof for this slice. It uses the standard library's test runner and temporary databases. +- Fixtures are synthetic. Mail addresses use `example.com`. No test opens a socket, and no test reads a secret. +- The store tests cover required fields, unknown fields, custom fields, partial update, revision conflict, select and number coercion, custom objects, association, activity rollback when a link is missing, soft delete, object mismatch, and external ids that collide across HubSpot object types. +- The surface tests run the command line and the MCP server as processes and check the JSON they print. +- Later import and connector tickets need their own fixtures. A passing test here does not prove a live Salesforce or HubSpot read. Connector work also needs the live check below, and an approval before the first live call. + +## Live check + +This slice does not touch a person's machine, account, or CRM. There is nothing to live-check until a connector ticket exists. That ticket's live check is a read of one approved installation, compared with the checkpoint the connector claims, and it does not include a write to the provider unless that write was itself approved. + +## Proof + +The slice is proven by `python3 -I products/crm/test_crm.py` and by the commands in [products/crm/README.md](../../products/crm/README.md). The proof is local and synthetic. The research claims in the notes are proven by the linked pages, not by this test. + +## Out of Scope + +- A live client for Salesforce, HubSpot, Slack, email, GitHub or X. +- OAuth, tokens, webhooks, Change Data Capture and any code deployed into a customer org. +- A web application, permissions, reporting, or a pipeline engine. +- Dedupe beyond the external binding, full-text search, and queries deeper than one hop. +- Hosting a multi-tenant service, region routing, and billing. +- Changing the OpenWiz command, the fleet records, or the Rust workspace. +- Treating this draft file as the live spec. ADR 0004 still holds. + +## Further Notes + +Open decisions: + +- Confirm or rewrite this draft, then make it a parent issue. Until then the file contradicts ADR 0004 on purpose, as a review copy. +- The public name. +- Whether OpenWiz's own relationships and an agent product's relationships are two databases of this model, or whether they must be one database. This draft says two databases, one model. +- Whether a deal stage is enough, or whether Attio-style lists are required so one person can sit on a contributor process and an applicant process with different fields. +- Whether the implementation stays in Python or moves into Rust after a crate is approved. +- Which lead sources are in the first real workspace: contributors, partners, university applications, outside repositories. +- Who may approve a live read, and which installation is the first one. The factory rules already say a live read waits for approval. +- Whether high-risk fields are proposed by the agent and confirmed before they land, even in this CRM, or whether a passed revision is enough. +- How the changelog check should treat `products/crm`. The path is a product path, and there is no ticket number to name in `changes/`. The honest line waits on a ticket. Exempting it needs an explicit decision, because the changelog rule says the no-changelog label is not a way to skip a product change. diff --git a/products/crm/.gitignore b/products/crm/.gitignore new file mode 100644 index 00000000..f1d7c144 --- /dev/null +++ b/products/crm/.gitignore @@ -0,0 +1,5 @@ +__pycache__/ +*.sqlite +*.sqlite3 +*.sqlite-wal +*.sqlite-shm diff --git a/products/crm/README.md b/products/crm/README.md new file mode 100644 index 00000000..7ede6558 --- /dev/null +++ b/products/crm/README.md @@ -0,0 +1,48 @@ +# Local CRM + +A small CRM an agent can run on one machine. It stores people, companies, deals, activities and custom objects in a SQLite file. The command line and the MCP server speak JSON. Nothing in this folder calls Salesforce, HubSpot or any other network service. + +It is separate from the Rust workspace. The workspace only approves `serde`, `serde_json` and `rustix`, and a new crate needs approval. This slice uses the Python standard library. + +The database can hold notes about real people. Keep the file outside the git checkout. + +## Run + +```sh +python3 -I products/crm/test_crm.py +python3 -I products/crm/crm.py --db /tmp/openwiz-crm.sqlite init +python3 -I products/crm/crm.py --db /tmp/openwiz-crm.sqlite record-create \ + --object person --set name=Ada --set email=ada@example.com +python3 -I products/crm/crm.py --db /tmp/openwiz-crm.sqlite context --id rec_... +OPENWIZ_CRM_DB=/tmp/openwiz-crm.sqlite python3 -I products/crm/mcp.py +``` + +`--db` or `OPENWIZ_CRM_DB` chooses the file. `--actor` is stored on each change and defaults to `agent`. Every command prints one JSON object. `ok` is true and `result` holds the payload, or `ok` is false and `error.code` is one of `validation`, `unknown_object`, `unknown_field`, `not_found`, `conflict`, `object_mismatch` or `internal`. + +## Commands + +| Command | What it does | +| --- | --- | +| `init`, `schema` | Create the file and list objects and fields | +| `object-add`, `field-add` | Add a custom object or field | +| `record-create`, `record-get`, `record-update`, `record-delete`, `record-search` | Records. Search skips deleted rows. Get still returns them | +| `associate` | A labeled link from one record to another | +| `activity-log` | An activity linked to one or more records with the label `about` | +| `context` | The record, one hop of linked records, and recent changes | +| `ref-bind`, `ref-get` | Bind or find `provider` + object type + external id | + +`record-update` and `record-delete` take `--if-revision`. Pass the `revision` from the record you read. A newer write is refused with `conflict`. Omit it only when a lost update is acceptable. + +`record-search --query` is a case-insensitive match on text and select fields. `--where name=value` is exact, after the field type is applied. `--set` and `--where` are repeated `name=value` pairs. + +Field types are `text`, `number`, `boolean`, `date` and `select`. A select field needs `--option` values that are themselves api names. Dates are `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM:SSZ`. + +## MCP + +`mcp.py` reads newline-delimited JSON-RPC on stdin and writes it on stdout. It accepts protocol versions `2024-11-05`, `2025-03-26` and `2025-06-18`. The tools are `crm_schema`, `crm_object_add`, `crm_field_add`, `crm_record_create`, `crm_record_update`, `crm_record_search`, `crm_record_context`, `crm_associate`, `crm_activity_log` and `crm_ref_bind`. A tool error is a result with `isError` true and the same JSON shape as the command line. + +## Standard objects + +`person` (name, email, role), `company` (name, domain), `deal` (name, stage, amount) and `activity` (kind, summary, body, happened_at, source). Stage is `new`, `qualifying`, `proposal`, `won` or `lost`. Activity kind is `note`, `email`, `meeting`, `call`, `slack`, `github`, `x` or `other`. Custom objects use the same record API. + +External ids include the provider object type. HubSpot record ids are unique inside one object, so contact `1001` and company `1001` are different bindings. diff --git a/products/crm/crm.py b/products/crm/crm.py new file mode 100644 index 00000000..da408cbd --- /dev/null +++ b/products/crm/crm.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python3 +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from openwiz_crm.cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/products/crm/mcp.py b/products/crm/mcp.py new file mode 100644 index 00000000..7e170c6b --- /dev/null +++ b/products/crm/mcp.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python3 +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +from openwiz_crm.mcp import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/products/crm/openwiz_crm/__init__.py b/products/crm/openwiz_crm/__init__.py new file mode 100644 index 00000000..c75a3d25 --- /dev/null +++ b/products/crm/openwiz_crm/__init__.py @@ -0,0 +1,3 @@ +"""Local agent-native CRM. No network imports belong in this package.""" + +__version__ = "0.1.0" diff --git a/products/crm/openwiz_crm/cli.py b/products/crm/openwiz_crm/cli.py new file mode 100644 index 00000000..fd36aec5 --- /dev/null +++ b/products/crm/openwiz_crm/cli.py @@ -0,0 +1,170 @@ +"""JSON command line for the local CRM. stdout is one JSON object.""" + +import argparse +import json +import os +import sqlite3 +import sys + +from openwiz_crm.errors import CrmError +from openwiz_crm.store import Store + + +def emit(payload): + sys.stdout.write(json.dumps(payload, sort_keys=True) + "\n") + + +def fail(error): + emit(error.payload()) + return 1 + + +def pairs(values): + fields = {} + for item in values or []: + if "=" not in item: + raise CrmError("validation", "expected name=value") + name, raw = item.split("=", 1) + if not name or name in fields: + raise CrmError("validation", "each field may be set once") + fields[name] = raw + return fields + + +def build_parser(): + parser = argparse.ArgumentParser( + prog="crm.py", + description="Local CRM for agents. Prints one JSON object to stdout.", + ) + parser.add_argument("--db", default=os.environ.get("OPENWIZ_CRM_DB")) + parser.add_argument("--actor", default="agent") + commands = parser.add_subparsers(dest="command", required=True) + + commands.add_parser("init", help="Create the database and standard objects") + commands.add_parser("schema", help="List objects and fields") + + object_add = commands.add_parser("object-add", help="Add a custom object") + object_add.add_argument("--name", required=True) + object_add.add_argument("--label", required=True) + + field_add = commands.add_parser("field-add", help="Add a custom field") + field_add.add_argument("--object", required=True) + field_add.add_argument("--name", required=True) + field_add.add_argument("--label") + field_add.add_argument("--type", required=True, dest="field_type") + field_add.add_argument("--required", action="store_true") + field_add.add_argument("--option", action="append", dest="options") + + create = commands.add_parser("record-create", help="Create a record") + create.add_argument("--object", required=True) + create.add_argument("--set", action="append", dest="sets") + + get = commands.add_parser("record-get", help="Get one record, including a deleted one") + get.add_argument("--id", required=True) + + update = commands.add_parser("record-update", help="Change fields on a record") + update.add_argument("--object", required=True) + update.add_argument("--id", required=True) + update.add_argument("--set", action="append", dest="sets") + update.add_argument("--clear", action="append", dest="clear") + update.add_argument("--if-revision", type=int) + + delete = commands.add_parser("record-delete", help="Soft-delete a record") + delete.add_argument("--object", required=True) + delete.add_argument("--id", required=True) + delete.add_argument("--if-revision", type=int) + + search = commands.add_parser("record-search", help="Search live records") + search.add_argument("--object", required=True) + search.add_argument("--query") + search.add_argument("--where", action="append", dest="wheres") + search.add_argument("--limit", type=int, default=50) + + associate = commands.add_parser("associate", help="Link two records") + associate.add_argument("--from", dest="from_id", required=True) + associate.add_argument("--to", required=True) + associate.add_argument("--label", required=True) + + activity = commands.add_parser("activity-log", help="Record an activity and link it") + activity.add_argument("--kind", required=True) + activity.add_argument("--summary", required=True) + activity.add_argument("--body") + activity.add_argument("--happened-at") + activity.add_argument("--source", default="cli") + activity.add_argument("--link", action="append", dest="links", required=True) + + context = commands.add_parser("context", help="Record, one hop of links, and recent changes") + context.add_argument("--id", required=True) + + bind = commands.add_parser("ref-bind", help="Bind an external id to a record") + bind.add_argument("--provider", required=True) + bind.add_argument("--type", required=True) + bind.add_argument("--external-id", required=True) + bind.add_argument("--id", required=True) + + find = commands.add_parser("ref-get", help="Find a record by external id") + find.add_argument("--provider", required=True) + find.add_argument("--type", required=True) + find.add_argument("--external-id", required=True) + return parser + + +def run(args): + if not args.db: + raise CrmError("validation", "pass --db or set OPENWIZ_CRM_DB") + store = Store.open(args.db) + try: + if args.command == "init": + result = store.schema() + elif args.command == "schema": + result = store.schema() + elif args.command == "object-add": + result = store.add_object(args.name, args.label) + elif args.command == "field-add": + result = store.add_field( + args.object, args.name, args.label, args.field_type, + args.required, args.options, + ) + elif args.command == "record-create": + result = store.create_record(args.object, pairs(args.sets), args.actor) + elif args.command == "record-get": + result = store.get_record(args.id) + elif args.command == "record-update": + result = store.update_record( + args.object, args.id, pairs(args.sets), args.clear or [], args.actor, + args.if_revision, + ) + elif args.command == "record-delete": + result = store.delete_record(args.object, args.id, args.actor, args.if_revision) + elif args.command == "record-search": + result = store.search(args.object, args.query, pairs(args.wheres), args.limit) + elif args.command == "associate": + result = store.associate(args.from_id, args.to, args.label, args.actor) + elif args.command == "activity-log": + result = store.log_activity( + args.kind, args.summary, args.links, args.actor, + args.body, args.happened_at, args.source, + ) + elif args.command == "context": + result = store.context(args.id) + elif args.command == "ref-bind": + result = store.bind_ref(args.provider, args.type, args.external_id, args.id) + elif args.command == "ref-get": + result = store.find_ref(args.provider, args.type, args.external_id) + else: + raise CrmError("validation", "unknown command") + finally: + store.close() + return result + + +def main(argv=None): + parser = build_parser() + try: + args = parser.parse_args(argv) + emit({"ok": True, "result": run(args)}) + return 0 + except CrmError as error: + return fail(error) + except sqlite3.Error: + return fail(CrmError("internal", "database error")) diff --git a/products/crm/openwiz_crm/errors.py b/products/crm/openwiz_crm/errors.py new file mode 100644 index 00000000..08b2bf37 --- /dev/null +++ b/products/crm/openwiz_crm/errors.py @@ -0,0 +1,11 @@ +"""Errors an agent can handle without reading a traceback.""" + + +class CrmError(Exception): + def __init__(self, code, message): + super().__init__(message) + self.code = code + self.message = message + + def payload(self): + return {"ok": False, "error": {"code": self.code, "message": self.message}} diff --git a/products/crm/openwiz_crm/mcp.py b/products/crm/openwiz_crm/mcp.py new file mode 100644 index 00000000..ce19ec31 --- /dev/null +++ b/products/crm/openwiz_crm/mcp.py @@ -0,0 +1,333 @@ +"""Newline-delimited JSON-RPC MCP server for the local CRM. + +The server speaks protocol versions 2024-11-05, 2025-03-26 and 2025-06-18. +It reads one JSON object per line on stdin and writes one JSON object per +line on stdout. It does not open a network connection. +""" + +import json +import os +import sqlite3 +import sys + +from openwiz_crm import __version__ +from openwiz_crm.errors import CrmError +from openwiz_crm.store import Store + +PROTOCOL_VERSIONS = ("2024-11-05", "2025-03-26", "2025-06-18") +SERVER_NAME = "openwiz-crm" + +TOOLS = ( + { + "name": "crm_schema", + "description": "List CRM objects and their fields, including custom ones.", + "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}, + }, + { + "name": "crm_object_add", + "description": "Add a custom object. Standard objects are person, company, deal and activity.", + "inputSchema": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "label": {"type": "string"}, + }, + "required": ["name", "label"], + "additionalProperties": False, + }, + }, + { + "name": "crm_field_add", + "description": "Add a custom field to an object. type is text, number, boolean, date or select.", + "inputSchema": { + "type": "object", + "properties": { + "object": {"type": "string"}, + "name": {"type": "string"}, + "label": {"type": "string"}, + "type": {"type": "string"}, + "required": {"type": "boolean"}, + "options": {"type": "array", "items": {"type": "string"}}, + }, + "required": ["object", "name", "type"], + "additionalProperties": False, + }, + }, + { + "name": "crm_record_create", + "description": "Create a record. fields uses the object's api names.", + "inputSchema": { + "type": "object", + "properties": { + "object": {"type": "string"}, + "fields": {"type": "object"}, + "actor": {"type": "string"}, + }, + "required": ["object", "fields"], + "additionalProperties": False, + }, + }, + { + "name": "crm_record_update", + "description": "Update a live record. clear removes optional fields. Pass if_revision from a prior read to refuse a stale write.", + "inputSchema": { + "type": "object", + "properties": { + "object": {"type": "string"}, + "id": {"type": "string"}, + "fields": {"type": "object"}, + "clear": {"type": "array", "items": {"type": "string"}}, + "actor": {"type": "string"}, + "if_revision": {"type": "integer"}, + }, + "required": ["object", "id"], + "additionalProperties": False, + }, + }, + { + "name": "crm_record_search", + "description": "Search live records of one object. query matches text and select fields. where is exact.", + "inputSchema": { + "type": "object", + "properties": { + "object": {"type": "string"}, + "query": {"type": "string"}, + "where": {"type": "object"}, + "limit": {"type": "integer"}, + }, + "required": ["object"], + "additionalProperties": False, + }, + }, + { + "name": "crm_record_context", + "description": "Return one record, one hop of linked records, and recent changes.", + "inputSchema": { + "type": "object", + "properties": {"id": {"type": "string"}}, + "required": ["id"], + "additionalProperties": False, + }, + }, + { + "name": "crm_associate", + "description": "Create a labeled association from one record to another.", + "inputSchema": { + "type": "object", + "properties": { + "from_id": {"type": "string"}, + "to_id": {"type": "string"}, + "label": {"type": "string"}, + "actor": {"type": "string"}, + }, + "required": ["from_id", "to_id", "label"], + "additionalProperties": False, + }, + }, + { + "name": "crm_activity_log", + "description": "Log an activity and link it to one or more records with the label about.", + "inputSchema": { + "type": "object", + "properties": { + "kind": {"type": "string"}, + "summary": {"type": "string"}, + "body": {"type": "string"}, + "happened_at": {"type": "string"}, + "source": {"type": "string"}, + "links": {"type": "array", "items": {"type": "string"}}, + "actor": {"type": "string"}, + }, + "required": ["kind", "summary", "links"], + "additionalProperties": False, + }, + }, + { + "name": "crm_ref_bind", + "description": "Bind a provider, object type and external id to a live record. The type is required because some CRMs reuse ids across objects.", + "inputSchema": { + "type": "object", + "properties": { + "provider": {"type": "string"}, + "external_type": {"type": "string"}, + "external_id": {"type": "string"}, + "id": {"type": "string"}, + }, + "required": ["provider", "external_type", "external_id", "id"], + "additionalProperties": False, + }, + }, +) + + +def _object(value): + if not isinstance(value, dict): + raise CrmError("validation", "arguments must be an object") + return value + + +def _call(store, name, arguments): + args = _object(arguments or {}) + actor = args.get("actor", "mcp") + if name == "crm_schema": + _only(args, set()) + return store.schema() + if name == "crm_object_add": + _only(args, {"name", "label"}) + _need(args, "name", "label") + return store.add_object(args["name"], args["label"]) + if name == "crm_field_add": + _only(args, {"object", "name", "label", "type", "required", "options"}) + _need(args, "object", "name", "type") + return store.add_field( + args["object"], args["name"], args.get("label"), args["type"], + args.get("required", False), args.get("options"), + ) + if name == "crm_record_create": + _only(args, {"object", "fields", "actor"}) + _need(args, "object", "fields") + return store.create_record(args["object"], args["fields"], actor) + if name == "crm_record_update": + _only(args, {"object", "id", "fields", "clear", "actor", "if_revision"}) + _need(args, "object", "id") + return store.update_record( + args["object"], args["id"], args.get("fields", {}), args.get("clear", []), actor, + args.get("if_revision"), + ) + if name == "crm_record_search": + _only(args, {"object", "query", "where", "limit"}) + _need(args, "object") + return store.search( + args["object"], args.get("query"), args.get("where"), args.get("limit", 50), + ) + if name == "crm_record_context": + _only(args, {"id"}) + _need(args, "id") + return store.context(args["id"]) + if name == "crm_associate": + _only(args, {"from_id", "to_id", "label", "actor"}) + _need(args, "from_id", "to_id", "label") + return store.associate(args["from_id"], args["to_id"], args["label"], actor) + if name == "crm_activity_log": + _only(args, {"kind", "summary", "body", "happened_at", "source", "links", "actor"}) + _need(args, "kind", "summary", "links") + return store.log_activity( + args["kind"], args["summary"], args["links"], actor, + args.get("body"), args.get("happened_at"), args.get("source", "mcp"), + ) + if name == "crm_ref_bind": + _only(args, {"provider", "external_type", "external_id", "id"}) + _need(args, "provider", "external_type", "external_id", "id") + return store.bind_ref( + args["provider"], args["external_type"], args["external_id"], args["id"], + ) + raise CrmError("unknown_tool", "unknown tool: " + str(name)) + + +def _only(args, allowed): + extra = set(args) - allowed + if extra: + raise CrmError("validation", "unexpected argument: " + ", ".join(sorted(extra))) + + +def _need(args, *keys): + missing = [key for key in keys if key not in args] + if missing: + raise CrmError("validation", "missing argument: " + ", ".join(missing)) + + +def _required(name, args, keys): + missing = [key for key in keys if key not in args] + if missing: + raise CrmError("validation", name + " missing " + ", ".join(missing)) + + +def dispatch(store, message): + if not isinstance(message, dict): + return _rpc_error(None, -32600, "invalid request") + method = message.get("method") + has_id = "id" in message + msg_id = message.get("id") + if not isinstance(method, str): + if not has_id: + return None + return _rpc_error(msg_id, -32600, "invalid request") + if method == "notifications/initialized" or method.startswith("notifications/"): + return None + if not has_id: + return None + if method == "initialize": + params = message.get("params") if isinstance(message.get("params"), dict) else {} + requested = params.get("protocolVersion") + version = requested if requested in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0] + return { + "jsonrpc": "2.0", + "id": msg_id, + "result": { + "protocolVersion": version, + "capabilities": {"tools": {"listChanged": False}}, + "serverInfo": {"name": SERVER_NAME, "version": __version__}, + }, + } + if method == "tools/list": + return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": list(TOOLS)}} + if method == "ping": + return {"jsonrpc": "2.0", "id": msg_id, "result": {}} + if method == "tools/call": + params = message.get("params") if isinstance(message.get("params"), dict) else {} + try: + _required("tools/call", params, ["name"]) + result = _call(store, params.get("name"), params.get("arguments") or {}) + text = json.dumps({"ok": True, "result": result}, sort_keys=True) + is_error = False + except CrmError as error: + text = json.dumps(error.payload(), sort_keys=True) + is_error = True + except sqlite3.Error: + text = json.dumps(CrmError("internal", "database error").payload(), sort_keys=True) + is_error = True + except Exception: + text = json.dumps(CrmError("internal", "tool failed").payload(), sort_keys=True) + is_error = True + return { + "jsonrpc": "2.0", + "id": msg_id, + "result": {"content": [{"type": "text", "text": text}], "isError": is_error}, + } + return _rpc_error(msg_id, -32601, "method not found") + + +def _rpc_error(msg_id, code, message): + return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": message}} + + +def serve(store, stdin, stdout): + for line in stdin: + if not line.strip(): + continue + try: + message = json.loads(line) + except json.JSONDecodeError: + response = _rpc_error(None, -32700, "parse error") + else: + response = dispatch(store, message) + if response is not None: + stdout.write(json.dumps(response, sort_keys=True) + "\n") + stdout.flush() + + +def main(): + path = os.environ.get("OPENWIZ_CRM_DB") + if not path: + sys.stderr.write("openwiz-crm: set OPENWIZ_CRM_DB\n") + return 2 + try: + store = Store.open(path) + except sqlite3.Error: + sys.stderr.write("openwiz-crm: database error\n") + return 1 + try: + serve(store, sys.stdin, sys.stdout) + finally: + store.close() + return 0 diff --git a/products/crm/openwiz_crm/store.py b/products/crm/openwiz_crm/store.py new file mode 100644 index 00000000..571c56c2 --- /dev/null +++ b/products/crm/openwiz_crm/store.py @@ -0,0 +1,719 @@ +"""SQLite store for people, companies, deals, activities and custom objects. + +Records share one table. Fields are metadata, and values are JSON, so a custom +field does not need a migration. The process that opens this file does not +contact Salesforce, HubSpot or any other network service. +""" + +import json +import math +import re +import secrets +import sqlite3 +from datetime import datetime, timezone +from pathlib import Path + +from openwiz_crm.errors import CrmError + +API_NAME = re.compile(r"[a-z][a-z0-9_]{0,40}") +LABEL_MAX = 80 +TEXT_MAX = 8000 +ACTOR_MAX = 80 +SEARCH_DEFAULT = 50 +SEARCH_MAX = 200 +CONTEXT_LINKS = 50 +CONTEXT_CHANGES = 20 +RESERVED_FIELDS = frozenset({"id", "object"}) +FIELD_TYPES = frozenset({"text", "number", "boolean", "date", "select"}) +DATE_DAY = re.compile(r"\d{4}-\d{2}-\d{2}") +DATE_TIME = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z") +PROVIDER = re.compile(r"[a-z][a-z0-9_-]{0,40}") +EXTERNAL_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:-]{0,200}") + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS objects ( + id INTEGER PRIMARY KEY, + api_name TEXT NOT NULL UNIQUE, + label TEXT NOT NULL, + kind TEXT NOT NULL CHECK (kind IN ('standard', 'custom')), + created_at TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS fields ( + id INTEGER PRIMARY KEY, + object_id INTEGER NOT NULL REFERENCES objects(id), + api_name TEXT NOT NULL, + label TEXT NOT NULL, + field_type TEXT NOT NULL, + required INTEGER NOT NULL CHECK (required IN (0, 1)), + options_json TEXT, + origin TEXT NOT NULL CHECK (origin IN ('standard', 'custom')), + UNIQUE (object_id, api_name) +); +CREATE TABLE IF NOT EXISTS records ( + id TEXT PRIMARY KEY, + object_id INTEGER NOT NULL REFERENCES objects(id), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + deleted_at TEXT, + revision INTEGER NOT NULL DEFAULT 1 +); +CREATE TABLE IF NOT EXISTS values_ ( + record_id TEXT NOT NULL REFERENCES records(id), + field_id INTEGER NOT NULL REFERENCES fields(id), + value_json TEXT NOT NULL, + PRIMARY KEY (record_id, field_id) +); +CREATE TABLE IF NOT EXISTS associations ( + id TEXT PRIMARY KEY, + from_id TEXT NOT NULL REFERENCES records(id), + to_id TEXT NOT NULL REFERENCES records(id), + label TEXT NOT NULL, + created_at TEXT NOT NULL, + UNIQUE (from_id, to_id, label) +); +CREATE TABLE IF NOT EXISTS changes ( + id INTEGER PRIMARY KEY, + record_id TEXT NOT NULL, + op TEXT NOT NULL, + detail_json TEXT NOT NULL, + actor TEXT NOT NULL, + at TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS external_refs ( + provider TEXT NOT NULL, + external_type TEXT NOT NULL, + external_id TEXT NOT NULL, + record_id TEXT NOT NULL REFERENCES records(id), + PRIMARY KEY (provider, external_type, external_id) +); +CREATE INDEX IF NOT EXISTS records_object ON records(object_id); +CREATE INDEX IF NOT EXISTS values_field ON values_(field_id); +CREATE INDEX IF NOT EXISTS assoc_from ON associations(from_id); +CREATE INDEX IF NOT EXISTS assoc_to ON associations(to_id); +CREATE INDEX IF NOT EXISTS changes_record ON changes(record_id); +""" + +STANDARD = ( + ("person", "Person", ( + ("name", "Name", "text", True, None), + ("email", "Email", "text", False, None), + ("role", "Role", "text", False, None), + )), + ("company", "Company", ( + ("name", "Name", "text", True, None), + ("domain", "Domain", "text", False, None), + )), + ("deal", "Deal", ( + ("name", "Name", "text", True, None), + ("stage", "Stage", "select", True, + ["new", "qualifying", "proposal", "won", "lost"]), + ("amount", "Amount", "number", False, None), + )), + ("activity", "Activity", ( + ("kind", "Kind", "select", True, + ["note", "email", "meeting", "call", "slack", "github", "x", "other"]), + ("summary", "Summary", "text", True, None), + ("body", "Body", "text", False, None), + ("happened_at", "Happened at", "date", False, None), + ("source", "Source", "text", False, None), + )), +) + + +def now(): + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def new_id(prefix): + return prefix + secrets.token_hex(8) + + +def _api_name(value, label): + if not isinstance(value, str) or API_NAME.fullmatch(value) is None: + raise CrmError("validation", label + " must be a lowercase api name") + if value in RESERVED_FIELDS: + raise CrmError("validation", label + " is reserved") + return value + + +def _label(value): + if not isinstance(value, str): + raise CrmError("validation", "label must be text") + cleaned = value.strip() + if not cleaned or len(cleaned) > LABEL_MAX or any(ord(c) < 32 for c in cleaned): + raise CrmError("validation", "label must be 1 to 80 visible characters") + return cleaned + + +def _external(provider, external_type, external_id): + if not isinstance(provider, str) or PROVIDER.fullmatch(provider) is None: + raise CrmError("validation", "provider must be a lowercase name") + if not isinstance(external_type, str) or EXTERNAL_ID.fullmatch(external_type) is None: + raise CrmError("validation", "external type has an unsupported shape") + if not isinstance(external_id, str) or EXTERNAL_ID.fullmatch(external_id) is None: + raise CrmError("validation", "external id has an unsupported shape") + return provider, external_type, external_id + + +def _revision(value): + if value is None: + return + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise CrmError("validation", "if_revision must be the record's revision") + + +def _expect_revision(row, if_revision): + if if_revision is not None and row["revision"] != if_revision: + raise CrmError("conflict", "record changed since it was read") + + +def _actor(value): + if not isinstance(value, str) or not value.strip() or len(value) > ACTOR_MAX: + raise CrmError("validation", "actor must be 1 to 80 characters") + if any(ord(c) < 32 for c in value): + raise CrmError("validation", "actor must not contain control characters") + return value + + +def _options(value): + if not isinstance(value, list) or not value or len(value) > 50: + raise CrmError("validation", "select needs 1 to 50 options") + seen = [] + for item in value: + if not isinstance(item, str) or API_NAME.fullmatch(item) is None or item in seen: + raise CrmError("validation", "each option must be a unique api name") + seen.append(item) + return seen + + +def normalize(field, value): + kind = field["field_type"] + if kind == "text": + if not isinstance(value, str) or not value or len(value) > TEXT_MAX: + raise CrmError("validation", field["api_name"] + " must be text of 1 to 8000 characters") + if any(ord(c) < 32 and c not in "\n\t" for c in value): + raise CrmError("validation", field["api_name"] + " contains a control character") + return value + if kind == "number": + if isinstance(value, bool) or not isinstance(value, (int, float, str)): + raise CrmError("validation", field["api_name"] + " must be a number") + if isinstance(value, str): + try: + number = float(value) if "." in value else int(value) + except ValueError: + raise CrmError("validation", field["api_name"] + " must be a number") from None + else: + number = value + if isinstance(number, float) and not math.isfinite(number): + raise CrmError("validation", field["api_name"] + " must be a finite number") + if isinstance(number, float) and number.is_integer(): + number = int(number) + if abs(number) >= 10 ** 15: + raise CrmError("validation", field["api_name"] + " is out of range") + return number + if kind == "boolean": + if isinstance(value, bool): + return value + if isinstance(value, str) and value.lower() in ("true", "false"): + return value.lower() == "true" + raise CrmError("validation", field["api_name"] + " must be true or false") + if kind == "date": + if not isinstance(value, str): + raise CrmError("validation", field["api_name"] + " must be a date") + try: + if DATE_DAY.fullmatch(value): + datetime.strptime(value, "%Y-%m-%d") + elif DATE_TIME.fullmatch(value): + datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ") + else: + raise ValueError + except ValueError: + raise CrmError( + "validation", + field["api_name"] + " must be YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ", + ) from None + return value + if kind == "select": + options = json.loads(field["options_json"]) + if not isinstance(value, str) or value not in options: + raise CrmError( + "validation", + field["api_name"] + " must be one of: " + ", ".join(options), + ) + return value + raise CrmError("validation", "unknown field type") + + +class Store: + def __init__(self, connection): + self._conn = connection + + @classmethod + def open(cls, path): + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + connection = sqlite3.connect(target) + connection.row_factory = sqlite3.Row + connection.execute("PRAGMA foreign_keys = ON") + connection.executescript(SCHEMA) + store = cls(connection) + store._seed() + return store + + def close(self): + self._conn.close() + + def _seed(self): + with self._conn: + count = self._conn.execute("SELECT COUNT(*) AS n FROM objects").fetchone()["n"] + if count: + return + stamp = now() + for api_name, label, fields in STANDARD: + cursor = self._conn.execute( + "INSERT INTO objects (api_name, label, kind, created_at) VALUES (?, ?, 'standard', ?)", + (api_name, label, stamp), + ) + object_id = cursor.lastrowid + for name, field_label, field_type, required, options in fields: + self._conn.execute( + """INSERT INTO fields + (object_id, api_name, label, field_type, required, options_json, origin) + VALUES (?, ?, ?, ?, ?, ?, 'standard')""", + (object_id, name, field_label, field_type, int(required), + None if options is None else json.dumps(options)), + ) + + def schema(self): + objects = [] + rows = self._conn.execute( + "SELECT * FROM objects ORDER BY id" + ).fetchall() + for row in rows: + fields = self._conn.execute( + "SELECT * FROM fields WHERE object_id = ? ORDER BY id", (row["id"],) + ).fetchall() + objects.append({ + "api_name": row["api_name"], + "label": row["label"], + "kind": row["kind"], + "fields": [self._field_public(field) for field in fields], + }) + return {"objects": objects} + + def add_object(self, api_name, label): + api_name = _api_name(api_name, "object name") + label = _label(label) + with self._conn: + if self._object(api_name, required=False) is not None: + raise CrmError("conflict", "object already exists") + self._conn.execute( + "INSERT INTO objects (api_name, label, kind, created_at) VALUES (?, ?, 'custom', ?)", + (api_name, label, now()), + ) + return {"api_name": api_name, "label": label, "kind": "custom", "fields": []} + + def add_field(self, object_name, api_name, label, field_type, required=False, options=None): + api_name = _api_name(api_name, "field name") + label = _label(label if label is not None else api_name) + if field_type not in FIELD_TYPES: + raise CrmError("validation", "type must be text, number, boolean, date or select") + if not isinstance(required, bool): + raise CrmError("validation", "required must be true or false") + if field_type == "select": + options = _options(options) + elif options not in (None, []): + raise CrmError("validation", "options are only for select fields") + else: + options = None + with self._conn: + obj = self._object(object_name) + existing = self._conn.execute( + "SELECT id FROM fields WHERE object_id = ? AND api_name = ?", + (obj["id"], api_name), + ).fetchone() + if existing is not None: + raise CrmError("conflict", "field already exists") + if required: + count = self._conn.execute( + "SELECT COUNT(*) AS n FROM records WHERE object_id = ?", + (obj["id"],), + ).fetchone()["n"] + if count: + raise CrmError( + "validation", + "cannot add a required field when records already exist", + ) + self._conn.execute( + """INSERT INTO fields + (object_id, api_name, label, field_type, required, options_json, origin) + VALUES (?, ?, ?, ?, ?, ?, 'custom')""", + (obj["id"], api_name, label, field_type, int(required), + None if options is None else json.dumps(options)), + ) + return { + "object": object_name, + "api_name": api_name, + "label": label, + "type": field_type, + "required": required, + "options": options, + "origin": "custom", + } + + def create_record(self, object_name, fields, actor): + actor = _actor(actor) + with self._conn: + return self._insert_record(object_name, fields, actor) + + def update_record(self, object_name, record_id, fields, clear, actor, if_revision=None): + actor = _actor(actor) + _revision(if_revision) + if not isinstance(fields, dict) or not isinstance(clear, list): + raise CrmError("validation", "fields must be an object and clear must be a list") + if not fields and not clear: + raise CrmError("validation", "nothing to change") + overlap = set(fields).intersection(clear) + if overlap: + raise CrmError("validation", "cannot set and clear the same field") + with self._conn: + obj = self._object(object_name) + row = self._live(record_id) + if row["object_id"] != obj["id"]: + raise CrmError("object_mismatch", "record is not a " + object_name) + _expect_revision(row, if_revision) + known = self._fields(obj["id"]) + self._known_names(known, list(fields) + list(clear)) + current = self._values(record_id) + changes = [] + for name in clear: + field = known[name] + if field["required"]: + raise CrmError("validation", name + " is required") + if name not in current: + continue + self._conn.execute( + "DELETE FROM values_ WHERE record_id = ? AND field_id = ?", + (record_id, field["id"]), + ) + changes.append({"field": name, "before": current[name], "after": None}) + for name, raw in fields.items(): + field = known[name] + value = normalize(field, raw) + if current.get(name) == value: + continue + self._conn.execute( + """INSERT INTO values_ (record_id, field_id, value_json) VALUES (?, ?, ?) + ON CONFLICT (record_id, field_id) DO UPDATE SET value_json = excluded.value_json""", + (record_id, field["id"], json.dumps(value)), + ) + changes.append({"field": name, "before": current.get(name), "after": value}) + if not changes: + return self._public_record(record_id) + stamp = now() + self._touch(record_id, stamp) + self._change(record_id, "update", {"fields": changes}, actor, stamp) + return self._public_record(record_id) + + def get_record(self, record_id): + self._record_row(record_id) + return self._public_record(record_id) + + def delete_record(self, object_name, record_id, actor, if_revision=None): + actor = _actor(actor) + _revision(if_revision) + with self._conn: + obj = self._object(object_name) + row = self._live(record_id) + if row["object_id"] != obj["id"]: + raise CrmError("object_mismatch", "record is not a " + object_name) + _expect_revision(row, if_revision) + stamp = now() + self._conn.execute( + """UPDATE records + SET deleted_at = ?, updated_at = ?, revision = revision + 1 + WHERE id = ?""", + (stamp, stamp, record_id), + ) + self._change(record_id, "delete", {}, actor, stamp) + return self._public_record(record_id) + + def search(self, object_name, query=None, where=None, limit=SEARCH_DEFAULT): + if where is None: + where = {} + if not isinstance(where, dict): + raise CrmError("validation", "where must be an object") + if query is not None and (not isinstance(query, str) or not query.strip()): + raise CrmError("validation", "query must be non-empty text") + if not isinstance(limit, int) or isinstance(limit, bool) or not 1 <= limit <= SEARCH_MAX: + raise CrmError("validation", "limit must be an integer from 1 to 200") + obj = self._object(object_name) + known = self._fields(obj["id"]) + self._known_names(known, list(where)) + wanted = {name: normalize(known[name], raw) for name, raw in where.items()} + needle = query.casefold() if query else None + rows = self._conn.execute( + """SELECT id FROM records + WHERE object_id = ? AND deleted_at IS NULL + ORDER BY updated_at DESC, id DESC""", + (obj["id"],), + ).fetchall() + matched = [] + for row in rows: + values = self._values(row["id"]) + if any(values.get(name) != wanted[name] for name in wanted): + continue + if needle is not None: + haystack = "\n".join( + str(values[name]) for name, field in known.items() + if field["field_type"] in ("text", "select") and name in values + ).casefold() + if needle not in haystack: + continue + matched.append(self._public_record(row["id"])) + if len(matched) > limit: + break + truncated = len(matched) > limit + return {"records": matched[:limit], "truncated": truncated} + + def associate(self, from_id, to_id, label, actor): + actor = _actor(actor) + label = _api_name(label, "association label") + with self._conn: + self._live(from_id) + self._live(to_id) + existing = self._conn.execute( + "SELECT id FROM associations WHERE from_id = ? AND to_id = ? AND label = ?", + (from_id, to_id, label), + ).fetchone() + if existing is not None: + raise CrmError("conflict", "association already exists") + stamp = now() + assoc_id = new_id("rel_") + self._conn.execute( + "INSERT INTO associations (id, from_id, to_id, label, created_at) VALUES (?, ?, ?, ?, ?)", + (assoc_id, from_id, to_id, label, stamp), + ) + detail = {"id": assoc_id, "from_id": from_id, "to_id": to_id, "label": label} + self._touch(from_id, stamp) + self._touch(to_id, stamp) + self._change(from_id, "associate", detail, actor, stamp) + self._change(to_id, "associate", detail, actor, stamp) + return detail | {"created_at": stamp} + + def log_activity(self, kind, summary, links, actor, body=None, happened_at=None, source="agent"): + actor = _actor(actor) + if not isinstance(links, list) or not links: + raise CrmError("validation", "an activity needs at least one linked record") + if len(set(links)) != len(links): + raise CrmError("validation", "activity links must be unique") + if not all(isinstance(item, str) for item in links): + raise CrmError("validation", "activity links must be record ids") + fields = { + "kind": kind, + "summary": summary, + "happened_at": happened_at or now(), + "source": source, + } + if body is not None: + fields["body"] = body + with self._conn: + for link in links: + self._live(link) + record = self._insert_record("activity", fields, actor) + created = [] + stamp = now() + for link in links: + assoc_id = new_id("rel_") + self._conn.execute( + "INSERT INTO associations (id, from_id, to_id, label, created_at) VALUES (?, ?, ?, 'about', ?)", + (assoc_id, record["id"], link, stamp), + ) + detail = {"id": assoc_id, "from_id": record["id"], "to_id": link, "label": "about"} + self._change(record["id"], "associate", detail, actor, stamp) + self._change(link, "associate", detail, actor, stamp) + self._touch(link, stamp) + created.append(detail | {"created_at": stamp}) + return {"record": self._public_record(record["id"]), "links": created} + + def context(self, record_id): + self._record_row(record_id) + links = self._conn.execute( + """SELECT * FROM associations + WHERE from_id = ? OR to_id = ? + ORDER BY created_at DESC, id DESC""", + (record_id, record_id), + ).fetchall() + published = [] + for link in links[:CONTEXT_LINKS]: + other = link["to_id"] if link["from_id"] == record_id else link["from_id"] + direction = "out" if link["from_id"] == record_id else "in" + published.append({ + "id": link["id"], + "label": link["label"], + "direction": direction, + "created_at": link["created_at"], + "record": self._public_record(other), + }) + changes = self._conn.execute( + """SELECT id, op, detail_json, actor, at FROM changes + WHERE record_id = ? ORDER BY id DESC LIMIT ?""", + (record_id, CONTEXT_CHANGES), + ).fetchall() + return { + "record": self._public_record(record_id), + "links": published, + "changes": [ + { + "id": change["id"], + "op": change["op"], + "detail": json.loads(change["detail_json"]), + "actor": change["actor"], + "at": change["at"], + } + for change in changes + ], + "truncated": len(links) > CONTEXT_LINKS, + } + + def bind_ref(self, provider, external_type, external_id, record_id): + provider, external_type, external_id = _external(provider, external_type, external_id) + with self._conn: + self._live(record_id) + current = self._conn.execute( + """SELECT record_id FROM external_refs + WHERE provider = ? AND external_type = ? AND external_id = ?""", + (provider, external_type, external_id), + ).fetchone() + if current is not None and current["record_id"] != record_id: + raise CrmError("conflict", "external id is already bound") + if current is None: + self._conn.execute( + """INSERT INTO external_refs + (provider, external_type, external_id, record_id) VALUES (?, ?, ?, ?)""", + (provider, external_type, external_id, record_id), + ) + return { + "provider": provider, + "external_type": external_type, + "external_id": external_id, + "id": record_id, + } + + def find_ref(self, provider, external_type, external_id): + provider, external_type, external_id = _external(provider, external_type, external_id) + row = self._conn.execute( + """SELECT record_id FROM external_refs + WHERE provider = ? AND external_type = ? AND external_id = ?""", + (provider, external_type, external_id), + ).fetchone() + if row is None: + raise CrmError("not_found", "external id is not bound") + return self._public_record(row["record_id"]) + + def _insert_record(self, object_name, fields, actor): + if not isinstance(fields, dict): + raise CrmError("validation", "fields must be an object") + obj = self._object(object_name) + known = self._fields(obj["id"]) + self._known_names(known, list(fields)) + missing = [ + name for name, field in known.items() if field["required"] and name not in fields + ] + if missing: + raise CrmError("validation", "missing required field: " + ", ".join(missing)) + normalized = {name: normalize(known[name], raw) for name, raw in fields.items()} + stamp = now() + record_id = new_id("rec_") + self._conn.execute( + "INSERT INTO records (id, object_id, created_at, updated_at) VALUES (?, ?, ?, ?)", + (record_id, obj["id"], stamp, stamp), + ) + for name, value in normalized.items(): + self._conn.execute( + "INSERT INTO values_ (record_id, field_id, value_json) VALUES (?, ?, ?)", + (record_id, known[name]["id"], json.dumps(value)), + ) + self._change(record_id, "create", {"fields": normalized}, actor, stamp) + return self._public_record(record_id) + + def _object(self, api_name, required=True): + if not isinstance(api_name, str): + raise CrmError("validation", "object must be a name") + row = self._conn.execute( + "SELECT * FROM objects WHERE api_name = ?", (api_name,) + ).fetchone() + if row is None and required: + raise CrmError("unknown_object", "unknown object: " + api_name) + return row + + def _fields(self, object_id): + rows = self._conn.execute( + "SELECT * FROM fields WHERE object_id = ? ORDER BY id", (object_id,) + ).fetchall() + return {row["api_name"]: row for row in rows} + + def _known_names(self, known, names): + unknown = [name for name in names if name not in known] + if unknown: + raise CrmError("unknown_field", "unknown field: " + ", ".join(unknown)) + + def _record_row(self, record_id): + if not isinstance(record_id, str) or not record_id.startswith("rec_"): + raise CrmError("not_found", "record not found") + row = self._conn.execute("SELECT * FROM records WHERE id = ?", (record_id,)).fetchone() + if row is None: + raise CrmError("not_found", "record not found") + return row + + def _live(self, record_id): + row = self._record_row(record_id) + if row["deleted_at"] is not None: + raise CrmError("not_found", "record is deleted") + return row + + def _values(self, record_id): + rows = self._conn.execute( + """SELECT fields.api_name AS name, values_.value_json AS value_json + FROM values_ JOIN fields ON fields.id = values_.field_id + WHERE values_.record_id = ?""", + (record_id,), + ).fetchall() + return {row["name"]: json.loads(row["value_json"]) for row in rows} + + def _public_record(self, record_id): + row = self._record_row(record_id) + obj = self._conn.execute( + "SELECT api_name FROM objects WHERE id = ?", (row["object_id"],) + ).fetchone() + return { + "id": row["id"], + "object": obj["api_name"], + "fields": self._values(record_id), + "created_at": row["created_at"], + "updated_at": row["updated_at"], + "deleted_at": row["deleted_at"], + "revision": row["revision"], + } + + def _touch(self, record_id, stamp): + self._conn.execute( + "UPDATE records SET updated_at = ?, revision = revision + 1 WHERE id = ?", + (stamp, record_id), + ) + + def _change(self, record_id, op, detail, actor, stamp): + self._conn.execute( + "INSERT INTO changes (record_id, op, detail_json, actor, at) VALUES (?, ?, ?, ?, ?)", + (record_id, op, json.dumps(detail, sort_keys=True), actor, stamp), + ) + + def _field_public(self, field): + return { + "api_name": field["api_name"], + "label": field["label"], + "type": field["field_type"], + "required": bool(field["required"]), + "options": None if field["options_json"] is None else json.loads(field["options_json"]), + "origin": field["origin"], + } diff --git a/products/crm/test_crm.py b/products/crm/test_crm.py new file mode 100644 index 00000000..cf2c927a --- /dev/null +++ b/products/crm/test_crm.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +"""Proofs for the local CRM. Synthetic records only. No network.""" + +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT)) + +from openwiz_crm.errors import CrmError +from openwiz_crm.store import Store + +CLI = [sys.executable, "-I", str(ROOT / "crm.py")] +MCP = [sys.executable, "-I", str(ROOT / "mcp.py")] + + +class StoreTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.store = Store.open(Path(self.tmp.name) / "crm.sqlite") + + def tearDown(self): + self.store.close() + self.tmp.cleanup() + + def test_schema_starts_with_standard_objects(self): + names = [obj["api_name"] for obj in self.store.schema()["objects"]] + self.assertEqual(names, ["person", "company", "deal", "activity"]) + person = self.store.schema()["objects"][0] + self.assertEqual(person["kind"], "standard") + self.assertTrue(person["fields"][0]["required"]) + self.assertEqual(person["fields"][0]["origin"], "standard") + + def test_create_requires_name_and_rejects_unknown_fields(self): + with self.assertRaises(CrmError) as missing: + self.store.create_record("person", {}, "agent") + self.assertEqual(missing.exception.code, "validation") + with self.assertRaises(CrmError) as unknown: + self.store.create_record("person", {"name": "Ada", "nope": "x"}, "agent") + self.assertEqual(unknown.exception.code, "unknown_field") + + def test_custom_field_round_trip_and_search(self): + self.store.add_field("person", "github", "GitHub", "text") + created = self.store.create_record( + "person", {"name": "Ada", "email": "ada@example.com", "github": "ada"}, "agent", + ) + self.store.create_record("person", {"name": "Grace", "github": "grace"}, "agent") + found = self.store.search("person", where={"github": "ada"}) + self.assertEqual([row["id"] for row in found["records"]], [created["id"]]) + queried = self.store.search("person", query="Ada@example.com") + self.assertEqual(queried["records"][0]["fields"]["email"], "ada@example.com") + + def test_update_keeps_other_fields_and_records_history(self): + self.store.add_field("person", "active", "Active", "boolean") + created = self.store.create_record( + "person", {"name": "Ada", "email": "ada@example.com", "active": True}, "agent", + ) + updated = self.store.update_record( + "person", created["id"], {"role": "contributor"}, ["active"], "agent", + ) + self.assertEqual(updated["fields"]["email"], "ada@example.com") + self.assertEqual(updated["fields"]["role"], "contributor") + self.assertNotIn("active", updated["fields"]) + context = self.store.context(created["id"]) + self.assertEqual(context["changes"][0]["op"], "update") + self.assertEqual(context["changes"][0]["actor"], "agent") + with self.assertRaises(CrmError) as stale: + self.store.update_record( + "person", created["id"], {"role": "partner"}, [], "agent", + if_revision=created["revision"], + ) + self.assertEqual(stale.exception.code, "conflict") + current = self.store.get_record(created["id"]) + self.store.update_record( + "person", created["id"], {"role": "partner"}, [], "agent", + if_revision=current["revision"], + ) + + def test_select_number_and_custom_object(self): + with self.assertRaises(CrmError): + self.store.create_record("deal", {"name": "Outside", "stage": "nope"}, "agent") + deal = self.store.create_record( + "deal", {"name": "Outside repo", "stage": "qualifying", "amount": "12.0"}, "agent", + ) + self.assertEqual(deal["fields"]["amount"], 12) + self.store.add_object("listing", "Listing") + self.store.add_field( + "listing", "status", "Status", "select", options=["open", "closed"], + ) + listing = self.store.create_record("listing", {"status": "open"}, "agent") + self.assertEqual(listing["object"], "listing") + with self.assertRaises(CrmError) as required: + self.store.add_field("listing", "city", "City", "text", required=True) + self.assertEqual(required.exception.code, "validation") + + def test_association_context_and_activity_rollback(self): + person = self.store.create_record( + "person", {"name": "Ada", "email": "ada@example.com"}, "agent", + ) + company = self.store.create_record( + "company", {"name": "Example", "domain": "example.com"}, "agent", + ) + link = self.store.associate(person["id"], company["id"], "works_at", "agent") + self.assertEqual(link["label"], "works_at") + with self.assertRaises(CrmError) as duplicate: + self.store.associate(person["id"], company["id"], "works_at", "agent") + self.assertEqual(duplicate.exception.code, "conflict") + with self.assertRaises(CrmError): + self.store.log_activity( + "github", "Opened a pull request", [person["id"], "rec_missing"], "agent", + happened_at="2026-11-25T00:00:00Z", source="test", + ) + self.assertEqual(self.store.search("activity")["records"], []) + logged = self.store.log_activity( + "github", "Opened a pull request", [person["id"], company["id"]], "agent", + body="Synthetic pull request.", happened_at="2026-11-25T00:00:00Z", source="github", + ) + context = self.store.context(person["id"]) + labels = sorted(item["label"] for item in context["links"]) + self.assertEqual(labels, ["about", "works_at"]) + activity = next(item for item in context["links"] if item["label"] == "about") + self.assertEqual(activity["direction"], "in") + self.assertEqual(activity["record"]["id"], logged["record"]["id"]) + company_context = self.store.context(company["id"]) + self.assertIn("about", [item["label"] for item in company_context["links"]]) + + def test_delete_hides_search_and_blocks_update(self): + created = self.store.create_record("person", {"name": "Ada"}, "agent") + deleted = self.store.delete_record("person", created["id"], "agent") + self.assertIsNotNone(deleted["deleted_at"]) + self.assertEqual(self.store.search("person", query="Ada")["records"], []) + self.assertEqual(self.store.get_record(created["id"])["deleted_at"], deleted["deleted_at"]) + with self.assertRaises(CrmError) as update: + self.store.update_record("person", created["id"], {"role": "x"}, [], "agent") + self.assertEqual(update.exception.code, "not_found") + + def test_object_mismatch_and_external_ref(self): + person = self.store.create_record("person", {"name": "Ada"}, "agent") + with self.assertRaises(CrmError) as mismatch: + self.store.update_record("company", person["id"], {"name": "Other"}, [], "agent") + self.assertEqual(mismatch.exception.code, "object_mismatch") + bound = self.store.bind_ref("salesforce", "Account", "001EXAMPLE", person["id"]) + self.assertEqual(bound["id"], person["id"]) + again = self.store.bind_ref("salesforce", "Account", "001EXAMPLE", person["id"]) + self.assertEqual(again, bound) + self.assertEqual( + self.store.find_ref("salesforce", "Account", "001EXAMPLE")["id"], person["id"], + ) + company = self.store.create_record("company", {"name": "Example"}, "agent") + same_number = self.store.bind_ref("hubspot", "0-2", "1001", company["id"]) + self.store.bind_ref("hubspot", "0-1", "1001", person["id"]) + self.assertNotEqual(same_number["id"], person["id"]) + other = self.store.create_record("person", {"name": "Grace"}, "agent") + with self.assertRaises(CrmError) as conflict: + self.store.bind_ref("salesforce", "Account", "001EXAMPLE", other["id"]) + self.assertEqual(conflict.exception.code, "conflict") + + def test_search_limit_truncates(self): + for index in range(3): + self.store.create_record("person", {"name": "Person " + str(index)}, "agent") + page = self.store.search("person", limit=2) + self.assertEqual(len(page["records"]), 2) + self.assertTrue(page["truncated"]) + + +class SurfaceTest(unittest.TestCase): + def test_cli_create_search_and_context(self): + with tempfile.TemporaryDirectory() as tmp: + db = str(Path(tmp) / "crm.sqlite") + created = self.cli(db, [ + "record-create", "--object", "company", + "--set", "name=Example", "--set", "domain=example.com", + ]) + company = created["result"]["id"] + person = self.cli(db, [ + "record-create", "--object", "person", + "--set", "name=Ada", "--set", "email=ada@example.com", + ])["result"]["id"] + self.cli(db, ["associate", "--from", person, "--to", company, "--label", "works_at"]) + self.cli(db, [ + "activity-log", "--kind", "email", "--summary", "Introduced the product", + "--link", person, "--happened-at", "2026-11-25", + ]) + found = self.cli(db, ["record-search", "--object", "person", "--query", "ada"]) + self.assertEqual(found["result"]["records"][0]["id"], person) + context = self.cli(db, ["context", "--id", person]) + self.assertEqual(len(context["result"]["links"]), 2) + missing = self.cli(db, ["record-get", "--id", "rec_missing"], expect=1) + self.assertEqual(missing["error"]["code"], "not_found") + + def test_mcp_lists_tools_and_creates_a_record(self): + with tempfile.TemporaryDirectory() as tmp: + db = str(Path(tmp) / "crm.sqlite") + lines = [ + {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { + "protocolVersion": "2024-11-05", + "capabilities": {}, + "clientInfo": {"name": "test", "version": "0"}, + }}, + {"jsonrpc": "2.0", "method": "notifications/initialized"}, + {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, + {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { + "name": "crm_record_create", + "arguments": {"object": "person", "fields": {"name": "Ada"}}, + }}, + {"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": { + "name": "crm_record_search", + "arguments": {"object": "person", "query": "Ada"}, + }}, + ] + payload = "".join(json.dumps(line) + "\n" for line in lines) + result = subprocess.run( + MCP, input=payload, text=True, capture_output=True, + env={"OPENWIZ_CRM_DB": db}, check=False, + ) + self.assertEqual(result.returncode, 0, result.stderr) + messages = [json.loads(line) for line in result.stdout.splitlines() if line.strip()] + self.assertEqual([message["id"] for message in messages], [1, 2, 3, 4]) + self.assertEqual(messages[0]["result"]["serverInfo"]["name"], "openwiz-crm") + names = [tool["name"] for tool in messages[1]["result"]["tools"]] + self.assertIn("crm_record_context", names) + created = json.loads(messages[2]["result"]["content"][0]["text"]) + self.assertTrue(created["ok"]) + found = json.loads(messages[3]["result"]["content"][0]["text"]) + self.assertEqual(found["result"]["records"][0]["fields"]["name"], "Ada") + + def test_package_does_not_reference_a_network_client(self): + banned = ("urllib", "http.client", "import socket", "requests", "httpx") + for path in (ROOT / "openwiz_crm").glob("*.py"): + text = path.read_text(encoding="utf-8") + for name in banned: + self.assertNotIn(name, text, path.name) + + def cli(self, db, args, expect=0): + result = subprocess.run( + CLI + ["--db", db, *args], text=True, capture_output=True, check=False, + ) + self.assertEqual(result.returncode, expect, result.stderr + result.stdout) + self.assertEqual(result.stderr, "") + return json.loads(result.stdout) + + +if __name__ == "__main__": + raise SystemExit(0 if unittest.main(verbosity=1, exit=False).result.wasSuccessful() else 1) From 4a0e4628577761df8b490481a34c2b97f929edc1 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 03:08:37 +0000 Subject: [PATCH 2/2] Remove CRM module comments the comment check refuses. The owned-paths job rejects comments that are not one of its allowed kinds. The module notes now live in the CRM README. Co-authored-by: Jake Parker --- products/crm/openwiz_crm/__init__.py | 2 -- products/crm/openwiz_crm/cli.py | 2 -- products/crm/openwiz_crm/errors.py | 3 --- products/crm/openwiz_crm/mcp.py | 7 ------- products/crm/openwiz_crm/store.py | 7 ------- products/crm/test_crm.py | 2 -- 6 files changed, 23 deletions(-) diff --git a/products/crm/openwiz_crm/__init__.py b/products/crm/openwiz_crm/__init__.py index c75a3d25..3dc1f76b 100644 --- a/products/crm/openwiz_crm/__init__.py +++ b/products/crm/openwiz_crm/__init__.py @@ -1,3 +1 @@ -"""Local agent-native CRM. No network imports belong in this package.""" - __version__ = "0.1.0" diff --git a/products/crm/openwiz_crm/cli.py b/products/crm/openwiz_crm/cli.py index fd36aec5..42fbae4f 100644 --- a/products/crm/openwiz_crm/cli.py +++ b/products/crm/openwiz_crm/cli.py @@ -1,5 +1,3 @@ -"""JSON command line for the local CRM. stdout is one JSON object.""" - import argparse import json import os diff --git a/products/crm/openwiz_crm/errors.py b/products/crm/openwiz_crm/errors.py index 08b2bf37..e2b2ac3f 100644 --- a/products/crm/openwiz_crm/errors.py +++ b/products/crm/openwiz_crm/errors.py @@ -1,6 +1,3 @@ -"""Errors an agent can handle without reading a traceback.""" - - class CrmError(Exception): def __init__(self, code, message): super().__init__(message) diff --git a/products/crm/openwiz_crm/mcp.py b/products/crm/openwiz_crm/mcp.py index ce19ec31..6b80177f 100644 --- a/products/crm/openwiz_crm/mcp.py +++ b/products/crm/openwiz_crm/mcp.py @@ -1,10 +1,3 @@ -"""Newline-delimited JSON-RPC MCP server for the local CRM. - -The server speaks protocol versions 2024-11-05, 2025-03-26 and 2025-06-18. -It reads one JSON object per line on stdin and writes one JSON object per -line on stdout. It does not open a network connection. -""" - import json import os import sqlite3 diff --git a/products/crm/openwiz_crm/store.py b/products/crm/openwiz_crm/store.py index 571c56c2..ac9e7965 100644 --- a/products/crm/openwiz_crm/store.py +++ b/products/crm/openwiz_crm/store.py @@ -1,10 +1,3 @@ -"""SQLite store for people, companies, deals, activities and custom objects. - -Records share one table. Fields are metadata, and values are JSON, so a custom -field does not need a migration. The process that opens this file does not -contact Salesforce, HubSpot or any other network service. -""" - import json import math import re diff --git a/products/crm/test_crm.py b/products/crm/test_crm.py index cf2c927a..e3d93e24 100644 --- a/products/crm/test_crm.py +++ b/products/crm/test_crm.py @@ -1,6 +1,4 @@ #!/usr/bin/env python3 -"""Proofs for the local CRM. Synthetic records only. No network.""" - import json import subprocess import sys