AIP-79: COLLECT (collect/v1): collecting public items and their counters with provenance

Specifies a source-agnostic format and engine contract for collecting public items (articles, posts, threads, submissions, reviews, videos) and their metrics with provenance: the collection recipe (collect.recipe/v1: sources, queries with subject labels, window, sampling bands with quota, per-domain cap and seed, caps, workers, lookahead), the collected item, the append-only observation (a missing counter is never zero, the displayed value is kept), the actor with dated audience readings (karma is not audience, an unknown audience carries a reason), the pickup (kind, method, verified rule), the connector contract (a deterministic plan, a network-only fetch, a pure replayable parse, plus a declaration of counters, access, capabilities and pace), the transport contract (api, http, browser, with the failures that escalate and the browser challenge hard stop), dedup at three levels, and run provenance (content-addressed raw bodies, a task log, deterministic resume). It fixes no source: platforms appear only as non-normative examples. A collected item can be imported as an AIP-10 knowledge source.

FieldValue
AIP79
TitleCOLLECT (collect/v1): collecting public items and their counters with provenance
AuthorJeremy André <[email protected]>
StatusDraft
TypeSchema
RequiresAIP-1 (process), AIP-10 (KNOWLEDGE: a collected item can be imported as a knowledge.source/v1, see §Bridge to AIP-10)
Composes withAIP-18 (COLLECTION: a different concept, see §Not to be confused with), AIP-63 (BROWSER: its recipe/v1 is a site recipe, a different doctype)
Doctypescollect.recipe/v1, collect.item/v1, collect.observation/v1, collect.actor/v1, collect.pickup/v1; run log shapes collect.run/v1, collect.plan/v1, collect.task/v1, collect.sampling/v1, collect.raw-index/v1, collect.report/v1
Created2026-11-28
Packages (ref-impl)@agentproto/collect (schemas, connector contract, engine, stores, HTTP and API transports), @agentproto/collect-cli (the collect binary). Both Apache-2.0.
Schemasresources/aip-79/draft/*.schema.json (generated from the reference zod schemas)

Abstract

COLLECT defines how a program gathers public content from places that were not built to be read by programs, and keeps enough evidence to trust the result. It fixes five record shapes (item, observation, actor, pickup and the recipe that drives a run), a connector contract that separates planning, fetching and parsing so that every stored body can be parsed again without a network, a transport contract with explicit rules for when to try the next way of reaching a page and when to stop, and the dedup and provenance rules that make a run resumable and its numbers auditable. No source is standardized here: a connector is the only place a platform is named.

Motivation

Agents are asked to measure things on the open web: what was published about a topic, how far a post travelled, who said it, who repeated it. Every team rebuilds the same plumbing, and the same mistakes recur:

  • A missing number becomes zero. A platform that hides a counter, or a page that did not load it, yields 0 in a spreadsheet and the statistics downstream are wrong without anyone noticing.
  • Audiences are conflated. A forum's karma, a follower count and a subscriber count are different quantities. Merged into one column they support no conclusion.
  • No evidence. The number is in a table, the page it came from is gone, so a parser fix cannot be replayed and a claim cannot be checked.
  • Duplicates distort. The same article reached through two URLs, or the same post collected twice, counts twice.
  • Crashes and reruns double-count. A run that dies half way cannot be resumed without re-fetching, so it is run again and writes again.
  • Challenge pages are bypassed. Fallback logic grows until it tries to defeat a verification page.

AIP-10 turns sources into a curated wiki, but says nothing of how a source is gathered. COLLECT is that upstream half: it produces dated, attributed, replayable records that AIP-10 can ingest.

Scope

In scope: the record shapes, the connector and transport contracts, the sampling and dedup rules, and the run provenance an interoperable implementation must keep.

Out of scope: any specific source (no connector is normative), analysis or scoring of what was collected, a scheduler, the choice of a store (the on-disk layout is informative), and any technique to defeat access controls.

Terminology

The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119.

TermMeaning
RecipeA collect.recipe/v1 document: what to collect and how hard to push.
ConnectorA module that knows one source. It plans tasks, fetches bodies, parses them.
TaskA unit of work a connector plans: a stable id and plain-JSON parameters.
RawA body a connector fetched, stored as received, whatever its status.
TransportA way to reach a page: api, http or browser.
ItemOne collected piece of public content.
ObservationOne dated reading of an item's counters.
ActorAn author or submitter.
PickupA link from an item to a later item that republishes or cites it.
RunOne execution of a recipe, identified by a runId.
StoreWhere raws, records and the run log are kept.

Not to be confused with

AIP-18 COLLECTION defines typed, user-authored record collections (a COLLECTION.md schema, instantiated by ITEM.md files). Those are hand-managed workspace records. COLLECT is the opposite: records are produced by a machine from outside sources, are append-oriented, and carry fetch provenance. The two share the word "item" and nothing else; a COLLECT item is a collect.item/v1, never an AIP-18 ITEM.md. A host MAY materialize collected items as an AIP-18 collection, which is outside this AIP.

AIP-63 BROWSER defines a recipe/v1 manifest (RECIPE.md) for driving one site in a browser. The COLLECT recipe is named collect.recipe/v1 and has no relation to it: no shared fields, no shared file. A COLLECT recipe is a YAML or JSON document that is not required to be a file named RECIPE.md; an implementation MUST NOT accept a collect.recipe/v1 where a recipe/v1 is expected, or the reverse.

Specification

Conformance

A conforming collector implements the engine rules of §Connector, §Transport, §Dedup and §Run provenance and writes records that validate against the shapes below. A conforming connector satisfies §Connector. A conforming reader accepts the shapes below and applies the reader rules (for example the first-record-of-a-key rule). One program may be all three.

JSON Schemas under resources/aip-79/draft/ (one per doctype, with valid and invalid examples) encode the property sets and the cross-field rules a schema can express: a counter is not both in metrics and missing; a rawValues key is a metrics key; an audience reading has exactly one of value and unknown; the verified flag follows method; link and content_id pickups need evidence and a non-empty evidence.rawRef; a declared pickup needs an excerpt, an outbound link or an outlet. A validator MUST accept exactly the same records as the schemas plus the semantic checks no schema can express, which are normative prose here: a sampling band has min ≤ max; the rules of §Connector (What the connector supplies); and the id namespace of §Dedup.

The five record shapes (recipe, item, observation, actor, pickup) are the interoperable core: every implementation MUST read and write them. The run log shapes (run, plan, task, sampling, raw-index, report) are MUST for an implementation that exports a store or resumes a run it did not write, and MAY be kept in any other form by one that does neither.

Timestamps (firstSeenAt, measuredAt, window bounds) are RFC 3339 date-times with an offset. Fields marked day or timestamp (postedAt, publishedAt, accountCreatedAt) accept a calendar day (2026-11-20) as well, because some sources display only the date.

The recipe (collect.recipe/v1)

A recipe is an object with these properties. The reference implementation drops unknown properties silently; a reader MUST NOT fail on one, and a writer SHOULD NOT emit one.

PropertyTypeRule
namestringOptional label.
sourcesarray, at least 1Each entry: connector (string, required, a connector id), instance (optional string naming an instance of a multi-instance source), queries (array, default empty, each { text, subject } with both non-empty), options (free object handed to the connector).
window{ from?, to? }Optional timestamps bounding what is of interest. A connector SHOULD use it to limit work; the engine does not filter on it.
samplingobjectOptional, see §Sampling.
caps{ perConnector?, total? }Positive integers. Most tasks a connector may start, and most tasks overall.
workerspositive integerDefault 8. Concurrency of the non-browser lane.
lookaheadpositive integerMost tasks fetched or held ahead of the ordered commit cursor. Default 4 times workers.
sinksarray of stringOptional names of downstream consumers. Opaque here.

A subject is the label under which a query's results are filed. It is a topic the recipe author chose, not something the source asserts. The connector that returns an item found through a query MUST add that label to the item's subjects with provenance query; the engine does not add it.

A host that stores the recipe with a run MUST store it as it was when the run started, with its defaults filled, together with a hash of it (§Run provenance).

The collected item (collect.item/v1)

FieldRule
idRequired, non-empty. Stable identity inside the store, of the form <source>:<rest> (§Dedup, id namespace). With a native id: <source>:<nativeId>. Otherwise <source>: followed by the lowercase hex SHA-256 of the canonical URL.
sourceRequired. The source; SHOULD equal the id prefix and the connector id.
sourceInstanceOptional instance of the source (§Dedup, id namespace).
kindRequired, one of article, post, thread, submission, review, video, query. A submission is an entry that points at something else (for example an aggregator entry linking to an article) and sets links.target.
url, canonicalUrlThe URL as seen, and its canonical form (§Dedup). The engine computes canonicalUrl from url when absent. Both SHOULD be kept: the canonical form is a dedup key only.
contentIdOptional content fingerprint (§Dedup). The engine computes it from text when absent.
contentGroupIdOptional id of a near-duplicate group (§Dedup, optional).
subjectsArray of { label, provenance, classifier? }. provenance is query, source_tag or classifier; classifier ({ name, version }) MUST be given by the connector when the provenance is classifier (the schema does not require it). An item MAY have no subject.
title, text, textTruncated, language, wordCount, formatContent descriptors. textTruncated is true when text is not the whole text.
authorRef, submitterRefRefs of actors (§Actor). The author wrote it; the submitter posted it to the place where it was found.
publishedAt, postedAtDay or timestamp. Editorial date and platform date.
firstSeenAtRequired timestamp. When the collector first stored the item.
links{ target?, parent?, root?, quoted? }. Strings (URLs or item ids).
outboundLinks, parts, tags, hasMedia, queryOutbound URLs; sub-items (parts: { id, text, authorRef?, postedAt? }, for example the posts of a thread); free tags; media flag; the query text that found it.
runId, rawRefsThe run that wrote it and the refs of the raws it was parsed from (§Run provenance).
extFree object. A connector MAY validate it against its own schema. Consumers MUST ignore keys they do not know.

An item MUST NOT be required to have a subject, an author, or any counter.

The observation (collect.observation/v1)

An observation is one dated reading of the counters of one item.

FieldRule
itemId, measuredAtRequired.
metricsObject, default empty. Keys from the counter vocabulary below; values are numbers.
partMetricsOptional map from a part id to a metrics object.
rawValuesOptional map from a counter name to the text the source displayed ("1.2K").
missingOptional map from a counter name to a reason: not_exposed (the source does not show it), hidden (the owner hid it), blocked (the access was refused).
transport, runId, taskId, rawRefProvenance.
recordKeyDurable identity of an engine-written record (§Run provenance).

Counter vocabulary: views, likes, reposts, replies, bookmarks, points, comments, reactions, score, rating, helpfulVotes. A connector declares which of these it supplies and what each counts (§Connector). A counter name means what the connector declares; this AIP does not claim two sources' likes are comparable.

Observation rules (all MUST):

  1. Append-only. A new reading is a new observation. An implementation MUST NOT overwrite or edit a stored observation. The history of a counter is the ordered list of its observations.
  2. Missing is never zero. A counter that was not read MUST be absent from metrics. A counter MUST NOT appear in both metrics and missing of one observation. A reader MUST NOT infer 0 from absence.
  3. Raw values. Every key of rawValues MUST also be a key of metrics: a displayed value belongs to a parsed number. The parsed number may be rounded or approximate ("1.2K" parsed as 1200). A consumer that needs the precision of the display reads rawValues.
  4. Redo identity. An observation written by an engine MUST carry the recordKey of §Run provenance, and a reader MUST keep the first record of a key.

Recommendations (SHOULD):

  • When the reason a counter is missing is known, list it in missing.
  • Carry rawRef, so the reading can be checked against the stored body.

The actor (collect.actor/v1)

FieldRule
refRequired. Same shape as an item id: <source>:<native id or handle>.
displayName, handle, profileUrl, verifiedOptional descriptors.
accountCreatedAtDay or timestamp.
audienceArray of audience readings, default empty. Append-only, like observations: a new reading is added, never substituted.

An audience reading is { measuredAt, kind, value?, rawValue?, unknown? }:

  • kind is followers, karma or subscribers. They are different quantities. A karma reading MUST stay typed karma and MUST NOT be presented or counted as an audience of readers. The coverage count withAuthorAudience counts only followers and subscribers.
  • Exactly one of value (a non-negative number) and unknown MUST be present. unknown is one of not_exposed, not_fetched, blocked and says why the figure is not known. An unknown audience is never 0.
  • rawValue is the displayed text, as for observations.

A source that exposes no audience produces an actor with an empty audience or readings with unknown: not_exposed; either is valid and neither is zero.

The pickup (collect.pickup/v1)

A pickup records that something later repeated or cited an item.

FieldRule
itemIdRequired. The item that was picked up.
kindmedia_pickup, crosspost or media_publication.
pickupItemId, pickupUrl, outletThe picking item (when it was collected), its URL, and the outlet it appeared in.
relationrepublication or citation.
evidence{ outboundLink?, excerpt?, similarity? (0..1), rawRef? }.
methodlink, content_id, near_text, declared or legacy_flag.
verifiedBoolean, see below.
firstSeenAt, measuredAtRequired timestamps.
runId, taskId, recordKeyProvenance.

The verified rule: verified MUST be true exactly when method is link, content_id or declared (the methods whose evidence is exact), and false for near_text and legacy_flag. A record that breaks this MUST be rejected. Per method:

  • link, content_id: the pickup MUST carry some evidence (an outboundLink, an excerpt or a similarity) AND evidence.rawRef. A verified pickup is one a reader can re-check against a stored body.
  • declared: the picking party stated it; it MUST carry an excerpt, an outboundLink or an outlet.
  • near_text: approximate text similarity. Never verified.
  • legacy_flag: imported from a source that only said "picked up". Never verified.

Pickups are append-only, like observations.

Connector

A connector has a declaration and three functions. Where this section says "the engine" it means the collector that runs connectors.

Declaration

FieldRule
idLowercase letters, digits and dashes, starting with a letter or digit.
versionNon-empty string. A change in what parse outputs SHOULD change the version.
transportsOrdered, at least one, no duplicates, from api, http, browser. The preference order: the engine tries them in this order, among those it was given.
access{ level: "none" }, { level: "key", secret } (needs the named secret) or { level: "session", site } (needs a logged-in session on site). Default none.
capabilitiesSubset of search, list, read-by-url, author-profile, re-observe.
countersArray of { name, unit, scope, primary }. name is from the counter vocabulary; unit says what is counted (count, points, stars); scope is root (the root message only) or thread (the whole thread); primary marks the source's own main counter (default false). At most one counter is primary and a name appears once.
pace{ delayMs (default 0), maxTasksPerRun? }. delayMs is the minimum interval between two requests to one host. maxTasksPerRun is the per-run task budget unless the recipe sets caps.perConnector, which takes precedence (§Run provenance, Cap accounting).
extOptional schema for the ext of the items it returns.

A declaration that breaks a rule above MUST be refused when the connector is defined (construct time), naming the connector. A connector does not hold secrets: it names them (access.secret) and the engine's secrets port supplies them. access.level: "session" is declarative: the engine does not check that a session exists; the transport that carries it does.

A future revision may add a declaration of how a session-level connector checks that its session is still valid. It is not part of collect/v1.

The three functions

  1. plan(recipe, sources) returns the root tasks for the recipe's sources that name this connector. It MUST be deterministic: the same recipe gives the same tasks with the same ids, in the same order, and it MUST NOT do I/O. A task is { id, kind?, params } with id non-empty and unique within its connector, and params plain JSON. A task id seen twice in a plan is kept once (the first). A task of kind: "read" fetches one item by URL and is never sampled.
  2. fetch(task, transport, context) is the only phase that touches the network. It returns { raws, tasks? }: the raw bodies (each with url, file extension, bytes, optional HTTP status, optional challenge flag set when the page is a verification page) and follow-up tasks (next page, linked article, author profile). It MUST use the transport the engine gives it, and it MUST NOT put a secret value in a raw it returns, a follow-up task or a record. Its follow-up tasks MUST be a deterministic function of the raws it fetched. A follow-up whose key (<connector>/<task id>) is already known in the run is ignored.
  3. parse(input) turns one stored raw into { items, observations, actors, pickups }. It MUST be pure: a function of its input only. The input is exactly: the connector id; the task; and, for the raw, its store ref, URL, extension, bytes, HTTP status (if any), the fetch time (fetchedAt) and the transport name. parse MAY read any of those and nothing else: no clock, no randomness, no I/O, no other raw, no state kept between calls. The same input MUST give the same output, so that parsing a stored raw again (replay) gives the same records.

What the connector supplies, what the engine fills

The engine fills what the connector leaves out, and then validates the whole record against the shapes above:

RecordDefaults the engine appliesThe connector MUST
itemid = <source>: + SHA-256 hex of the canonical URL when the item has a URL and no id; canonicalUrl from url; contentId from text (§Dedup); firstSeenAt = fetch time; runId; the raw's ref added to rawRefssupply an id or a url; give id the form <source>:<rest> (§Dedup, id namespace); give dates only as the source states them (never the collection time as postedAt); label each subject with its true provenance, and give classifier ({ name, version }) on every subject whose provenance is classifier; add a query-provenance subject for the recipe query that found the item
observationmeasuredAt = fetch time; transport, rawRef (the connector's values win); runId, taskId, recordKey (the engine's values always win)name only counters it declares; put an unread counter in missing, never 0
actornonegive ref the same <source>:<rest> form as an item id
pickupfirstSeenAt, measuredAt = fetch time; evidence.rawRef = the raw's ref (the connector's wins); runId, taskId, recordKeyset verified consistently with method (§The pickup)

Validation happens twice: the declaration at construct time, and every record at ingest. If a connector declares ext, an item whose ext fails it is a validation failure.

Ingest

Per task, a conforming engine MUST:

  1. store every raw of the task, then parse them in order;
  2. validate every record of every raw, and every follow-up task;
  3. if any step 2 validation or parse fails: record the task failed with cause parse and write none of that task's records. The raws stay stored (they were stored first, so the failure can be investigated and replayed);
  4. otherwise, in plan order (§Sampling, Order guarantee): sample, dedup, then write items, item links, observations, actors and pickups, then the follow-up tasks, then mark the task done with its counters.

The "all or none" guarantee of step 3 covers validation and parse failures only. Step 4 is not transactional: it is a sequence of separate writes. A crash or an I/O error between them leaves a partial commit and a task that is not done; a store failure stops the run with an error and the run stays resumable. A partial commit is safe to redo because of recordKey (observations and pickups) and the seen index (items); actors may be written again identically, and a consumer MUST tolerate a repeated identical actor record.

Reference implementation note (informative). Parsing and validation run in parallel across tasks; only sampling, dedup and writes go through one serialised queue.

Transport

A connector's fetch receives one of three transports. The method shapes below are informative; the behaviour is normative.

  • http: a plain request answered by { status, headers, body, url } (url is the final URL after redirects). It adds no credential of its own.
  • api: the same request interface, with authentication added from the secrets port. A missing or empty secret MUST fail before any request, with a missing secret error that names the secret and never its value.
  • browser: drives a real page the transport opened itself. Operations: open a background page, evaluate a script, fetch from inside the page (same origin), scroll, wait for a selector or predicate, close.

Requirements on the http and api transports

These bind a transport that offers the http or api name. A custom transport that does not follow them MUST NOT use those names. Numbers are the reference defaults, all configurable, and are informative.

  • Timeout and size cap. Each request has a timeout (30 s) and a body size cap (10 MiB). A 2xx body over the cap is a failure of cause http with the response status, not retried, and does not fall back: a bigger page is not a transport problem. A non-2xx body is truncated to the cap and kept.
  • Retries. A network error, a 429 and a 5xx are retried (3 attempts in all) with exponential backoff and jitter (first step 500 ms, steps capped at 10 s). POST and PATCH MUST NOT be retried unless the transport is configured to.
  • Retry-After (a non-negative integer of seconds, or an HTTP date; anything else is ignored) is honoured on 429 and 503 and replaces the backoff for that wait. A wait longer than the bound (30 s) is not waited: the request is abandoned at once with cause http and the response status. Only a 429 then falls back (§Failure classification); a 503 is final.
  • Redirects are followed one hop at a time (at most 10); the response url is the final one. Credential headers (Authorization, Cookie, Proxy-Authorization and any header the transport marked as a credential) MUST be dropped when a hop changes origin. A request whose credential is in the URL (query authentication) MUST refuse a hop that leaves the origin, with cause blocked. A redirect that turns a POST into a GET drops the body.
  • Pacing. A transport SHOULD pace sends to one host (1 s apart by default) at the send boundary, so that every retry and every redirect hop is paced, not only the first send. The engine separately gates the start of each request a task makes through fetch to one host with the connector's pace.delayMs; the two gaps overlap (the later deadline wins) and do not add up. Retries and redirect hops never go back through the engine, so only the transport's own limiter paces them.
  • API secrets. The api transport MUST remove its own secret from what it returns: every occurrence (raw, percent-encoded, form-encoded) is replaced by [redacted] in the body bytes and headers of responses and in the message, URL and body of its errors; a query-parameter secret is removed from the returned url.

The browser transport has no network policy of its own beyond the rules in §Browser rules.

Failure classification and fallback

The engine tries a task's transports in the order of the connector's transports, restricted to those it was given. A failure has a cause: blocked, empty, network, http, challenge, parse, other. The engine MUST apply these rules.

Before any task starts. A connector with access: { level: "key" } whose secret is missing or empty is skipped as a whole, reason missing_secret:<NAME>: none of its tasks is fetched (its plan still runs and the plan is written; on a new run it has no task records; on resume its tasks are recorded skipped). A connector with no usable transport (none of its declared transports provided) is skipped the same way. A connector that is not registered is skipped. The run goes on for the others.

During a task, per attempt:

  1. A request-level missing secret (the api transport could not find its secret) is not a failure: the engine moves to the next usable transport (recording the escalation with cause missing_secret), and when none remains the task is skipped with reason missing_secret:<NAME>.
  2. If fetch returns raws, each raw is classified, in this order: a raw flagged challenge is a challenge; else its status decides (401, 403 and 429 fall back, cause blocked; any other non-2xx status is final, cause http); else a raw with zero bytes (whatever its status, or none) falls back, cause empty. A fetch that returns no raw at all falls back, cause empty.
  3. For several raws: a challenge wins wherever it appears among them (the browser kind first); otherwise the first failing raw in order decides.
  4. If fetch throws a transport error: a challenge wins; otherwise a non-2xx status decides as in 2 (a thrown cause http with status 429 is recorded as blocked and falls back); otherwise a thrown cause blocked or empty falls back; network (DNS, reset, TLS, timeout, abort) is final; http without a fallback status is final.
  5. Parse failures and any error that is not a transport error are terminal (causes parse and other): no fallback.
  6. Every fallback MUST be recorded (from, to) on the task and counted in the run report. A body returned with a failure is kept as a raw, with the failure cause in the index.
  7. When no transport remains the task fails with the cause of the last attempt.

Challenge pages

A verification or challenge page asks the visitor to prove they are human. A transport reports one only on real evidence (a machine-readable mitigation header; or a 403, 429 or 503 status together with an interstitial marker; or a page that is nothing but an interstitial); a normal page that embeds a widget or quotes the phrase is content, and non-HTML content is never flagged. Heuristics that miss a challenge are tolerated; heuristics that flag content are not.

  • Seen by http or api: the task moves to the next transport, or fails with cause challenge when none remains.
  • Seen by the browser: a hard stop for that connector (MUST). The raw is kept. There is no fallback and no retry. The engine MUST NOT start any new request for that connector for the rest of the run, MUST signal cancellation to the connector's in-flight work (a connector that ignores the signal cannot be forced), and MUST record the connector's queued tasks as skipped with reason challenge. The task that met the challenge is failed with cause challenge. The run continues for other connectors.
  • What the hard stop does not promise: a task that was already in flight may still finish and be recorded (as failed if it returns a failure of its own, or skipped with reason challenge if it was aborted or reaches its commit after the stop); and a commit already being written when the stop occurs completes. After the stop, no new sampling, writes or follow-up tasks for that connector begin.
  • An explicit resume retries the tasks of a stopped connector (failed and skipped alike): the stop does not carry over. A resumed run starts a new attempt, which the same rules can stop again.
  • An implementation MUST NOT attempt to solve, bypass or wait out a challenge.

Browser rules

The browser transport MUST be read-only. It touches only pages it opened itself, never a page the user already had. It MUST NOT submit forms, post, send, purchase or otherwise mutate state at the source, and its interface offers no operation to click or type. Requests a page makes by itself are outside the engine's pacing, so the browser lane runs one task at a time and is paced by the connector's pace.delayMs on each page open and each in-page fetch.

Scheduling

The engine runs api and http attempts in a bounded pool of workers, and the browser in a lane of one. Each attempt is queued in the lane of its own transport, so a fallback moves a task between lanes. Start order inside a lane follows the global order key (connector index in the recipe, plan index, then follow-up depth and index); there is no order across the two lanes.

Sampling

recipe.sampling thins the candidate items that a task's parse returns. Tasks of kind read are never sampled. Without sampling nothing changes.

sampling:
  bands:
    - { metric: views, min: 0, max: 999, quota: 50 }
    - { min: 1000, max: 99999, quota: 50 }
  keepMissingMetric: false
  perDomainCap: 2
  seed: 42
FieldRule
bandsArray of { metric?, min?, max?, quota? }. metric is a counter (default: the connector's primary counter). min and max are inclusive and either may be absent; min MUST NOT exceed max (a semantic check no JSON Schema expresses). quota is the most candidates the band keeps.
keepMissingMetricWhen a candidate has no value for any band's counter: drop it as no_metric (default) or, if true, keep it outside every band.
perDomainCapPositive integer. Most kept items per host.
seedInteger. Makes a forced choice reproducible.

Rules a conforming engine MUST satisfy:

  1. Bands, then per-domain cap. A candidate falls in the first band whose counter it has and whose range holds that counter. With no value for any band counter: dropped as no_metric (or kept if keepMissingMetric). With a value that fits no band: out_of_bands. Over a band's quota: band_quota. Over perDomainCap for its host: domain_cap. A candidate that fails one rule MUST NOT use the quota or cap of the other. For a submission the host is that of the article it points to (links.target, else the first outbound link), not the aggregator's.
  2. Determinism. Decisions MUST be deterministic for a given recipe, seed and candidate set: they MUST NOT depend on the order in which the connector listed the candidates, nor on which request finished first. With a seed, a forced choice is a function of the seed, the task and the set of candidate ids. Without a seed, the first candidate listed wins.
  3. Order guarantee. Fetching and parsing MAY run in parallel, but outcomes MUST be committed (sampled, deduplicated, written) strictly in plan order (a follow-up task right after its parent), so that decisions do not depend on the worker count or on latency. A terminal failure or a skip releases a task's turn; a task in transport fallback keeps it. lookahead bounds how many tasks may be fetched or held ahead of the commit cursor. Limit. This makes decisions over the admitted candidates equal to those of a one-worker run. It does not make the admitted set equal: caps (which task is the last to start under caps), a challenge stop, a cancellation or a crash can change which tasks run, and so which candidates exist.
  4. Known items are not sampled. An item that already exists in the store (same id, or same canonical URL) uses no quota or cap, is never dropped by sampling, and gets its new observation as usual.
  5. Journal. Every distinct candidate MUST get exactly one decision line in the run log (shape collect.sampling/v1), written before any counter moves: candidate (the item id), decision (kept or dropped), rule when dropped (no_metric, out_of_bands, band_quota, domain_cap), band, url, domain, seed, connector, taskId (<connector>/<task id>) and at. A dropped candidate writes no item, observation, pickup or seen key, and no actor that only it referenced. The report adds, per connector, sampled: { candidates, kept, dropped: { <rule>: n } }. A decision already in the journal MUST be reused on resume and the counters rebuilt from it.
  6. Several ids, one URL. Repeated ids and ids sharing one canonical URL are one candidate: one decision, applied to all its members.

Reference algorithm (informative)

Another implementation MAY choose differently as long as the rules above hold; this is what the reference does, so that two implementations can be compared.

  • Counter values. A candidate's value for a counter is the first numeric value for it in the observations of the same parse that name the item.
  • Grouping. Candidates are grouped by id; two groups sharing a candidate URL (the item's canonical URL, else its URL) merge. A group's representative is its member with the highest rank, ties broken by the smaller URL (a candidate with no URL sorts last), then the smaller id (UTF-16 code unit order). The rank of a candidate is its value of the first band counter it has a value for, else of the primary counter, else minus infinity. The decision is taken on the representative and applied to the whole group.
  • Order of decisions. The groups that are not already items are ordered by the representative's id sorted ascending, then shuffled with a Fisher-Yates shuffle (from the last index down, j = floor(rnd() * (i + 1))) driven by mulberry32((seed XOR fnv1a32(batchKey)) >>> 0), where batchKey is the task key <connector>/<task id> and fnv1a32 is the 32-bit FNV-1a hash over the string's UTF-16 code units. Without a seed the order is the order of first appearance in the listing. Decisions are taken in that order against counters that include the earlier tasks of the connector.
  • Host. The lowercase hostname of the URL (WHATWG parsing, no port), with one trailing dot and a leading www. removed; no public-suffix list. A candidate with no host counts against no domain cap.
  • Quota and cap counters are per connector and count kept candidates.

Dedup

An implementation MUST keep one item per identity and MUST NOT write a second item for a key it has already seen. Keys, from the strongest:

  1. Native id. The item id.
  2. Canonical URL. canonicalUrl, the key for a page that has no native id and a second key for one that has.
  3. Content fingerprint. contentId, an exact-text signal.
  4. Near-duplicate grouping (contentGroupId) is OPTIONAL and reserved: collect/v1 defines the field and no algorithm. An implementation that fills it SHOULD record the method in ext and MUST NOT treat a near duplicate as a verified pickup.

Id namespace. An item id and an actor ref have the form <source>:<rest>. The <source> is the text before the first colon: it MUST be 1 or more characters of letters, digits, ., _ and -, starting with a letter or a digit, and MUST NOT contain ..; stores file records by it. <rest> is free (it may contain colons). The source SHOULD be the connector id, and the engine's coverage matches a source to a connector's primary counter by item.source. A native id given as a number MUST be a safe integer; larger ids MUST be given as strings. The id of an item without a native id is <source>: followed by the lowercase hex SHA-256 of its canonical URL. A connector that serves several instances of one source (sourceInstance) shares one <source> prefix, so it MUST make <rest> unique across its instances (for example by including the instance in it): two instances MUST NOT produce the same id for different items.

Canonical URL, baseline (canonicalUrl(input)):

  1. Trim the input. Parse it with the WHATWG URL algorithm. If it is not an absolute URL, or its scheme is not http or https, return the trimmed input unchanged.
  2. Empty the fragment, the username and the password. Remove the port when it is the scheme's default. The scheme and host are those the parser gives (lowercase); the path keeps its case.
  3. Drop every query parameter whose name, compared case-insensitively, starts with utm_ or is one of the closed list: fbclid, gclid, dclid, gbraid, wbraid, msclkid, yclid, twclid, ttclid, mc_cid, mc_eid, ref_src, ref_url, igshid, _hsenc, _hsmi, mkt_tok.
  4. Sort the remaining parameters by name (comparison of UTF-16 code units), stably: the relative order of a repeated name is kept, so ?a=2&a=1 and ?a=1&a=2 are different keys.
  5. Serialise the query with the application/x-www-form-urlencoded serialiser (the one URLSearchParams.toString() implements); emit ? only when the query is not empty.
  6. Remove all trailing slashes from the path; a path of / becomes empty, so https://example.com/?a=1 is https://example.com?a=1.
  7. The result is scheme://host[:port]path[?query]. It is a dedup key only: the original URL MUST be kept next to it, and the function does not follow redirects, so the caller passes the final URL.

Two implementations that follow these steps produce the same key for the same input. A deployment MAY add a profile: extra, named, source-specific stripping applied before step 3. A profile is not part of collect/v1, and keys from different profiles MUST NOT be mixed in one store.

Non-normative profile (video hosts). The reference also removes the si share parameter, but only on the hosts of a video site (youtube.com, youtu.be, with www., m. and music. prefixes ignored), because on other hosts si can carry meaning. A store that uses it MUST record that it does.

Content fingerprint. contentId is the lowercase hex SHA-256 of the UTF-8 bytes of the normalised text: Unicode NFKC, lowercase, every run of punctuation and symbol characters (Unicode categories P and S) replaced by one space, whitespace runs collapsed to one space, trimmed. Text that normalises to nothing has no contentId, so unrelated empty items never share one. The same text under two URLs gives two items that share one contentId: a content match is a signal, not a merge.

Seen index. The seen index maps each key (id:<id>, url:<canonical URL>, content:<contentId>) to the item that owns it. A key MUST NOT contain a newline or a tab. A new item whose id or canonical URL is already owned is a duplicate: it writes no item, it is counted as a duplicate in the report, and the owner receives its observations, links and pickups (an alias is resolved to its owner). A match on the canonical URL records the new id as an alias of the owner. A contentId match does not merge.

Run provenance

A run MUST leave enough to answer "where did this number come from" and to resume.

Raws. Every fetched body MUST be stored as the engine received it from the transport, that is, after any redaction the transport applied (the api transport redacts its secret; the engine does not rewrite bodies). Each is addressed by the lowercase hex SHA-256 of the bytes as stored, and indexed (collect.raw-index/v1) with: the store ref, connector, hash, extension, byte count, URL, fetch time, HTTP status, transport, runId, the task key (<connector>/<task id>) of the task that fetched it, and the failure cause when the fetch failed. The index line is appended on every fetch, failures included, and a body returned with a failure is kept. A ref is opaque to consumers. The address of a body is a function of the connector, the month (UTC) of the fetch time, the hash and the extension: the same bytes, extension and connector in the same month share one address and are stored once; the HTTP status, the URL and the transport are not part of it. An item's rawRefs and an observation's rawRef point at these refs.

Redaction scope. The engine removes the values of secrets it resolved through its secrets port (those of 4 or more characters, in raw, percent-encoded, form-encoded and JSON-escaped forms) from events, task records, the plan, the report, onEvent payloads and the message of a run error. It does not rewrite raws, items, observations, actors or pickups. A connector and a custom transport MUST sanitise their own outputs: no secret in a raw, a URL, a task params value or a record. The api transport redacts its own (§Transport).

The run record. At start a run MUST write, in this order of importance:

  • the run record (collect.run/v1): the run id, the creation time, the recipe as parsed with its defaults filled (so workers is 8 if it was omitted and a source's queries is [] if it was omitted), and the recipe hash: the lowercase hex SHA-256 of the UTF-8 text of that defaulted recipe serialised as JSON with object keys sorted ascending at every level and undefined values omitted, no whitespace; and optionally the connector modules the run was started with;
  • the root plan (collect.plan/v1 entries), written whole and atomically before any task runs: per task, the key <connector>/<task id>, the connector, the order ([connector index in the recipe, plan index]) and the task payload ({ id, kind?, params }).

The task log (collect.task/v1) is an append-only list of task states. The last line for a task key is its state. A task is pending, started, done, failed or skipped. A line carries: the key, the connector, the status, the transport, a reason (skip reason, or failure message), a cause for a failure, the global order (an array of integers; a follow-up appends its index to its parent's order), the counters of what the task did (items, new items, duplicates, observations, metric values, duration), the escalations, the task payload (so the run can be rebuilt from the log alone) and the time. Event lines (type, time, data) and the final report (collect.report/v1) are kept as well.

The report has, per connector: status ok, partial, failed or skipped; task counts; new items; observations; duplicates; failures by cause; escalations; duration; the sampling summary; coverage. A connector is skipped with a reason when it could not run; failed when every task failed, or on the two shape checks below; partial when some task failed, was skipped or is pending. The two shape checks apply to a connector with at least one done task: the run returned no items (the sum of items over its tasks is 0) and every counter is missing (the connector declares counters and the sum of metric values is 0). They exist so that a parser broken by a page redesign shows as failed and not as an empty success.

Coverage. Coverage is computed over the whole store, not only over the run. The cells are keyed by (platform = item source, format, language, subject). A missing format or language reads unknown; an item with no subject counts in the subject none; an item with several subjects counts in each subject's cell. Each cell holds counts (never shares): items; withAuthorAudience (the item's author has a followers or subscribers reading with a value; karma never counts); withPrimaryMetric (the item has an observation with the connector's declared primary counter; a source with no connector or no primary counter never counts); withAge (postedAt present and at least one observation); withAuthorId (authorRef present); withUniqueContent (the contentId is shared with no other item); and eligible (audience, primary metric, age and author id all present). The per-connector coverage of a report is the cells of that connector's source.

Record keys. Each observation and pickup written by the engine carries a recordKey, defined exactly as: the lowercase hex SHA-256 of the UTF-8 bytes of the compact JSON array (no whitespace)

[runId, taskKey, rawHash, kind, index]

where runId is the run id; taskKey is <connector>/<task id>, the same string as the record's taskId; rawHash is the lowercase hex SHA-256 of the raw's stored bytes (the raw the record was parsed from); kind is the string observation or pickup; and index is the zero-based position of the record in the observations (respectively pickups) array that parse returned for that raw, as a JSON number. A reader MUST keep the first record it reads of a given recordKey and drop later ones. Records without a recordKey (not written by an engine) are always kept. Consequences: a task redone after a crash that fetched the same bytes does not double-count, a page whose bytes changed is a new raw and gives new readings, and distinct readings with equal values (different indices) are all kept. Known limitation: two raws of one task with identical bytes share their keys, so the second is dropped as a redo.

Resume. resume(runId) is an explicit action by the operator. The engine MUST:

  1. reload the recipe as frozen in the run record, the plan, and the task log (if no plan was written, plan again from the frozen recipe; an absent plan is never read as an empty one);
  2. never fetch again a task whose last state is done;
  3. retry every other task (pending, started, failed, skipped) in its recorded global order, from its first usable transport: the fallback progress of the earlier attempt is not remembered, and a transport that was not provided before may be used now;
  4. re-check each connector against the registry, the secrets and the transports available now: a connector that is no longer registered, or has no usable transport, or whose key secret is missing, has its non-done tasks recorded skipped with that reason (a task already recorded with the same reason is not written again). Connectors that came back are tried normally;
  5. start with no challenge stop: a stop does not carry over;
  6. rebuild the sampling counters from the journal and reuse earlier decisions;
  7. report on the whole run, earlier attempts included.

Cap accounting. A task is charged when its started line is written, once per task key, before it is fetched, so that a crash after the start still counts. The per-connector budget is recipe.caps.perConnector when set, otherwise the connector's pace.maxTasksPerRun (the recipe wins; they are not combined); caps.total counts across connectors. A task that would exceed a budget is recorded skipped with a reason that names the cap, and takes no charge. On resume the charges are restored from the log: a task whose last state is done, failed or started counts as already charged (to its connector and to the total), so redoing it takes no new budget; a pending or skipped task counts as not charged and charges when it starts.

Known limitation (cap accounting). The restoration reads only a task's last state. A task that was charged and whose last state is then skipped loses its charge on the next resume and charges again when it restarts. That happens when (a) a request-level missing secret skips a task after its start, (b) a connector's challenge stop skips a task after its start, and (c) a resume records skipped (connector unavailable) over a started task. The effect is that, across resumes, caps.perConnector, pace.maxTasksPerRun and caps.total can be exceeded by the number of such tasks. An implementation SHOULD instead remember that a task was charged (for example by counting any task that has a started line), but collect/v1 guarantees only the behaviour above.

Replay. Because parse is pure and raws are stored, an implementation SHOULD offer a rebuild that parses stored raws again into a new store with no network, using for each raw the task that fetched it (found through the task key in the raw index). It MUST NOT rewrite the source store.

Reference implementation note (informative). The reference rebuild takes the task from the run log; for a raw of an older store that has no task key it invents a synthetic task, counts and warns about it, and exits with a partial status. The result is written at the current schema version with the raw bodies and index copied.

One writer. A store MUST be written by one writer at a time (a lock held for the whole run), and a log append MUST NOT interleave with another. A reader MUST tolerate an unreadable line (for example a torn last line after a crash) by skipping it and reporting the count, and MUST NOT throw on it.

Storage layout (informative)

The reference stores records under a root directory. Another store is conforming if it provides the same operations (raws by content hash, items with last write wins, append-only observations, actors and pickups, a seen index, run logs, a writer lock). The layout of the reference:

<store>/
  collect.json                 { "schemaVersion": 1 }
  raw/<connector>/<yyyy-mm>/<sha256>.<ext>.gz
  raw/index.jsonl
  items/<source>.jsonl         last line for an id wins
  observations/<source>.jsonl  append-only
  actors/<source>.jsonl        append-only
  pickups.jsonl                append-only
  seen.idx
  runs/<runId>/                recipe.json, plan.jsonl, tasks.jsonl, sampling.jsonl, events.jsonl, report.json

A store SHOULD carry a schema version, refuse a newer one than it knows, and migrate an older one in idempotent steps. A stale lock from a dead process on the same host MAY be broken automatically; a lock from another host MUST NOT.

Bridge to AIP-10 (informative)

AIP-10 ingests immutable knowledge.source/v1 files that an LLM curates into entries. A collected item maps onto one as follows. The bridge itself is not part of collect/v1 and its package is not published at the time of writing; this section describes the intended mapping so that implementations converge.

COLLECTAIP-10 source
title, else the first words of texttitle
text (and parts rendered in order)the source body
canonicalUrl, else urlthe origin URL of the source
idthe source id, so re-import is idempotent
publishedAt, else postedAtthe source date
subjects[].labelcandidate tags or topics, with the provenance kept
rawRefs, runId, firstSeenAtprovenance fields, so a curated entry cites the stored body
extcarried in vendor extensions, never interpreted

An import MUST NOT edit the item (AIP-10 sources are immutable) and SHOULD skip an item whose textTruncated is true unless the importer says so. A submission with a links.target SHOULD import the target when it was collected, and the submission only as context.

Rationale

Why a recipe, a connector and a transport, three things? The recipe says what to collect and is portable. The connector says what a source means and is the only place a platform is named. The transport says how to reach a page and is the only place network policy lives. Keeping them apart lets a recipe run against a different connector, a connector gain a transport, and a transport policy change without touching either.

Why plan / fetch / parse? A deterministic plan makes a run resumable without trusting a log of what a connector decided. Confining the network to fetch and keeping parse pure means every parser fix can be replayed over stored raws with no network, and a number can be traced to the exact bytes it came from.

Why "missing is never zero"? Because a zero looks like data. The three reasons (not_exposed, hidden, blocked) turn a gap into information.

Why is a challenge a hard stop in the browser? The browser is the last transport. A challenge there means the source is asking for a human; every further request is a bypass attempt or a wasted one. Stopping the connector keeps the other connectors going and keeps the operator in control.

Why per-plan-order commit? Without it, the sample would depend on which request happened to answer first, and two runs of one recipe could keep different items. The cost is bounded buffering (lookahead).

Why recordKey and not a database transaction? Stores can be plain append-only files. An identity derived from run, task, raw and position makes a redone task idempotent for readers without a transaction.

Alternatives. Extending AIP-18 COLLECTION was rejected: it is a hand-edited record type, not a fetch pipeline. Putting the pipeline in AIP-10 was rejected: KNOWLEDGE starts after the source exists. Reusing AIP-63 recipe/v1 was rejected: it drives one site's browser tools and has a closed manifest with no notion of sampling, observations or provenance.

Reference Implementation

  • @agentproto/collect (packages/collect): the zod schemas (CollectItem, Observation, Actor, Pickup, Recipe, RunReport, Coverage), defineConnector and the registry, the transport contracts, the engine (createCollector, run, resume), sampling, canonicalUrl and textFingerprint, a memory store and an on-disk store, an HTTP transport and an API transport (Node entry).
  • @agentproto/collect-cli (packages/collect-cli): the collect binary (init, connectors, doctor, run, resume, runs, status, export, reparse).

Both are Apache-2.0. The browser transport is a contract in the reference; a shipped implementation of it is not part of the packages above at the time of writing, and the CLI reports a connector that needs it as unusable. The JSON Schemas in resources/aip-79/draft/ are generated from the reference zod schemas and then completed with the cross-field rules JSON Schema can express.

Non-normative examples

These illustrate the shapes. Nothing here is part of the contract and no source is endorsed.

  • An aggregator submission linked to its article. An item of kind submission with links.target pointing at the article. Its points and comments are counters (primary: points). The article is collected as a second item of kind article. A pickup of method link may record that a later page links back to the submission. See examples/item.json and examples/pickup.json.
  • A social post with rounded counters. An observation whose metrics hold likes: 1200 and whose rawValues hold "1.2K"; views is listed in missing as not_exposed. The author is an actor with a followers reading and a separate karma reading. See examples/observation.json and examples/actor.json.

Backwards Compatibility

New. No AIP is replaced. The doctype ids collect.recipe/v1 and the four record doctypes are new and do not collide with recipe/v1 of AIP-63 or with the AIP-18 collection/v1 doctypes.

Security Considerations

  • Secrets. A connector names a secret, never holds one. The guarantee is scoped to what an implementation controls (§Run provenance, Redaction scope): the engine keeps secret values it resolved out of its events, task records, plan, report and error messages, and the api transport out of what it returns. Bodies fetched by other transports, and records a connector builds, are not scrubbed by the engine: connectors and custom transports MUST NOT emit secrets into them. Values under four characters cannot be scrubbed reliably and SHOULD NOT be used as secrets.
  • Credential leaks on redirect. Credential headers MUST be dropped when a redirect changes origin. A credential in a URL MUST refuse such a hop.
  • Access controls. COLLECT does not authorize anything. A collector MUST respect the access a source grants the operator, MUST NOT try to defeat a challenge, paywall, rate limit or access control, and SHOULD honour a source's published terms and robots rules. Pacing (pace.delayMs, the per-host gate) is a normative minimum of politeness, not a guarantee of permission.
  • Browser. A logged-in browser session is ambient authority. The read-only and own-pages-only rules bound it; a session-level connector SHOULD run against a profile dedicated to collection.
  • Untrusted content. Everything fetched is untrusted: text, markup, links and ext. A consumer MUST NOT execute it, and an importer that feeds collected text to an LLM (for example the AIP-10 bridge) MUST treat it as data that may contain instructions, not as instructions.
  • Personal data. Items and actors are public personal data when they name people. A deployment SHOULD define retention and deletion, and a store SHOULD allow removing an actor and the records that reference it. Audience readings describe public counters only.
  • Raw bodies. A raw can contain content the operator did not intend to keep (a page with a signed-in banner, a tracking identifier). Storage SHOULD be access-controlled like any store of fetched pages.
  • Resource bounds. Size caps, timeouts, caps on tasks and a bounded lookahead keep a hostile or broken source from exhausting the collector.

Open questions

  • Known limitation: cap accounting across resumes (§Run provenance, Cap accounting): a charged task whose last state is skipped is charged again after a resume, so budgets can be exceeded across resumes.
  • Known limitation: identical raws. Two raws of one task with the same bytes share record keys, so the second raw's readings are dropped as a redo.
  • Known limitation: actors. Actor records have no redo key; a redone commit may write an identical actor again.
  • Known limitation: non-transactional commit. A crash can leave a partial commit; it is safe to redo but is visible until the task is redone.
  • A declaration for how a session-level connector checks that its session is still valid.
  • A near-duplicate grouping method for contentGroupId.
  • A normative view that flattens items, their latest observations and their author's audience (the reference CLI reserves the name and does not provide it yet).
  • Whether the on-disk layout should become a contract once a second store implementation exists.

See also

  • AIP-10 KNOWLEDGE: where collected items can be ingested.
  • AIP-18 COLLECTION: typed record collections, a different concept.
  • AIP-63 BROWSER: site recipes (recipe/v1), a different doctype.

Resources

Supporting artifacts for AIP-79. Links open the file on GitHub — markdown and JSON render natively in GitHub's viewer. Browse the full resource tree →