/** * interview: ATProto-native interview infrastructure. * * Three custom lexicons under `network.sensemaker.*`: * - session — interview metadata, ties Q's together * - question — a question posed to a subject DID (lives on interviewer's PDS) * - answer — a response to a question (URI ref) (lives on answerer's PDS) * * Records live on the author's PDS and can be read by anyone with the URI. * Questions and answers can live on different repos; the link is by AT-URI, * so each side writes to their own PDS. * * Lexicon JSON files live in lexicons/network/sensemaker/ and can be published * as com.atproto.lexicon.schema records via `sensemaker interview publish-lexicons`. */ import { stringify } from "yaml" import { readFileSync, existsSync } from "node:fs" import { resolve as pathResolve, dirname, join as pathJoin } from "node:path" import { fileURLToPath } from "node:url" interface InterviewSessionRecord { $type: "network.sensemaker.session" title: string subject: string interviewer: string topic?: string introduction?: string createdAt: string } interface InterviewQuestionRecord { $type: "network.sensemaker.question" text: string subject: string session?: string topic?: string inReplyTo?: string context?: string createdAt: string } interface InterviewAnswerRecord { $type: "network.sensemaker.answer" text: string question: string sources?: string[] createdAt: string } // ============================================================================ // Auth + XRPC helpers // ============================================================================ async function createSession( pds: string, handle: string, appPassword: string ): Promise<{ accessJwt: string; did: string }> { const response = await fetch(`${pds}/xrpc/com.atproto.server.createSession`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ identifier: handle, password: appPassword }), }) if (!response.ok) { throw new Error(`Failed to create session: ${response.status} ${await response.text()}`) } const data = (await response.json()) as { accessJwt: string; did: string } return { accessJwt: data.accessJwt, did: data.did } } async function authenticate(): Promise<{ pds: string; jwt: string; did: string }> { const pds = process.env.ATPROTO_PDS || "https://bsky.social" const handle = process.env.ATPROTO_HANDLE const appPassword = process.env.ATPROTO_APP_PASSWORD if (!handle || !appPassword) { throw new Error( "Missing ATPROTO_HANDLE or ATPROTO_APP_PASSWORD env vars. " + "Set them (e.g., in ~/.bashrc, .env, or your shell), or pass via --env-file." ) } const session = await createSession(pds, handle, appPassword) return { pds, jwt: session.accessJwt, did: session.did } } async function putRecord( pds: string, jwt: string, did: string, collection: string, rkey: string | undefined, record: object ): Promise<{ uri: string; cid: string }> { const body: Record = { repo: did, collection, record } if (rkey) body.rkey = rkey const endpoint = rkey ? "putRecord" : "createRecord" const response = await fetch(`${pds}/xrpc/com.atproto.repo.${endpoint}`, { method: "POST", headers: { Authorization: `Bearer ${jwt}`, "Content-Type": "application/json", }, body: JSON.stringify(body), }) if (!response.ok) { throw new Error(`putRecord failed: ${response.status} ${await response.text()}`) } return (await response.json()) as { uri: string; cid: string } } async function getRecord( pds: string, did: string, collection: string, rkey: string ): Promise<{ uri: string; cid: string; value: unknown } | null> { const params = new URLSearchParams({ repo: did, collection, rkey }) const response = await fetch(`${pds}/xrpc/com.atproto.repo.getRecord?${params}`) if (!response.ok) return null return (await response.json()) as { uri: string; cid: string; value: unknown } } async function listRecords( pds: string, did: string, collection: string, limit = 50, cursor?: string ): Promise<{ records: Array<{ uri: string; cid: string; value: unknown }>; cursor?: string }> { const params = new URLSearchParams({ repo: did, collection, limit: String(limit) }) if (cursor) params.set("cursor", cursor) const response = await fetch(`${pds}/xrpc/com.atproto.repo.listRecords?${params}`) if (!response.ok) { throw new Error(`listRecords failed: ${response.status} ${await response.text()}`) } return (await response.json()) as { records: Array<{ uri: string; cid: string; value: unknown }> cursor?: string } } /** Resolve a handle to a DID via the public AppView. */ async function resolveHandle(handle: string): Promise { const cleaned = handle.replace(/^@/, "") const response = await fetch( `https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(cleaned)}` ) if (!response.ok) { throw new Error(`Failed to resolve handle ${handle}: ${response.status}`) } const data = (await response.json()) as { did: string } return data.did } /** Resolve subject string to DID (accepts a DID as-is, otherwise treats as handle). */ async function resolveSubject(subject: string): Promise { if (subject.startsWith("did:")) return subject return resolveHandle(subject) } /** Resolve PDS endpoint for a DID via PLC directory or did:web. */ async function resolvePds(did: string): Promise { if (did.startsWith("did:plc:")) { const r = await fetch(`https://plc.directory/${did}`) if (!r.ok) throw new Error(`PLC lookup failed for ${did}: ${r.status}`) const doc = (await r.json()) as { service?: Array<{ id: string; serviceEndpoint: string }> } const svc = (doc.service || []).find(s => s.id === "#atproto_pds") if (!svc) throw new Error(`No #atproto_pds service in PLC doc for ${did}`) return svc.serviceEndpoint } if (did.startsWith("did:web:")) { const host = did.slice("did:web:".length) const r = await fetch(`https://${host}/.well-known/did.json`) if (!r.ok) throw new Error(`did:web lookup failed for ${did}: ${r.status}`) const doc = (await r.json()) as { service?: Array<{ id: string; serviceEndpoint: string }> } const svc = (doc.service || []).find(s => s.id?.endsWith("atproto_pds")) if (!svc) throw new Error(`No atproto_pds service in did:web doc for ${did}`) return svc.serviceEndpoint } throw new Error(`Unsupported DID method: ${did}`) } /** Parse an AT-URI into {did, collection, rkey}. */ function parseAtUri(uri: string): { did: string; collection: string; rkey: string } { const m = uri.match(/^at:\/\/([^/]+)\/([^/]+)\/(.+)$/) if (!m) throw new Error(`Invalid AT-URI: ${uri}`) return { did: m[1], collection: m[2], rkey: m[3] } } // ============================================================================ // Commands // ============================================================================ /** Create a new interview session record on the interviewer's PDS. */ export async function createInterviewSession(opts: { title: string subject: string topic?: string introduction?: string }): Promise { const { pds, jwt, did } = await authenticate() const subjectDid = await resolveSubject(opts.subject) const record: InterviewSessionRecord = { $type: "network.sensemaker.session", title: opts.title, subject: subjectDid, interviewer: did, createdAt: new Date().toISOString(), } if (opts.topic) record.topic = opts.topic if (opts.introduction) record.introduction = opts.introduction const result = await putRecord(pds, jwt, did, "network.sensemaker.session", undefined, record) console.log(stringify({ action: "session-created", uri: result.uri, cid: result.cid, title: opts.title, subject: subjectDid, interviewer: did, })) } /** Write a question record. */ export async function createQuestion(opts: { text: string subject: string session?: string topic?: string inReplyTo?: string context?: string }): Promise { const { pds, jwt, did } = await authenticate() const subjectDid = await resolveSubject(opts.subject) const record: InterviewQuestionRecord = { $type: "network.sensemaker.question", text: opts.text, subject: subjectDid, createdAt: new Date().toISOString(), } if (opts.session) record.session = opts.session if (opts.topic) record.topic = opts.topic if (opts.inReplyTo) record.inReplyTo = opts.inReplyTo if (opts.context) record.context = opts.context const result = await putRecord(pds, jwt, did, "network.sensemaker.question", undefined, record) console.log(stringify({ action: "question-created", uri: result.uri, cid: result.cid, subject: subjectDid, session: opts.session, text: opts.text.length > 200 ? opts.text.slice(0, 200) + "…" : opts.text, })) } /** Write an answer record. */ export async function createAnswer(opts: { text: string question: string sources?: string[] }): Promise { const { pds, jwt, did } = await authenticate() const record: InterviewAnswerRecord = { $type: "network.sensemaker.answer", text: opts.text, question: opts.question, createdAt: new Date().toISOString(), } if (opts.sources && opts.sources.length > 0) record.sources = opts.sources const result = await putRecord(pds, jwt, did, "network.sensemaker.answer", undefined, record) console.log(stringify({ action: "answer-created", uri: result.uri, cid: result.cid, question: opts.question, text: opts.text.length > 200 ? opts.text.slice(0, 200) + "…" : opts.text, })) } /** List sessions on a given DID's repo. */ export async function listSessions(opts: { repo?: string; limit?: number }): Promise { const targetDid = opts.repo ? await resolveSubject(opts.repo) : (await authenticate()).did const pds = await resolvePds(targetDid) const result = await listRecords(pds, targetDid, "network.sensemaker.session", opts.limit ?? 50) const sessions = result.records.map(r => { const v = r.value as InterviewSessionRecord return { uri: r.uri, title: v.title, subject: v.subject, interviewer: v.interviewer, topic: v.topic, createdAt: v.createdAt, } }) console.log(stringify({ count: sessions.length, sessions })) } /** List questions, optionally filtered by session URI. */ export async function listQuestions(opts: { repo?: string session?: string limit?: number }): Promise { const targetDid = opts.repo ? await resolveSubject(opts.repo) : (await authenticate()).did const pds = await resolvePds(targetDid) const result = await listRecords(pds, targetDid, "network.sensemaker.question", opts.limit ?? 50) const questions = result.records .map(r => { const v = r.value as InterviewQuestionRecord return { uri: r.uri, ...v } }) .filter(q => !opts.session || q.session === opts.session) console.log(stringify({ count: questions.length, questions })) } /** List answers, optionally for a specific question URI. */ export async function listAnswers(opts: { repo?: string question?: string limit?: number }): Promise { const targetDid = opts.repo ? await resolveSubject(opts.repo) : (await authenticate()).did const pds = await resolvePds(targetDid) const result = await listRecords(pds, targetDid, "network.sensemaker.answer", opts.limit ?? 50) const answers = result.records .map(r => { const v = r.value as InterviewAnswerRecord return { uri: r.uri, ...v } }) .filter(a => !opts.question || a.question === opts.question) console.log(stringify({ count: answers.length, answers })) } /** Render a session as a structured Q&A — fetches questions on the interviewer's PDS, then answers from each subject's PDS. */ export async function showInterview(sessionUri: string): Promise { const { did: sessionDid, collection, rkey: sessionRkey } = parseAtUri(sessionUri) if (collection !== "network.sensemaker.session") { throw new Error(`Not a session URI: ${sessionUri}`) } const interviewerPds = await resolvePds(sessionDid) const sessionRec = await getRecord(interviewerPds, sessionDid, collection, sessionRkey) if (!sessionRec) throw new Error(`Session not found: ${sessionUri}`) const session = sessionRec.value as InterviewSessionRecord const allQs = await listRecords(interviewerPds, sessionDid, "network.sensemaker.question", 100) const questions = allQs.records .map(r => ({ uri: r.uri, ...(r.value as InterviewQuestionRecord) })) .filter(q => q.session === sessionUri) .sort((a, b) => a.createdAt.localeCompare(b.createdAt)) let answers: Array<{ uri: string; record: InterviewAnswerRecord }> = [] try { const subjectPds = await resolvePds(session.subject) const allAs = await listRecords(subjectPds, session.subject, "network.sensemaker.answer", 100) const qUriSet = new Set(questions.map(q => q.uri)) answers = allAs.records .map(r => ({ uri: r.uri, record: r.value as InterviewAnswerRecord })) .filter(a => qUriSet.has(a.record.question)) } catch (e) { console.error(`[warn] could not fetch answers from subject's PDS: ${e}`) } const pairs = questions.map(q => { const a = answers.find(x => x.record.question === q.uri) return { question: { uri: q.uri, text: q.text, topic: q.topic, context: q.context }, answer: a ? { uri: a.uri, text: a.record.text, sources: a.record.sources } : null, } }) console.log(stringify({ session: { uri: sessionUri, ...session }, questionCount: questions.length, answerCount: pairs.filter(p => p.answer).length, pending: pairs.filter(p => !p.answer).length, qa: pairs, })) } /** Publish the lexicon JSON files as com.atproto.lexicon.schema records. */ export async function publishLexicons(opts: { dryRun?: boolean }): Promise { const { pds, jwt, did } = await authenticate() // Resolve lexicon files relative to the package root, not CWD. // src/interview.ts → ../lexicons/network/sensemaker const here = dirname(fileURLToPath(import.meta.url)) const lexDir = pathResolve(here, "..", "lexicons", "network", "sensemaker") const lexicons = ["question", "answer", "session"] for (const name of lexicons) { const filePath = pathJoin(lexDir, `${name}.json`) if (!existsSync(filePath)) { console.error(`[skip] missing lexicon file: ${filePath}`) continue } const json = JSON.parse(readFileSync(filePath, "utf-8")) as { id: string } const rkey = json.id if (opts.dryRun) { console.log(stringify({ action: "would-publish", rkey, file: filePath })) continue } const result = await putRecord(pds, jwt, did, "com.atproto.lexicon.schema", rkey, json) console.log(stringify({ action: "lexicon-published", rkey, uri: result.uri, cid: result.cid, })) } }