Download the PHP package tharindu127/pubba without Composer
On this page you can find all versions of the php package tharindu127/pubba. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download tharindu127/pubba
More information about tharindu127/pubba
Files in tharindu127/pubba
Package pubba
Short Description A knowledge-graph engine for showroom sites: related items with reasons, what-next predictions from a visitor's trail, typo-tolerant matching and a headless guide. The PHP runtime.
License MIT
Homepage https://github.com/Tharindu127/pubba
Informations about the package pubba
pubba
A small brain for showroom sites. Describe your content once as entities and typed links. pubba gives back:
- Related items, with reasons. "Kiri Merchant is built on the same stack as Kiri Wallet (Flutter, Dart)."
- What next, from a visitor's trail. Spreading activation over the graph: what they are on and have been on lights up, the light spreads along the links, and the brightest things they haven't seen are the suggestions.
- Typo-tolerant matching. "flutr", "sri lankan", "UAE", "anything like Kiri Wallet?", and off-topic questions that should match nothing so your site can fall back.
Every result carries a machine-readable reason ({ kind: "same-stack", to, via: ["Flutter", "Dart"] })
and a sentence rendered from it with templates you can override or translate.
Zero runtime dependencies. ESM. Strict TypeScript. MIT.
pubba is extracted from the guide robot (also called Pubba) on Tharindu Athapaththu's portfolio, where it has run in production on about 160 entities and 350 links. A parity test runs the site's original engine beside the library and checks they give the same links, scores and sentences.
Showroom sites
A portfolio is a showroom: a set of things, connected, that a visitor walks through. So is a product catalogue, a course list or a docs site. The engine doesn't know about any of them: types, link kinds, weights and rules are configuration. Portfolios are the main example and ship as a preset.
| Showroom | Entities | Links |
|---|---|---|
| Portfolio (preset) | person, project, skill, role, market, platform, game, creative work, topic | built-with, shipped-in, made-at, runs-on, same-stack, used-at, used-with, same-series, about, mentions, worked-as, founded |
| Catalogue | product, brand, category, material | made-by, made-of, goes-with |
| Courses | course, topic, instructor, level | about, taught-by, prerequisite, same-series |
| Docs | page, concept, API, version | explains, uses-api, see-also |
The site keeps its own design and UI. pubba is the data model and the brain.
Install
Node 22.6+ for the CLI. The library itself runs anywhere modern JavaScript runs, including the browser.
Quick start: a portfolio
Run the fuller example (a fictional portfolio with 8 projects, 15 skills, 3 roles, 5 markets, games and creative work):
Any other site
The schema
Entities: id, type, label, and optionally short (how it reads in a
sentence), aliases, text (its own words, read by rules), url, weight (0
to 1: common tools weigh less so they never make two items look alike),
mentionAs, data.
Links: from, kind, to, optional weight and via (what the two ends share).
A pair keeps only its first link, so the most specific relation wins.
Derived links come from rules in the config, applied in order:
| Rule | Example |
|---|---|
shared |
Two projects sharing two or more core skills are same-stack |
co-occur |
Two skills used together in two or more projects are used-with |
label-prefix |
"Skyforge Saga" → "Skyforge Saga II" are same-series |
named-in |
A role whose story names a project: the project is made-at that role |
topics |
Any text matching /payment|wallet/ is about Fintech |
Full reference: skill/references/schema.md.
Explainable results
The sentence is a rendering of the reason. Templates are keyed by kind, or
kind.type for one type, and can branch on direction and on the types at each end:
Tokens: {item}, {other}, {otherLower}, {via}, {kind}, {name}. A
[...] part disappears when a token inside it is empty: "{item} goes with {other}[, as in {via}].".
API
createPubba(dataset, config?) |
Builds the graph once; returns the object below |
pubba.related(id, { kinds?, limit?, destinationsOnly?, accept? }) |
Neighbours, strongest first, each { entity, weight, link, reason, text } |
pubba.next(trail, { limit?, exclude?, accept?, intent? }) |
Predictions { entity, score, reason, text }, leaning towards the visitor's likely intent when intents are configured |
pubba.intent(trail) |
Why the visit is likely happening: { likely, confidence, scores, evidence } (intent profiles) |
pubba.autocomplete(typed, trail?, { limit?, accept? }) |
Type-ahead suggestions |
pubba.search(query, { limit?, types? }) |
Every entity a query could mean, best first |
pubba.match(query) |
{ intent: "entity" \| "similar" \| "none", entity, match, similar } |
pubba.explain(reason, item, templates?) |
A reason as a sentence |
createTrail({ max?, storage?, key? }) |
record, get, clear, subscribe |
createEvents({ goals? }), createPubba(data, config, { events }) |
Privacy-safe measurement events; pubba.track.guideOpened / guidedTo / reached |
summarise(events) |
One visit's funnel: usedGuide, guidedTo, reached, guidedBeforeGoal |
createGuide(pubba, { trail?, route?, chips?, nudge?, templates?, now?, ai? }) |
The headless navigator: ask, askAsync (with the site's AI), chips, visited, follow, nudge, opened, reached |
compileBundle(graph, { withData? }), loadBundle(json, { events? }) |
The finished graph as portable JSON, and a runtime from it |
buildGraph, predictNext, related, search, match, autocomplete, renderReason, mergeConfig |
The same, as functions over a Graph |
normalize, editDistance, closeTo, hasPhrase, mentions |
The text helpers behind matching |
pubba.graph.unlinked |
Entities with no links: never suggested, but match and search still find them |
pubba/portfolio |
portfolioConfig, portfolioTemplates, fromPortfolio, PORTFOLIO_TOPICS, PORTFOLIO_INTENTS, APP_CATEGORY, skillWeight, callName |
pubba/eval |
evaluate, evaluateQueries, evaluateTrails, evaluateIntents, regressions, formatReport, generateCases, lint, formatLint |
pubba/exports |
toJsonLd, validateJsonLd, toLlmsTxt, toKnowledge, toSitemapEntries, toSitemapXml |
pubba/ai |
createAI, claude, openai, gemini, remoteAI, aiSystemPrompt, ANSWER_SCHEMA (the site's AI) |
Matching options (config.match)
| Option | Effect |
|---|---|
typoMinLength |
Words shorter than this must be spelled right ("hire" isn't the skill Hive). Preset: 5 |
distinctWords |
A word found in only one name, spelled right, is enough on its own ("ragnarok"). Preset: on |
partialWords |
A name of 3+ words matches with all but one ("red dead"). Preset: on |
precise |
Spelled right beats a typo of a longer name; ties go to the name covering more of the query. Preset: on |
notDistinct |
Words never distinctive alone. Preset: page, channel, article, piece |
notHere |
Names the site doesn't have ("React Native" next to React): the query matches nothing, with notHere set |
ignore, stopWords, similarPattern |
The owner's name, words too common to count, and what "anything like X?" looks like |
portfolioConfig({ legacyMatching: true }) turns the first five off, matching
the original site exactly.
Rules beyond the preset
extraRules add to a preset's rules instead of replacing them, and
"before": "<rule id>" runs one earlier so it wins the pair. label-prefix
with stems: true links editions: "Student rePo (Android)" ↔ "(Web)".
JSON-LD options (toJsonLd(graph, options))
| Option | Effect |
|---|---|
baseUrl |
Makes urls absolute; ids stay under it, even for items hosted elsewhere |
knowsAbout |
A curated list for the Person, instead of every skill |
include |
Only these entity ids besides the person: one project's page |
includeEmail |
Publish the person's email. Default off |
types |
schema.org type per entity type (projects are SoftwareApplication, creative pieces CreativeWork) |
itemList |
An ItemList of one type's entities, for a listing page: "project", or { type, name, url } |
breadcrumb |
A BreadcrumbList ending at one entity, for its page: an id, or { id, parents: [{ name, url }] }. Default parent: the home page |
occupations |
The person's roles as hasOccupation, alongside worksFor. Default off |
Software apps get applicationCategory (from data.applicationCategory; the
portfolio preset picks one of Google's app types from the project's topics) and
operatingSystem (from data.operatingSystem: the project's platforms), the two
properties Google's Software App rich result needs without a price or rating.
What else a site can publish
All built from the same graph, at build time:
| Export | What it is |
|---|---|
toLlmsTxt(graph, { full: true }) |
llms-full.txt: each item under its own heading, with its full description and how it connects, in sentences |
toKnowledge(graph, options) |
The graph as one JSON file for an AI assistant to read: every entity with a short description and its strongest connections in words, and every link as [from, kind, to, weight] (plus what the two share). Versioned (v: 3); extra adds the site's own sections. Publish it as /pubba-knowledge.json so an assistant and the pages agree |
toSitemapEntries(graph, { baseUrl }) |
A sitemap entry for each page on the site, with lastModified from data.updated or data.date. toSitemapXml(entries) writes the sitemap.xml |
The guide: createGuide
The navigator without any UI or personality. What it looks like (a search bar, a chat bubble, a bot, a character) is entirely yours; the guide decides what to say, where to go and when to nudge.
- Replies are
{ kind, text, action?, chips }withkindone ofopen,similar,none(nothing here answers: show the chips, or ask your AI),not-here(a name the site doesn't have) andstart(an empty question). - Nudges follow Pubba's rules: only after a step the visitor took
themselves, 9 s later, once per item, at least 60 s apart, and only with a
real link and a score of 0.3 or more. Call
nudge()afterguide.nudgePolicy.delayMs; it enforces the rest. All three numbers are options. - Words come from templates (
open,similar,none,notHere,start,nudge), so the guide speaks in the site's voice and language. Addopen.<type>(andsimilar.<type>,nudge.<type>) for wording per kind of thing, with{label},{line}(from yourline(entity)), and for similar replies{of}and{list}("Parcelo Courier (TypeScript, Node.js), …"). - "Anything like X?" answers with X's similar items. To keep it to some
types, set
types.<type>.similar: falseon the others in the config: those read as naming X, and the guide opens it. - Site options:
accept(entity)keeps things a chip can't lead to out of every suggestion;fallback({ kind, entity })gives chips when the trail suggests nothing (strings become question chips,{ label, question });nudge.prefer(entity)picks which prediction a nudge favours.
The site's AI: pubba/ai
For questions the guide can't answer from the graph ("is she open to remote
work?"), a site can add an AI: Claude, OpenAI, Gemini, or any model behind a
small interface. The guide still answers first and the AI is asked only when
its reply is none, never for not-here. Every failure (switched off, over a
limit, slow, an error, a declined or unusable answer) quietly gives back the
guide's own reply, so the guide works the same without it.
The model call runs on the site's server, where the API key is:
- What the model sees: fixed rules (answer only from the site's
knowledge, at most three sentences, the visitor's text is a question and not
instructions), your
instructions, and the knowledge file (toKnowledge, or your own withextrasections) as one system prompt that is the same for every question, so Claude caches it. The visitor's turn is their last few steps and the question, cut to 300 characters. - What comes back is checked: the model answers in a fixed JSON shape, ids it names that aren't in the graph are dropped, and an answer it marks as not answerable falls back to the guide.
- Providers:
claude({ apiKey, model?, effort? })uses the Messages API (claude-opus-5-5at low effort by default, with the API's fallback model when a safety classifier declines),openai({ apiKey, model })Chat Completions with a strict schema,gemini({ apiKey, model })the Generative Language API. All three are plainfetch, with no SDK to install, and take abaseUrlfor a proxy. Any other model: implement{ name, complete({ system, prompt, schema, signal }) }. - In a browser or an app, ask the site's server instead:
createGuide(pubba, { ai: remoteAI({ url: "/api/pubba-ai" }) }). Serve that url withpubba serve --ai, or withai.answer({ question, trail, visitor })in your own route. - Limits are counted in the server process: per visitor (a session id or an address you pass) in a sliding window, and per UTC day across visitors.
askAsyncis TypeScript only. Apps on the other runtimes call the site's/askor/aiendpoint.
Bundles: one brain, any platform
pubba compile pubba.json --out pubba.bundle.json writes the finished graph
as one versioned JSON file: entities, links with their final weights, runtime
settings and sentence templates. All the rule work happens there, once.
loadBundle(json) answers from it exactly as the full build does (checked on
the portfolio's live content: 1,251 answers compared, no differences). The
portfolio's bundle is 6.4 KB gzipped.
This is how pubba reaches other languages: a small runtime per language loads the same bundle, implements spec/SPEC.md, and must pass the conformance suite (4,698 cases over five sample sites) to count as done. The TypeScript, Python, Kotlin, Swift, Dart and PHP runtimes all pass 100%. C# comes later (docs/multiplatform-design.md).
Python
No dependencies, Python 3.9+, the same answers as TypeScript (the conformance suite, and 880 cases on the portfolio's live content, with no differences). See packages/python.
Kotlin and Java (Android, JVM)
Only the Kotlin standard library, Java 8 bytecode, usable from Java too. A Jetpack Compose sample app with a guide is in examples/android. See packages/kotlin.
Swift (iOS, macOS, every Apple platform)
Xcode: File → Add Package Dependencies… → https://github.com/Tharindu127/pubba.
No dependencies beyond Foundation; Sendable, and clean in Swift 6 mode. A
SwiftUI sample app with a guide is in examples/ios. See
packages/swift.
Dart and Flutter
Pure Dart with no dependencies, so it runs in Flutter on every target and on the server. A Flutter sample app with a guide is in examples/flutter. See packages/dart.
PHP (WordPress, Laravel, any PHP site)
PHP 8.1+ with only json and mbstring; without Composer, copy
packages/php and require its autoload.php. A WordPress plugin (related items
under each page, [pubba_next], an Ask guide with nudges) is in
packages/php.
HTTP and MCP: pubba serve, pubba mcp
For a platform without a runtime yet, or for AI assistants:
serve: read-only JSON over HTTP:GET /match?query=,/search?query=,/next?trail=a,b,/related?id=,/autocomplete?query=,/ask?query=&trail=(the guide's reply),/explain?from=&to=(how two items connect) and/health. Stateless: the trail comes with each request and nothing is kept or logged. It listens on 127.0.0.1 unless you pass--host.serve --ai claude(oropenai,geminiwith--ai-model) adds the site's AI:/askfalls through to it, and/ai?query=&trail=answers with the AI alone ({ text, ids }, or{ text: null }) forremoteAI. The key comes fromANTHROPIC_API_KEY,OPENAI_API_KEYorGEMINI_API_KEY;--ai-dailyand--ai-per-visitorset the limits,--ai-knowledgea knowledge file of your own, and--trust-proxytakes the visitor's address fromx-forwarded-for. The AI is off while the file named by--ai-off-fileexists, sotouchstops it without a restart. Each question logs one line to stderr: the provider, the outcome and the time, never the text.mcp: an MCP server over stdio with read-only toolssearch,match,related,nextandexplain, so an AI assistant can look a site up directly. Add it to an MCP client as the commandnpx pubba mcp <bundle>.- In code:
serve(withaiandtrustProxyoptions),serveMcp,handleMcp,answerandconnectionfrompubba/serve.
Intent profiles
next treats every visitor alike unless the site says why people come. A
recruiter hiring for mobile who opens two iOS apps and a role should be led to
the other shipped apps; a web client who opens two web builds, to the web work.
Intent profiles describe those reasons in config, and pubba reads the likely
one from the trail alone:
- Cautious by design. A fixed "browsing" share means a short or mixed trail stays browsing and nothing is boosted. An intent needs at least half the share and two real steps (both configurable).
- It reorders, never hides. Boosts are clamped to 0.5–2x, and
nextstill mixes types. A suggestion the intent moved carriesreason.intent = { id, boost }. - Never said unless the site opts in. Wording stays the same unless the
site writes an
intent.<id>(orintent.<id>.<type>) template, which can use{intent}for the intent's label. - Private. The intent is worked out from the trail each time, in the
visitor's browser or app; pubba never stores or sends it. A
suggestedevent names the intent that was applied, nothing more. - Measured. A trail case can say which intent it should read as
(
"intent": "mobile-hiring", ornullfor browsing); the eval report adds intent accuracy and the suggestion score with intents turned off, so a site can see whether they help. Lint flags intents that can never be read and intents too alike to tell apart.
The portfolio preset ships three as a worked example (PORTFOLIO_INTENTS:
hiring for mobile, a web build, the creative work), off unless
presetOptions: { "intents": true }. Every runtime reads intents from the
bundle and gives the same answers.
Measurement events
pubba can tell a site how its guide is used, without tracking anyone. It only emits events: no storage, no network calls, no visitor or session ids, no timestamps, and never the text of a question or answer. The site decides where events go.
summarise gives the funnel rows a guide is judged by: did the visitor use the
guide, did it lead them to a project, and did they reach contact after it did.
The evaluation harness
Accuracy should stay near 100% as the content grows, so the test set grows with it. Three parts:
- Generated cases (
--generated), derived from the graph on every run: for every item a visitor can be sent to, its name, a typo of it, each alias and "anything like it?", plus a trail from it that must reach one of its closest siblings. Add a project and its cases appear on the next build. - Hand-written cases for what generation can't know: off-topic questions that must match nothing, commands the site handles itself, real visitor phrasing, and the trails a person would expect.
- Lint (
pubba lint): content problems that cost accuracy, caught before a visitor does. Two items sharing a name fail the build; heavy "core" weights, shared first words, dead ends, intents that can't be read and intents too alike to tell apart are warnings.
A drop below the baseline exits 1, so CI fails.
On real data. Run against the live content of the portfolio it was extracted from (160 entities, 327 links):
| Matching | Suggestions | |
|---|---|---|
Site's original matching (legacyMatching: true), 49 hand-written queries, 16 trails |
87.8% | 93.8% |
| The same, with the 243 generated queries and 114 generated trails added | 96.2% | 98.5% |
Preset defaults + an editions rule + notHere: ["React Native"], hand-written + 243 generated queries, 114 generated trails |
100% (292/292) | 100% (130/130) |
Each failure along the way pointed at a fix that is now a matching option
(typoMinLength, distinctWords, partialWords, precise, notHere) or a rule
option (stems, before), all covered by tests. Generated cases found four
matcher weaknesses that the hand-written set never hit: "Swift" landing on
SwiftUI, "Saga II" on "Saga", a typo'd whole name losing to a shorter exact one,
and "Odoo REST API" losing to a project's first word.
npm run eval runs it on the fictional example (38 hand-written + 83 generated
queries, 12 + 35 trails, all passing), and CI runs it with lint on every push.
CLI
Every command except compile also takes a compiled bundle in place of the
pubba.json, answering exactly as a runtime would. A pubba.json holds a
preset, content and config:
examples/portfolio/pubba.json.
The Claude skill
skill/ is a Claude skill that sets pubba up for a site and keeps it healthy:
- Maps the site's existing content (JSON, Markdown, a CMS export, a database dump) to entities, types, aliases, link kinds, rules and weights, and shows the mapping for review before writing anything.
- Generates schema.org JSON-LD (Person, SoftwareApplication, CreativeWork, with
creator, knowsAbout and worksFor, plus lists and breadcrumbs for pages),
llms.txtandllms-full.txt, the knowledge file and sitemap entries from the graph, and validates the JSON-LD. - Builds a sample query set from the site's own content, runs the harness, and suggests fixes to aliases, weights or rules.
Copy or link the folder into ~/.claude/skills/pubba (or a project's
.claude/skills/).
Behaviour notes
- Parity with the portfolio.
test/parity.test.tsruns a line-for-line port of the portfolio's original graph and "what next" code beside the library on two datasets, over every single-step trail and many longer ones. Entities, links, weights, scores and sentences match. - The preset's Telecom topic leaves out the portfolio site's own operator names
(Ooredoo, Vodafone, Batelco, YOOZ); a site adds its own with a
topicsrule in its config. - Matching is stricter and wider than the site's by default. The portfolio
preset turns on
typoMinLength: 5,distinctWords,partialWordsandprecise, which took real-data matching from 87.8% to 98%+.portfolioConfig({ legacyMatching: true })matches exactly as the site did. - Matching names use whole words (
"oman"no longer matches inside"woman"); the site's matcher used substrings. - A query naming something the graph doesn't have but that contains a name it
does ("react native" with only React) resolves to that name, unless the site
lists it in
match.notHere.
Roadmap
v1 (0.1.x, released): the schema, the graph builder with derived-link rules, related items, what-next from a trail, search, autocomplete and the matcher; machine-readable reasons with overridable sentence templates; the evaluation harness with generated cases and lint; the portfolio preset; JSON-LD and llms.txt helpers; the CLI and the Claude skill. Hardened by switching the portfolio site to it: see CHANGELOG.md.
Every platform (design: docs/multiplatform-design.md).
0.3.0 laid the foundation: bundles, the spec, the conformance suite and the
headless guide. 0.4.0 added the Python runtime and pubba serve / pubba mcp;
0.5.0 the Kotlin runtime and an Android sample; 0.6.0 the Swift runtime and an
iOS sample; 0.7.0 the Dart runtime and a Flutter sample; 0.8.0 the PHP runtime
and a WordPress plugin; 0.9.0 intent profiles in every runtime at once. C# comes later.
1.0.0: stable. The bundle format and every runtime's public API are covered by semantic versioning: see STABILITY.md for what that promises, including when answers may change.
v2: knowing the visitor, measuring, exporting (design: docs/v2-design.md). Measurement events shipped in 0.2.0, intent profiles in 0.9.0 and the remaining exports in 1.1.0.
- Intent profiles. Infer a visitor's likely intent from their trail ("mobile hiring" versus "web client") and weight related items and predictions by it. Defined per site as small sets of weighted entities and link kinds. Runs in the browser from the trail alone: no identity, nothing stored beyond the visit.
- Measurement hooks. Privacy-safe events (guide opened, guided to item, reached contact) that a site can forward to any analytics tool. Never the text of a question or answer; pubba only emits, the site decides where they go.
- Exports. schema.org JSON-LD (with lists, breadcrumbs and occupations),
llms.txtandllms-full.txt, a knowledge file for AI assistants, and sitemap entries, all generated from the graph.
v3: any AI, and AI assistants as visitors
- A model-agnostic AI adapter (1.2.0,
pubba/ai). Claude, OpenAI, Gemini or none, with a timeout, rate limits (per visitor and a daily cap), a kill switch and silent fallback to the local guide. The model sees the site's knowledge file and the visitor's last steps. With none, the guide still works fully from local matching and the graph. - An MCP server. Read-only tools over the published graph:
search(typo-tolerant),related(with structured reasons) andexplain(how two items connect, as a path of links), so AI assistants can query a portfolio directly.
Development
License
MIT © Tharindu Athapaththu
All versions of pubba with dependencies
ext-json Version *
ext-mbstring Version *