Merge pull request 'Connect Company and political House J.A.R.V.I.S. contexts' (#398) from code/jarvis-organisation-contexts into main

This commit is contained in:
unimatrix 2026-11-17 21:31:32 +00:00
commit 650617790a
6 changed files with 84 additions and 5 deletions

View file

@ -66,3 +66,16 @@ PR394 connects Company identity and Company/Politics MOTD through one `organisat
Official requested news can be seeded once from `scripts/news-announcements.json`, separately from development patchnote bundles; the existing news outboxes handle distribution. The summary explicitly identifies the unconnected J.A.R.V.I.S. posting work.
Register browsing follows the clan access convention: available to signed-in community users; individual company and political House profiles remain publicly readable. Anonymous register pages offer sign-in rather than returning organisation rows.
## J.A.R.V.I.S. organisation contexts
Company Exchange verifies the active company founder/CEO register, separately
from personal clan membership. It does not infer a charter, member count or quota
from legacy leadership records. Protected political Exchange verifies exactly one
current matching office deed, rejecting ambiguous, expired and unrelated terms.
Its membership remains office-deed driven; recruitment cannot appoint officeholders.
Both workspaces now load their scoped records and explain unavailable domain actions
without treating a legitimate workspace as a service failure. Company recruitment
still needs a verified company charter/member source and domain acceptance writer.
Political candidacy links to the existing election service. Neither read-only context
can spend promotion credits or reserve a fee. Shared clan recruitment remains live.

View file

@ -10,10 +10,17 @@ export function mountJarvisRecruitment({mine,post,applications,promotions,banner
post.classList.add('jarvis-posting');
async function refresh(changed=false){
const query=new URLSearchParams({kind:scope.kind||'clan'});if(scope.id)query.set('id',scope.id);
try{const data=await request('/api/jarvis/context?'+query);if(!active)return;context=data;banner.textContent='J.A.R.V.I.S. recruitment · Published listings and real clan applications.';const tier={basic:'Basic',original:'Keyed',royal:'Royal'}[data.charterKind]||'Organisation';eligibility.textContent=tier+' deed · '+data.recruitment.occupiedMembers+' / '+data.recruitment.memberLimit+' members · '+Math.max(0,data.recruitment.availablePlaces-data.listings.filter(r=>r.state==='open').length)+' unadvertised places.';renderMine();renderPost();renderApplications();renderPromotions();if(changed)onChanged();}
try{const data=await request('/api/jarvis/context?'+query);if(!active)return;context=data;if(!data.recruitment){renderOrganisationContext();return;}banner.textContent='J.A.R.V.I.S. recruitment · Published listings and real clan applications.';const tier={basic:'Basic',original:'Keyed',royal:'Royal'}[data.charterKind]||'Organisation';eligibility.textContent=tier+' deed · '+data.recruitment.occupiedMembers+' / '+data.recruitment.memberLimit+' members · '+Math.max(0,data.recruitment.availablePlaces-data.listings.filter(r=>r.state==='open').length)+' unadvertised places.';renderMine();renderPost();renderApplications();renderPromotions();if(changed)onChanged();}
catch(error){if(!active)return;banner.textContent=error.message;eligibility.textContent='Organisation authority could not be confirmed. Publishing remains unavailable.';for(const host of [mine,post,applications,promotions])host.replaceChildren(el('p',error.message));}
}
function renderMine(){mine.replaceChildren(el('h3','My recruitment listings'));const {wrap,body}=table(['Listing','State','Publishing fee','Action']);for(const listing of context.listings){const row=el('tr'),controls=el('td');if(listing.state==='open'&&context.canPublish)controls.append(action('Close listing',async()=>{if(busy||!await confirmAction('Close this listing?','The advertisement will be removed. An incurred publishing fee remains payable.'))return;busy=true;try{await request('/api/jarvis/cancel',{id:listing.id,revision:listing.revision});await refresh(true);}catch(error){banner.textContent=error.message;}finally{busy=false;}}));row.append(el('td',listing.title),el('td',listing.state),el('td',listing.feeMinor?amount(listing.feeMinor):'Free'),controls);body.append(row);}if(!context.listings.length){const row=el('tr'),cell=el('td','No listings have been published.');cell.colSpan=4;row.append(cell);body.append(row);}mine.append(wrap);}
function renderOrganisationContext(){
for(const host of [mine,post,applications,promotions])host.classList.add('jarvis-listing-card');
const company=context.kind==='company',noun=company?'Company':'Political House';banner.textContent='J.A.R.V.I.S. · '+context.name;eligibility.textContent=company?'Company management · verified founder or CEO.':'Current office deed · membership follows the election register.';
renderMine();post.replaceChildren(el('h3',noun+' listings'),el('p',context.publishingReason));applications.replaceChildren(el('h3',noun+' applications'),el('p',context.applicationReason));promotions.replaceChildren(el('h3','Promotions & delivery'),el('p','Promotions become available with supported organisation listings. No fee or credit is charged.'));
for(const [host,key,label]of [[post,'settings','Open organisation settings →'],[applications,'elections','Open elections →']])if(context.links?.[key]){const a=el('a',label,'jarvis-action');a.href=context.links[key];host.append(a);}
if(context.officeDeed){const box=el('dl');for(const [name,value]of [['Authority','Current office deed'],['Term ends',new Date(context.officeDeed.expiresAt).toLocaleString('en-GB')]])box.append(el('dt',name),el('dd',value));applications.append(box);}
}
function renderMine(){mine.replaceChildren(el('h3',context.kind==='clan'?'My recruitment listings':'My organisation listings'));const {wrap,body}=table(['Listing','State','Publishing fee','Action']);for(const listing of context.listings){const row=el('tr'),controls=el('td');if(listing.state==='open'&&context.canPublish)controls.append(action('Close listing',async()=>{if(busy||!await confirmAction('Close this listing?','The advertisement will be removed. An incurred publishing fee remains payable.'))return;busy=true;try{await request('/api/jarvis/cancel',{id:listing.id,revision:listing.revision});await refresh(true);}catch(error){banner.textContent=error.message;}finally{busy=false;}}));row.append(el('td',listing.title),el('td',listing.state),el('td',listing.feeMinor?amount(listing.feeMinor):'Free'),controls);body.append(row);}if(!context.listings.length){const row=el('tr'),cell=el('td','No listings have been published.');cell.colSpan=4;row.append(cell);body.append(row);}mine.append(wrap);}
function renderPost(){
const data=context,quote=data.recruitment,stock=Math.max(0,quote.availablePlaces-data.listings.filter(r=>r.state==='open').length),form=el('form',undefined,'jarvis-form'),title=el('input'),message=el('textarea'),source=el('select'),promotion=el('fieldset'),confirmation=el('label',undefined,'jarvis-confirm'),check=el('input'),status=el('p');status.setAttribute('role','status');title.name='title';message.name='message';title.required=true;title.maxLength=100;message.maxLength=1000;check.type='checkbox';check.required=true;
post.replaceChildren(el('h3','Post a recruitment listing'));form.append(el('p',quote.unitPriceMinor===0?'Basic recruitment is free. Each advertisement offers one available membership place.':amount(quote.unitPriceMinor)+' publishing fee per place · reserved from the organisation account and credited to Tax at a four-hour bank window.'),field('Title',title),field('Message',message),el('p','Audience: Public Starport Exchange'));

View file

@ -1,3 +1,4 @@
import {createJarvisOrganisationContext} from './jarvis-organisation-context.mjs';
import {identity} from './auth.mjs';import {accessFor} from './permissions.mjs';
import {clanDeedAuthority} from './clan-deeds.mjs';import {CLAN_HOMEWORLDS} from '../control-panel/clans.mjs';
import {clanRecruitmentQuote} from './jarvis-recruitment-policy.mjs';
@ -8,7 +9,8 @@ const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}
export function createJarvisServices(central,bank,settings={},deps={}){
const authenticate=deps.authenticate||((r)=>identity(r,central)),access=deps.access||((u)=>accessFor(central,u)),origin=settings.CP_ORIGIN||'https://cp.dunerealms.com',clock=deps.clock||Date.now,edition=deps.edition||(()=>currentCodexEdition(central,settings));
const bankAuthority=deps.bankAuthority||createPostbankAuthority(central,{bank}),payments=bank?createJarvisPayments(bank,bankAuthority,{clock}):null;
const authority=deps.authority||(async(user,{kind,id})=>{if(kind!=='clan'||!uuid(id))throw new JarvisError('This organisation recruitment adapter is not available.',409);
const organisationContext=createJarvisOrganisationContext(central,{clock});
const authority=deps.authority||(async(user,{kind,id})=>{if(kind!=='clan')return organisationContext(user,{kind,id});if(!uuid(id))throw new JarvisError('Choose a clan.');
const rights=await clanDeedAuthority(central,user.id,id),clan=rights.deed?.clan;if(!clan)return {canPublish:false};
const member=await central.prepare('SELECT clan_role FROM site_clan_members WHERE clan_id=? AND user_id=?').bind(id,user.id).first(),count=await central.prepare('SELECT COUNT(*) total FROM site_clan_members WHERE clan_id=?').bind(id).first(),charterKind=rights.deed.kind;
return {name:clan.name,worldName:CLAN_HOMEWORLDS.find(w=>w.key===clan.home_world)?.name||'',charterKind,payerEntityId:entityId('clan',id),canPublish:rights.canManage&&!clan.institution_key,canReview:!clan.institution_key&&(rights.canManage||['owner','officer'].includes(member?.clan_role)),recruitment:clanRecruitmentQuote({charterKind,memberCount:Number(count.total),protectedInstitution:!!clan.institution_key})};
@ -33,7 +35,7 @@ export function createJarvisServices(central,bank,settings={},deps={}){
if(request.method==='GET'&&path==='/api/jarvis/context'){
if([...url.searchParams.keys()].some(k=>!['kind','id'].includes(k))||url.searchParams.getAll('kind').length>1||url.searchParams.getAll('id').length>1)throw new JarvisError('Choose one organisation.');
const kind=url.searchParams.get('kind')||'clan';let id=url.searchParams.get('id');if(!id&&kind==='clan')id=(await central.prepare('SELECT clan_id FROM site_clan_members WHERE user_id=?').bind(user.id).first())?.clan_id;
await closeFilledJarvisListings(central,bank,{clock});const data=await listings.context(user,{kind,id});const clan=await central.prepare('SELECT version FROM site_clans WHERE id=? AND active=1').bind(id).first();
await closeFilledJarvisListings(central,bank,{clock});const data=await listings.context(user,{kind,id});if(kind!=='clan')return reply({...data,applications:[],accounts:[]});const clan=await central.prepare('SELECT version FROM site_clans WHERE id=? AND active=1').bind(id).first();
const {results:applications}=await central.prepare('SELECT a.username,j.listing_id,j.message,r.status,j.created_at FROM site_jarvis_clan_applications j JOIN site_clan_requests r ON r.clan_id=j.clan_id AND r.user_id=j.user_id JOIN site_accounts a ON a.id=j.user_id WHERE j.clan_id=? ORDER BY j.created_at DESC LIMIT 100').bind(id).all();
const accounts=data.canPublish?(await new PostbankPayments(bank,bankAuthority,{clock}).accounts(user)).filter(a=>a.entityId===data.payerEntityId&&a.canDebit):[];return reply({...data,clanVersion:Number(clan?.version),applications,accounts});
}

View file

@ -14,7 +14,7 @@ export function publicJarvisListing(row){return {id:row.id,organisationKind:row.
export function createJarvisListings(store,{authority,reserveFee,edition,clock=Date.now,promotionChannels=[]}){
if(![authority,reserveFee,edition].every(f=>typeof f==='function'))throw TypeError('J.A.R.V.I.S. adapters required');
const validScope=(kind,id)=>['clan','company','politics'].includes(kind)&&typeof id==='string'&&/^[a-z0-9_-]{1,36}$/i.test(id);
const scope=async(actor,kind,id,review=false)=>{if(!actor?.id||!validScope(kind,id))throw new JarvisError('Choose an organisation.');const current=await authority(actor,{kind,id});if(!(current?.canPublish||review&&current?.canReview))throw new JarvisError('Current organisation deed authority is required.',403);return current;};
const scope=async(actor,kind,id,review=false)=>{if(!actor?.id||!validScope(kind,id))throw new JarvisError('Choose an organisation.');const current=await authority(actor,{kind,id});if(!(current?.canPublish||review&&(current?.canReview||current?.canView)))throw new JarvisError('Current organisation deed authority is required.',403);return current;};
return Object.freeze({
async context(actor,{kind,id}){const current=await scope(actor,kind,id,true),rows=await store.query("SELECT * FROM jarvis_listings WHERE organisation_kind=? AND organisation_id=? ORDER BY (state='open') DESC,created_at DESC LIMIT 100",[kind,id]),credits=await store.first('SELECT promotion_credits FROM jarvis_organisation_state WHERE organisation_kind=? AND organisation_id=?',[kind,id]);const jobs=await store.query('SELECT p.listing_id,p.channel,p.state FROM jarvis_promotion_jobs p JOIN jarvis_listings l ON l.id=p.listing_id WHERE l.organisation_kind=? AND l.organisation_id=? ORDER BY p.created_at DESC LIMIT 100',[kind,id]);return {...current,kind,id,promotions:jobs.map(p=>({listingId:p.listing_id,channel:p.channel,state:p.state})),credits:current.charterKind==='basic'?Number(credits?.promotion_credits??5):null,promotionChannels,listings:rows.map(row=>({...publicJarvisListing(row),feeMinor:Number(row.fee_minor)}))};},
async browse(){const rows=await store.query("SELECT * FROM jarvis_listings WHERE state='open' ORDER BY created_at DESC,id LIMIT 500");return rows.map(publicJarvisListing);},

View file

@ -0,0 +1,23 @@
import {PUBLIC_OFFICES} from './public-government.mjs';
import {entityId} from './postbank-authority.mjs';
import {JarvisError} from './jarvis-listings.mjs';
// A verified workspace is not itself a charter, a recruitment quota or an
// appointment. Keep these sources separate until their domain writers exist.
export function createJarvisOrganisationContext(db,{clock=Date.now}={}){
return async(user,{kind,id})=>{
if(kind==='company'){
const company=await db.prepare("SELECT id,slug,name,founded_by,ceo_account_id,status FROM corrino_companies WHERE id=? AND status='active'").bind(id).first();
if(!company||![company.founded_by,company.ceo_account_id].includes(user.id))throw new JarvisError('Company management authority required.',403);
return {name:company.name,canView:true,canPublish:false,canReview:false,charterKind:null,payerEntityId:entityId('company',company.id),recruitment:null,membershipSource:'company-register',publishingReason:'Company recruitment is not available yet. You can manage your company identity and welcome message in Settings.',applicationReason:'Company membership applications are not connected yet.',links:{settings:'/company-cp?company='+encodeURIComponent(id)+'#company/settings',profile:'https://www.dunerealms.com/companies/'+encodeURIComponent(company.slug)}};
}
if(kind==='politics'){
const office=PUBLIC_OFFICES.find(o=>o.key===id);if(!office)throw new JarvisError('Political House not found.',404);
const now=clock(),kinds=office.kind==='bene'?['bene','house']:office.kind==='guild'?['guild','court']:[office.kind];
const {results=[]}=await db.prepare("SELECT id,user_id,kind,starts_at,expires_at FROM political_office_terms WHERE faction=? AND office=? AND outcome='winner' AND starts_at<=? AND expires_at>?").bind(office.faction,office.office,now,now).all(),terms=results.filter(t=>kinds.includes(t.kind));
if(terms.length!==1||terms[0].user_id!==user.id)throw new JarvisError('A current unambiguous office deed is required.',403);
return {name:office.scope,canView:true,canPublish:false,canReview:false,charterKind:'protected',payerEntityId:null,recruitment:null,membershipSource:'active-office-deed',officeDeed:{id:terms[0].id,startsAt:Number(terms[0].starts_at),expiresAt:Number(terms[0].expires_at)},publishingReason:'Political House membership follows current office deeds. Recruitment advertisements cannot appoint officeholders.',applicationReason:'Candidacy and election decisions use the existing election service.',links:{settings:'/politics-cp?office='+encodeURIComponent(id)+'#household/settings',elections:'/politics-cp?office='+encodeURIComponent(id)+'#household/campaigns'}};
}
throw new JarvisError('Choose an organisation.',400);
};
}

View file

@ -0,0 +1,34 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {randomUUID} from 'node:crypto';
import {jarvisRequestFixture} from './jarvis-request-fixture.mjs';
import {createJarvisServices} from '../node/jarvis-api.mjs';
async function setup(){
const f=await jarvisRequestFixture(),companyId=randomUUID();let actor=f.people.Owner,now=50;
f.db.sqlite.exec('CREATE TABLE corrino_companies(id TEXT,slug TEXT,name TEXT,founded_by TEXT,ceo_account_id TEXT,status TEXT);CREATE TABLE political_office_terms(id TEXT,user_id TEXT,kind TEXT,faction TEXT,office TEXT,outcome TEXT,starts_at INT,expires_at INT);');
f.db.sqlite.prepare("INSERT INTO corrino_companies VALUES(?,'commercial','Commercial Enterprise',?,?,'active')").run(companyId,f.people.Owner.id,f.people.Alpha.id);
f.db.sqlite.prepare("INSERT INTO political_office_terms VALUES(?,?,'house','atreides','house_leader','winner',10,100)").run(randomUUID(),f.people.Owner.id);
const {api}=createJarvisServices(f.db,f.bank,{POSTBANK_ENABLED:'true'},{authenticate:async()=>actor,access:async()=>({nodes:['web.menu.game']}),clock:()=>now,edition:async()=>({stage:'alpha',version:'1.0.1.1',season:'S01'})});
return {...f,companyId,actor:name=>actor=f.people[name]||null,time:value=>now=value,call:(path,body)=>api(new Request('https://cp.dunerealms.com/api/jarvis/'+path,body?{method:'POST',headers:{origin:'https://cp.dunerealms.com','Content-Type':'application/json'},body:JSON.stringify(body)}:{}))};
}
test('Company Exchange context follows its own current register without borrowing a clan quota or charging',async()=>{
const f=await setup();try{
let r=await f.call('context?kind=company&id='+f.companyId);assert.equal(r.status,200);const data=await r.json();assert.equal(data.name,'Commercial Enterprise');assert.equal(data.canView,true);assert.equal(data.canPublish,false);assert.equal(data.recruitment,null);assert.equal(data.charterKind,null);assert.deepEqual(data.applications,[]);assert.deepEqual(data.accounts,[]);assert.match(data.links.profile,/companies\/commercial$/);
const before=(await f.bank.first('SELECT COUNT(*) n FROM jarvis_listings')).n;
r=await f.call('publish',{kind:'company',organisationId:f.companyId,requestId:randomUUID(),title:'Forged clan quota',message:'',expectedPriceMinor:0,confirmed:true});assert.equal(r.status,403);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM jarvis_listings')).n,before);assert.equal((await f.bank.first('SELECT COUNT(*) n FROM pb_orders')).n,0);
f.actor('Alpha');assert.equal((await f.call('context?kind=company&id='+f.companyId)).status,200);f.actor('Beta');assert.equal((await f.call('context?kind=company&id='+f.companyId)).status,403);f.actor('Owner');assert.equal((await f.call('context?kind=company&id='+f.clanId)).status,403);
f.db.sqlite.prepare("UPDATE corrino_companies SET status='archived' WHERE id=?").run(f.companyId);assert.equal((await f.call('context?kind=company&id='+f.companyId)).status,403);
}finally{f.close();}
});
test('Political House context requires exactly one current matching office deed and cannot create free membership',async()=>{
const f=await setup();try{
let r=await f.call('context?kind=politics&id=atreides');assert.equal(r.status,200);const data=await r.json();assert.equal(data.membershipSource,'active-office-deed');assert.equal(data.officeDeed.expiresAt,100);assert.equal(data.canPublish,false);assert.equal(data.canReview,false);assert.equal(data.recruitment,null);assert.match(data.links.elections,/#household\/campaigns$/);
assert.equal((await f.call('publish',{kind:'politics',organisationId:'atreides',requestId:randomUUID(),title:'Appoint someone',message:'',expectedPriceMinor:0,confirmed:true})).status,403);
f.actor('Alpha');assert.equal((await f.call('context?kind=politics&id=atreides')).status,403);f.actor('Owner');f.time(100);assert.equal((await f.call('context?kind=politics&id=atreides')).status,403);f.time(50);
f.db.sqlite.prepare("INSERT INTO political_office_terms VALUES(?,?,'house','atreides','house_leader','winner',10,100)").run(randomUUID(),f.people.Owner.id);assert.equal((await f.call('context?kind=politics&id=atreides')).status,403);
assert.equal((await f.call('context?kind=politics&id=unknown')).status,404);f.actor(null);assert.equal((await f.call('context?kind=politics&id=atreides')).status,401);
}finally{f.close();}
});