Merge pull request 'Rebuild staff Dev requests around Jarvis routes, ideas and devkey requests' (#413) from fix/dev-ticket-jarvis-fields into main
All checks were successful
DuneRealms Web CI / web (push) Successful in 2m31s

This commit is contained in:
unimatrix 2026-11-19 20:36:25 +00:00
commit 2c7a7b3169
14 changed files with 1036 additions and 14 deletions

View file

@ -0,0 +1,44 @@
<?php
// Explicit operator workflow for the human-requested permanent example ticket.
// Uses the installed form validator and native Ticket API, not a web login bypass.
if(PHP_SAPI!=='cli'||posix_geteuid()!==0)exit("Server administrator CLI required\n");
$mode=$argv[1]??'';if(!in_array($mode,['create','complete','verify-protection'],true))exit("Choose create, complete or verify-protection\n");
$root='/home/dunerealms/apps/integrations/osticket';chdir($root);
$_SERVER['SCRIPT_NAME']='dev-example-cli.php';$_SERVER['REQUEST_METHOD']='CLI';$_SERVER['REMOTE_ADDR']='127.0.0.1';$_SERVER['SERVER_PORT']='443';
require $root.'/main.inc.php';require_once $root.'/dev-policy.php';
$identity=json_decode(file_get_contents('/tmp/dune-dev-example-identity.json'),true,512,JSON_THROW_ON_ERROR);
if(!dune_dev_owner($identity))throw new RuntimeException('Verified current Dev owner authority required');
$c=json_decode(file_get_contents('/home/dunerealms/.config/integrations.json'),true);
$db=new PDO('mysql:host='.$c['host'].';dbname='.$c['database'].';charset=utf8mb4',$c['username'],$c['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
$key='gary:jarvis-dev-form-example:20261119';$q=$db->prepare('SELECT d.*,t.number FROM dune_dev_tasks d JOIN drsupport_ticket t ON t.ticket_id=d.ticket_id WHERE d.task_key=?');$q->execute([$key]);$row=$q->fetch();
if($mode==='create'&&!$row){
$input=['title'=>'Rebuild the staff Dev request form for J.A.R.V.I.S. — permanent worked example','type'=>'Feature','system'=>'osTicket Dev Center / J.A.R.V.I.S. request planning','objective'=>'Replace the old request form with a staff-friendly Jarvis form. Support existing actions, future feature ideas, new key/action proposals, code/interface work and explicit DEV KEY REQUESTS. Preserve the useful context, outcome and acceptance questions. This ticket demonstrates request, implementation, testing, publication and closure.','current'=>'The existing form assumes every approved task should lead to code changes and predates the Jarvis catalogue and controlled execution model.','expected'=>'Staff can state an idea without knowing implementation details. Existing actions collect typed parameters; new proposals explain their intended outcome; developer key requests are unambiguous review requests, never web key issuance.','acceptance'=>'Old form replaced; existing-action parameters validated; future ideas/new action proposals supported; devkey route records actor, environment, scope, lifetime, destructive effects and recovery. No real keys issued by this form. Existing tickets unchanged. Positive and negative tests pass, source commit and CI recorded, live form verified. Close this ticket only with actual evidence and preserve it against deletion.','scope'=>'Only the Dev request form, its planning/validation/publisher and this one worked-example ticket. Do not rewrite, bulk close or migrate older tickets. Do not change key execution permissions or issue developer keys.','reproduction'=>'Open the old Dev new-request form: it has no Jarvis route or typed action fields.','testplan'=>'Validate all routes and reject unknown actions, malformed typed parameters and incomplete developer requests. Check markup escaping, old-ticket preservation, publisher idempotency, PHP syntax and live form rendering. Verify this example cannot be deleted.','references'=>'https://support.dunerealms.com/dev-tasks.php?view=new','dependencies'=>'Existing osTicket approval/private visibility rules and Jarvis masterkey catalogue.','risk'=>'No domain data operations or devkey issuance. Preserve all older requests and their history. Publish via reviewed source and CI; retain the existing native view if its boundaries changed.','priority'=>'Medium','timing'=>'Current owner-requested batch','privacy'=>'1'];
[$values,$errors]=dune_dev_validate($input);if($errors)throw new RuntimeException(implode('; ',$errors));
$topic=$db->query("SELECT topic_id,dept_id,team_id FROM drsupport_help_topic WHERE topic='Development task' AND ispublic=0")->fetch();if(!$topic)throw new RuntimeException('Native Dev routing unavailable');
$email=$identity['id'].'@accounts.dunerealms.invalid';$user=User::lookupByEmail($email)?:User::fromVars(['name'=>$identity['username'],'email'=>$email]);if(!$user)throw new RuntimeException('Native requester unavailable');
$nativeErrors=[];$ticket=Ticket::create(['uid'=>$user->getId(),'name'=>$identity['username'],'email'=>$email,'topicId'=>$topic['topic_id'],'deptId'=>$topic['dept_id'],'teamId'=>$topic['team_id'],'subject'=>$values['title'],'message'=>nl2br(htmlspecialchars(dune_dev_prompt($values),ENT_QUOTES,'UTF-8')),'source'=>'API','ip'=>'127.0.0.1','autorespond'=>false],$nativeErrors,'API',false,false);
if(!$ticket)throw new RuntimeException('Native ticket creation failed');
$q=$db->prepare("INSERT INTO dune_dev_tasks(task_key,ticket_id,submitter_id,title,prompt_json,approval,priority,task_type,approved_by,decision_note,execution_spec,created_at,updated_at) VALUES(?,?,?,?,?,'approved',?,?,?,?,?,NOW(),NOW())");
$q->execute([$key,$ticket->getId(),$identity['id'],$values['title'],json_encode($values,JSON_THROW_ON_ERROR),'Medium','Feature',$identity['id'],'Explicit Owner submission: permanent worked example.',dune_dev_execution_brief($values)]);
$row=['ticket_id'=>$ticket->getId(),'number'=>$ticket->getNumber(),'approval'=>'approved'];
}
if(!$row)throw new RuntimeException('Example ticket unavailable');
// A restrictive foreign key protects native deletion routes and direct ticket DELETE.
$column=$db->query("SHOW COLUMNS FROM drsupport_ticket LIKE 'ticket_id'")->fetch();$type=$column['Type'];if(!preg_match('/^(?:int|bigint)\([0-9]+\)(?: unsigned)?$/i',$type)&&!preg_match('/^(?:int|bigint)(?: unsigned)?$/i',$type))throw new RuntimeException('Unexpected native ticket ID type');
$db->exec("CREATE TABLE IF NOT EXISTS dune_retained_dev_tickets(ticket_id $type PRIMARY KEY,reason VARCHAR(255) NOT NULL,created_at DATETIME NOT NULL,CONSTRAINT dune_retained_dev_ticket_fk FOREIGN KEY(ticket_id) REFERENCES drsupport_ticket(ticket_id) ON DELETE RESTRICT) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$q=$db->prepare('INSERT IGNORE INTO dune_retained_dev_tickets(ticket_id,reason,created_at) VALUES(?,?,NOW())');$q->execute([$row['ticket_id'],'Owner-requested permanent Jarvis worked example; preserve request, implementation and evidence.']);
if($mode==='verify-protection'){
$blocked=false;$db->beginTransaction();
try{$q=$db->prepare('DELETE FROM drsupport_ticket WHERE ticket_id=?');$q->execute([$row['ticket_id']]);}
catch(PDOException $error){$blocked=($error->errorInfo[1]??null)===1451;}
finally{$db->rollBack();}
if(!$blocked)throw new RuntimeException('Deletion protection was not confirmed');
echo json_encode(['ticketId'=>(int)$row['ticket_id'],'number'=>$row['number'],'nativeDeleteBlocked'=>true,'testTransactionRolledBack'=>true])."\n";exit;
}
if($mode==='complete'&&$row['approval']!=='completed'){
$note=file_get_contents('php://stdin');$next=dune_dev_transition($identity,'complete',$row['approval'],$note);$ticket=Ticket::lookup($row['ticket_id']);$errors=[];
if(!$ticket->setStatus(3,$note,$errors,false,true))throw new RuntimeException('Native close failed; completion not saved');
$q=$db->prepare("UPDATE dune_dev_tasks SET approval=?,approved_by=?,decision_note=?,updated_at=NOW() WHERE ticket_id=? AND approval='approved'");$q->execute([$next,$identity['id'],$note,$row['ticket_id']]);
$q=$db->prepare('INSERT INTO dune_dev_task_events(ticket_id,actor_id,action,note,created_at) VALUES(?,?,?,?,NOW())');$q->execute([$row['ticket_id'],$identity['id'],'completed',$note]);$row['approval']=$next;
}
echo json_encode(['ticketId'=>(int)$row['ticket_id'],'number'=>$row['number'],'state'=>$row['approval'],'deletionProtected'=>true,'url'=>'https://support.dunerealms.com/dev-tasks.php?id='.$row['ticket_id']],JSON_THROW_ON_ERROR)."\n";

View file

@ -0,0 +1,655 @@
{
"schemaVersion": 1,
"sourceHash": "bf56a715a8dc98171d2e81322da240672166f30a3a72da018f703503a3e1792d",
"actions": [
{
"id": "clan.clear-protected-rosters",
"label": "Clan · Clear protected clan rosters",
"version": 1,
"keyType": "clan-administration",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "Remove members and owner from Vaerkring and Veiled Concord. Preserve clans, claims, POL and Crysknife.",
"fixedTargets": [
"Vaerkring",
"Veiled Concord"
],
"webIssue": true,
"recordOnly": false
},
{
"id": "clan.original",
"label": "Clan · Original clan charter",
"version": 1,
"keyType": "clan-founding",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "clan.subhouse",
"label": "Clan · Subhouse founding",
"version": 1,
"keyType": "clan-subhouse",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "parentClanId",
"label": "Mother clan",
"type": "text",
"required": true
},
{
"name": "recipient",
"label": "Recipient",
"type": "text",
"required": true
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "company.original",
"label": "Company · Original company charter",
"version": 1,
"keyType": "company-founding",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "company.subsidiary",
"label": "Company · Subsidiary founding",
"version": 1,
"keyType": "company-subsidiary",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "parentCompanyId",
"label": "Mother company",
"type": "text",
"required": true
},
{
"name": "recipient",
"label": "Recipient",
"type": "text",
"required": true
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "company.royal",
"label": "Company · Royal company charter",
"version": 1,
"keyType": "staff-company-royal",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "companyId",
"label": "Company",
"type": "text",
"required": true
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "politics.appoint",
"label": "POL & orders · Political appointment",
"version": 1,
"keyType": "political-appointment",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "office",
"label": "Office",
"type": "text",
"required": true
},
{
"name": "recipient",
"label": "Recipient",
"type": "text",
"required": true
},
{
"name": "role",
"label": "Role",
"type": "text",
"required": true
},
{
"name": "expiresAt",
"label": "Term end",
"type": "datetime-local",
"required": true
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "politics.membership",
"label": "POL & orders · Office deed membership",
"version": 1,
"keyType": "political-clan",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "termId",
"label": "Office term",
"type": "text",
"required": true
},
{
"name": "recipient",
"label": "Recipient",
"type": "text",
"required": true
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "politics.royal",
"label": "POL & orders · Protected office charter",
"version": 1,
"keyType": "staff-office-royal",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "office",
"label": "Office",
"type": "text",
"required": true
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "relations.parent",
"label": "Deeds & relations · Protected parent relation",
"version": 1,
"keyType": "staff-parent-link",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "childId",
"label": "Child organisation",
"type": "text",
"required": true
},
{
"name": "parentId",
"label": "Mother organisation",
"type": "text",
"required": true
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "relations.transfer",
"label": "Deeds & relations · Entity transfer",
"version": 1,
"keyType": "entity-transfer",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "entityId",
"label": "Organisation",
"type": "text",
"required": true
},
{
"name": "recipient",
"label": "New controller",
"type": "text",
"required": true
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "economy.snapshot",
"label": "Economy · Sealed economic snapshot",
"version": 1,
"keyType": "economy-snapshot",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "snapshotId",
"label": "Verified snapshot",
"type": "text",
"required": true
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
},
{
"id": "xp.correct",
"label": "Progression & XP · Approved XP correction",
"version": 1,
"keyType": "xp-correction",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "recipient",
"label": "Recipient",
"type": "text",
"required": true
},
{
"name": "amountXP",
"label": "XP amount",
"type": "number",
"required": true,
"min": 1
},
{
"name": "caseReference",
"label": "Approved support case",
"type": "text",
"required": true
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "xp.transfer",
"label": "Progression & XP · Season XP transfer",
"version": 1,
"keyType": "xp-transfer",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "recipient",
"label": "Recipient",
"type": "text",
"required": true
},
{
"name": "fromSeason",
"label": "Source season",
"type": "text",
"required": true
},
{
"name": "toSeason",
"label": "Target season",
"type": "text",
"required": true
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "quest.instrument",
"label": "Progression & XP · Quest instrument",
"version": 1,
"keyType": "quest",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "questId",
"label": "Quest",
"type": "text",
"required": true
},
{
"name": "season",
"label": "Season",
"type": "text",
"required": true
},
{
"name": "recipient",
"label": "Recipient",
"type": "text",
"required": true
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "quest.milestone",
"label": "Progression & XP · Sealed milestone",
"version": 1,
"keyType": "quest-milestone",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "questId",
"label": "Milestone",
"type": "text",
"required": true
},
{
"name": "season",
"label": "Season",
"type": "text",
"required": true
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
},
{
"id": "progression.policy",
"label": "Progression & XP · Season progression policy",
"version": 1,
"keyType": "progression-policy",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "season",
"label": "Season",
"type": "text",
"required": true
},
{
"name": "policyVersion",
"label": "Policy version",
"type": "number",
"required": true,
"min": 1
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "projects.action",
"label": "Server projects · Project decision",
"version": 1,
"keyType": "project-action",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "projectId",
"label": "Project",
"type": "text",
"required": true
},
{
"name": "decision",
"label": "Decision",
"type": "text",
"required": true
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": false
},
{
"id": "news.record",
"label": "Gazette · Confirmed public announcement",
"version": 1,
"keyType": "gazette-news",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "sourceId",
"label": "Confirmed source event",
"type": "text",
"required": true
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "",
"fixedTargets": [],
"webIssue": false,
"recordOnly": true
},
{
"id": "accounts.test-minecraft-identity",
"label": "Accounts · Assign a synthetic test Minecraft UUID",
"version": 1,
"keyType": "account-test-identity",
"fields": [
{
"name": "ticketId",
"label": "Ban / support ticket ID",
"type": "text",
"required": true,
"maxLength": 80
},
{
"name": "accountName",
"label": "Target account name",
"type": "text",
"required": true
},
{
"name": "reference",
"label": "Reason / decision reference",
"type": "text",
"required": false
}
],
"effect": "Generate and assign one synthetic test UUID to the named unlinked account. Never overwrites a game link or pending link challenge. This is not proof of Minecraft ownership.",
"fixedTargets": [],
"webIssue": true,
"recordOnly": false
}
]
}

View file

@ -0,0 +1,11 @@
.dev-jarvis-request fieldset{min-width:0;margin:1.4rem 0;padding:1.3rem;border:1px solid #66734d;border-radius:12px;background:#10291f}
.dev-jarvis-request legend{padding:0 .6rem;color:#e4c478;font-weight:700;letter-spacing:.03em}
.dev-jarvis-request fieldset[hidden]{display:none}
.dev-jarvis-request .jarvis-devkey-request{border-color:#b8894c;background:#2c281c}
.dev-jarvis-request .dev-fields{gap:1.2rem}
.dev-jarvis-request label{display:flex;flex-direction:column;gap:.5rem}
.dev-jarvis-request textarea{min-height:7rem;resize:vertical}
.dev-jarvis-request .dev-check{display:flex;flex-direction:row;align-items:flex-start;gap:.7rem;margin:1.2rem 0}
.dev-jarvis-request .dev-check input{width:auto;flex-shrink:0;margin-top:.25rem}
.jarvis-request-receipt{padding:1rem;border-left:3px solid #c7a359;background:#17382c}
@media(max-width:650px){.dev-jarvis-request fieldset{padding:.85rem}.dev-jarvis-request .dev-fields{grid-template-columns:minmax(0,1fr)}}

View file

@ -0,0 +1,26 @@
const form=document.getElementById('jarvis-dev-request');
if(form){
const data=JSON.parse(document.getElementById('jarvis-request-catalogue').textContent),route=form.elements.workflow,action=form.elements.action_id,fields=document.getElementById('jarvis-action-fields'),help=document.getElementById('jarvis-route-help'),effect=document.getElementById('jarvis-action-effect');
const notes={existing:'Use the existing Jarvis adapter. Do not create a source change for an operation already supported.',idea:'Describe your future idea in plain language. Existing-action fields are disabled; a reviewer can check feasibility and the catalogue for you.',capability:'Describe what the new key or action should allow. A reviewer checks existing capabilities before any new implementation.',code:'Use Git and CI for implementation changes. Preserve existing Jarvis adapters and permissions.',devkey:'DEV KEY REQUEST: review only. Developer issuance and execution remain outside the website.'};
let initial={};try{initial=JSON.parse(data.values.action_parameters||'{}');}catch{}
function renderAction(values={}){
fields.replaceChildren();const chosen=data.catalogue.actions.find(a=>a.id===action.value);
effect.textContent=chosen?(chosen.effect||'Use the registered domain action; confirm its current adapter and authority.')+(chosen.fixedTargets.length?' Fixed targets: '+chosen.fixedTargets.join(', ')+'.':''):'';
for(const f of chosen?.fields||[]){
const label=document.createElement('label'),input=document.createElement(f.type==='textarea'?'textarea':'input'),caption=document.createElement('span');caption.textContent=f.label+(f.required?' *':'');
if(input.tagName==='INPUT')input.type=['number','datetime-local'].includes(f.type)?f.type:'text';input.name='jarvis_values['+f.name+']';input.required=!!f.required;input.maxLength=f.maxLength||240;if(f.min!==undefined)input.min=f.min;input.value=values[f.name]??'';
label.append(caption,input);fields.append(label);
}
}
function updateRoute(){
for(const block of form.querySelectorAll('[data-jarvis-routes]')){
const show=block.dataset.jarvisRoutes.split(' ').includes(route.value);block.hidden=!show;for(const control of block.querySelectorAll('input,select,textarea'))control.disabled=!show;
}
help.textContent=notes[route.value]||'Choose a route before completing the request.';
action.required=route.value==='existing';
form.elements.catalogue_review.required=['code','devkey'].includes(route.value);form.elements.missing_capability.required=route.value==='capability';
for(const name of ['dev_actor','dev_actions','dev_expiry','destructive_actions','dev_acknowledgement'])form.elements[name].required=route.value==='devkey';
form.elements.risk.required=route.value==='devkey';
}
action.addEventListener('change',()=>{renderAction();updateRoute();});route.addEventListener('change',updateRoute);renderAction(initial);updateRoute();
}

View file

@ -0,0 +1,37 @@
<?php
if(!defined('ROOT_DIR')||!isset($identity,$values,$owner))exit;
$jf=dune_jarvis_fields();$jc=dune_jarvis_catalogue();
$je=static fn($v)=>htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');
$render=function($key)use($jf,$values,$jc,$je){
[$label,$required,$max,$type,$hint]=$jf[$key];$value=$values[$key]??'';
echo '<label class="'.($type==='textarea'?'wide':'').'">'.$je($label).($required?' *':'');
if(in_array($type,['select','route','choice','action'],true)){
echo '<select name="'.$je($key).'"'.($required?' required':'').'>';
if($type!=='select')echo '<option value="">Choose…</option>';
$options=$type==='action'?array_column($jc['actions'],'label','id'):$hint;
foreach($options as$id=>$text){$id=$type==='select'?$text:$id;echo '<option value="'.$je($id).'"'.($value===$id?' selected':'').'>'.$je($text).'</option>';}
echo '</select>';
}elseif($type==='textarea')echo '<textarea name="'.$je($key).'" maxlength="'.$max.'"'.($required?' required':'').' placeholder="'.$je($hint).'">'.$je($value).'</textarea>';
else echo '<input name="'.$je($key).'" type="'.($type==='number'?'number':'text').'" maxlength="'.$max.'"'.($type==='number'?' min="1" max="15"':'').($required?' required':'').' placeholder="'.$je($hint).'" value="'.$je($value).'">';
echo '</label>';
};
?>
<section class="dev-box dev-jarvis-request" id="new-task">
<div class="dev-task-heading"><div><p class="eyebrow">A REQUEST IS NOT AN EXECUTED ACTION</p><h2>J.A.R.V.I.S. request desk</h2></div><img src="/assets/seals/team-dev-150.png" width="64" height="64" alt="Development bureau seal"></div>
<p>Choose the execution route, identify the exact targets and define the evidence needed to finish. Your request is preserved in a private ticket. Approval does not issue a key or execute a change.</p>
<form method="post" id="jarvis-dev-request">
<input type="hidden" name="action" value="create"><input type="hidden" name="csrf" value="<?=$je($_SESSION['dune_dev_csrf'])?>"><input type="hidden" name="submission" value="<?=$je($_SESSION['dune_dev_submission'])?>">
<fieldset><legend>1 · Route &amp; destination</legend><div class="dev-fields"><?php foreach(['title','workflow','type','system','environment']as$k)$render($k);?></div><p id="jarvis-route-help" role="status">A supported data operation uses an existing Jarvis action. A browser or access problem does not turn it into a developer operation.</p></fieldset>
<fieldset data-jarvis-routes="existing"><legend>2 · Existing action &amp; typed parameters</legend><div class="dev-fields"><?php $render('action_id');?></div><p id="jarvis-action-effect"></p><div class="dev-fields" id="jarvis-action-fields"></div><p>Catalogue membership is not execution authority. The current domain adapter and required normal key must still be verified at execution.</p></fieldset>
<fieldset data-jarvis-routes="idea capability code devkey"><legend>2 · Catalogue review</legend><div class="dev-fields"><?php $render('catalogue_review');?></div><p>For a future idea or new key proposal, leave this blank if you need a reviewer to check the catalogue. You do not need technical implementation knowledge. An unavailable interface never permits bypassing an access denial.</p></fieldset>
<fieldset data-jarvis-routes="capability"><legend>Missing capability</legend><div class="dev-fields"><?php $render('missing_capability');?></div></fieldset>
<fieldset data-jarvis-routes="devkey" class="jarvis-devkey-request"><legend>Dev key request · separately controlled</legend><p>Developer keys can authorise destructive operations. This form only requests review: no developer key is issued, displayed or executed here, including for Owners.</p><div class="dev-fields"><?php foreach(['dev_actor','dev_actions','dev_expiry','destructive_actions']as$k)$render($k);?></div><label class="dev-check"><input type="checkbox" name="dev_acknowledgement" value="1"> I understand that issuance and execution require the separately authorised server/CLI developer flow, bound to the exact actor, environment and manifest.</label></fieldset>
<fieldset><legend>3 · Outcome, context &amp; protected scope</legend><div class="dev-fields"><?php foreach(['targets','objective','current','expected','scope','preserve','acceptance']as$k)$render($k);?></div></fieldset>
<fieldset><legend>4 · Checks, recovery &amp; supporting material</legend><div class="dev-fields"><?php foreach(['risk','reproduction','testplan','references','dependencies','priority','timing']as$k)$render($k);?></div><p>Add relevant files to the resulting private ticket. Never attach credentials, a real key, an environment file or unnecessary personal information.</p></fieldset>
<label class="dev-check"><input type="checkbox" name="privacy" value="1" required> I have not included passwords, tokens, private keys or unnecessary personal data.</label>
<p class="jarvis-request-receipt">Completion must identify the real outcome and audit/receipt reference. Planned, tested, deployed and executed are different states.</p>
<button type="submit"><?=$owner?'Create reviewed request':'Submit request for review'?></button>
</form>
<noscript><p>JavaScript is required to choose typed action parameters. Other request fields still undergo server validation.</p></noscript>
<script type="application/json" id="jarvis-request-catalogue"><?=json_encode(['catalogue'=>$jc,'values'=>$values],JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_THROW_ON_ERROR)?></script>
</section>

View file

@ -0,0 +1,109 @@
<?php
// Request planning only. No issuance secret, executor, SQL or domain writes here.
function dune_jarvis_routes() {
return ['existing'=>'Execute an existing J.A.R.V.I.S. action','idea'=>'New feature / future idea','capability'=>'New key / J.A.R.V.I.S. action proposal','code'=>'Code / interface change','devkey'=>'Dev key request'];
}
function dune_jarvis_catalogue() {
$path=__DIR__.'/dev-jarvis-catalogue.json';
if(!is_file($path))return ['actions'=>[],'sourceHash'=>'unavailable'];
$data=json_decode(file_get_contents($path),true);
return is_array($data)&&isset($data['actions'],$data['sourceHash'])?$data:['actions'=>[],'sourceHash'=>'unavailable'];
}
function dune_jarvis_fields() {
return [
'title'=>['Request title',true,160,'input','A short, specific outcome'],
'workflow'=>['Execution route',true,40,'route',dune_jarvis_routes()],
'type'=>['Request category',true,40,'select',['Feature','Bug','Design / artwork','Operations','Documentation','Release / verification']],
'system'=>['System / component',true,120,'input','Website, Support, Shop, Minecraft, clan, company or server'],
'environment'=>['Target environment',true,40,'choice',['proposal'=>'Not decided — proposal only','test'=>'Test','staging'=>'Staging','production'=>'Production']],
'action_id'=>['Existing mastertemplate / action',false,80,'action',[]],
'catalogue_review'=>['Catalogue review / why the normal action is insufficient',false,2000,'textarea','Which existing actions were checked? Explain the specific gap; do not bypass them.'],
'targets'=>['Target users / organisations / records',true,2000,'textarea','For an operation: exact account names and record references. For an idea: intended users or audience; technical IDs are not required.'],
'objective'=>['Objective / full request',true,12000,'textarea','What must change, and why? Describe the requested outcome, not arbitrary executable code.'],
'current'=>['Current behaviour / context',true,6000,'textarea','What happens now? Include the relevant page, command or version.'],
'expected'=>['Expected result',true,6000,'textarea','Describe the finished result from the user’s point of view.'],
'acceptance'=>['Acceptance criteria / execution evidence',true,6000,'textarea','Observable before/after checks, expected result and the receipt or audit evidence needed to close this request.'],
'scope'=>['Scope and exclusions',true,4000,'textarea','Exact approved scope. What must remain untouched?'],
'preserve'=>['Records / behaviour that must be preserved',true,3000,'textarea','Protected organisations, members, balances, votes, uploads and unrelated records. Use None only when appropriate.'],
'missing_capability'=>['Proposed key / action and what it should allow',false,3000,'textarea','Describe the desired ability in plain language. You do not need to know how an adapter is implemented.'],
'dev_actor'=>['Requested developer executor',false,120,'input','Developer account or operator to review; this field does not grant authority.'],
'dev_actions'=>['Exact requested developer manifest / operations',false,6000,'textarea','List the exact actions and target IDs. The developer must create and independently validate the final manifest before issuance.'],
'dev_expiry'=>['Requested devkey lifetime in minutes (1–15)',false,2,'number','10'],
'destructive_actions'=>['Irreversible / destructive effects',false,3000,'textarea','Explicitly list deletions, resets or wipes and their exact boundaries. Write None if there are no destructive effects.'],
'risk'=>['Data, rollout and rollback considerations',false,4000,'textarea','Backup or restore plan, recovery limitations and service impact. A devkey request must include this.'],
'reproduction'=>['Reproduction steps / error messages',false,6000,'textarea','For bugs: steps, exact error, client and server versions.'],
'testplan'=>['Suggested tests',false,4000,'textarea','Positive and failure cases, preserved records, repeated requests and relevant devices.'],
'references'=>['Links / related tickets / receipts',false,4000,'textarea','Relevant HTTPS pages, source paths, ticket IDs or existing audit references. Never paste a key or credentials.'],
'dependencies'=>['Dependencies / related tasks',false,3000,'textarea','What must be ready first? Who can clarify the request?'],
'priority'=>['Requested priority',true,40,'select',['Medium','Low','High']],
'timing'=>['Desired timing / reason',false,500,'input','A request, not a guaranteed deadline'],
];
}
function dune_jarvis_request_validate($input) {
$values=[];$errors=[];$definitions=dune_jarvis_fields();
foreach($definitions as$key=>[$label,$required,$max,$type,$hint]) {
$value=is_string($input[$key]??null)?trim($input[$key]):'';
if(($required&&$value==='')||!dune_dev_text_valid($value,0,$max)||(isset($input[$key])&&!is_string($input[$key])))$errors[]=$label.': enter a valid value (maximum '.$max.' characters).';
if(in_array($type,['route','choice'],true)&&!array_key_exists($value,$hint))$errors[]=$label.': choose a listed option.';
if($type==='select'&&!in_array($value,$hint,true))$errors[]=$label.': choose a listed option.';
$values[$key]=$value;
}
$route=$values['workflow'];$catalogue=dune_jarvis_catalogue();$action=null;$parameters=[];
foreach($catalogue['actions']as$item)if($item['id']===$values['action_id'])$action=$item;
if($route==='existing'){
if(!$action)$errors[]='Choose an existing action from the current Jarvis catalogue.';
$submitted=$input['jarvis_values']??[];
if(!is_array($submitted)){$errors[]='Action fields must be a structured form.';$submitted=[];}
$allowed=array_column($action['fields']??[],'name');
foreach(array_keys($submitted)as$name)if(!in_array($name,$allowed,true))$errors[]='Unknown action parameter.';
foreach($action['fields']??[]as$field){
$name=$field['name'];$value=$submitted[$name]??'';$label=$field['label'];
if(!is_string($value)||!dune_dev_text_valid($value,0,$field['maxLength']??240)){$errors[]='Invalid action field: '.$label;continue;}
$value=trim($value);if(($field['required']??false)&&$value===''){$errors[]=$label.' is required.';continue;}
if($value===''&&!($field['required']??false))continue;
if(($field['type']??'text')==='number'){
if(!preg_match('/^-?[0-9]+$/D',$value)||filter_var($value,FILTER_VALIDATE_INT)===false||(int)$value<($field['min']??0)||abs((float)$value)>9007199254740991){$errors[]='Invalid action field: '.$label;continue;}
$value=(int)$value;
}
$parameters[$name]=$value;
}
}else{
// Never accept a hidden ordinary-action payload as developer authority.
$values['action_id']='';
if(!empty($input['jarvis_values']))$errors[]='Action parameters do not belong to the selected route.';
if(in_array($route,['idea','capability'],true)&&$values['catalogue_review']==='')$values['catalogue_review']='Not yet reviewed — reviewer must check the existing catalogue before implementation.';
if(!dune_dev_text_valid($values['catalogue_review'],10,2000))$errors[]='Explain which normal Jarvis actions were checked, or state that catalogue review is needed.';
}
if($values['environment']==='proposal'&&!in_array($route,['idea','capability'],true))$errors[]='Choose a concrete environment for an operation or developer request.';
if($route==='capability'&&!dune_dev_text_valid($values['missing_capability'],10,3000))$errors[]='Describe the missing Jarvis adapter or capability.';
if($route==='devkey'){
foreach(['dev_actor','dev_actions','destructive_actions','risk']as$key)if(!dune_dev_text_valid($values[$key],$key==='dev_actor'?1:4,$definitions[$key][2]))$errors[]=$definitions[$key][0].' is required for a dev key request.';
if(!preg_match('/^(?:[1-9]|1[0-5])$/D',$values['dev_expiry']))$errors[]='A developer key lifetime must be 1–15 minutes.';
if(($input['dev_acknowledgement']??'')!=='1')$errors[]='Acknowledge that this requests review only; developer issuance and execution remain separately controlled.';
}else{
foreach(['dev_actor','dev_actions','dev_expiry','destructive_actions']as$key){if($values[$key]!=='')$errors[]='Choose Dev key request for developer-only request fields.';$values[$key]='';}
}
if(($input['privacy']??'')!=='1')$errors[]='Confirm that the request contains no passwords, tokens or unnecessary personal data.';
$values['jarvis_request_version']=1;
$values['action_parameters']=json_encode((object)$parameters,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR);
$values['action_template_version']=$action&&$route==='existing'?(int)$action['version']:null;
$values['catalogue_source_hash']=$catalogue['sourceHash'];
$values['execution_state']='requested';
return [$values,array_values(array_unique($errors))];
}
function dune_jarvis_execution_brief($values) {
$route=$values['workflow']??'';
if(!isset(dune_jarvis_routes()[$route]))return "Legacy request — manual Jarvis review required. The original request is retained. Do not infer permission to code, issue keys or execute data operations from this legacy brief.";
$steps=[
'existing'=>"1. Recheck the current catalogue, identity, action scope and domain conditions.\n2. Use the existing validated domain adapter with the recorded typed parameters. Do not write code or direct SQL for a supported data operation. Select an available supported interface before starting; lack of browser control is not missing domain authority.\n3. Obtain any required normal scoped key through its existing flow; execute once and record the real receipt. If the adapter is unavailable, stop and report the exact missing capability.",
'idea'=>"1. Treat this as a feature proposal, not an instruction to execute a data operation.\n2. Review the desired outcome and existing Jarvis capabilities; staff need not know technical adapter names.\n3. Clarify feasibility and acceptance criteria during review. Agree the implementation scope before building or issuing any key.",
'capability'=>"1. Confirm the gap against the current masterkey catalogue and domain adapters.\n2. Implement only the smallest missing typed action; register it, test it and publish through Git/CI.\n3. Then execute the original request through the normal Jarvis action, with current authority and scope checks.",
'code'=>"1. Confirm this is an implementation change rather than an already supported data action.\n2. Make the smallest approved source change; reuse existing adapters and permissions.\n3. Run focused checks and required CI, then verify publication. Do not treat deployed code as proof a requested data operation ran.",
'devkey'=>"1. Treat this ticket as a DEV KEY REQUEST, never as an ordinary web key or an instruction to modify the database directly.\n2. Recheck why normal scoped Jarvis actions are insufficient. An authorised developer must independently validate the exact manifest, actor, environment, preservation rules, destructive effects and short lifetime.\n3. Developer issuance remains server/CLI-only. Ticket approval is not a key, not a grant of developer authority and not evidence of execution.\n4. Execute only through the separately permitted developer executor, bound to the exact manifest and current authorised actor. Record issuance/hash and execution results without any secret. Stop if the manifest, scope, environment or authority changes."
];
$parts=['J.A.R.V.I.S. REQUEST v1 — '.dune_jarvis_routes()[$route],"State: REQUESTED / NOT EXECUTED. Ticket approval does not execute an operation.","Execution route\n".$steps[$route]];
foreach(dune_jarvis_fields()as$key=>[$label])if(($values[$key]??'')!=='')$parts[]=$label."\n".$values[$key];
if($route==='existing')$parts[]="Recorded action template version: ".($values['action_template_version']??'unknown')."\nTyped action parameters:\n".($values['action_parameters']??'{}');
$parts[]='Completion requires actual results, preserved-record checks and an audit/receipt reference. Clearly distinguish planned, simulated, staged, deployed and executed. Never include a secret key in ticket text or attachments.';
return implode("\n\n",$parts);
}

View file

@ -1,4 +1,5 @@
<?php
require_once __DIR__.'/dev-jarvis-policy.php';
// UTF-8 code-point limits match the human-facing character contract; reject malformed bytes.
function dune_dev_text_valid($value,$min,$max){return is_string($value)&&mb_check_encoding($value,'UTF-8')&&mb_strlen(trim($value),'UTF-8')>=$min&&mb_strlen(trim($value),'UTF-8')<=$max;}
function dune_dev_id($value){return is_string($value)&&preg_match('/^[1-9][0-9]*$/D',$value)&&filter_var($value,FILTER_VALIDATE_INT)!==false?(int)$value:false;}
@ -30,7 +31,7 @@ function dune_dev_transition($identity,$action,$state,$note) {
throw new RuntimeException('This action is not available for the current task state.');
}
function dune_dev_priority_editor($identity) {return dune_dev_owner($identity)||(strtolower($identity['username']??'')==='dev'&&in_array('web_dev',$identity['ranks']??[],true));}
function dune_dev_fields() {
function dune_dev_legacy_fields() {
return [
'title'=>['Task title',true,160,'input','A short, specific outcome'],
'type'=>['Request type',true,40,'select',['Feature','Bug','Design / artwork','Operations','Documentation','Release / verification']],
@ -50,22 +51,17 @@ function dune_dev_fields() {
];
}
function dune_dev_validate($input) {
$values=[];$errors=[];
foreach(dune_dev_fields() as$key=>[$label,$required,$max,$type,$hint]) {
$value=is_string($input[$key]??null)?trim($input[$key]):'';
if(($required&&$value==='')||!dune_dev_text_valid($value,0,$max)|| (isset($input[$key])&&!is_string($input[$key]))||($type==='select'&&!in_array($value,$hint,true)))$errors[]=$label.': enter a valid value (maximum '.$max.' characters).';
$values[$key]=$value;
}
if(($input['privacy']??'')!=='1')$errors[]='Confirm that the request contains no passwords, tokens or unnecessary personal data.';
return [$values,$errors];
return dune_jarvis_request_validate($input);
}
function dune_dev_fields(){return dune_jarvis_fields()+[
'action_template_version'=>['Recorded action template version',false,20,'input',''],
'action_parameters'=>['Recorded typed action parameters',false,12000,'textarea',''],
'execution_state'=>['Execution state at submission',false,40,'input',''],
];}
function dune_dev_prompt($values) {
$parts=['DuneRealms development task — submitted through the private Dev form.'];
foreach(dune_dev_fields() as$key=>[$label])if(($values[$key]??'')!=='')$parts[]=$label."\n".$values[$key];
$parts[]='Workflow: Owner approval required before execution except explicit Owner submissions and the imported owner-approved backlog. Complete only with actual changes, checks, evidence and deployment/merge status. Scheduled morning/evening slots remain in effect.';
return implode("\n\n",$parts);
return dune_jarvis_execution_brief($values)."\n\nReview: existing Owner approval and private ticket visibility rules remain authoritative. Approval alone neither issues a key nor executes a change.";
}
function dune_dev_execution_brief($values) {
return "## Approved objective\n".($values['objective']??'')."\n\n## Scope and exclusions\n".($values['scope']??'Keep the approved request scope.')."\n\n## Implementation plan\n1. Inspect the current implementation and linked original request.\n2. Make the smallest complete change within approved scope.\n3. Run focused positive, failure and permission checks.\n4. Review and merge through the Dev fork; back up and verify any authorised rollout.\n\n## Acceptance criteria\n".($values['acceptance']??'')."\n\n## Test plan\n".($values['testplan']??'')."\n\n## Dependencies\n".($values['dependencies']??'')."\n\n## Completion report required\nChanges, actual checks/results, evidence, fork/merge link, deployed versus staged, rollback and remaining limits. Do not silently enlarge the approved scope.";
return dune_jarvis_execution_brief($values);
}

View file

@ -0,0 +1,30 @@
<?php
require dirname(__DIR__).'/dev-policy.php';
$checks=0;
function check($condition,$message){global $checks;$checks++;if(!$condition)throw new RuntimeException($message);}
function valid_request(){return ['title'=>'A clear staff request','workflow'=>'existing','type'=>'Operations','system'=>'Account service','environment'=>'test','action_id'=>'clan.clear-protected-rosters','targets'=>'The two fixed protected institutions','objective'=>'Perform the approved scoped operation.','current'=>'The current roster is populated.','expected'=>'Only the approved target roster changes.','acceptance'=>'Verify the exact result and audit receipt.','scope'=>'Only the selected action and its fixed targets.','preserve'=>'All unrelated clans, balances and votes.','priority'=>'Medium','privacy'=>'1','jarvis_values'=>['ticketId'=>'DR_DEV-0000098','reference'=>'Owner-approved example']];}
function invalid_request($input,$message){[$v,$e]=dune_dev_validate($input);check(count($e)>0,$message);return $v;}
[$v,$e]=dune_dev_validate(valid_request());check(!$e,'Existing action rejected: '.implode('; ',$e));
check($v['execution_state']==='requested','Submission must not claim execution');
check(json_decode($v['action_parameters'],true)['ticketId']==='DR_DEV-0000098','Typed action parameters missing');
check($v['action_template_version']===1,'Action version not pinned');
check(str_contains(dune_dev_execution_brief($v),'Do not write code or direct SQL'),'Existing action lost the execution route');
$q=valid_request();$q['action_id']='dev.issue';invalid_request($q,'Web developer issuance accepted');
$q=valid_request();$q['jarvis_values']['sql']='DELETE';invalid_request($q,'Unknown action parameter accepted');
$q=valid_request();unset($q['jarvis_values']['ticketId']);invalid_request($q,'Required typed field not checked');
$q=valid_request();$q['jarvis_values']['reference']=['bad'];invalid_request($q,'Nested action value accepted');
$q=valid_request();$q['action_id']='xp.correct';$q['jarvis_values']=['ticketId'=>'DR_DEV-0000098','recipient'=>'Example','amountXP'=>'50','caseReference'=>'Approved example'];[$v,$e]=dune_dev_validate($q);check(!$e,'Typed number rejected');check(json_decode($v['action_parameters'],true)['amountXP']===50,'Number was not typed');
$q['jarvis_values']['amountXP']='1e9';invalid_request($q,'Non-integer notation accepted');
$q=valid_request();$q['workflow']='idea';$q['environment']='proposal';unset($q['jarvis_values']);$q['action_id']='';[$v,$e]=dune_dev_validate($q);check(!$e,'Future idea requires technical catalogue knowledge');check(str_contains($v['catalogue_review'],'Not yet reviewed'),'Unknown catalogue status fabricated a completed review');check(str_contains(dune_dev_execution_brief($v),'feature proposal'),'Idea classified as an execution');
$q['workflow']='capability';invalid_request($q,'Missing new-action proposal accepted');$q['missing_capability']='A key that enables a proposed scoped staff task.';[$v,$e]=dune_dev_validate($q);check(!$e,'Plain-language new key proposal rejected');
$q=valid_request();$q['workflow']='devkey';$q['action_id']='';unset($q['jarvis_values']);$q+=['catalogue_review'=>'No normal scoped action supports the approved maintenance request.','dev_actor'=>'Reviewed developer account','dev_actions'=>'Review the exact approved manifest and target records.','dev_expiry'=>'10','destructive_actions'=>'None','risk'=>'Validate recovery and preserve unrelated records.','dev_acknowledgement'=>'1'];[$v,$e]=dune_dev_validate($q);check(!$e,'Complete devkey request rejected: '.implode('; ',$e));check($v['action_id']===''&&$v['action_parameters']==='{}','Developer request inherited ordinary action parameters');check(str_contains(dune_dev_prompt($v),'DEV KEY REQUEST'),'Developer intent absent from ticket');check(str_contains(dune_dev_execution_brief($v),'server/CLI-only'),'Developer boundary omitted');
foreach(['0','16','1e1']as$expiry){$bad=$q;$bad['dev_expiry']=$expiry;invalid_request($bad,'Invalid dev lifetime accepted');}
$bad=$q;unset($bad['dev_acknowledgement']);invalid_request($bad,'Developer review acknowledgement omitted');
$bad=$q;$bad['environment']='proposal';invalid_request($bad,'Developer request without concrete environment accepted');
$bad=valid_request();$bad['dev_actions']='Unexpected developer operation';invalid_request($bad,'Hidden developer operation accepted on ordinary route');
$bad=valid_request();$bad['privacy']='0';invalid_request($bad,'Privacy confirmation omitted');
$bad=valid_request();$bad['execution_state']='completed';[$v,$e]=dune_dev_validate($bad);check(!$e&&$v['execution_state']==='requested','Client overrode execution state');
check(str_contains(dune_dev_execution_brief(['objective'=>'Old request']),'Legacy request'),'Legacy ticket was reinterpreted as an executable instruction');
$original=['title'=>'Old title','objective'=>'Original request'];$copy=$original;dune_dev_execution_brief($original);check($original===$copy,'Legacy request data mutated');
$owner=['username'=>'unimatrix999','ranks'=>['owners']];check(dune_dev_owner($owner),'Existing owner approval changed');check(!dune_dev_owner(['username'=>'unimatrix999','ranks'=>['user']]),'Name alone gained owner authority');
echo json_encode(['passed'=>$checks,'failed'=>0,'ticket_created'=>false,'keys_issued'=>0])."\n";

View file

@ -0,0 +1,14 @@
import importlib.util,pathlib,unittest
path=pathlib.Path(__file__).resolve().parents[1]/'scripts/publish-jarvis-dev-form.py'
spec=importlib.util.spec_from_file_location('dev_form',path);module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
class DevFormPublisherTests(unittest.TestCase):
def test_only_new_form_replaced_and_history_preserved(self):
old="<head></head>HISTORY ORIGINAL<?php elseif($view==='new'):?>OLD FORM<?php endif;?>\n<footer>UNCHANGED FOOTER"
result=module.patch_view(old)
self.assertIn('HISTORY ORIGINAL',result);self.assertIn('UNCHANGED FOOTER',result)
self.assertNotIn('OLD FORM',result);self.assertIn("require __DIR__.'/dev-jarvis-form.php'",result)
self.assertEqual(result,module.patch_view(result))
def test_changed_boundaries_are_rejected(self):
for value in ['no marker',"<?php elseif($view==='new'):?>no end"]:
with self.assertRaises(ValueError):module.patch_view(value)
if __name__=='__main__':unittest.main()

View file

@ -0,0 +1,16 @@
// Operator CLI only; no web session or bearer token is created.
import {writeFileSync,renameSync} from 'node:fs';
if(process.getuid?.()!==0)throw Error('Explicit server administrator authority required');
process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');
const base='/home/dunerealms/apps/dunerealms/current/node/';
const {openDatabase}=await import(base+'mysql.mjs'),{accessFor}=await import(base+'permissions.mjs');
const db=await openDatabase(process.env);
try{
const user=await db.prepare('SELECT id,username,display_name,role FROM site_accounts WHERE LOWER(username)=?').bind('unimatrix999').first();
if(!user)throw Error('Owner account unavailable');
const access=await accessFor(db,user);
if(!access.nodes.includes('web.tickets.dev')||!access.nodes.includes('web.ranks.manage')&&!access.nodes.includes('cp.ranks.manage'))throw Error('Current owner Dev authority unavailable');
const identity={id:user.id,username:user.username,displayName:user.display_name,ranks:access.ranks,permissions:access.nodes,nativePermissionManagement:access.organisation?.mode!=='active'};
const tmp='/tmp/.dune-dev-example-identity-'+process.pid+'.json';writeFileSync(tmp,JSON.stringify(identity),{mode:0o600,flag:'wx'});renameSync(tmp,'/tmp/dune-dev-example-identity.json');
console.log(JSON.stringify({verified:true,username:user.username,source:'current central account and accessFor',webSessionCreated:false}));
}finally{await db.close();}

View file

@ -0,0 +1,8 @@
import {MASTER_KEY_TEMPLATES} from '../control-panel/public/jarvis-master-keys.mjs';
import {readFileSync,writeFileSync} from 'node:fs';import {createHash} from 'node:crypto';
export function devRequestCatalogue(){
return {schemaVersion:1,sourceHash:createHash('sha256').update(readFileSync(new URL('../control-panel/public/jarvis-master-keys.mjs',import.meta.url),'utf8').replaceAll('\r\n','\n')).digest('hex'),actions:MASTER_KEY_TEMPLATES.flatMap(t=>t.actions.map(a=>({id:a.id,label:t.label+' · '+a.label,version:a.version,keyType:a.keyType,fields:a.fields,effect:a.effect||'',fixedTargets:a.fixedTargets||[],webIssue:a.webIssue===true,recordOnly:a.recordOnly===true})))};
}
if(process.argv[1]&&import.meta.url.endsWith('/'+process.argv[1].replaceAll('\\','/').split('/').pop())){
const data=JSON.stringify(devRequestCatalogue(),null,2)+'\n';if(process.argv[2])writeFileSync(process.argv[2],data);else process.stdout.write(data);
}

View file

@ -0,0 +1,49 @@
"""Publish only the new Dev request form/policy; never change existing tickets."""
import argparse,hashlib,json,os,pathlib,subprocess,tempfile
def patch_view(text):
marker="<?php elseif($view==='new'):?>"
start=text.find(marker)
if start<0:raise ValueError('New-request view marker changed; inspect native view')
end=text.find('<?php endif;?>\n<footer',start)
if end<0:raise ValueError('Native view boundary changed; refusing replacement')
new=marker+"\n<?php require __DIR__.'/dev-jarvis-form.php'; ?>\n"
text=text[:start]+new+text[end:]
css='<link rel="stylesheet" href="/dev-jarvis-form.css?v=jarvis-request-1">'
js='<script src="/dev-jarvis-form.js?v=jarvis-request-1" defer></script>'
if css not in text:text=text.replace('</head>',css+js+'</head>',1)
return text
def atomic(path,data):
original=path.stat() if path.exists() else path.parent.stat()
fd,name=tempfile.mkstemp(prefix='.'+path.name+'.',dir=path.parent)
try:
with os.fdopen(fd,'wb')as stream:stream.write(data)
os.chown(name,original.st_uid,original.st_gid);os.chmod(name,0o644);os.replace(name,path)
finally:
if os.path.exists(name):os.unlink(name)
def main():
p=argparse.ArgumentParser();p.add_argument('--apply',action='store_true');p.add_argument('--root',default='/home/dunerealms/apps/integrations/osticket');p.add_argument('--node',default='/home/dunerealms/.nvm/versions/node/v22.23.3/bin/node');a=p.parse_args()
website=pathlib.Path(__file__).resolve().parents[1];source=website/'integrations/osticket';root=pathlib.Path(a.root).resolve(strict=True)
native=root/'dev-view.php';current=native.read_text();updated=patch_view(current)
catalogue=subprocess.check_output([a.node,str(website/'scripts/export-dev-request-catalogue.mjs')])
json.loads(catalogue)
files={name:(source/name).read_bytes() for name in ['dev-policy.php','dev-jarvis-policy.php','dev-jarvis-form.php','dev-jarvis-form.js','dev-jarvis-form.css']}
files['dev-jarvis-catalogue.json']=catalogue;files['dev-view.php']=updated.encode()
baseline='b99cbcc013172b1b6262cad7d2c6aa11e3847f1d6d48ff3475befc94ab4dbd5b'
current_policy=(root/'dev-policy.php').read_bytes()
if hashlib.sha256(current_policy).hexdigest() not in {baseline,hashlib.sha256(files['dev-policy.php']).hexdigest()}:raise RuntimeError('Installed Dev policy changed; inspect before replacing it')
# Check staged PHP syntax before replacing any native file.
with tempfile.TemporaryDirectory(prefix='dune-jarvis-form-')as stage:
for name,data in files.items():
path=pathlib.Path(stage)/name;path.write_bytes(data)
if name.endswith('.php'):subprocess.run(['/usr/bin/php','-l',str(path)],check=True,capture_output=True)
if a.apply:
if native.read_text()!=current or (root/'dev-policy.php').read_bytes()!=current_policy:raise RuntimeError('Native view or policy changed during publication')
# Shared policy is switched last; existing ticket data is never migrated.
for name,data in files.items():
if name!='dev-policy.php':atomic(root/name,data)
atomic(root/'dev-policy.php',files['dev-policy.php'])
print(json.dumps({'applied':a.apply,'files':list(files),'catalogue_actions':len(json.loads(catalogue)['actions']),'native_view_sha256':hashlib.sha256(updated.encode()).hexdigest(),'existing_tickets_modified':0}))
if __name__=='__main__':main()

View file

@ -0,0 +1,9 @@
import test from 'node:test';import assert from 'node:assert/strict';import{readFileSync}from'node:fs';
import {devRequestCatalogue} from '../scripts/export-dev-request-catalogue.mjs';
test('staff request fields use the current public master catalogue without developer issuance',()=>{
const catalogue=devRequestCatalogue();assert.ok(catalogue.actions.length>0);
assert.equal(new Set(catalogue.actions.map(a=>a.id)).size,catalogue.actions.length);
assert.equal(catalogue.actions.some(a=>/dev/i.test(a.keyType)),false);
const account=catalogue.actions.find(a=>a.id==='accounts.test-minecraft-identity');assert.ok(account);assert.ok(account.fields.some(f=>f.name==='accountName'));
assert.deepEqual(JSON.parse(readFileSync(new URL('../integrations/osticket/dev-jarvis-catalogue.json',import.meta.url))),catalogue,'Regenerate catalogue after changing mastertemplates');
});

View file

@ -0,0 +1,18 @@
import test from 'node:test';import assert from 'node:assert/strict';import{readFileSync}from'node:fs';import{runInNewContext}from'node:vm';
const source=readFileSync(new URL('../integrations/osticket/dev-jarvis-form.js',import.meta.url),'utf8');
function fixture({route='existing',action='test.action',values={}}={}){
class Node{constructor(tag='input'){this.tagName=tag.toUpperCase();this.children=[];this.value='';this.required=false;this.disabled=false;this.listeners={};this.textContent='';}append(...children){this.children.push(...children);}replaceChildren(...children){this.children=children;}addEventListener(name,fn){this.listeners[name]=fn;}}
const elements=Object.fromEntries(['workflow','action_id','catalogue_review','missing_capability','dev_actor','dev_actions','dev_expiry','destructive_actions','dev_acknowledgement','risk'].map(k=>[k,new Node()]));elements.workflow.value=route;elements.action_id.value=action;
const fields=new Node('div'),help=new Node('p'),effect=new Node('p'),blocks=['existing','idea capability code devkey','capability','devkey'].map(routes=>({dataset:{jarvisRoutes:routes},hidden:false,controls:[new Node()],querySelectorAll(){return this.controls;}}));
const form={elements,querySelectorAll(){return blocks;}};
const data={catalogue:{actions:[{id:'test.action',label:'Test',fields:[{name:'recipient',label:'Recipient',required:true,type:'text'},{name:'amount',label:'Amount',type:'number',min:1}],effect:'Only the selected record',fixedTargets:['Protected target']}]},values};
const nodes={'jarvis-dev-request':form,'jarvis-request-catalogue':{textContent:JSON.stringify(data)},'jarvis-action-fields':fields,'jarvis-route-help':help,'jarvis-action-effect':effect};
runInNewContext(source,{document:{getElementById:id=>nodes[id],createElement:t=>new Node(t)}});
return{elements,fields,help,effect,blocks,changeRoute(value){elements.workflow.value=value;elements.workflow.listeners.change();}};
}
test('ordinary action uses typed fields and hides/disables developer controls',()=>{const f=fixture();assert.equal(f.elements.action_id.required,true);assert.equal(f.fields.children[0].children[1].name,'jarvis_values[recipient]');assert.equal(f.fields.children[1].children[1].type,'number');assert.equal(f.blocks[3].hidden,true);assert.equal(f.blocks[3].controls[0].disabled,true);assert.match(f.effect.textContent,/Protected target/);});
test('future ideas disable existing action fields without requiring technical catalogue review',()=>{const f=fixture();f.changeRoute('idea');assert.equal(f.blocks[0].hidden,true);assert.equal(f.blocks[0].controls[0].disabled,true);assert.equal(f.elements.catalogue_review.required,false);assert.equal(f.elements.missing_capability.required,false);assert.match(f.help.textContent,/plain language/);});
test('new key proposal requests capability details, not developer issuance',()=>{const f=fixture({route:'capability'});assert.equal(f.elements.missing_capability.required,true);assert.equal(f.elements.dev_actor.required,false);assert.equal(f.blocks[3].hidden,true);});
test('developer request requires actor, short lifetime, destructive scope, recovery and acknowledgement',()=>{const f=fixture({route:'devkey'});for(const key of ['dev_actor','dev_actions','dev_expiry','destructive_actions','dev_acknowledgement','risk'])assert.equal(f.elements[key].required,true,key);assert.equal(f.blocks[3].hidden,false);assert.equal(f.elements.action_id.required,false);assert.match(f.help.textContent,/outside the website/);});
test('failed submission repopulates typed parameters using input values, not HTML',()=>{const hostile='<img src=x onerror=alert(1)>';const f=fixture({values:{action_parameters:JSON.stringify({recipient:hostile,amount:5})}});assert.equal(f.fields.children[0].children[1].value,hostile);assert.equal(f.fields.children[1].children[1].value,5);});
test('changing action resets old action parameter values',()=>{const f=fixture({values:{action_parameters:JSON.stringify({recipient:'Before'})}});f.elements.action_id.listeners.change();assert.equal(f.fields.children[0].children[1].value,'');});